1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/Constant.h" 90 #include "llvm/IR/ConstantRange.h" 91 #include "llvm/IR/Constants.h" 92 #include "llvm/IR/DataLayout.h" 93 #include "llvm/IR/DerivedTypes.h" 94 #include "llvm/IR/Dominators.h" 95 #include "llvm/IR/Function.h" 96 #include "llvm/IR/GlobalAlias.h" 97 #include "llvm/IR/GlobalValue.h" 98 #include "llvm/IR/GlobalVariable.h" 99 #include "llvm/IR/InstIterator.h" 100 #include "llvm/IR/InstrTypes.h" 101 #include "llvm/IR/Instruction.h" 102 #include "llvm/IR/Instructions.h" 103 #include "llvm/IR/IntrinsicInst.h" 104 #include "llvm/IR/Intrinsics.h" 105 #include "llvm/IR/LLVMContext.h" 106 #include "llvm/IR/Metadata.h" 107 #include "llvm/IR/Operator.h" 108 #include "llvm/IR/PatternMatch.h" 109 #include "llvm/IR/Type.h" 110 #include "llvm/IR/Use.h" 111 #include "llvm/IR/User.h" 112 #include "llvm/IR/Value.h" 113 #include "llvm/IR/Verifier.h" 114 #include "llvm/InitializePasses.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 229 //===----------------------------------------------------------------------===// 230 // SCEV class definitions 231 //===----------------------------------------------------------------------===// 232 233 //===----------------------------------------------------------------------===// 234 // Implementation of the SCEV class. 235 // 236 237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 238 LLVM_DUMP_METHOD void SCEV::dump() const { 239 print(dbgs()); 240 dbgs() << '\n'; 241 } 242 #endif 243 244 void SCEV::print(raw_ostream &OS) const { 245 switch (static_cast<SCEVTypes>(getSCEVType())) { 246 case scConstant: 247 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 248 return; 249 case scTruncate: { 250 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 251 const SCEV *Op = Trunc->getOperand(); 252 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 253 << *Trunc->getType() << ")"; 254 return; 255 } 256 case scZeroExtend: { 257 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 258 const SCEV *Op = ZExt->getOperand(); 259 OS << "(zext " << *Op->getType() << " " << *Op << " to " 260 << *ZExt->getType() << ")"; 261 return; 262 } 263 case scSignExtend: { 264 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 265 const SCEV *Op = SExt->getOperand(); 266 OS << "(sext " << *Op->getType() << " " << *Op << " to " 267 << *SExt->getType() << ")"; 268 return; 269 } 270 case scAddRecExpr: { 271 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 272 OS << "{" << *AR->getOperand(0); 273 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 274 OS << ",+," << *AR->getOperand(i); 275 OS << "}<"; 276 if (AR->hasNoUnsignedWrap()) 277 OS << "nuw><"; 278 if (AR->hasNoSignedWrap()) 279 OS << "nsw><"; 280 if (AR->hasNoSelfWrap() && 281 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 282 OS << "nw><"; 283 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 284 OS << ">"; 285 return; 286 } 287 case scAddExpr: 288 case scMulExpr: 289 case scUMaxExpr: 290 case scSMaxExpr: 291 case scUMinExpr: 292 case scSMinExpr: { 293 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 294 const char *OpStr = nullptr; 295 switch (NAry->getSCEVType()) { 296 case scAddExpr: OpStr = " + "; break; 297 case scMulExpr: OpStr = " * "; break; 298 case scUMaxExpr: OpStr = " umax "; break; 299 case scSMaxExpr: OpStr = " smax "; break; 300 case scUMinExpr: 301 OpStr = " umin "; 302 break; 303 case scSMinExpr: 304 OpStr = " smin "; 305 break; 306 } 307 OS << "("; 308 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 309 I != E; ++I) { 310 OS << **I; 311 if (std::next(I) != E) 312 OS << OpStr; 313 } 314 OS << ")"; 315 switch (NAry->getSCEVType()) { 316 case scAddExpr: 317 case scMulExpr: 318 if (NAry->hasNoUnsignedWrap()) 319 OS << "<nuw>"; 320 if (NAry->hasNoSignedWrap()) 321 OS << "<nsw>"; 322 } 323 return; 324 } 325 case scUDivExpr: { 326 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 327 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 328 return; 329 } 330 case scUnknown: { 331 const SCEVUnknown *U = cast<SCEVUnknown>(this); 332 Type *AllocTy; 333 if (U->isSizeOf(AllocTy)) { 334 OS << "sizeof(" << *AllocTy << ")"; 335 return; 336 } 337 if (U->isAlignOf(AllocTy)) { 338 OS << "alignof(" << *AllocTy << ")"; 339 return; 340 } 341 342 Type *CTy; 343 Constant *FieldNo; 344 if (U->isOffsetOf(CTy, FieldNo)) { 345 OS << "offsetof(" << *CTy << ", "; 346 FieldNo->printAsOperand(OS, false); 347 OS << ")"; 348 return; 349 } 350 351 // Otherwise just print it normally. 352 U->getValue()->printAsOperand(OS, false); 353 return; 354 } 355 case scCouldNotCompute: 356 OS << "***COULDNOTCOMPUTE***"; 357 return; 358 } 359 llvm_unreachable("Unknown SCEV kind!"); 360 } 361 362 Type *SCEV::getType() const { 363 switch (static_cast<SCEVTypes>(getSCEVType())) { 364 case scConstant: 365 return cast<SCEVConstant>(this)->getType(); 366 case scTruncate: 367 case scZeroExtend: 368 case scSignExtend: 369 return cast<SCEVCastExpr>(this)->getType(); 370 case scAddRecExpr: 371 case scMulExpr: 372 case scUMaxExpr: 373 case scSMaxExpr: 374 case scUMinExpr: 375 case scSMinExpr: 376 return cast<SCEVNAryExpr>(this)->getType(); 377 case scAddExpr: 378 return cast<SCEVAddExpr>(this)->getType(); 379 case scUDivExpr: 380 return cast<SCEVUDivExpr>(this)->getType(); 381 case scUnknown: 382 return cast<SCEVUnknown>(this)->getType(); 383 case scCouldNotCompute: 384 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 385 } 386 llvm_unreachable("Unknown SCEV kind!"); 387 } 388 389 bool SCEV::isZero() const { 390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 391 return SC->getValue()->isZero(); 392 return false; 393 } 394 395 bool SCEV::isOne() const { 396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 397 return SC->getValue()->isOne(); 398 return false; 399 } 400 401 bool SCEV::isAllOnesValue() const { 402 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 403 return SC->getValue()->isMinusOne(); 404 return false; 405 } 406 407 bool SCEV::isNonConstantNegative() const { 408 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 409 if (!Mul) return false; 410 411 // If there is a constant factor, it will be first. 412 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 413 if (!SC) return false; 414 415 // Return true if the value is negative, this matches things like (-42 * V). 416 return SC->getAPInt().isNegative(); 417 } 418 419 SCEVCouldNotCompute::SCEVCouldNotCompute() : 420 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 421 422 bool SCEVCouldNotCompute::classof(const SCEV *S) { 423 return S->getSCEVType() == scCouldNotCompute; 424 } 425 426 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 427 FoldingSetNodeID ID; 428 ID.AddInteger(scConstant); 429 ID.AddPointer(V); 430 void *IP = nullptr; 431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 432 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 433 UniqueSCEVs.InsertNode(S, IP); 434 return S; 435 } 436 437 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 438 return getConstant(ConstantInt::get(getContext(), Val)); 439 } 440 441 const SCEV * 442 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 443 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 444 return getConstant(ConstantInt::get(ITy, V, isSigned)); 445 } 446 447 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 448 unsigned SCEVTy, const SCEV *op, Type *ty) 449 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 450 451 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 452 const SCEV *op, Type *ty) 453 : SCEVCastExpr(ID, scTruncate, op, ty) { 454 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 455 "Cannot truncate non-integer value!"); 456 } 457 458 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 459 const SCEV *op, Type *ty) 460 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 461 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 462 "Cannot zero extend non-integer value!"); 463 } 464 465 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 466 const SCEV *op, Type *ty) 467 : SCEVCastExpr(ID, scSignExtend, op, ty) { 468 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 469 "Cannot sign extend non-integer value!"); 470 } 471 472 void SCEVUnknown::deleted() { 473 // Clear this SCEVUnknown from various maps. 474 SE->forgetMemoizedResults(this); 475 476 // Remove this SCEVUnknown from the uniquing map. 477 SE->UniqueSCEVs.RemoveNode(this); 478 479 // Release the value. 480 setValPtr(nullptr); 481 } 482 483 void SCEVUnknown::allUsesReplacedWith(Value *New) { 484 // Remove this SCEVUnknown from the uniquing map. 485 SE->UniqueSCEVs.RemoveNode(this); 486 487 // Update this SCEVUnknown to point to the new value. This is needed 488 // because there may still be outstanding SCEVs which still point to 489 // this SCEVUnknown. 490 setValPtr(New); 491 } 492 493 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 494 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 495 if (VCE->getOpcode() == Instruction::PtrToInt) 496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 497 if (CE->getOpcode() == Instruction::GetElementPtr && 498 CE->getOperand(0)->isNullValue() && 499 CE->getNumOperands() == 2) 500 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 501 if (CI->isOne()) { 502 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 503 ->getElementType(); 504 return true; 505 } 506 507 return false; 508 } 509 510 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 511 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 512 if (VCE->getOpcode() == Instruction::PtrToInt) 513 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 514 if (CE->getOpcode() == Instruction::GetElementPtr && 515 CE->getOperand(0)->isNullValue()) { 516 Type *Ty = 517 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 518 if (StructType *STy = dyn_cast<StructType>(Ty)) 519 if (!STy->isPacked() && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(1)->isNullValue()) { 522 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 523 if (CI->isOne() && 524 STy->getNumElements() == 2 && 525 STy->getElementType(0)->isIntegerTy(1)) { 526 AllocTy = STy->getElementType(1); 527 return true; 528 } 529 } 530 } 531 532 return false; 533 } 534 535 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 536 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 537 if (VCE->getOpcode() == Instruction::PtrToInt) 538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 539 if (CE->getOpcode() == Instruction::GetElementPtr && 540 CE->getNumOperands() == 3 && 541 CE->getOperand(0)->isNullValue() && 542 CE->getOperand(1)->isNullValue()) { 543 Type *Ty = 544 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 545 // Ignore vector types here so that ScalarEvolutionExpander doesn't 546 // emit getelementptrs that index into vectors. 547 if (Ty->isStructTy() || Ty->isArrayTy()) { 548 CTy = Ty; 549 FieldNo = CE->getOperand(2); 550 return true; 551 } 552 } 553 554 return false; 555 } 556 557 //===----------------------------------------------------------------------===// 558 // SCEV Utilities 559 //===----------------------------------------------------------------------===// 560 561 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 562 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 563 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 564 /// have been previously deemed to be "equally complex" by this routine. It is 565 /// intended to avoid exponential time complexity in cases like: 566 /// 567 /// %a = f(%x, %y) 568 /// %b = f(%a, %a) 569 /// %c = f(%b, %b) 570 /// 571 /// %d = f(%x, %y) 572 /// %e = f(%d, %d) 573 /// %f = f(%e, %e) 574 /// 575 /// CompareValueComplexity(%f, %c) 576 /// 577 /// Since we do not continue running this routine on expression trees once we 578 /// have seen unequal values, there is no need to track them in the cache. 579 static int 580 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 581 const LoopInfo *const LI, Value *LV, Value *RV, 582 unsigned Depth) { 583 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 584 return 0; 585 586 // Order pointer values after integer values. This helps SCEVExpander form 587 // GEPs. 588 bool LIsPointer = LV->getType()->isPointerTy(), 589 RIsPointer = RV->getType()->isPointerTy(); 590 if (LIsPointer != RIsPointer) 591 return (int)LIsPointer - (int)RIsPointer; 592 593 // Compare getValueID values. 594 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 595 if (LID != RID) 596 return (int)LID - (int)RID; 597 598 // Sort arguments by their position. 599 if (const auto *LA = dyn_cast<Argument>(LV)) { 600 const auto *RA = cast<Argument>(RV); 601 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 602 return (int)LArgNo - (int)RArgNo; 603 } 604 605 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 606 const auto *RGV = cast<GlobalValue>(RV); 607 608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 609 auto LT = GV->getLinkage(); 610 return !(GlobalValue::isPrivateLinkage(LT) || 611 GlobalValue::isInternalLinkage(LT)); 612 }; 613 614 // Use the names to distinguish the two values, but only if the 615 // names are semantically important. 616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 617 return LGV->getName().compare(RGV->getName()); 618 } 619 620 // For instructions, compare their loop depth, and their operand count. This 621 // is pretty loose. 622 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 623 const auto *RInst = cast<Instruction>(RV); 624 625 // Compare loop depths. 626 const BasicBlock *LParent = LInst->getParent(), 627 *RParent = RInst->getParent(); 628 if (LParent != RParent) { 629 unsigned LDepth = LI->getLoopDepth(LParent), 630 RDepth = LI->getLoopDepth(RParent); 631 if (LDepth != RDepth) 632 return (int)LDepth - (int)RDepth; 633 } 634 635 // Compare the number of operands. 636 unsigned LNumOps = LInst->getNumOperands(), 637 RNumOps = RInst->getNumOperands(); 638 if (LNumOps != RNumOps) 639 return (int)LNumOps - (int)RNumOps; 640 641 for (unsigned Idx : seq(0u, LNumOps)) { 642 int Result = 643 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 644 RInst->getOperand(Idx), Depth + 1); 645 if (Result != 0) 646 return Result; 647 } 648 } 649 650 EqCacheValue.unionSets(LV, RV); 651 return 0; 652 } 653 654 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 655 // than RHS, respectively. A three-way result allows recursive comparisons to be 656 // more efficient. 657 static int CompareSCEVComplexity( 658 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 659 EquivalenceClasses<const Value *> &EqCacheValue, 660 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 661 DominatorTree &DT, unsigned Depth = 0) { 662 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 663 if (LHS == RHS) 664 return 0; 665 666 // Primarily, sort the SCEVs by their getSCEVType(). 667 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 668 if (LType != RType) 669 return (int)LType - (int)RType; 670 671 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 672 return 0; 673 // Aside from the getSCEVType() ordering, the particular ordering 674 // isn't very important except that it's beneficial to be consistent, 675 // so that (a + b) and (b + a) don't end up as different expressions. 676 switch (static_cast<SCEVTypes>(LType)) { 677 case scUnknown: { 678 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 679 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 680 681 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 682 RU->getValue(), Depth + 1); 683 if (X == 0) 684 EqCacheSCEV.unionSets(LHS, RHS); 685 return X; 686 } 687 688 case scConstant: { 689 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 690 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 691 692 // Compare constant values. 693 const APInt &LA = LC->getAPInt(); 694 const APInt &RA = RC->getAPInt(); 695 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 696 if (LBitWidth != RBitWidth) 697 return (int)LBitWidth - (int)RBitWidth; 698 return LA.ult(RA) ? -1 : 1; 699 } 700 701 case scAddRecExpr: { 702 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 703 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 704 705 // There is always a dominance between two recs that are used by one SCEV, 706 // so we can safely sort recs by loop header dominance. We require such 707 // order in getAddExpr. 708 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 709 if (LLoop != RLoop) { 710 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 711 assert(LHead != RHead && "Two loops share the same header?"); 712 if (DT.dominates(LHead, RHead)) 713 return 1; 714 else 715 assert(DT.dominates(RHead, LHead) && 716 "No dominance between recurrences used by one SCEV?"); 717 return -1; 718 } 719 720 // Addrec complexity grows with operand count. 721 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 722 if (LNumOps != RNumOps) 723 return (int)LNumOps - (int)RNumOps; 724 725 // Lexicographically compare. 726 for (unsigned i = 0; i != LNumOps; ++i) { 727 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 728 LA->getOperand(i), RA->getOperand(i), DT, 729 Depth + 1); 730 if (X != 0) 731 return X; 732 } 733 EqCacheSCEV.unionSets(LHS, RHS); 734 return 0; 735 } 736 737 case scAddExpr: 738 case scMulExpr: 739 case scSMaxExpr: 740 case scUMaxExpr: 741 case scSMinExpr: 742 case scUMinExpr: { 743 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 744 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 745 746 // Lexicographically compare n-ary expressions. 747 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 748 if (LNumOps != RNumOps) 749 return (int)LNumOps - (int)RNumOps; 750 751 for (unsigned i = 0; i != LNumOps; ++i) { 752 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 753 LC->getOperand(i), RC->getOperand(i), DT, 754 Depth + 1); 755 if (X != 0) 756 return X; 757 } 758 EqCacheSCEV.unionSets(LHS, RHS); 759 return 0; 760 } 761 762 case scUDivExpr: { 763 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 764 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 765 766 // Lexicographically compare udiv expressions. 767 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 768 RC->getLHS(), DT, Depth + 1); 769 if (X != 0) 770 return X; 771 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 772 RC->getRHS(), DT, Depth + 1); 773 if (X == 0) 774 EqCacheSCEV.unionSets(LHS, RHS); 775 return X; 776 } 777 778 case scTruncate: 779 case scZeroExtend: 780 case scSignExtend: { 781 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 782 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 783 784 // Compare cast expressions by operand. 785 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 786 LC->getOperand(), RC->getOperand(), DT, 787 Depth + 1); 788 if (X == 0) 789 EqCacheSCEV.unionSets(LHS, RHS); 790 return X; 791 } 792 793 case scCouldNotCompute: 794 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 795 } 796 llvm_unreachable("Unknown SCEV kind!"); 797 } 798 799 /// Given a list of SCEV objects, order them by their complexity, and group 800 /// objects of the same complexity together by value. When this routine is 801 /// finished, we know that any duplicates in the vector are consecutive and that 802 /// complexity is monotonically increasing. 803 /// 804 /// Note that we go take special precautions to ensure that we get deterministic 805 /// results from this routine. In other words, we don't want the results of 806 /// this to depend on where the addresses of various SCEV objects happened to 807 /// land in memory. 808 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 809 LoopInfo *LI, DominatorTree &DT) { 810 if (Ops.size() < 2) return; // Noop 811 812 EquivalenceClasses<const SCEV *> EqCacheSCEV; 813 EquivalenceClasses<const Value *> EqCacheValue; 814 if (Ops.size() == 2) { 815 // This is the common case, which also happens to be trivially simple. 816 // Special case it. 817 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 818 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 819 std::swap(LHS, RHS); 820 return; 821 } 822 823 // Do the rough sort by complexity. 824 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 825 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 826 0; 827 }); 828 829 // Now that we are sorted by complexity, group elements of the same 830 // complexity. Note that this is, at worst, N^2, but the vector is likely to 831 // be extremely short in practice. Note that we take this approach because we 832 // do not want to depend on the addresses of the objects we are grouping. 833 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 834 const SCEV *S = Ops[i]; 835 unsigned Complexity = S->getSCEVType(); 836 837 // If there are any objects of the same complexity and same value as this 838 // one, group them. 839 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 840 if (Ops[j] == S) { // Found a duplicate. 841 // Move it to immediately after i'th element. 842 std::swap(Ops[i+1], Ops[j]); 843 ++i; // no need to rescan it. 844 if (i == e-2) return; // Done! 845 } 846 } 847 } 848 } 849 850 // Returns the size of the SCEV S. 851 static inline int sizeOfSCEV(const SCEV *S) { 852 struct FindSCEVSize { 853 int Size = 0; 854 855 FindSCEVSize() = default; 856 857 bool follow(const SCEV *S) { 858 ++Size; 859 // Keep looking at all operands of S. 860 return true; 861 } 862 863 bool isDone() const { 864 return false; 865 } 866 }; 867 868 FindSCEVSize F; 869 SCEVTraversal<FindSCEVSize> ST(F); 870 ST.visitAll(S); 871 return F.Size; 872 } 873 874 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 875 /// least HugeExprThreshold nodes). 876 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 877 return any_of(Ops, [](const SCEV *S) { 878 return S->getExpressionSize() >= HugeExprThreshold; 879 }); 880 } 881 882 namespace { 883 884 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 885 public: 886 // Computes the Quotient and Remainder of the division of Numerator by 887 // Denominator. 888 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 889 const SCEV *Denominator, const SCEV **Quotient, 890 const SCEV **Remainder) { 891 assert(Numerator && Denominator && "Uninitialized SCEV"); 892 893 SCEVDivision D(SE, Numerator, Denominator); 894 895 // Check for the trivial case here to avoid having to check for it in the 896 // rest of the code. 897 if (Numerator == Denominator) { 898 *Quotient = D.One; 899 *Remainder = D.Zero; 900 return; 901 } 902 903 if (Numerator->isZero()) { 904 *Quotient = D.Zero; 905 *Remainder = D.Zero; 906 return; 907 } 908 909 // A simple case when N/1. The quotient is N. 910 if (Denominator->isOne()) { 911 *Quotient = Numerator; 912 *Remainder = D.Zero; 913 return; 914 } 915 916 // Split the Denominator when it is a product. 917 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 918 const SCEV *Q, *R; 919 *Quotient = Numerator; 920 for (const SCEV *Op : T->operands()) { 921 divide(SE, *Quotient, Op, &Q, &R); 922 *Quotient = Q; 923 924 // Bail out when the Numerator is not divisible by one of the terms of 925 // the Denominator. 926 if (!R->isZero()) { 927 *Quotient = D.Zero; 928 *Remainder = Numerator; 929 return; 930 } 931 } 932 *Remainder = D.Zero; 933 return; 934 } 935 936 D.visit(Numerator); 937 *Quotient = D.Quotient; 938 *Remainder = D.Remainder; 939 } 940 941 // Except in the trivial case described above, we do not know how to divide 942 // Expr by Denominator for the following functions with empty implementation. 943 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 944 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 945 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 946 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 947 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 948 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 949 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 950 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 951 void visitUnknown(const SCEVUnknown *Numerator) {} 952 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 953 954 void visitConstant(const SCEVConstant *Numerator) { 955 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 956 APInt NumeratorVal = Numerator->getAPInt(); 957 APInt DenominatorVal = D->getAPInt(); 958 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 959 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 960 961 if (NumeratorBW > DenominatorBW) 962 DenominatorVal = DenominatorVal.sext(NumeratorBW); 963 else if (NumeratorBW < DenominatorBW) 964 NumeratorVal = NumeratorVal.sext(DenominatorBW); 965 966 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 967 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 968 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 969 Quotient = SE.getConstant(QuotientVal); 970 Remainder = SE.getConstant(RemainderVal); 971 return; 972 } 973 } 974 975 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 976 const SCEV *StartQ, *StartR, *StepQ, *StepR; 977 if (!Numerator->isAffine()) 978 return cannotDivide(Numerator); 979 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 980 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 981 // Bail out if the types do not match. 982 Type *Ty = Denominator->getType(); 983 if (Ty != StartQ->getType() || Ty != StartR->getType() || 984 Ty != StepQ->getType() || Ty != StepR->getType()) 985 return cannotDivide(Numerator); 986 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 987 Numerator->getNoWrapFlags()); 988 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 989 Numerator->getNoWrapFlags()); 990 } 991 992 void visitAddExpr(const SCEVAddExpr *Numerator) { 993 SmallVector<const SCEV *, 2> Qs, Rs; 994 Type *Ty = Denominator->getType(); 995 996 for (const SCEV *Op : Numerator->operands()) { 997 const SCEV *Q, *R; 998 divide(SE, Op, Denominator, &Q, &R); 999 1000 // Bail out if types do not match. 1001 if (Ty != Q->getType() || Ty != R->getType()) 1002 return cannotDivide(Numerator); 1003 1004 Qs.push_back(Q); 1005 Rs.push_back(R); 1006 } 1007 1008 if (Qs.size() == 1) { 1009 Quotient = Qs[0]; 1010 Remainder = Rs[0]; 1011 return; 1012 } 1013 1014 Quotient = SE.getAddExpr(Qs); 1015 Remainder = SE.getAddExpr(Rs); 1016 } 1017 1018 void visitMulExpr(const SCEVMulExpr *Numerator) { 1019 SmallVector<const SCEV *, 2> Qs; 1020 Type *Ty = Denominator->getType(); 1021 1022 bool FoundDenominatorTerm = false; 1023 for (const SCEV *Op : Numerator->operands()) { 1024 // Bail out if types do not match. 1025 if (Ty != Op->getType()) 1026 return cannotDivide(Numerator); 1027 1028 if (FoundDenominatorTerm) { 1029 Qs.push_back(Op); 1030 continue; 1031 } 1032 1033 // Check whether Denominator divides one of the product operands. 1034 const SCEV *Q, *R; 1035 divide(SE, Op, Denominator, &Q, &R); 1036 if (!R->isZero()) { 1037 Qs.push_back(Op); 1038 continue; 1039 } 1040 1041 // Bail out if types do not match. 1042 if (Ty != Q->getType()) 1043 return cannotDivide(Numerator); 1044 1045 FoundDenominatorTerm = true; 1046 Qs.push_back(Q); 1047 } 1048 1049 if (FoundDenominatorTerm) { 1050 Remainder = Zero; 1051 if (Qs.size() == 1) 1052 Quotient = Qs[0]; 1053 else 1054 Quotient = SE.getMulExpr(Qs); 1055 return; 1056 } 1057 1058 if (!isa<SCEVUnknown>(Denominator)) 1059 return cannotDivide(Numerator); 1060 1061 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1062 ValueToValueMap RewriteMap; 1063 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1064 cast<SCEVConstant>(Zero)->getValue(); 1065 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1066 1067 if (Remainder->isZero()) { 1068 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1069 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1070 cast<SCEVConstant>(One)->getValue(); 1071 Quotient = 1072 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1073 return; 1074 } 1075 1076 // Quotient is (Numerator - Remainder) divided by Denominator. 1077 const SCEV *Q, *R; 1078 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1079 // This SCEV does not seem to simplify: fail the division here. 1080 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1081 return cannotDivide(Numerator); 1082 divide(SE, Diff, Denominator, &Q, &R); 1083 if (R != Zero) 1084 return cannotDivide(Numerator); 1085 Quotient = Q; 1086 } 1087 1088 private: 1089 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1090 const SCEV *Denominator) 1091 : SE(S), Denominator(Denominator) { 1092 Zero = SE.getZero(Denominator->getType()); 1093 One = SE.getOne(Denominator->getType()); 1094 1095 // We generally do not know how to divide Expr by Denominator. We 1096 // initialize the division to a "cannot divide" state to simplify the rest 1097 // of the code. 1098 cannotDivide(Numerator); 1099 } 1100 1101 // Convenience function for giving up on the division. We set the quotient to 1102 // be equal to zero and the remainder to be equal to the numerator. 1103 void cannotDivide(const SCEV *Numerator) { 1104 Quotient = Zero; 1105 Remainder = Numerator; 1106 } 1107 1108 ScalarEvolution &SE; 1109 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1110 }; 1111 1112 } // end anonymous namespace 1113 1114 //===----------------------------------------------------------------------===// 1115 // Simple SCEV method implementations 1116 //===----------------------------------------------------------------------===// 1117 1118 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1119 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1120 ScalarEvolution &SE, 1121 Type *ResultTy) { 1122 // Handle the simplest case efficiently. 1123 if (K == 1) 1124 return SE.getTruncateOrZeroExtend(It, ResultTy); 1125 1126 // We are using the following formula for BC(It, K): 1127 // 1128 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1129 // 1130 // Suppose, W is the bitwidth of the return value. We must be prepared for 1131 // overflow. Hence, we must assure that the result of our computation is 1132 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1133 // safe in modular arithmetic. 1134 // 1135 // However, this code doesn't use exactly that formula; the formula it uses 1136 // is something like the following, where T is the number of factors of 2 in 1137 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1138 // exponentiation: 1139 // 1140 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1141 // 1142 // This formula is trivially equivalent to the previous formula. However, 1143 // this formula can be implemented much more efficiently. The trick is that 1144 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1145 // arithmetic. To do exact division in modular arithmetic, all we have 1146 // to do is multiply by the inverse. Therefore, this step can be done at 1147 // width W. 1148 // 1149 // The next issue is how to safely do the division by 2^T. The way this 1150 // is done is by doing the multiplication step at a width of at least W + T 1151 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1152 // when we perform the division by 2^T (which is equivalent to a right shift 1153 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1154 // truncated out after the division by 2^T. 1155 // 1156 // In comparison to just directly using the first formula, this technique 1157 // is much more efficient; using the first formula requires W * K bits, 1158 // but this formula less than W + K bits. Also, the first formula requires 1159 // a division step, whereas this formula only requires multiplies and shifts. 1160 // 1161 // It doesn't matter whether the subtraction step is done in the calculation 1162 // width or the input iteration count's width; if the subtraction overflows, 1163 // the result must be zero anyway. We prefer here to do it in the width of 1164 // the induction variable because it helps a lot for certain cases; CodeGen 1165 // isn't smart enough to ignore the overflow, which leads to much less 1166 // efficient code if the width of the subtraction is wider than the native 1167 // register width. 1168 // 1169 // (It's possible to not widen at all by pulling out factors of 2 before 1170 // the multiplication; for example, K=2 can be calculated as 1171 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1172 // extra arithmetic, so it's not an obvious win, and it gets 1173 // much more complicated for K > 3.) 1174 1175 // Protection from insane SCEVs; this bound is conservative, 1176 // but it probably doesn't matter. 1177 if (K > 1000) 1178 return SE.getCouldNotCompute(); 1179 1180 unsigned W = SE.getTypeSizeInBits(ResultTy); 1181 1182 // Calculate K! / 2^T and T; we divide out the factors of two before 1183 // multiplying for calculating K! / 2^T to avoid overflow. 1184 // Other overflow doesn't matter because we only care about the bottom 1185 // W bits of the result. 1186 APInt OddFactorial(W, 1); 1187 unsigned T = 1; 1188 for (unsigned i = 3; i <= K; ++i) { 1189 APInt Mult(W, i); 1190 unsigned TwoFactors = Mult.countTrailingZeros(); 1191 T += TwoFactors; 1192 Mult.lshrInPlace(TwoFactors); 1193 OddFactorial *= Mult; 1194 } 1195 1196 // We need at least W + T bits for the multiplication step 1197 unsigned CalculationBits = W + T; 1198 1199 // Calculate 2^T, at width T+W. 1200 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1201 1202 // Calculate the multiplicative inverse of K! / 2^T; 1203 // this multiplication factor will perform the exact division by 1204 // K! / 2^T. 1205 APInt Mod = APInt::getSignedMinValue(W+1); 1206 APInt MultiplyFactor = OddFactorial.zext(W+1); 1207 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1208 MultiplyFactor = MultiplyFactor.trunc(W); 1209 1210 // Calculate the product, at width T+W 1211 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1212 CalculationBits); 1213 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1214 for (unsigned i = 1; i != K; ++i) { 1215 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1216 Dividend = SE.getMulExpr(Dividend, 1217 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1218 } 1219 1220 // Divide by 2^T 1221 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1222 1223 // Truncate the result, and divide by K! / 2^T. 1224 1225 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1226 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1227 } 1228 1229 /// Return the value of this chain of recurrences at the specified iteration 1230 /// number. We can evaluate this recurrence by multiplying each element in the 1231 /// chain by the binomial coefficient corresponding to it. In other words, we 1232 /// can evaluate {A,+,B,+,C,+,D} as: 1233 /// 1234 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1235 /// 1236 /// where BC(It, k) stands for binomial coefficient. 1237 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1238 ScalarEvolution &SE) const { 1239 const SCEV *Result = getStart(); 1240 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1241 // The computation is correct in the face of overflow provided that the 1242 // multiplication is performed _after_ the evaluation of the binomial 1243 // coefficient. 1244 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1245 if (isa<SCEVCouldNotCompute>(Coeff)) 1246 return Coeff; 1247 1248 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1249 } 1250 return Result; 1251 } 1252 1253 //===----------------------------------------------------------------------===// 1254 // SCEV Expression folder implementations 1255 //===----------------------------------------------------------------------===// 1256 1257 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1258 unsigned Depth) { 1259 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1260 "This is not a truncating conversion!"); 1261 assert(isSCEVable(Ty) && 1262 "This is not a conversion to a SCEVable type!"); 1263 Ty = getEffectiveSCEVType(Ty); 1264 1265 FoldingSetNodeID ID; 1266 ID.AddInteger(scTruncate); 1267 ID.AddPointer(Op); 1268 ID.AddPointer(Ty); 1269 void *IP = nullptr; 1270 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1271 1272 // Fold if the operand is constant. 1273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1274 return getConstant( 1275 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1276 1277 // trunc(trunc(x)) --> trunc(x) 1278 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1279 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1280 1281 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1282 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1283 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1284 1285 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1286 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1287 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1288 1289 if (Depth > MaxCastDepth) { 1290 SCEV *S = 1291 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1292 UniqueSCEVs.InsertNode(S, IP); 1293 addToLoopUseLists(S); 1294 return S; 1295 } 1296 1297 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1298 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1299 // if after transforming we have at most one truncate, not counting truncates 1300 // that replace other casts. 1301 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1302 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1303 SmallVector<const SCEV *, 4> Operands; 1304 unsigned numTruncs = 0; 1305 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1306 ++i) { 1307 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1308 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1309 numTruncs++; 1310 Operands.push_back(S); 1311 } 1312 if (numTruncs < 2) { 1313 if (isa<SCEVAddExpr>(Op)) 1314 return getAddExpr(Operands); 1315 else if (isa<SCEVMulExpr>(Op)) 1316 return getMulExpr(Operands); 1317 else 1318 llvm_unreachable("Unexpected SCEV type for Op."); 1319 } 1320 // Although we checked in the beginning that ID is not in the cache, it is 1321 // possible that during recursion and different modification ID was inserted 1322 // into the cache. So if we find it, just return it. 1323 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1324 return S; 1325 } 1326 1327 // If the input value is a chrec scev, truncate the chrec's operands. 1328 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1329 SmallVector<const SCEV *, 4> Operands; 1330 for (const SCEV *Op : AddRec->operands()) 1331 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1332 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1333 } 1334 1335 // The cast wasn't folded; create an explicit cast node. We can reuse 1336 // the existing insert position since if we get here, we won't have 1337 // made any changes which would invalidate it. 1338 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1339 Op, Ty); 1340 UniqueSCEVs.InsertNode(S, IP); 1341 addToLoopUseLists(S); 1342 return S; 1343 } 1344 1345 // Get the limit of a recurrence such that incrementing by Step cannot cause 1346 // signed overflow as long as the value of the recurrence within the 1347 // loop does not exceed this limit before incrementing. 1348 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1349 ICmpInst::Predicate *Pred, 1350 ScalarEvolution *SE) { 1351 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1352 if (SE->isKnownPositive(Step)) { 1353 *Pred = ICmpInst::ICMP_SLT; 1354 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1355 SE->getSignedRangeMax(Step)); 1356 } 1357 if (SE->isKnownNegative(Step)) { 1358 *Pred = ICmpInst::ICMP_SGT; 1359 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1360 SE->getSignedRangeMin(Step)); 1361 } 1362 return nullptr; 1363 } 1364 1365 // Get the limit of a recurrence such that incrementing by Step cannot cause 1366 // unsigned overflow as long as the value of the recurrence within the loop does 1367 // not exceed this limit before incrementing. 1368 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1369 ICmpInst::Predicate *Pred, 1370 ScalarEvolution *SE) { 1371 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1372 *Pred = ICmpInst::ICMP_ULT; 1373 1374 return SE->getConstant(APInt::getMinValue(BitWidth) - 1375 SE->getUnsignedRangeMax(Step)); 1376 } 1377 1378 namespace { 1379 1380 struct ExtendOpTraitsBase { 1381 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1382 unsigned); 1383 }; 1384 1385 // Used to make code generic over signed and unsigned overflow. 1386 template <typename ExtendOp> struct ExtendOpTraits { 1387 // Members present: 1388 // 1389 // static const SCEV::NoWrapFlags WrapType; 1390 // 1391 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1392 // 1393 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1394 // ICmpInst::Predicate *Pred, 1395 // ScalarEvolution *SE); 1396 }; 1397 1398 template <> 1399 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1400 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1401 1402 static const GetExtendExprTy GetExtendExpr; 1403 1404 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1405 ICmpInst::Predicate *Pred, 1406 ScalarEvolution *SE) { 1407 return getSignedOverflowLimitForStep(Step, Pred, SE); 1408 } 1409 }; 1410 1411 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1412 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1413 1414 template <> 1415 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1416 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1417 1418 static const GetExtendExprTy GetExtendExpr; 1419 1420 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1421 ICmpInst::Predicate *Pred, 1422 ScalarEvolution *SE) { 1423 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1424 } 1425 }; 1426 1427 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1428 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1429 1430 } // end anonymous namespace 1431 1432 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1433 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1434 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1435 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1436 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1437 // expression "Step + sext/zext(PreIncAR)" is congruent with 1438 // "sext/zext(PostIncAR)" 1439 template <typename ExtendOpTy> 1440 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1441 ScalarEvolution *SE, unsigned Depth) { 1442 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1443 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1444 1445 const Loop *L = AR->getLoop(); 1446 const SCEV *Start = AR->getStart(); 1447 const SCEV *Step = AR->getStepRecurrence(*SE); 1448 1449 // Check for a simple looking step prior to loop entry. 1450 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1451 if (!SA) 1452 return nullptr; 1453 1454 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1455 // subtraction is expensive. For this purpose, perform a quick and dirty 1456 // difference, by checking for Step in the operand list. 1457 SmallVector<const SCEV *, 4> DiffOps; 1458 for (const SCEV *Op : SA->operands()) 1459 if (Op != Step) 1460 DiffOps.push_back(Op); 1461 1462 if (DiffOps.size() == SA->getNumOperands()) 1463 return nullptr; 1464 1465 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1466 // `Step`: 1467 1468 // 1. NSW/NUW flags on the step increment. 1469 auto PreStartFlags = 1470 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1471 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1472 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1473 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1474 1475 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1476 // "S+X does not sign/unsign-overflow". 1477 // 1478 1479 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1480 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1481 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1482 return PreStart; 1483 1484 // 2. Direct overflow check on the step operation's expression. 1485 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1486 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1487 const SCEV *OperandExtendedStart = 1488 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1489 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1490 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1491 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1492 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1493 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1494 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1495 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1496 } 1497 return PreStart; 1498 } 1499 1500 // 3. Loop precondition. 1501 ICmpInst::Predicate Pred; 1502 const SCEV *OverflowLimit = 1503 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1504 1505 if (OverflowLimit && 1506 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1507 return PreStart; 1508 1509 return nullptr; 1510 } 1511 1512 // Get the normalized zero or sign extended expression for this AddRec's Start. 1513 template <typename ExtendOpTy> 1514 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1515 ScalarEvolution *SE, 1516 unsigned Depth) { 1517 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1518 1519 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1520 if (!PreStart) 1521 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1522 1523 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1524 Depth), 1525 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1526 } 1527 1528 // Try to prove away overflow by looking at "nearby" add recurrences. A 1529 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1530 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1531 // 1532 // Formally: 1533 // 1534 // {S,+,X} == {S-T,+,X} + T 1535 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1536 // 1537 // If ({S-T,+,X} + T) does not overflow ... (1) 1538 // 1539 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1540 // 1541 // If {S-T,+,X} does not overflow ... (2) 1542 // 1543 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1544 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1545 // 1546 // If (S-T)+T does not overflow ... (3) 1547 // 1548 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1549 // == {Ext(S),+,Ext(X)} == LHS 1550 // 1551 // Thus, if (1), (2) and (3) are true for some T, then 1552 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1553 // 1554 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1555 // does not overflow" restricted to the 0th iteration. Therefore we only need 1556 // to check for (1) and (2). 1557 // 1558 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1559 // is `Delta` (defined below). 1560 template <typename ExtendOpTy> 1561 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1562 const SCEV *Step, 1563 const Loop *L) { 1564 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1565 1566 // We restrict `Start` to a constant to prevent SCEV from spending too much 1567 // time here. It is correct (but more expensive) to continue with a 1568 // non-constant `Start` and do a general SCEV subtraction to compute 1569 // `PreStart` below. 1570 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1571 if (!StartC) 1572 return false; 1573 1574 APInt StartAI = StartC->getAPInt(); 1575 1576 for (unsigned Delta : {-2, -1, 1, 2}) { 1577 const SCEV *PreStart = getConstant(StartAI - Delta); 1578 1579 FoldingSetNodeID ID; 1580 ID.AddInteger(scAddRecExpr); 1581 ID.AddPointer(PreStart); 1582 ID.AddPointer(Step); 1583 ID.AddPointer(L); 1584 void *IP = nullptr; 1585 const auto *PreAR = 1586 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1587 1588 // Give up if we don't already have the add recurrence we need because 1589 // actually constructing an add recurrence is relatively expensive. 1590 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1591 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1592 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1593 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1594 DeltaS, &Pred, this); 1595 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1596 return true; 1597 } 1598 } 1599 1600 return false; 1601 } 1602 1603 // Finds an integer D for an expression (C + x + y + ...) such that the top 1604 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1605 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1606 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1607 // the (C + x + y + ...) expression is \p WholeAddExpr. 1608 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1609 const SCEVConstant *ConstantTerm, 1610 const SCEVAddExpr *WholeAddExpr) { 1611 const APInt C = ConstantTerm->getAPInt(); 1612 const unsigned BitWidth = C.getBitWidth(); 1613 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1614 uint32_t TZ = BitWidth; 1615 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1616 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1617 if (TZ) { 1618 // Set D to be as many least significant bits of C as possible while still 1619 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1620 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1621 } 1622 return APInt(BitWidth, 0); 1623 } 1624 1625 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1626 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1627 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1628 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1629 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1630 const APInt &ConstantStart, 1631 const SCEV *Step) { 1632 const unsigned BitWidth = ConstantStart.getBitWidth(); 1633 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1634 if (TZ) 1635 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1636 : ConstantStart; 1637 return APInt(BitWidth, 0); 1638 } 1639 1640 const SCEV * 1641 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1642 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1643 "This is not an extending conversion!"); 1644 assert(isSCEVable(Ty) && 1645 "This is not a conversion to a SCEVable type!"); 1646 Ty = getEffectiveSCEVType(Ty); 1647 1648 // Fold if the operand is constant. 1649 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1650 return getConstant( 1651 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1652 1653 // zext(zext(x)) --> zext(x) 1654 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1655 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1656 1657 // Before doing any expensive analysis, check to see if we've already 1658 // computed a SCEV for this Op and Ty. 1659 FoldingSetNodeID ID; 1660 ID.AddInteger(scZeroExtend); 1661 ID.AddPointer(Op); 1662 ID.AddPointer(Ty); 1663 void *IP = nullptr; 1664 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1665 if (Depth > MaxCastDepth) { 1666 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1667 Op, Ty); 1668 UniqueSCEVs.InsertNode(S, IP); 1669 addToLoopUseLists(S); 1670 return S; 1671 } 1672 1673 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1674 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1675 // It's possible the bits taken off by the truncate were all zero bits. If 1676 // so, we should be able to simplify this further. 1677 const SCEV *X = ST->getOperand(); 1678 ConstantRange CR = getUnsignedRange(X); 1679 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1680 unsigned NewBits = getTypeSizeInBits(Ty); 1681 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1682 CR.zextOrTrunc(NewBits))) 1683 return getTruncateOrZeroExtend(X, Ty, Depth); 1684 } 1685 1686 // If the input value is a chrec scev, and we can prove that the value 1687 // did not overflow the old, smaller, value, we can zero extend all of the 1688 // operands (often constants). This allows analysis of something like 1689 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1690 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1691 if (AR->isAffine()) { 1692 const SCEV *Start = AR->getStart(); 1693 const SCEV *Step = AR->getStepRecurrence(*this); 1694 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1695 const Loop *L = AR->getLoop(); 1696 1697 if (!AR->hasNoUnsignedWrap()) { 1698 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1700 } 1701 1702 // If we have special knowledge that this addrec won't overflow, 1703 // we don't need to do any further analysis. 1704 if (AR->hasNoUnsignedWrap()) 1705 return getAddRecExpr( 1706 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1707 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1708 1709 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1710 // Note that this serves two purposes: It filters out loops that are 1711 // simply not analyzable, and it covers the case where this code is 1712 // being called from within backedge-taken count analysis, such that 1713 // attempting to ask for the backedge-taken count would likely result 1714 // in infinite recursion. In the later case, the analysis code will 1715 // cope with a conservative value, and it will take care to purge 1716 // that value once it has finished. 1717 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1718 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1719 // Manually compute the final value for AR, checking for 1720 // overflow. 1721 1722 // Check whether the backedge-taken count can be losslessly casted to 1723 // the addrec's type. The count is always unsigned. 1724 const SCEV *CastedMaxBECount = 1725 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1726 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1727 CastedMaxBECount, MaxBECount->getType(), Depth); 1728 if (MaxBECount == RecastedMaxBECount) { 1729 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1730 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1731 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1732 SCEV::FlagAnyWrap, Depth + 1); 1733 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1734 SCEV::FlagAnyWrap, 1735 Depth + 1), 1736 WideTy, Depth + 1); 1737 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1738 const SCEV *WideMaxBECount = 1739 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1740 const SCEV *OperandExtendedAdd = 1741 getAddExpr(WideStart, 1742 getMulExpr(WideMaxBECount, 1743 getZeroExtendExpr(Step, WideTy, Depth + 1), 1744 SCEV::FlagAnyWrap, Depth + 1), 1745 SCEV::FlagAnyWrap, Depth + 1); 1746 if (ZAdd == OperandExtendedAdd) { 1747 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1748 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1749 // Return the expression with the addrec on the outside. 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1752 Depth + 1), 1753 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1754 AR->getNoWrapFlags()); 1755 } 1756 // Similar to above, only this time treat the step value as signed. 1757 // This covers loops that count down. 1758 OperandExtendedAdd = 1759 getAddExpr(WideStart, 1760 getMulExpr(WideMaxBECount, 1761 getSignExtendExpr(Step, WideTy, Depth + 1), 1762 SCEV::FlagAnyWrap, Depth + 1), 1763 SCEV::FlagAnyWrap, Depth + 1); 1764 if (ZAdd == OperandExtendedAdd) { 1765 // Cache knowledge of AR NW, which is propagated to this AddRec. 1766 // Negative step causes unsigned wrap, but it still can't self-wrap. 1767 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1768 // Return the expression with the addrec on the outside. 1769 return getAddRecExpr( 1770 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1771 Depth + 1), 1772 getSignExtendExpr(Step, Ty, Depth + 1), L, 1773 AR->getNoWrapFlags()); 1774 } 1775 } 1776 } 1777 1778 // Normally, in the cases we can prove no-overflow via a 1779 // backedge guarding condition, we can also compute a backedge 1780 // taken count for the loop. The exceptions are assumptions and 1781 // guards present in the loop -- SCEV is not great at exploiting 1782 // these to compute max backedge taken counts, but can still use 1783 // these to prove lack of overflow. Use this fact to avoid 1784 // doing extra work that may not pay off. 1785 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1786 !AC.assumptions().empty()) { 1787 // If the backedge is guarded by a comparison with the pre-inc 1788 // value the addrec is safe. Also, if the entry is guarded by 1789 // a comparison with the start value and the backedge is 1790 // guarded by a comparison with the post-inc value, the addrec 1791 // is safe. 1792 if (isKnownPositive(Step)) { 1793 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1794 getUnsignedRangeMax(Step)); 1795 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1796 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1797 // Cache knowledge of AR NUW, which is propagated to this 1798 // AddRec. 1799 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1800 // Return the expression with the addrec on the outside. 1801 return getAddRecExpr( 1802 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1803 Depth + 1), 1804 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1805 AR->getNoWrapFlags()); 1806 } 1807 } else if (isKnownNegative(Step)) { 1808 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1809 getSignedRangeMin(Step)); 1810 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1811 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1812 // Cache knowledge of AR NW, which is propagated to this 1813 // AddRec. Negative step causes unsigned wrap, but it 1814 // still can't self-wrap. 1815 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1816 // Return the expression with the addrec on the outside. 1817 return getAddRecExpr( 1818 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1819 Depth + 1), 1820 getSignExtendExpr(Step, Ty, Depth + 1), L, 1821 AR->getNoWrapFlags()); 1822 } 1823 } 1824 } 1825 1826 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1827 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1828 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1829 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1830 const APInt &C = SC->getAPInt(); 1831 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1832 if (D != 0) { 1833 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1834 const SCEV *SResidual = 1835 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1836 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1837 return getAddExpr(SZExtD, SZExtR, 1838 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1839 Depth + 1); 1840 } 1841 } 1842 1843 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1844 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1845 return getAddRecExpr( 1846 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1847 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1848 } 1849 } 1850 1851 // zext(A % B) --> zext(A) % zext(B) 1852 { 1853 const SCEV *LHS; 1854 const SCEV *RHS; 1855 if (matchURem(Op, LHS, RHS)) 1856 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1857 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1858 } 1859 1860 // zext(A / B) --> zext(A) / zext(B). 1861 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1862 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1863 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1864 1865 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1866 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1867 if (SA->hasNoUnsignedWrap()) { 1868 // If the addition does not unsign overflow then we can, by definition, 1869 // commute the zero extension with the addition operation. 1870 SmallVector<const SCEV *, 4> Ops; 1871 for (const auto *Op : SA->operands()) 1872 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1873 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1874 } 1875 1876 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1877 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1878 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1879 // 1880 // Often address arithmetics contain expressions like 1881 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1882 // This transformation is useful while proving that such expressions are 1883 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1884 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1885 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1886 if (D != 0) { 1887 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1888 const SCEV *SResidual = 1889 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1890 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1891 return getAddExpr(SZExtD, SZExtR, 1892 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1893 Depth + 1); 1894 } 1895 } 1896 } 1897 1898 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1899 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1900 if (SM->hasNoUnsignedWrap()) { 1901 // If the multiply does not unsign overflow then we can, by definition, 1902 // commute the zero extension with the multiply operation. 1903 SmallVector<const SCEV *, 4> Ops; 1904 for (const auto *Op : SM->operands()) 1905 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1906 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1907 } 1908 1909 // zext(2^K * (trunc X to iN)) to iM -> 1910 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1911 // 1912 // Proof: 1913 // 1914 // zext(2^K * (trunc X to iN)) to iM 1915 // = zext((trunc X to iN) << K) to iM 1916 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1917 // (because shl removes the top K bits) 1918 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1919 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1920 // 1921 if (SM->getNumOperands() == 2) 1922 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1923 if (MulLHS->getAPInt().isPowerOf2()) 1924 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1925 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1926 MulLHS->getAPInt().logBase2(); 1927 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1928 return getMulExpr( 1929 getZeroExtendExpr(MulLHS, Ty), 1930 getZeroExtendExpr( 1931 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1932 SCEV::FlagNUW, Depth + 1); 1933 } 1934 } 1935 1936 // The cast wasn't folded; create an explicit cast node. 1937 // Recompute the insert position, as it may have been invalidated. 1938 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1939 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1940 Op, Ty); 1941 UniqueSCEVs.InsertNode(S, IP); 1942 addToLoopUseLists(S); 1943 return S; 1944 } 1945 1946 const SCEV * 1947 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1948 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1949 "This is not an extending conversion!"); 1950 assert(isSCEVable(Ty) && 1951 "This is not a conversion to a SCEVable type!"); 1952 Ty = getEffectiveSCEVType(Ty); 1953 1954 // Fold if the operand is constant. 1955 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1956 return getConstant( 1957 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1958 1959 // sext(sext(x)) --> sext(x) 1960 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1961 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1962 1963 // sext(zext(x)) --> zext(x) 1964 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1965 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1966 1967 // Before doing any expensive analysis, check to see if we've already 1968 // computed a SCEV for this Op and Ty. 1969 FoldingSetNodeID ID; 1970 ID.AddInteger(scSignExtend); 1971 ID.AddPointer(Op); 1972 ID.AddPointer(Ty); 1973 void *IP = nullptr; 1974 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1975 // Limit recursion depth. 1976 if (Depth > MaxCastDepth) { 1977 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1978 Op, Ty); 1979 UniqueSCEVs.InsertNode(S, IP); 1980 addToLoopUseLists(S); 1981 return S; 1982 } 1983 1984 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1985 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1986 // It's possible the bits taken off by the truncate were all sign bits. If 1987 // so, we should be able to simplify this further. 1988 const SCEV *X = ST->getOperand(); 1989 ConstantRange CR = getSignedRange(X); 1990 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1991 unsigned NewBits = getTypeSizeInBits(Ty); 1992 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1993 CR.sextOrTrunc(NewBits))) 1994 return getTruncateOrSignExtend(X, Ty, Depth); 1995 } 1996 1997 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1998 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1999 if (SA->hasNoSignedWrap()) { 2000 // If the addition does not sign overflow then we can, by definition, 2001 // commute the sign extension with the addition operation. 2002 SmallVector<const SCEV *, 4> Ops; 2003 for (const auto *Op : SA->operands()) 2004 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2005 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2006 } 2007 2008 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2009 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2010 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2011 // 2012 // For instance, this will bring two seemingly different expressions: 2013 // 1 + sext(5 + 20 * %x + 24 * %y) and 2014 // sext(6 + 20 * %x + 24 * %y) 2015 // to the same form: 2016 // 2 + sext(4 + 20 * %x + 24 * %y) 2017 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2018 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2019 if (D != 0) { 2020 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2021 const SCEV *SResidual = 2022 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2023 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2024 return getAddExpr(SSExtD, SSExtR, 2025 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2026 Depth + 1); 2027 } 2028 } 2029 } 2030 // If the input value is a chrec scev, and we can prove that the value 2031 // did not overflow the old, smaller, value, we can sign extend all of the 2032 // operands (often constants). This allows analysis of something like 2033 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2034 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2035 if (AR->isAffine()) { 2036 const SCEV *Start = AR->getStart(); 2037 const SCEV *Step = AR->getStepRecurrence(*this); 2038 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2039 const Loop *L = AR->getLoop(); 2040 2041 if (!AR->hasNoSignedWrap()) { 2042 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2043 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2044 } 2045 2046 // If we have special knowledge that this addrec won't overflow, 2047 // we don't need to do any further analysis. 2048 if (AR->hasNoSignedWrap()) 2049 return getAddRecExpr( 2050 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2051 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2052 2053 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2054 // Note that this serves two purposes: It filters out loops that are 2055 // simply not analyzable, and it covers the case where this code is 2056 // being called from within backedge-taken count analysis, such that 2057 // attempting to ask for the backedge-taken count would likely result 2058 // in infinite recursion. In the later case, the analysis code will 2059 // cope with a conservative value, and it will take care to purge 2060 // that value once it has finished. 2061 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2062 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2063 // Manually compute the final value for AR, checking for 2064 // overflow. 2065 2066 // Check whether the backedge-taken count can be losslessly casted to 2067 // the addrec's type. The count is always unsigned. 2068 const SCEV *CastedMaxBECount = 2069 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2070 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2071 CastedMaxBECount, MaxBECount->getType(), Depth); 2072 if (MaxBECount == RecastedMaxBECount) { 2073 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2074 // Check whether Start+Step*MaxBECount has no signed overflow. 2075 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2076 SCEV::FlagAnyWrap, Depth + 1); 2077 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2078 SCEV::FlagAnyWrap, 2079 Depth + 1), 2080 WideTy, Depth + 1); 2081 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2082 const SCEV *WideMaxBECount = 2083 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2084 const SCEV *OperandExtendedAdd = 2085 getAddExpr(WideStart, 2086 getMulExpr(WideMaxBECount, 2087 getSignExtendExpr(Step, WideTy, Depth + 1), 2088 SCEV::FlagAnyWrap, Depth + 1), 2089 SCEV::FlagAnyWrap, Depth + 1); 2090 if (SAdd == OperandExtendedAdd) { 2091 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2092 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2093 // Return the expression with the addrec on the outside. 2094 return getAddRecExpr( 2095 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2096 Depth + 1), 2097 getSignExtendExpr(Step, Ty, Depth + 1), L, 2098 AR->getNoWrapFlags()); 2099 } 2100 // Similar to above, only this time treat the step value as unsigned. 2101 // This covers loops that count up with an unsigned step. 2102 OperandExtendedAdd = 2103 getAddExpr(WideStart, 2104 getMulExpr(WideMaxBECount, 2105 getZeroExtendExpr(Step, WideTy, Depth + 1), 2106 SCEV::FlagAnyWrap, Depth + 1), 2107 SCEV::FlagAnyWrap, Depth + 1); 2108 if (SAdd == OperandExtendedAdd) { 2109 // If AR wraps around then 2110 // 2111 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2112 // => SAdd != OperandExtendedAdd 2113 // 2114 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2115 // (SAdd == OperandExtendedAdd => AR is NW) 2116 2117 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2118 2119 // Return the expression with the addrec on the outside. 2120 return getAddRecExpr( 2121 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2122 Depth + 1), 2123 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2124 AR->getNoWrapFlags()); 2125 } 2126 } 2127 } 2128 2129 // Normally, in the cases we can prove no-overflow via a 2130 // backedge guarding condition, we can also compute a backedge 2131 // taken count for the loop. The exceptions are assumptions and 2132 // guards present in the loop -- SCEV is not great at exploiting 2133 // these to compute max backedge taken counts, but can still use 2134 // these to prove lack of overflow. Use this fact to avoid 2135 // doing extra work that may not pay off. 2136 2137 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2138 !AC.assumptions().empty()) { 2139 // If the backedge is guarded by a comparison with the pre-inc 2140 // value the addrec is safe. Also, if the entry is guarded by 2141 // a comparison with the start value and the backedge is 2142 // guarded by a comparison with the post-inc value, the addrec 2143 // is safe. 2144 ICmpInst::Predicate Pred; 2145 const SCEV *OverflowLimit = 2146 getSignedOverflowLimitForStep(Step, &Pred, this); 2147 if (OverflowLimit && 2148 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2149 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2150 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2151 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2152 return getAddRecExpr( 2153 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2154 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2155 } 2156 } 2157 2158 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2159 // if D + (C - D + Step * n) could be proven to not signed wrap 2160 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2161 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2162 const APInt &C = SC->getAPInt(); 2163 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2164 if (D != 0) { 2165 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2166 const SCEV *SResidual = 2167 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2168 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2169 return getAddExpr(SSExtD, SSExtR, 2170 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2171 Depth + 1); 2172 } 2173 } 2174 2175 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2176 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2177 return getAddRecExpr( 2178 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2179 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2180 } 2181 } 2182 2183 // If the input value is provably positive and we could not simplify 2184 // away the sext build a zext instead. 2185 if (isKnownNonNegative(Op)) 2186 return getZeroExtendExpr(Op, Ty, Depth + 1); 2187 2188 // The cast wasn't folded; create an explicit cast node. 2189 // Recompute the insert position, as it may have been invalidated. 2190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2191 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2192 Op, Ty); 2193 UniqueSCEVs.InsertNode(S, IP); 2194 addToLoopUseLists(S); 2195 return S; 2196 } 2197 2198 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2199 /// unspecified bits out to the given type. 2200 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2201 Type *Ty) { 2202 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2203 "This is not an extending conversion!"); 2204 assert(isSCEVable(Ty) && 2205 "This is not a conversion to a SCEVable type!"); 2206 Ty = getEffectiveSCEVType(Ty); 2207 2208 // Sign-extend negative constants. 2209 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2210 if (SC->getAPInt().isNegative()) 2211 return getSignExtendExpr(Op, Ty); 2212 2213 // Peel off a truncate cast. 2214 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2215 const SCEV *NewOp = T->getOperand(); 2216 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2217 return getAnyExtendExpr(NewOp, Ty); 2218 return getTruncateOrNoop(NewOp, Ty); 2219 } 2220 2221 // Next try a zext cast. If the cast is folded, use it. 2222 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2223 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2224 return ZExt; 2225 2226 // Next try a sext cast. If the cast is folded, use it. 2227 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2228 if (!isa<SCEVSignExtendExpr>(SExt)) 2229 return SExt; 2230 2231 // Force the cast to be folded into the operands of an addrec. 2232 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2233 SmallVector<const SCEV *, 4> Ops; 2234 for (const SCEV *Op : AR->operands()) 2235 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2236 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2237 } 2238 2239 // If the expression is obviously signed, use the sext cast value. 2240 if (isa<SCEVSMaxExpr>(Op)) 2241 return SExt; 2242 2243 // Absent any other information, use the zext cast value. 2244 return ZExt; 2245 } 2246 2247 /// Process the given Ops list, which is a list of operands to be added under 2248 /// the given scale, update the given map. This is a helper function for 2249 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2250 /// that would form an add expression like this: 2251 /// 2252 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2253 /// 2254 /// where A and B are constants, update the map with these values: 2255 /// 2256 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2257 /// 2258 /// and add 13 + A*B*29 to AccumulatedConstant. 2259 /// This will allow getAddRecExpr to produce this: 2260 /// 2261 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2262 /// 2263 /// This form often exposes folding opportunities that are hidden in 2264 /// the original operand list. 2265 /// 2266 /// Return true iff it appears that any interesting folding opportunities 2267 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2268 /// the common case where no interesting opportunities are present, and 2269 /// is also used as a check to avoid infinite recursion. 2270 static bool 2271 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2272 SmallVectorImpl<const SCEV *> &NewOps, 2273 APInt &AccumulatedConstant, 2274 const SCEV *const *Ops, size_t NumOperands, 2275 const APInt &Scale, 2276 ScalarEvolution &SE) { 2277 bool Interesting = false; 2278 2279 // Iterate over the add operands. They are sorted, with constants first. 2280 unsigned i = 0; 2281 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2282 ++i; 2283 // Pull a buried constant out to the outside. 2284 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2285 Interesting = true; 2286 AccumulatedConstant += Scale * C->getAPInt(); 2287 } 2288 2289 // Next comes everything else. We're especially interested in multiplies 2290 // here, but they're in the middle, so just visit the rest with one loop. 2291 for (; i != NumOperands; ++i) { 2292 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2293 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2294 APInt NewScale = 2295 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2296 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2297 // A multiplication of a constant with another add; recurse. 2298 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2299 Interesting |= 2300 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2301 Add->op_begin(), Add->getNumOperands(), 2302 NewScale, SE); 2303 } else { 2304 // A multiplication of a constant with some other value. Update 2305 // the map. 2306 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2307 const SCEV *Key = SE.getMulExpr(MulOps); 2308 auto Pair = M.insert({Key, NewScale}); 2309 if (Pair.second) { 2310 NewOps.push_back(Pair.first->first); 2311 } else { 2312 Pair.first->second += NewScale; 2313 // The map already had an entry for this value, which may indicate 2314 // a folding opportunity. 2315 Interesting = true; 2316 } 2317 } 2318 } else { 2319 // An ordinary operand. Update the map. 2320 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2321 M.insert({Ops[i], Scale}); 2322 if (Pair.second) { 2323 NewOps.push_back(Pair.first->first); 2324 } else { 2325 Pair.first->second += Scale; 2326 // The map already had an entry for this value, which may indicate 2327 // a folding opportunity. 2328 Interesting = true; 2329 } 2330 } 2331 } 2332 2333 return Interesting; 2334 } 2335 2336 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2337 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2338 // can't-overflow flags for the operation if possible. 2339 static SCEV::NoWrapFlags 2340 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2341 const ArrayRef<const SCEV *> Ops, 2342 SCEV::NoWrapFlags Flags) { 2343 using namespace std::placeholders; 2344 2345 using OBO = OverflowingBinaryOperator; 2346 2347 bool CanAnalyze = 2348 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2349 (void)CanAnalyze; 2350 assert(CanAnalyze && "don't call from other places!"); 2351 2352 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2353 SCEV::NoWrapFlags SignOrUnsignWrap = 2354 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2355 2356 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2357 auto IsKnownNonNegative = [&](const SCEV *S) { 2358 return SE->isKnownNonNegative(S); 2359 }; 2360 2361 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2362 Flags = 2363 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2364 2365 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2366 2367 if (SignOrUnsignWrap != SignOrUnsignMask && 2368 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2369 isa<SCEVConstant>(Ops[0])) { 2370 2371 auto Opcode = [&] { 2372 switch (Type) { 2373 case scAddExpr: 2374 return Instruction::Add; 2375 case scMulExpr: 2376 return Instruction::Mul; 2377 default: 2378 llvm_unreachable("Unexpected SCEV op."); 2379 } 2380 }(); 2381 2382 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2383 2384 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2385 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2386 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2387 Opcode, C, OBO::NoSignedWrap); 2388 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2389 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2390 } 2391 2392 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2393 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2394 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2395 Opcode, C, OBO::NoUnsignedWrap); 2396 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2397 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2398 } 2399 } 2400 2401 return Flags; 2402 } 2403 2404 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2405 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2406 } 2407 2408 /// Get a canonical add expression, or something simpler if possible. 2409 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2410 SCEV::NoWrapFlags Flags, 2411 unsigned Depth) { 2412 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2413 "only nuw or nsw allowed"); 2414 assert(!Ops.empty() && "Cannot get empty add!"); 2415 if (Ops.size() == 1) return Ops[0]; 2416 #ifndef NDEBUG 2417 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2418 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2419 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2420 "SCEVAddExpr operand types don't match!"); 2421 #endif 2422 2423 // Sort by complexity, this groups all similar expression types together. 2424 GroupByComplexity(Ops, &LI, DT); 2425 2426 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2427 2428 // If there are any constants, fold them together. 2429 unsigned Idx = 0; 2430 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2431 ++Idx; 2432 assert(Idx < Ops.size()); 2433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2434 // We found two constants, fold them together! 2435 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2436 if (Ops.size() == 2) return Ops[0]; 2437 Ops.erase(Ops.begin()+1); // Erase the folded element 2438 LHSC = cast<SCEVConstant>(Ops[0]); 2439 } 2440 2441 // If we are left with a constant zero being added, strip it off. 2442 if (LHSC->getValue()->isZero()) { 2443 Ops.erase(Ops.begin()); 2444 --Idx; 2445 } 2446 2447 if (Ops.size() == 1) return Ops[0]; 2448 } 2449 2450 // Limit recursion calls depth. 2451 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2452 return getOrCreateAddExpr(Ops, Flags); 2453 2454 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2455 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2456 return S; 2457 } 2458 2459 // Okay, check to see if the same value occurs in the operand list more than 2460 // once. If so, merge them together into an multiply expression. Since we 2461 // sorted the list, these values are required to be adjacent. 2462 Type *Ty = Ops[0]->getType(); 2463 bool FoundMatch = false; 2464 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2465 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2466 // Scan ahead to count how many equal operands there are. 2467 unsigned Count = 2; 2468 while (i+Count != e && Ops[i+Count] == Ops[i]) 2469 ++Count; 2470 // Merge the values into a multiply. 2471 const SCEV *Scale = getConstant(Ty, Count); 2472 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2473 if (Ops.size() == Count) 2474 return Mul; 2475 Ops[i] = Mul; 2476 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2477 --i; e -= Count - 1; 2478 FoundMatch = true; 2479 } 2480 if (FoundMatch) 2481 return getAddExpr(Ops, Flags, Depth + 1); 2482 2483 // Check for truncates. If all the operands are truncated from the same 2484 // type, see if factoring out the truncate would permit the result to be 2485 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2486 // if the contents of the resulting outer trunc fold to something simple. 2487 auto FindTruncSrcType = [&]() -> Type * { 2488 // We're ultimately looking to fold an addrec of truncs and muls of only 2489 // constants and truncs, so if we find any other types of SCEV 2490 // as operands of the addrec then we bail and return nullptr here. 2491 // Otherwise, we return the type of the operand of a trunc that we find. 2492 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2493 return T->getOperand()->getType(); 2494 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2495 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2496 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2497 return T->getOperand()->getType(); 2498 } 2499 return nullptr; 2500 }; 2501 if (auto *SrcType = FindTruncSrcType()) { 2502 SmallVector<const SCEV *, 8> LargeOps; 2503 bool Ok = true; 2504 // Check all the operands to see if they can be represented in the 2505 // source type of the truncate. 2506 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2507 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2508 if (T->getOperand()->getType() != SrcType) { 2509 Ok = false; 2510 break; 2511 } 2512 LargeOps.push_back(T->getOperand()); 2513 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2514 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2515 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2516 SmallVector<const SCEV *, 8> LargeMulOps; 2517 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2518 if (const SCEVTruncateExpr *T = 2519 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2520 if (T->getOperand()->getType() != SrcType) { 2521 Ok = false; 2522 break; 2523 } 2524 LargeMulOps.push_back(T->getOperand()); 2525 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2526 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2527 } else { 2528 Ok = false; 2529 break; 2530 } 2531 } 2532 if (Ok) 2533 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2534 } else { 2535 Ok = false; 2536 break; 2537 } 2538 } 2539 if (Ok) { 2540 // Evaluate the expression in the larger type. 2541 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2542 // If it folds to something simple, use it. Otherwise, don't. 2543 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2544 return getTruncateExpr(Fold, Ty); 2545 } 2546 } 2547 2548 // Skip past any other cast SCEVs. 2549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2550 ++Idx; 2551 2552 // If there are add operands they would be next. 2553 if (Idx < Ops.size()) { 2554 bool DeletedAdd = false; 2555 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2556 if (Ops.size() > AddOpsInlineThreshold || 2557 Add->getNumOperands() > AddOpsInlineThreshold) 2558 break; 2559 // If we have an add, expand the add operands onto the end of the operands 2560 // list. 2561 Ops.erase(Ops.begin()+Idx); 2562 Ops.append(Add->op_begin(), Add->op_end()); 2563 DeletedAdd = true; 2564 } 2565 2566 // If we deleted at least one add, we added operands to the end of the list, 2567 // and they are not necessarily sorted. Recurse to resort and resimplify 2568 // any operands we just acquired. 2569 if (DeletedAdd) 2570 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2571 } 2572 2573 // Skip over the add expression until we get to a multiply. 2574 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2575 ++Idx; 2576 2577 // Check to see if there are any folding opportunities present with 2578 // operands multiplied by constant values. 2579 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2580 uint64_t BitWidth = getTypeSizeInBits(Ty); 2581 DenseMap<const SCEV *, APInt> M; 2582 SmallVector<const SCEV *, 8> NewOps; 2583 APInt AccumulatedConstant(BitWidth, 0); 2584 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2585 Ops.data(), Ops.size(), 2586 APInt(BitWidth, 1), *this)) { 2587 struct APIntCompare { 2588 bool operator()(const APInt &LHS, const APInt &RHS) const { 2589 return LHS.ult(RHS); 2590 } 2591 }; 2592 2593 // Some interesting folding opportunity is present, so its worthwhile to 2594 // re-generate the operands list. Group the operands by constant scale, 2595 // to avoid multiplying by the same constant scale multiple times. 2596 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2597 for (const SCEV *NewOp : NewOps) 2598 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2599 // Re-generate the operands list. 2600 Ops.clear(); 2601 if (AccumulatedConstant != 0) 2602 Ops.push_back(getConstant(AccumulatedConstant)); 2603 for (auto &MulOp : MulOpLists) 2604 if (MulOp.first != 0) 2605 Ops.push_back(getMulExpr( 2606 getConstant(MulOp.first), 2607 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2608 SCEV::FlagAnyWrap, Depth + 1)); 2609 if (Ops.empty()) 2610 return getZero(Ty); 2611 if (Ops.size() == 1) 2612 return Ops[0]; 2613 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2614 } 2615 } 2616 2617 // If we are adding something to a multiply expression, make sure the 2618 // something is not already an operand of the multiply. If so, merge it into 2619 // the multiply. 2620 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2621 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2622 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2623 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2624 if (isa<SCEVConstant>(MulOpSCEV)) 2625 continue; 2626 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2627 if (MulOpSCEV == Ops[AddOp]) { 2628 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2629 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2630 if (Mul->getNumOperands() != 2) { 2631 // If the multiply has more than two operands, we must get the 2632 // Y*Z term. 2633 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2634 Mul->op_begin()+MulOp); 2635 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2636 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2637 } 2638 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2639 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2640 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2641 SCEV::FlagAnyWrap, Depth + 1); 2642 if (Ops.size() == 2) return OuterMul; 2643 if (AddOp < Idx) { 2644 Ops.erase(Ops.begin()+AddOp); 2645 Ops.erase(Ops.begin()+Idx-1); 2646 } else { 2647 Ops.erase(Ops.begin()+Idx); 2648 Ops.erase(Ops.begin()+AddOp-1); 2649 } 2650 Ops.push_back(OuterMul); 2651 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2652 } 2653 2654 // Check this multiply against other multiplies being added together. 2655 for (unsigned OtherMulIdx = Idx+1; 2656 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2657 ++OtherMulIdx) { 2658 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2659 // If MulOp occurs in OtherMul, we can fold the two multiplies 2660 // together. 2661 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2662 OMulOp != e; ++OMulOp) 2663 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2664 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2665 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2666 if (Mul->getNumOperands() != 2) { 2667 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2668 Mul->op_begin()+MulOp); 2669 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2670 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2671 } 2672 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2673 if (OtherMul->getNumOperands() != 2) { 2674 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2675 OtherMul->op_begin()+OMulOp); 2676 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2677 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2678 } 2679 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2680 const SCEV *InnerMulSum = 2681 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2682 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2683 SCEV::FlagAnyWrap, Depth + 1); 2684 if (Ops.size() == 2) return OuterMul; 2685 Ops.erase(Ops.begin()+Idx); 2686 Ops.erase(Ops.begin()+OtherMulIdx-1); 2687 Ops.push_back(OuterMul); 2688 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2689 } 2690 } 2691 } 2692 } 2693 2694 // If there are any add recurrences in the operands list, see if any other 2695 // added values are loop invariant. If so, we can fold them into the 2696 // recurrence. 2697 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2698 ++Idx; 2699 2700 // Scan over all recurrences, trying to fold loop invariants into them. 2701 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2702 // Scan all of the other operands to this add and add them to the vector if 2703 // they are loop invariant w.r.t. the recurrence. 2704 SmallVector<const SCEV *, 8> LIOps; 2705 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2706 const Loop *AddRecLoop = AddRec->getLoop(); 2707 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2708 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2709 LIOps.push_back(Ops[i]); 2710 Ops.erase(Ops.begin()+i); 2711 --i; --e; 2712 } 2713 2714 // If we found some loop invariants, fold them into the recurrence. 2715 if (!LIOps.empty()) { 2716 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2717 LIOps.push_back(AddRec->getStart()); 2718 2719 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2720 AddRec->op_end()); 2721 // This follows from the fact that the no-wrap flags on the outer add 2722 // expression are applicable on the 0th iteration, when the add recurrence 2723 // will be equal to its start value. 2724 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2725 2726 // Build the new addrec. Propagate the NUW and NSW flags if both the 2727 // outer add and the inner addrec are guaranteed to have no overflow. 2728 // Always propagate NW. 2729 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2730 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2731 2732 // If all of the other operands were loop invariant, we are done. 2733 if (Ops.size() == 1) return NewRec; 2734 2735 // Otherwise, add the folded AddRec by the non-invariant parts. 2736 for (unsigned i = 0;; ++i) 2737 if (Ops[i] == AddRec) { 2738 Ops[i] = NewRec; 2739 break; 2740 } 2741 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2742 } 2743 2744 // Okay, if there weren't any loop invariants to be folded, check to see if 2745 // there are multiple AddRec's with the same loop induction variable being 2746 // added together. If so, we can fold them. 2747 for (unsigned OtherIdx = Idx+1; 2748 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2749 ++OtherIdx) { 2750 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2751 // so that the 1st found AddRecExpr is dominated by all others. 2752 assert(DT.dominates( 2753 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2754 AddRec->getLoop()->getHeader()) && 2755 "AddRecExprs are not sorted in reverse dominance order?"); 2756 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2757 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2758 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2759 AddRec->op_end()); 2760 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2761 ++OtherIdx) { 2762 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2763 if (OtherAddRec->getLoop() == AddRecLoop) { 2764 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2765 i != e; ++i) { 2766 if (i >= AddRecOps.size()) { 2767 AddRecOps.append(OtherAddRec->op_begin()+i, 2768 OtherAddRec->op_end()); 2769 break; 2770 } 2771 SmallVector<const SCEV *, 2> TwoOps = { 2772 AddRecOps[i], OtherAddRec->getOperand(i)}; 2773 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2774 } 2775 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2776 } 2777 } 2778 // Step size has changed, so we cannot guarantee no self-wraparound. 2779 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2780 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2781 } 2782 } 2783 2784 // Otherwise couldn't fold anything into this recurrence. Move onto the 2785 // next one. 2786 } 2787 2788 // Okay, it looks like we really DO need an add expr. Check to see if we 2789 // already have one, otherwise create a new one. 2790 return getOrCreateAddExpr(Ops, Flags); 2791 } 2792 2793 const SCEV * 2794 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2795 SCEV::NoWrapFlags Flags) { 2796 FoldingSetNodeID ID; 2797 ID.AddInteger(scAddExpr); 2798 for (const SCEV *Op : Ops) 2799 ID.AddPointer(Op); 2800 void *IP = nullptr; 2801 SCEVAddExpr *S = 2802 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2803 if (!S) { 2804 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2805 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2806 S = new (SCEVAllocator) 2807 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2808 UniqueSCEVs.InsertNode(S, IP); 2809 addToLoopUseLists(S); 2810 } 2811 S->setNoWrapFlags(Flags); 2812 return S; 2813 } 2814 2815 const SCEV * 2816 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2817 const Loop *L, SCEV::NoWrapFlags Flags) { 2818 FoldingSetNodeID ID; 2819 ID.AddInteger(scAddRecExpr); 2820 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2821 ID.AddPointer(Ops[i]); 2822 ID.AddPointer(L); 2823 void *IP = nullptr; 2824 SCEVAddRecExpr *S = 2825 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2826 if (!S) { 2827 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2828 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2829 S = new (SCEVAllocator) 2830 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2831 UniqueSCEVs.InsertNode(S, IP); 2832 addToLoopUseLists(S); 2833 } 2834 S->setNoWrapFlags(Flags); 2835 return S; 2836 } 2837 2838 const SCEV * 2839 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2840 SCEV::NoWrapFlags Flags) { 2841 FoldingSetNodeID ID; 2842 ID.AddInteger(scMulExpr); 2843 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2844 ID.AddPointer(Ops[i]); 2845 void *IP = nullptr; 2846 SCEVMulExpr *S = 2847 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2848 if (!S) { 2849 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2850 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2851 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2852 O, Ops.size()); 2853 UniqueSCEVs.InsertNode(S, IP); 2854 addToLoopUseLists(S); 2855 } 2856 S->setNoWrapFlags(Flags); 2857 return S; 2858 } 2859 2860 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2861 uint64_t k = i*j; 2862 if (j > 1 && k / j != i) Overflow = true; 2863 return k; 2864 } 2865 2866 /// Compute the result of "n choose k", the binomial coefficient. If an 2867 /// intermediate computation overflows, Overflow will be set and the return will 2868 /// be garbage. Overflow is not cleared on absence of overflow. 2869 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2870 // We use the multiplicative formula: 2871 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2872 // At each iteration, we take the n-th term of the numeral and divide by the 2873 // (k-n)th term of the denominator. This division will always produce an 2874 // integral result, and helps reduce the chance of overflow in the 2875 // intermediate computations. However, we can still overflow even when the 2876 // final result would fit. 2877 2878 if (n == 0 || n == k) return 1; 2879 if (k > n) return 0; 2880 2881 if (k > n/2) 2882 k = n-k; 2883 2884 uint64_t r = 1; 2885 for (uint64_t i = 1; i <= k; ++i) { 2886 r = umul_ov(r, n-(i-1), Overflow); 2887 r /= i; 2888 } 2889 return r; 2890 } 2891 2892 /// Determine if any of the operands in this SCEV are a constant or if 2893 /// any of the add or multiply expressions in this SCEV contain a constant. 2894 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2895 struct FindConstantInAddMulChain { 2896 bool FoundConstant = false; 2897 2898 bool follow(const SCEV *S) { 2899 FoundConstant |= isa<SCEVConstant>(S); 2900 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2901 } 2902 2903 bool isDone() const { 2904 return FoundConstant; 2905 } 2906 }; 2907 2908 FindConstantInAddMulChain F; 2909 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2910 ST.visitAll(StartExpr); 2911 return F.FoundConstant; 2912 } 2913 2914 /// Get a canonical multiply expression, or something simpler if possible. 2915 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2916 SCEV::NoWrapFlags Flags, 2917 unsigned Depth) { 2918 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2919 "only nuw or nsw allowed"); 2920 assert(!Ops.empty() && "Cannot get empty mul!"); 2921 if (Ops.size() == 1) return Ops[0]; 2922 #ifndef NDEBUG 2923 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2924 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2925 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2926 "SCEVMulExpr operand types don't match!"); 2927 #endif 2928 2929 // Sort by complexity, this groups all similar expression types together. 2930 GroupByComplexity(Ops, &LI, DT); 2931 2932 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2933 2934 // Limit recursion calls depth, but fold all-constant expressions. 2935 // `Ops` is sorted, so it's enough to check just last one. 2936 if ((Depth > MaxArithDepth || hasHugeExpression(Ops)) && 2937 !isa<SCEVConstant>(Ops.back())) 2938 return getOrCreateMulExpr(Ops, Flags); 2939 2940 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2941 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2942 return S; 2943 } 2944 2945 // If there are any constants, fold them together. 2946 unsigned Idx = 0; 2947 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2948 2949 if (Ops.size() == 2) 2950 // C1*(C2+V) -> C1*C2 + C1*V 2951 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2952 // If any of Add's ops are Adds or Muls with a constant, apply this 2953 // transformation as well. 2954 // 2955 // TODO: There are some cases where this transformation is not 2956 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2957 // this transformation should be narrowed down. 2958 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2959 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2960 SCEV::FlagAnyWrap, Depth + 1), 2961 getMulExpr(LHSC, Add->getOperand(1), 2962 SCEV::FlagAnyWrap, Depth + 1), 2963 SCEV::FlagAnyWrap, Depth + 1); 2964 2965 ++Idx; 2966 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2967 // We found two constants, fold them together! 2968 ConstantInt *Fold = 2969 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2970 Ops[0] = getConstant(Fold); 2971 Ops.erase(Ops.begin()+1); // Erase the folded element 2972 if (Ops.size() == 1) return Ops[0]; 2973 LHSC = cast<SCEVConstant>(Ops[0]); 2974 } 2975 2976 // If we are left with a constant one being multiplied, strip it off. 2977 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2978 Ops.erase(Ops.begin()); 2979 --Idx; 2980 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2981 // If we have a multiply of zero, it will always be zero. 2982 return Ops[0]; 2983 } else if (Ops[0]->isAllOnesValue()) { 2984 // If we have a mul by -1 of an add, try distributing the -1 among the 2985 // add operands. 2986 if (Ops.size() == 2) { 2987 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2988 SmallVector<const SCEV *, 4> NewOps; 2989 bool AnyFolded = false; 2990 for (const SCEV *AddOp : Add->operands()) { 2991 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2992 Depth + 1); 2993 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2994 NewOps.push_back(Mul); 2995 } 2996 if (AnyFolded) 2997 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2998 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2999 // Negation preserves a recurrence's no self-wrap property. 3000 SmallVector<const SCEV *, 4> Operands; 3001 for (const SCEV *AddRecOp : AddRec->operands()) 3002 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3003 Depth + 1)); 3004 3005 return getAddRecExpr(Operands, AddRec->getLoop(), 3006 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3007 } 3008 } 3009 } 3010 3011 if (Ops.size() == 1) 3012 return Ops[0]; 3013 } 3014 3015 // Skip over the add expression until we get to a multiply. 3016 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3017 ++Idx; 3018 3019 // If there are mul operands inline them all into this expression. 3020 if (Idx < Ops.size()) { 3021 bool DeletedMul = false; 3022 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3023 if (Ops.size() > MulOpsInlineThreshold) 3024 break; 3025 // If we have an mul, expand the mul operands onto the end of the 3026 // operands list. 3027 Ops.erase(Ops.begin()+Idx); 3028 Ops.append(Mul->op_begin(), Mul->op_end()); 3029 DeletedMul = true; 3030 } 3031 3032 // If we deleted at least one mul, we added operands to the end of the 3033 // list, and they are not necessarily sorted. Recurse to resort and 3034 // resimplify any operands we just acquired. 3035 if (DeletedMul) 3036 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3037 } 3038 3039 // If there are any add recurrences in the operands list, see if any other 3040 // added values are loop invariant. If so, we can fold them into the 3041 // recurrence. 3042 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3043 ++Idx; 3044 3045 // Scan over all recurrences, trying to fold loop invariants into them. 3046 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3047 // Scan all of the other operands to this mul and add them to the vector 3048 // if they are loop invariant w.r.t. the recurrence. 3049 SmallVector<const SCEV *, 8> LIOps; 3050 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3051 const Loop *AddRecLoop = AddRec->getLoop(); 3052 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3053 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3054 LIOps.push_back(Ops[i]); 3055 Ops.erase(Ops.begin()+i); 3056 --i; --e; 3057 } 3058 3059 // If we found some loop invariants, fold them into the recurrence. 3060 if (!LIOps.empty()) { 3061 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3062 SmallVector<const SCEV *, 4> NewOps; 3063 NewOps.reserve(AddRec->getNumOperands()); 3064 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3065 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3066 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3067 SCEV::FlagAnyWrap, Depth + 1)); 3068 3069 // Build the new addrec. Propagate the NUW and NSW flags if both the 3070 // outer mul and the inner addrec are guaranteed to have no overflow. 3071 // 3072 // No self-wrap cannot be guaranteed after changing the step size, but 3073 // will be inferred if either NUW or NSW is true. 3074 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3075 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3076 3077 // If all of the other operands were loop invariant, we are done. 3078 if (Ops.size() == 1) return NewRec; 3079 3080 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3081 for (unsigned i = 0;; ++i) 3082 if (Ops[i] == AddRec) { 3083 Ops[i] = NewRec; 3084 break; 3085 } 3086 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3087 } 3088 3089 // Okay, if there weren't any loop invariants to be folded, check to see 3090 // if there are multiple AddRec's with the same loop induction variable 3091 // being multiplied together. If so, we can fold them. 3092 3093 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3094 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3095 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3096 // ]]],+,...up to x=2n}. 3097 // Note that the arguments to choose() are always integers with values 3098 // known at compile time, never SCEV objects. 3099 // 3100 // The implementation avoids pointless extra computations when the two 3101 // addrec's are of different length (mathematically, it's equivalent to 3102 // an infinite stream of zeros on the right). 3103 bool OpsModified = false; 3104 for (unsigned OtherIdx = Idx+1; 3105 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3106 ++OtherIdx) { 3107 const SCEVAddRecExpr *OtherAddRec = 3108 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3109 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3110 continue; 3111 3112 // Limit max number of arguments to avoid creation of unreasonably big 3113 // SCEVAddRecs with very complex operands. 3114 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3115 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3116 continue; 3117 3118 bool Overflow = false; 3119 Type *Ty = AddRec->getType(); 3120 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3121 SmallVector<const SCEV*, 7> AddRecOps; 3122 for (int x = 0, xe = AddRec->getNumOperands() + 3123 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3124 SmallVector <const SCEV *, 7> SumOps; 3125 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3126 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3127 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3128 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3129 z < ze && !Overflow; ++z) { 3130 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3131 uint64_t Coeff; 3132 if (LargerThan64Bits) 3133 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3134 else 3135 Coeff = Coeff1*Coeff2; 3136 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3137 const SCEV *Term1 = AddRec->getOperand(y-z); 3138 const SCEV *Term2 = OtherAddRec->getOperand(z); 3139 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3140 SCEV::FlagAnyWrap, Depth + 1)); 3141 } 3142 } 3143 if (SumOps.empty()) 3144 SumOps.push_back(getZero(Ty)); 3145 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3146 } 3147 if (!Overflow) { 3148 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3149 SCEV::FlagAnyWrap); 3150 if (Ops.size() == 2) return NewAddRec; 3151 Ops[Idx] = NewAddRec; 3152 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3153 OpsModified = true; 3154 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3155 if (!AddRec) 3156 break; 3157 } 3158 } 3159 if (OpsModified) 3160 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3161 3162 // Otherwise couldn't fold anything into this recurrence. Move onto the 3163 // next one. 3164 } 3165 3166 // Okay, it looks like we really DO need an mul expr. Check to see if we 3167 // already have one, otherwise create a new one. 3168 return getOrCreateMulExpr(Ops, Flags); 3169 } 3170 3171 /// Represents an unsigned remainder expression based on unsigned division. 3172 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3173 const SCEV *RHS) { 3174 assert(getEffectiveSCEVType(LHS->getType()) == 3175 getEffectiveSCEVType(RHS->getType()) && 3176 "SCEVURemExpr operand types don't match!"); 3177 3178 // Short-circuit easy cases 3179 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3180 // If constant is one, the result is trivial 3181 if (RHSC->getValue()->isOne()) 3182 return getZero(LHS->getType()); // X urem 1 --> 0 3183 3184 // If constant is a power of two, fold into a zext(trunc(LHS)). 3185 if (RHSC->getAPInt().isPowerOf2()) { 3186 Type *FullTy = LHS->getType(); 3187 Type *TruncTy = 3188 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3189 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3190 } 3191 } 3192 3193 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3194 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3195 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3196 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3197 } 3198 3199 /// Get a canonical unsigned division expression, or something simpler if 3200 /// possible. 3201 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3202 const SCEV *RHS) { 3203 assert(getEffectiveSCEVType(LHS->getType()) == 3204 getEffectiveSCEVType(RHS->getType()) && 3205 "SCEVUDivExpr operand types don't match!"); 3206 3207 FoldingSetNodeID ID; 3208 ID.AddInteger(scUDivExpr); 3209 ID.AddPointer(LHS); 3210 ID.AddPointer(RHS); 3211 void *IP = nullptr; 3212 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3213 return S; 3214 3215 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3216 if (RHSC->getValue()->isOne()) 3217 return LHS; // X udiv 1 --> x 3218 // If the denominator is zero, the result of the udiv is undefined. Don't 3219 // try to analyze it, because the resolution chosen here may differ from 3220 // the resolution chosen in other parts of the compiler. 3221 if (!RHSC->getValue()->isZero()) { 3222 // Determine if the division can be folded into the operands of 3223 // its operands. 3224 // TODO: Generalize this to non-constants by using known-bits information. 3225 Type *Ty = LHS->getType(); 3226 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3227 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3228 // For non-power-of-two values, effectively round the value up to the 3229 // nearest power of two. 3230 if (!RHSC->getAPInt().isPowerOf2()) 3231 ++MaxShiftAmt; 3232 IntegerType *ExtTy = 3233 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3234 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3235 if (const SCEVConstant *Step = 3236 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3237 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3238 const APInt &StepInt = Step->getAPInt(); 3239 const APInt &DivInt = RHSC->getAPInt(); 3240 if (!StepInt.urem(DivInt) && 3241 getZeroExtendExpr(AR, ExtTy) == 3242 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3243 getZeroExtendExpr(Step, ExtTy), 3244 AR->getLoop(), SCEV::FlagAnyWrap)) { 3245 SmallVector<const SCEV *, 4> Operands; 3246 for (const SCEV *Op : AR->operands()) 3247 Operands.push_back(getUDivExpr(Op, RHS)); 3248 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3249 } 3250 /// Get a canonical UDivExpr for a recurrence. 3251 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3252 // We can currently only fold X%N if X is constant. 3253 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3254 if (StartC && !DivInt.urem(StepInt) && 3255 getZeroExtendExpr(AR, ExtTy) == 3256 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3257 getZeroExtendExpr(Step, ExtTy), 3258 AR->getLoop(), SCEV::FlagAnyWrap)) { 3259 const APInt &StartInt = StartC->getAPInt(); 3260 const APInt &StartRem = StartInt.urem(StepInt); 3261 if (StartRem != 0) { 3262 const SCEV *NewLHS = 3263 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3264 AR->getLoop(), SCEV::FlagNW); 3265 if (LHS != NewLHS) { 3266 LHS = NewLHS; 3267 3268 // Reset the ID to include the new LHS, and check if it is 3269 // already cached. 3270 ID.clear(); 3271 ID.AddInteger(scUDivExpr); 3272 ID.AddPointer(LHS); 3273 ID.AddPointer(RHS); 3274 IP = nullptr; 3275 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3276 return S; 3277 } 3278 } 3279 } 3280 } 3281 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3282 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3283 SmallVector<const SCEV *, 4> Operands; 3284 for (const SCEV *Op : M->operands()) 3285 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3286 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3287 // Find an operand that's safely divisible. 3288 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3289 const SCEV *Op = M->getOperand(i); 3290 const SCEV *Div = getUDivExpr(Op, RHSC); 3291 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3292 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3293 M->op_end()); 3294 Operands[i] = Div; 3295 return getMulExpr(Operands); 3296 } 3297 } 3298 } 3299 3300 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3301 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3302 if (auto *DivisorConstant = 3303 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3304 bool Overflow = false; 3305 APInt NewRHS = 3306 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3307 if (Overflow) { 3308 return getConstant(RHSC->getType(), 0, false); 3309 } 3310 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3311 } 3312 } 3313 3314 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3315 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3316 SmallVector<const SCEV *, 4> Operands; 3317 for (const SCEV *Op : A->operands()) 3318 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3319 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3320 Operands.clear(); 3321 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3322 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3323 if (isa<SCEVUDivExpr>(Op) || 3324 getMulExpr(Op, RHS) != A->getOperand(i)) 3325 break; 3326 Operands.push_back(Op); 3327 } 3328 if (Operands.size() == A->getNumOperands()) 3329 return getAddExpr(Operands); 3330 } 3331 } 3332 3333 // Fold if both operands are constant. 3334 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3335 Constant *LHSCV = LHSC->getValue(); 3336 Constant *RHSCV = RHSC->getValue(); 3337 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3338 RHSCV))); 3339 } 3340 } 3341 } 3342 3343 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3344 // changes). Make sure we get a new one. 3345 IP = nullptr; 3346 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3347 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3348 LHS, RHS); 3349 UniqueSCEVs.InsertNode(S, IP); 3350 addToLoopUseLists(S); 3351 return S; 3352 } 3353 3354 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3355 APInt A = C1->getAPInt().abs(); 3356 APInt B = C2->getAPInt().abs(); 3357 uint32_t ABW = A.getBitWidth(); 3358 uint32_t BBW = B.getBitWidth(); 3359 3360 if (ABW > BBW) 3361 B = B.zext(ABW); 3362 else if (ABW < BBW) 3363 A = A.zext(BBW); 3364 3365 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3366 } 3367 3368 /// Get a canonical unsigned division expression, or something simpler if 3369 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3370 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3371 /// it's not exact because the udiv may be clearing bits. 3372 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3373 const SCEV *RHS) { 3374 // TODO: we could try to find factors in all sorts of things, but for now we 3375 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3376 // end of this file for inspiration. 3377 3378 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3379 if (!Mul || !Mul->hasNoUnsignedWrap()) 3380 return getUDivExpr(LHS, RHS); 3381 3382 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3383 // If the mulexpr multiplies by a constant, then that constant must be the 3384 // first element of the mulexpr. 3385 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3386 if (LHSCst == RHSCst) { 3387 SmallVector<const SCEV *, 2> Operands; 3388 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3389 return getMulExpr(Operands); 3390 } 3391 3392 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3393 // that there's a factor provided by one of the other terms. We need to 3394 // check. 3395 APInt Factor = gcd(LHSCst, RHSCst); 3396 if (!Factor.isIntN(1)) { 3397 LHSCst = 3398 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3399 RHSCst = 3400 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3401 SmallVector<const SCEV *, 2> Operands; 3402 Operands.push_back(LHSCst); 3403 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3404 LHS = getMulExpr(Operands); 3405 RHS = RHSCst; 3406 Mul = dyn_cast<SCEVMulExpr>(LHS); 3407 if (!Mul) 3408 return getUDivExactExpr(LHS, RHS); 3409 } 3410 } 3411 } 3412 3413 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3414 if (Mul->getOperand(i) == RHS) { 3415 SmallVector<const SCEV *, 2> Operands; 3416 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3417 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3418 return getMulExpr(Operands); 3419 } 3420 } 3421 3422 return getUDivExpr(LHS, RHS); 3423 } 3424 3425 /// Get an add recurrence expression for the specified loop. Simplify the 3426 /// expression as much as possible. 3427 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3428 const Loop *L, 3429 SCEV::NoWrapFlags Flags) { 3430 SmallVector<const SCEV *, 4> Operands; 3431 Operands.push_back(Start); 3432 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3433 if (StepChrec->getLoop() == L) { 3434 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3435 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3436 } 3437 3438 Operands.push_back(Step); 3439 return getAddRecExpr(Operands, L, Flags); 3440 } 3441 3442 /// Get an add recurrence expression for the specified loop. Simplify the 3443 /// expression as much as possible. 3444 const SCEV * 3445 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3446 const Loop *L, SCEV::NoWrapFlags Flags) { 3447 if (Operands.size() == 1) return Operands[0]; 3448 #ifndef NDEBUG 3449 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3450 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3451 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3452 "SCEVAddRecExpr operand types don't match!"); 3453 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3454 assert(isLoopInvariant(Operands[i], L) && 3455 "SCEVAddRecExpr operand is not loop-invariant!"); 3456 #endif 3457 3458 if (Operands.back()->isZero()) { 3459 Operands.pop_back(); 3460 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3461 } 3462 3463 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3464 // use that information to infer NUW and NSW flags. However, computing a 3465 // BE count requires calling getAddRecExpr, so we may not yet have a 3466 // meaningful BE count at this point (and if we don't, we'd be stuck 3467 // with a SCEVCouldNotCompute as the cached BE count). 3468 3469 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3470 3471 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3472 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3473 const Loop *NestedLoop = NestedAR->getLoop(); 3474 if (L->contains(NestedLoop) 3475 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3476 : (!NestedLoop->contains(L) && 3477 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3478 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3479 NestedAR->op_end()); 3480 Operands[0] = NestedAR->getStart(); 3481 // AddRecs require their operands be loop-invariant with respect to their 3482 // loops. Don't perform this transformation if it would break this 3483 // requirement. 3484 bool AllInvariant = all_of( 3485 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3486 3487 if (AllInvariant) { 3488 // Create a recurrence for the outer loop with the same step size. 3489 // 3490 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3491 // inner recurrence has the same property. 3492 SCEV::NoWrapFlags OuterFlags = 3493 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3494 3495 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3496 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3497 return isLoopInvariant(Op, NestedLoop); 3498 }); 3499 3500 if (AllInvariant) { 3501 // Ok, both add recurrences are valid after the transformation. 3502 // 3503 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3504 // the outer recurrence has the same property. 3505 SCEV::NoWrapFlags InnerFlags = 3506 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3507 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3508 } 3509 } 3510 // Reset Operands to its original state. 3511 Operands[0] = NestedAR; 3512 } 3513 } 3514 3515 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3516 // already have one, otherwise create a new one. 3517 return getOrCreateAddRecExpr(Operands, L, Flags); 3518 } 3519 3520 const SCEV * 3521 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3522 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3523 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3524 // getSCEV(Base)->getType() has the same address space as Base->getType() 3525 // because SCEV::getType() preserves the address space. 3526 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3527 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3528 // instruction to its SCEV, because the Instruction may be guarded by control 3529 // flow and the no-overflow bits may not be valid for the expression in any 3530 // context. This can be fixed similarly to how these flags are handled for 3531 // adds. 3532 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3533 : SCEV::FlagAnyWrap; 3534 3535 const SCEV *TotalOffset = getZero(IntIdxTy); 3536 Type *CurTy = GEP->getType(); 3537 bool FirstIter = true; 3538 for (const SCEV *IndexExpr : IndexExprs) { 3539 // Compute the (potentially symbolic) offset in bytes for this index. 3540 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3541 // For a struct, add the member offset. 3542 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3543 unsigned FieldNo = Index->getZExtValue(); 3544 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3545 3546 // Add the field offset to the running total offset. 3547 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3548 3549 // Update CurTy to the type of the field at Index. 3550 CurTy = STy->getTypeAtIndex(Index); 3551 } else { 3552 // Update CurTy to its element type. 3553 if (FirstIter) { 3554 assert(isa<PointerType>(CurTy) && 3555 "The first index of a GEP indexes a pointer"); 3556 CurTy = GEP->getSourceElementType(); 3557 FirstIter = false; 3558 } else { 3559 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3560 } 3561 // For an array, add the element offset, explicitly scaled. 3562 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3563 // Getelementptr indices are signed. 3564 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3565 3566 // Multiply the index by the element size to compute the element offset. 3567 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3568 3569 // Add the element offset to the running total offset. 3570 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3571 } 3572 } 3573 3574 // Add the total offset from all the GEP indices to the base. 3575 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3576 } 3577 3578 std::tuple<SCEV *, FoldingSetNodeID, void *> 3579 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3580 ArrayRef<const SCEV *> Ops) { 3581 FoldingSetNodeID ID; 3582 void *IP = nullptr; 3583 ID.AddInteger(SCEVType); 3584 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3585 ID.AddPointer(Ops[i]); 3586 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3587 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3588 } 3589 3590 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3591 SmallVectorImpl<const SCEV *> &Ops) { 3592 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3593 if (Ops.size() == 1) return Ops[0]; 3594 #ifndef NDEBUG 3595 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3596 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3597 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3598 "Operand types don't match!"); 3599 #endif 3600 3601 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3602 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3603 3604 // Sort by complexity, this groups all similar expression types together. 3605 GroupByComplexity(Ops, &LI, DT); 3606 3607 // Check if we have created the same expression before. 3608 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3609 return S; 3610 } 3611 3612 // If there are any constants, fold them together. 3613 unsigned Idx = 0; 3614 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3615 ++Idx; 3616 assert(Idx < Ops.size()); 3617 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3618 if (Kind == scSMaxExpr) 3619 return APIntOps::smax(LHS, RHS); 3620 else if (Kind == scSMinExpr) 3621 return APIntOps::smin(LHS, RHS); 3622 else if (Kind == scUMaxExpr) 3623 return APIntOps::umax(LHS, RHS); 3624 else if (Kind == scUMinExpr) 3625 return APIntOps::umin(LHS, RHS); 3626 llvm_unreachable("Unknown SCEV min/max opcode"); 3627 }; 3628 3629 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3630 // We found two constants, fold them together! 3631 ConstantInt *Fold = ConstantInt::get( 3632 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3633 Ops[0] = getConstant(Fold); 3634 Ops.erase(Ops.begin()+1); // Erase the folded element 3635 if (Ops.size() == 1) return Ops[0]; 3636 LHSC = cast<SCEVConstant>(Ops[0]); 3637 } 3638 3639 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3640 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3641 3642 if (IsMax ? IsMinV : IsMaxV) { 3643 // If we are left with a constant minimum(/maximum)-int, strip it off. 3644 Ops.erase(Ops.begin()); 3645 --Idx; 3646 } else if (IsMax ? IsMaxV : IsMinV) { 3647 // If we have a max(/min) with a constant maximum(/minimum)-int, 3648 // it will always be the extremum. 3649 return LHSC; 3650 } 3651 3652 if (Ops.size() == 1) return Ops[0]; 3653 } 3654 3655 // Find the first operation of the same kind 3656 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3657 ++Idx; 3658 3659 // Check to see if one of the operands is of the same kind. If so, expand its 3660 // operands onto our operand list, and recurse to simplify. 3661 if (Idx < Ops.size()) { 3662 bool DeletedAny = false; 3663 while (Ops[Idx]->getSCEVType() == Kind) { 3664 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3665 Ops.erase(Ops.begin()+Idx); 3666 Ops.append(SMME->op_begin(), SMME->op_end()); 3667 DeletedAny = true; 3668 } 3669 3670 if (DeletedAny) 3671 return getMinMaxExpr(Kind, Ops); 3672 } 3673 3674 // Okay, check to see if the same value occurs in the operand list twice. If 3675 // so, delete one. Since we sorted the list, these values are required to 3676 // be adjacent. 3677 llvm::CmpInst::Predicate GEPred = 3678 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3679 llvm::CmpInst::Predicate LEPred = 3680 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3681 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3682 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3683 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3684 if (Ops[i] == Ops[i + 1] || 3685 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3686 // X op Y op Y --> X op Y 3687 // X op Y --> X, if we know X, Y are ordered appropriately 3688 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3689 --i; 3690 --e; 3691 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3692 Ops[i + 1])) { 3693 // X op Y --> Y, if we know X, Y are ordered appropriately 3694 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3695 --i; 3696 --e; 3697 } 3698 } 3699 3700 if (Ops.size() == 1) return Ops[0]; 3701 3702 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3703 3704 // Okay, it looks like we really DO need an expr. Check to see if we 3705 // already have one, otherwise create a new one. 3706 const SCEV *ExistingSCEV; 3707 FoldingSetNodeID ID; 3708 void *IP; 3709 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3710 if (ExistingSCEV) 3711 return ExistingSCEV; 3712 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3713 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3714 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3715 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3716 3717 UniqueSCEVs.InsertNode(S, IP); 3718 addToLoopUseLists(S); 3719 return S; 3720 } 3721 3722 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3723 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3724 return getSMaxExpr(Ops); 3725 } 3726 3727 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3728 return getMinMaxExpr(scSMaxExpr, Ops); 3729 } 3730 3731 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3732 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3733 return getUMaxExpr(Ops); 3734 } 3735 3736 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3737 return getMinMaxExpr(scUMaxExpr, Ops); 3738 } 3739 3740 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3741 const SCEV *RHS) { 3742 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3743 return getSMinExpr(Ops); 3744 } 3745 3746 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3747 return getMinMaxExpr(scSMinExpr, Ops); 3748 } 3749 3750 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3751 const SCEV *RHS) { 3752 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3753 return getUMinExpr(Ops); 3754 } 3755 3756 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3757 return getMinMaxExpr(scUMinExpr, Ops); 3758 } 3759 3760 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3761 // We can bypass creating a target-independent 3762 // constant expression and then folding it back into a ConstantInt. 3763 // This is just a compile-time optimization. 3764 if (isa<ScalableVectorType>(AllocTy)) { 3765 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3766 Constant *One = ConstantInt::get(IntTy, 1); 3767 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3768 return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); 3769 } 3770 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3771 } 3772 3773 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3774 StructType *STy, 3775 unsigned FieldNo) { 3776 // We can bypass creating a target-independent 3777 // constant expression and then folding it back into a ConstantInt. 3778 // This is just a compile-time optimization. 3779 return getConstant( 3780 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3781 } 3782 3783 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3784 // Don't attempt to do anything other than create a SCEVUnknown object 3785 // here. createSCEV only calls getUnknown after checking for all other 3786 // interesting possibilities, and any other code that calls getUnknown 3787 // is doing so in order to hide a value from SCEV canonicalization. 3788 3789 FoldingSetNodeID ID; 3790 ID.AddInteger(scUnknown); 3791 ID.AddPointer(V); 3792 void *IP = nullptr; 3793 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3794 assert(cast<SCEVUnknown>(S)->getValue() == V && 3795 "Stale SCEVUnknown in uniquing map!"); 3796 return S; 3797 } 3798 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3799 FirstUnknown); 3800 FirstUnknown = cast<SCEVUnknown>(S); 3801 UniqueSCEVs.InsertNode(S, IP); 3802 return S; 3803 } 3804 3805 //===----------------------------------------------------------------------===// 3806 // Basic SCEV Analysis and PHI Idiom Recognition Code 3807 // 3808 3809 /// Test if values of the given type are analyzable within the SCEV 3810 /// framework. This primarily includes integer types, and it can optionally 3811 /// include pointer types if the ScalarEvolution class has access to 3812 /// target-specific information. 3813 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3814 // Integers and pointers are always SCEVable. 3815 return Ty->isIntOrPtrTy(); 3816 } 3817 3818 /// Return the size in bits of the specified type, for which isSCEVable must 3819 /// return true. 3820 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3821 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3822 if (Ty->isPointerTy()) 3823 return getDataLayout().getIndexTypeSizeInBits(Ty); 3824 return getDataLayout().getTypeSizeInBits(Ty); 3825 } 3826 3827 /// Return a type with the same bitwidth as the given type and which represents 3828 /// how SCEV will treat the given type, for which isSCEVable must return 3829 /// true. For pointer types, this is the pointer index sized integer type. 3830 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3831 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3832 3833 if (Ty->isIntegerTy()) 3834 return Ty; 3835 3836 // The only other support type is pointer. 3837 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3838 return getDataLayout().getIndexType(Ty); 3839 } 3840 3841 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3842 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3843 } 3844 3845 const SCEV *ScalarEvolution::getCouldNotCompute() { 3846 return CouldNotCompute.get(); 3847 } 3848 3849 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3850 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3851 auto *SU = dyn_cast<SCEVUnknown>(S); 3852 return SU && SU->getValue() == nullptr; 3853 }); 3854 3855 return !ContainsNulls; 3856 } 3857 3858 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3859 HasRecMapType::iterator I = HasRecMap.find(S); 3860 if (I != HasRecMap.end()) 3861 return I->second; 3862 3863 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3864 HasRecMap.insert({S, FoundAddRec}); 3865 return FoundAddRec; 3866 } 3867 3868 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3869 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3870 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3871 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3872 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3873 if (!Add) 3874 return {S, nullptr}; 3875 3876 if (Add->getNumOperands() != 2) 3877 return {S, nullptr}; 3878 3879 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3880 if (!ConstOp) 3881 return {S, nullptr}; 3882 3883 return {Add->getOperand(1), ConstOp->getValue()}; 3884 } 3885 3886 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3887 /// by the value and offset from any ValueOffsetPair in the set. 3888 SetVector<ScalarEvolution::ValueOffsetPair> * 3889 ScalarEvolution::getSCEVValues(const SCEV *S) { 3890 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3891 if (SI == ExprValueMap.end()) 3892 return nullptr; 3893 #ifndef NDEBUG 3894 if (VerifySCEVMap) { 3895 // Check there is no dangling Value in the set returned. 3896 for (const auto &VE : SI->second) 3897 assert(ValueExprMap.count(VE.first)); 3898 } 3899 #endif 3900 return &SI->second; 3901 } 3902 3903 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3904 /// cannot be used separately. eraseValueFromMap should be used to remove 3905 /// V from ValueExprMap and ExprValueMap at the same time. 3906 void ScalarEvolution::eraseValueFromMap(Value *V) { 3907 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3908 if (I != ValueExprMap.end()) { 3909 const SCEV *S = I->second; 3910 // Remove {V, 0} from the set of ExprValueMap[S] 3911 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3912 SV->remove({V, nullptr}); 3913 3914 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3915 const SCEV *Stripped; 3916 ConstantInt *Offset; 3917 std::tie(Stripped, Offset) = splitAddExpr(S); 3918 if (Offset != nullptr) { 3919 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3920 SV->remove({V, Offset}); 3921 } 3922 ValueExprMap.erase(V); 3923 } 3924 } 3925 3926 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3927 /// TODO: In reality it is better to check the poison recursively 3928 /// but this is better than nothing. 3929 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3930 if (auto *I = dyn_cast<Instruction>(V)) { 3931 if (isa<OverflowingBinaryOperator>(I)) { 3932 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3933 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3934 return true; 3935 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3936 return true; 3937 } 3938 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3939 return true; 3940 } 3941 return false; 3942 } 3943 3944 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3945 /// create a new one. 3946 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3947 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3948 3949 const SCEV *S = getExistingSCEV(V); 3950 if (S == nullptr) { 3951 S = createSCEV(V); 3952 // During PHI resolution, it is possible to create two SCEVs for the same 3953 // V, so it is needed to double check whether V->S is inserted into 3954 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3955 std::pair<ValueExprMapType::iterator, bool> Pair = 3956 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3957 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3958 ExprValueMap[S].insert({V, nullptr}); 3959 3960 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3961 // ExprValueMap. 3962 const SCEV *Stripped = S; 3963 ConstantInt *Offset = nullptr; 3964 std::tie(Stripped, Offset) = splitAddExpr(S); 3965 // If stripped is SCEVUnknown, don't bother to save 3966 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3967 // increase the complexity of the expansion code. 3968 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3969 // because it may generate add/sub instead of GEP in SCEV expansion. 3970 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3971 !isa<GetElementPtrInst>(V)) 3972 ExprValueMap[Stripped].insert({V, Offset}); 3973 } 3974 } 3975 return S; 3976 } 3977 3978 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3979 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3980 3981 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3982 if (I != ValueExprMap.end()) { 3983 const SCEV *S = I->second; 3984 if (checkValidity(S)) 3985 return S; 3986 eraseValueFromMap(V); 3987 forgetMemoizedResults(S); 3988 } 3989 return nullptr; 3990 } 3991 3992 /// Return a SCEV corresponding to -V = -1*V 3993 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3994 SCEV::NoWrapFlags Flags) { 3995 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3996 return getConstant( 3997 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3998 3999 Type *Ty = V->getType(); 4000 Ty = getEffectiveSCEVType(Ty); 4001 return getMulExpr( 4002 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4003 } 4004 4005 /// If Expr computes ~A, return A else return nullptr 4006 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4007 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4008 if (!Add || Add->getNumOperands() != 2 || 4009 !Add->getOperand(0)->isAllOnesValue()) 4010 return nullptr; 4011 4012 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4013 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4014 !AddRHS->getOperand(0)->isAllOnesValue()) 4015 return nullptr; 4016 4017 return AddRHS->getOperand(1); 4018 } 4019 4020 /// Return a SCEV corresponding to ~V = -1-V 4021 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4022 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4023 return getConstant( 4024 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4025 4026 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4027 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4028 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4029 SmallVector<const SCEV *, 2> MatchedOperands; 4030 for (const SCEV *Operand : MME->operands()) { 4031 const SCEV *Matched = MatchNotExpr(Operand); 4032 if (!Matched) 4033 return (const SCEV *)nullptr; 4034 MatchedOperands.push_back(Matched); 4035 } 4036 return getMinMaxExpr( 4037 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 4038 MatchedOperands); 4039 }; 4040 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4041 return Replaced; 4042 } 4043 4044 Type *Ty = V->getType(); 4045 Ty = getEffectiveSCEVType(Ty); 4046 const SCEV *AllOnes = 4047 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4048 return getMinusSCEV(AllOnes, V); 4049 } 4050 4051 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4052 SCEV::NoWrapFlags Flags, 4053 unsigned Depth) { 4054 // Fast path: X - X --> 0. 4055 if (LHS == RHS) 4056 return getZero(LHS->getType()); 4057 4058 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4059 // makes it so that we cannot make much use of NUW. 4060 auto AddFlags = SCEV::FlagAnyWrap; 4061 const bool RHSIsNotMinSigned = 4062 !getSignedRangeMin(RHS).isMinSignedValue(); 4063 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4064 // Let M be the minimum representable signed value. Then (-1)*RHS 4065 // signed-wraps if and only if RHS is M. That can happen even for 4066 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4067 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4068 // (-1)*RHS, we need to prove that RHS != M. 4069 // 4070 // If LHS is non-negative and we know that LHS - RHS does not 4071 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4072 // either by proving that RHS > M or that LHS >= 0. 4073 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4074 AddFlags = SCEV::FlagNSW; 4075 } 4076 } 4077 4078 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4079 // RHS is NSW and LHS >= 0. 4080 // 4081 // The difficulty here is that the NSW flag may have been proven 4082 // relative to a loop that is to be found in a recurrence in LHS and 4083 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4084 // larger scope than intended. 4085 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4086 4087 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4088 } 4089 4090 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4091 unsigned Depth) { 4092 Type *SrcTy = V->getType(); 4093 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4094 "Cannot truncate or zero extend with non-integer arguments!"); 4095 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4096 return V; // No conversion 4097 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4098 return getTruncateExpr(V, Ty, Depth); 4099 return getZeroExtendExpr(V, Ty, Depth); 4100 } 4101 4102 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4103 unsigned Depth) { 4104 Type *SrcTy = V->getType(); 4105 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4106 "Cannot truncate or zero extend with non-integer arguments!"); 4107 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4108 return V; // No conversion 4109 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4110 return getTruncateExpr(V, Ty, Depth); 4111 return getSignExtendExpr(V, Ty, Depth); 4112 } 4113 4114 const SCEV * 4115 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4116 Type *SrcTy = V->getType(); 4117 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4118 "Cannot noop or zero extend with non-integer arguments!"); 4119 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4120 "getNoopOrZeroExtend cannot truncate!"); 4121 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4122 return V; // No conversion 4123 return getZeroExtendExpr(V, Ty); 4124 } 4125 4126 const SCEV * 4127 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4128 Type *SrcTy = V->getType(); 4129 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4130 "Cannot noop or sign extend with non-integer arguments!"); 4131 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4132 "getNoopOrSignExtend cannot truncate!"); 4133 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4134 return V; // No conversion 4135 return getSignExtendExpr(V, Ty); 4136 } 4137 4138 const SCEV * 4139 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4140 Type *SrcTy = V->getType(); 4141 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4142 "Cannot noop or any extend with non-integer arguments!"); 4143 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4144 "getNoopOrAnyExtend cannot truncate!"); 4145 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4146 return V; // No conversion 4147 return getAnyExtendExpr(V, Ty); 4148 } 4149 4150 const SCEV * 4151 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4152 Type *SrcTy = V->getType(); 4153 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4154 "Cannot truncate or noop with non-integer arguments!"); 4155 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4156 "getTruncateOrNoop cannot extend!"); 4157 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4158 return V; // No conversion 4159 return getTruncateExpr(V, Ty); 4160 } 4161 4162 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4163 const SCEV *RHS) { 4164 const SCEV *PromotedLHS = LHS; 4165 const SCEV *PromotedRHS = RHS; 4166 4167 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4168 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4169 else 4170 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4171 4172 return getUMaxExpr(PromotedLHS, PromotedRHS); 4173 } 4174 4175 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4176 const SCEV *RHS) { 4177 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4178 return getUMinFromMismatchedTypes(Ops); 4179 } 4180 4181 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4182 SmallVectorImpl<const SCEV *> &Ops) { 4183 assert(!Ops.empty() && "At least one operand must be!"); 4184 // Trivial case. 4185 if (Ops.size() == 1) 4186 return Ops[0]; 4187 4188 // Find the max type first. 4189 Type *MaxType = nullptr; 4190 for (auto *S : Ops) 4191 if (MaxType) 4192 MaxType = getWiderType(MaxType, S->getType()); 4193 else 4194 MaxType = S->getType(); 4195 4196 // Extend all ops to max type. 4197 SmallVector<const SCEV *, 2> PromotedOps; 4198 for (auto *S : Ops) 4199 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4200 4201 // Generate umin. 4202 return getUMinExpr(PromotedOps); 4203 } 4204 4205 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4206 // A pointer operand may evaluate to a nonpointer expression, such as null. 4207 if (!V->getType()->isPointerTy()) 4208 return V; 4209 4210 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4211 return getPointerBase(Cast->getOperand()); 4212 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4213 const SCEV *PtrOp = nullptr; 4214 for (const SCEV *NAryOp : NAry->operands()) { 4215 if (NAryOp->getType()->isPointerTy()) { 4216 // Cannot find the base of an expression with multiple pointer operands. 4217 if (PtrOp) 4218 return V; 4219 PtrOp = NAryOp; 4220 } 4221 } 4222 if (!PtrOp) 4223 return V; 4224 return getPointerBase(PtrOp); 4225 } 4226 return V; 4227 } 4228 4229 /// Push users of the given Instruction onto the given Worklist. 4230 static void 4231 PushDefUseChildren(Instruction *I, 4232 SmallVectorImpl<Instruction *> &Worklist) { 4233 // Push the def-use children onto the Worklist stack. 4234 for (User *U : I->users()) 4235 Worklist.push_back(cast<Instruction>(U)); 4236 } 4237 4238 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4239 SmallVector<Instruction *, 16> Worklist; 4240 PushDefUseChildren(PN, Worklist); 4241 4242 SmallPtrSet<Instruction *, 8> Visited; 4243 Visited.insert(PN); 4244 while (!Worklist.empty()) { 4245 Instruction *I = Worklist.pop_back_val(); 4246 if (!Visited.insert(I).second) 4247 continue; 4248 4249 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4250 if (It != ValueExprMap.end()) { 4251 const SCEV *Old = It->second; 4252 4253 // Short-circuit the def-use traversal if the symbolic name 4254 // ceases to appear in expressions. 4255 if (Old != SymName && !hasOperand(Old, SymName)) 4256 continue; 4257 4258 // SCEVUnknown for a PHI either means that it has an unrecognized 4259 // structure, it's a PHI that's in the progress of being computed 4260 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4261 // additional loop trip count information isn't going to change anything. 4262 // In the second case, createNodeForPHI will perform the necessary 4263 // updates on its own when it gets to that point. In the third, we do 4264 // want to forget the SCEVUnknown. 4265 if (!isa<PHINode>(I) || 4266 !isa<SCEVUnknown>(Old) || 4267 (I != PN && Old == SymName)) { 4268 eraseValueFromMap(It->first); 4269 forgetMemoizedResults(Old); 4270 } 4271 } 4272 4273 PushDefUseChildren(I, Worklist); 4274 } 4275 } 4276 4277 namespace { 4278 4279 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4280 /// expression in case its Loop is L. If it is not L then 4281 /// if IgnoreOtherLoops is true then use AddRec itself 4282 /// otherwise rewrite cannot be done. 4283 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4284 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4285 public: 4286 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4287 bool IgnoreOtherLoops = true) { 4288 SCEVInitRewriter Rewriter(L, SE); 4289 const SCEV *Result = Rewriter.visit(S); 4290 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4291 return SE.getCouldNotCompute(); 4292 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4293 ? SE.getCouldNotCompute() 4294 : Result; 4295 } 4296 4297 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4298 if (!SE.isLoopInvariant(Expr, L)) 4299 SeenLoopVariantSCEVUnknown = true; 4300 return Expr; 4301 } 4302 4303 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4304 // Only re-write AddRecExprs for this loop. 4305 if (Expr->getLoop() == L) 4306 return Expr->getStart(); 4307 SeenOtherLoops = true; 4308 return Expr; 4309 } 4310 4311 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4312 4313 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4314 4315 private: 4316 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4317 : SCEVRewriteVisitor(SE), L(L) {} 4318 4319 const Loop *L; 4320 bool SeenLoopVariantSCEVUnknown = false; 4321 bool SeenOtherLoops = false; 4322 }; 4323 4324 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4325 /// increment expression in case its Loop is L. If it is not L then 4326 /// use AddRec itself. 4327 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4328 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4329 public: 4330 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4331 SCEVPostIncRewriter Rewriter(L, SE); 4332 const SCEV *Result = Rewriter.visit(S); 4333 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4334 ? SE.getCouldNotCompute() 4335 : Result; 4336 } 4337 4338 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4339 if (!SE.isLoopInvariant(Expr, L)) 4340 SeenLoopVariantSCEVUnknown = true; 4341 return Expr; 4342 } 4343 4344 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4345 // Only re-write AddRecExprs for this loop. 4346 if (Expr->getLoop() == L) 4347 return Expr->getPostIncExpr(SE); 4348 SeenOtherLoops = true; 4349 return Expr; 4350 } 4351 4352 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4353 4354 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4355 4356 private: 4357 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4358 : SCEVRewriteVisitor(SE), L(L) {} 4359 4360 const Loop *L; 4361 bool SeenLoopVariantSCEVUnknown = false; 4362 bool SeenOtherLoops = false; 4363 }; 4364 4365 /// This class evaluates the compare condition by matching it against the 4366 /// condition of loop latch. If there is a match we assume a true value 4367 /// for the condition while building SCEV nodes. 4368 class SCEVBackedgeConditionFolder 4369 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4370 public: 4371 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4372 ScalarEvolution &SE) { 4373 bool IsPosBECond = false; 4374 Value *BECond = nullptr; 4375 if (BasicBlock *Latch = L->getLoopLatch()) { 4376 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4377 if (BI && BI->isConditional()) { 4378 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4379 "Both outgoing branches should not target same header!"); 4380 BECond = BI->getCondition(); 4381 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4382 } else { 4383 return S; 4384 } 4385 } 4386 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4387 return Rewriter.visit(S); 4388 } 4389 4390 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4391 const SCEV *Result = Expr; 4392 bool InvariantF = SE.isLoopInvariant(Expr, L); 4393 4394 if (!InvariantF) { 4395 Instruction *I = cast<Instruction>(Expr->getValue()); 4396 switch (I->getOpcode()) { 4397 case Instruction::Select: { 4398 SelectInst *SI = cast<SelectInst>(I); 4399 Optional<const SCEV *> Res = 4400 compareWithBackedgeCondition(SI->getCondition()); 4401 if (Res.hasValue()) { 4402 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4403 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4404 } 4405 break; 4406 } 4407 default: { 4408 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4409 if (Res.hasValue()) 4410 Result = Res.getValue(); 4411 break; 4412 } 4413 } 4414 } 4415 return Result; 4416 } 4417 4418 private: 4419 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4420 bool IsPosBECond, ScalarEvolution &SE) 4421 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4422 IsPositiveBECond(IsPosBECond) {} 4423 4424 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4425 4426 const Loop *L; 4427 /// Loop back condition. 4428 Value *BackedgeCond = nullptr; 4429 /// Set to true if loop back is on positive branch condition. 4430 bool IsPositiveBECond; 4431 }; 4432 4433 Optional<const SCEV *> 4434 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4435 4436 // If value matches the backedge condition for loop latch, 4437 // then return a constant evolution node based on loopback 4438 // branch taken. 4439 if (BackedgeCond == IC) 4440 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4441 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4442 return None; 4443 } 4444 4445 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4446 public: 4447 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4448 ScalarEvolution &SE) { 4449 SCEVShiftRewriter Rewriter(L, SE); 4450 const SCEV *Result = Rewriter.visit(S); 4451 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4452 } 4453 4454 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4455 // Only allow AddRecExprs for this loop. 4456 if (!SE.isLoopInvariant(Expr, L)) 4457 Valid = false; 4458 return Expr; 4459 } 4460 4461 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4462 if (Expr->getLoop() == L && Expr->isAffine()) 4463 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4464 Valid = false; 4465 return Expr; 4466 } 4467 4468 bool isValid() { return Valid; } 4469 4470 private: 4471 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4472 : SCEVRewriteVisitor(SE), L(L) {} 4473 4474 const Loop *L; 4475 bool Valid = true; 4476 }; 4477 4478 } // end anonymous namespace 4479 4480 SCEV::NoWrapFlags 4481 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4482 if (!AR->isAffine()) 4483 return SCEV::FlagAnyWrap; 4484 4485 using OBO = OverflowingBinaryOperator; 4486 4487 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4488 4489 if (!AR->hasNoSignedWrap()) { 4490 ConstantRange AddRecRange = getSignedRange(AR); 4491 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4492 4493 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4494 Instruction::Add, IncRange, OBO::NoSignedWrap); 4495 if (NSWRegion.contains(AddRecRange)) 4496 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4497 } 4498 4499 if (!AR->hasNoUnsignedWrap()) { 4500 ConstantRange AddRecRange = getUnsignedRange(AR); 4501 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4502 4503 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4504 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4505 if (NUWRegion.contains(AddRecRange)) 4506 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4507 } 4508 4509 return Result; 4510 } 4511 4512 namespace { 4513 4514 /// Represents an abstract binary operation. This may exist as a 4515 /// normal instruction or constant expression, or may have been 4516 /// derived from an expression tree. 4517 struct BinaryOp { 4518 unsigned Opcode; 4519 Value *LHS; 4520 Value *RHS; 4521 bool IsNSW = false; 4522 bool IsNUW = false; 4523 4524 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4525 /// constant expression. 4526 Operator *Op = nullptr; 4527 4528 explicit BinaryOp(Operator *Op) 4529 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4530 Op(Op) { 4531 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4532 IsNSW = OBO->hasNoSignedWrap(); 4533 IsNUW = OBO->hasNoUnsignedWrap(); 4534 } 4535 } 4536 4537 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4538 bool IsNUW = false) 4539 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4540 }; 4541 4542 } // end anonymous namespace 4543 4544 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4545 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4546 auto *Op = dyn_cast<Operator>(V); 4547 if (!Op) 4548 return None; 4549 4550 // Implementation detail: all the cleverness here should happen without 4551 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4552 // SCEV expressions when possible, and we should not break that. 4553 4554 switch (Op->getOpcode()) { 4555 case Instruction::Add: 4556 case Instruction::Sub: 4557 case Instruction::Mul: 4558 case Instruction::UDiv: 4559 case Instruction::URem: 4560 case Instruction::And: 4561 case Instruction::Or: 4562 case Instruction::AShr: 4563 case Instruction::Shl: 4564 return BinaryOp(Op); 4565 4566 case Instruction::Xor: 4567 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4568 // If the RHS of the xor is a signmask, then this is just an add. 4569 // Instcombine turns add of signmask into xor as a strength reduction step. 4570 if (RHSC->getValue().isSignMask()) 4571 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4572 return BinaryOp(Op); 4573 4574 case Instruction::LShr: 4575 // Turn logical shift right of a constant into a unsigned divide. 4576 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4577 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4578 4579 // If the shift count is not less than the bitwidth, the result of 4580 // the shift is undefined. Don't try to analyze it, because the 4581 // resolution chosen here may differ from the resolution chosen in 4582 // other parts of the compiler. 4583 if (SA->getValue().ult(BitWidth)) { 4584 Constant *X = 4585 ConstantInt::get(SA->getContext(), 4586 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4587 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4588 } 4589 } 4590 return BinaryOp(Op); 4591 4592 case Instruction::ExtractValue: { 4593 auto *EVI = cast<ExtractValueInst>(Op); 4594 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4595 break; 4596 4597 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4598 if (!WO) 4599 break; 4600 4601 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4602 bool Signed = WO->isSigned(); 4603 // TODO: Should add nuw/nsw flags for mul as well. 4604 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4605 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4606 4607 // Now that we know that all uses of the arithmetic-result component of 4608 // CI are guarded by the overflow check, we can go ahead and pretend 4609 // that the arithmetic is non-overflowing. 4610 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4611 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4612 } 4613 4614 default: 4615 break; 4616 } 4617 4618 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4619 // semantics as a Sub, return a binary sub expression. 4620 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4621 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4622 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4623 4624 return None; 4625 } 4626 4627 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4628 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4629 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4630 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4631 /// follows one of the following patterns: 4632 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4633 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4634 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4635 /// we return the type of the truncation operation, and indicate whether the 4636 /// truncated type should be treated as signed/unsigned by setting 4637 /// \p Signed to true/false, respectively. 4638 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4639 bool &Signed, ScalarEvolution &SE) { 4640 // The case where Op == SymbolicPHI (that is, with no type conversions on 4641 // the way) is handled by the regular add recurrence creating logic and 4642 // would have already been triggered in createAddRecForPHI. Reaching it here 4643 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4644 // because one of the other operands of the SCEVAddExpr updating this PHI is 4645 // not invariant). 4646 // 4647 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4648 // this case predicates that allow us to prove that Op == SymbolicPHI will 4649 // be added. 4650 if (Op == SymbolicPHI) 4651 return nullptr; 4652 4653 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4654 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4655 if (SourceBits != NewBits) 4656 return nullptr; 4657 4658 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4659 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4660 if (!SExt && !ZExt) 4661 return nullptr; 4662 const SCEVTruncateExpr *Trunc = 4663 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4664 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4665 if (!Trunc) 4666 return nullptr; 4667 const SCEV *X = Trunc->getOperand(); 4668 if (X != SymbolicPHI) 4669 return nullptr; 4670 Signed = SExt != nullptr; 4671 return Trunc->getType(); 4672 } 4673 4674 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4675 if (!PN->getType()->isIntegerTy()) 4676 return nullptr; 4677 const Loop *L = LI.getLoopFor(PN->getParent()); 4678 if (!L || L->getHeader() != PN->getParent()) 4679 return nullptr; 4680 return L; 4681 } 4682 4683 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4684 // computation that updates the phi follows the following pattern: 4685 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4686 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4687 // If so, try to see if it can be rewritten as an AddRecExpr under some 4688 // Predicates. If successful, return them as a pair. Also cache the results 4689 // of the analysis. 4690 // 4691 // Example usage scenario: 4692 // Say the Rewriter is called for the following SCEV: 4693 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4694 // where: 4695 // %X = phi i64 (%Start, %BEValue) 4696 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4697 // and call this function with %SymbolicPHI = %X. 4698 // 4699 // The analysis will find that the value coming around the backedge has 4700 // the following SCEV: 4701 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4702 // Upon concluding that this matches the desired pattern, the function 4703 // will return the pair {NewAddRec, SmallPredsVec} where: 4704 // NewAddRec = {%Start,+,%Step} 4705 // SmallPredsVec = {P1, P2, P3} as follows: 4706 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4707 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4708 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4709 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4710 // under the predicates {P1,P2,P3}. 4711 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4712 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4713 // 4714 // TODO's: 4715 // 4716 // 1) Extend the Induction descriptor to also support inductions that involve 4717 // casts: When needed (namely, when we are called in the context of the 4718 // vectorizer induction analysis), a Set of cast instructions will be 4719 // populated by this method, and provided back to isInductionPHI. This is 4720 // needed to allow the vectorizer to properly record them to be ignored by 4721 // the cost model and to avoid vectorizing them (otherwise these casts, 4722 // which are redundant under the runtime overflow checks, will be 4723 // vectorized, which can be costly). 4724 // 4725 // 2) Support additional induction/PHISCEV patterns: We also want to support 4726 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4727 // after the induction update operation (the induction increment): 4728 // 4729 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4730 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4731 // 4732 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4733 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4734 // 4735 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4736 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4737 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4738 SmallVector<const SCEVPredicate *, 3> Predicates; 4739 4740 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4741 // return an AddRec expression under some predicate. 4742 4743 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4744 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4745 assert(L && "Expecting an integer loop header phi"); 4746 4747 // The loop may have multiple entrances or multiple exits; we can analyze 4748 // this phi as an addrec if it has a unique entry value and a unique 4749 // backedge value. 4750 Value *BEValueV = nullptr, *StartValueV = nullptr; 4751 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4752 Value *V = PN->getIncomingValue(i); 4753 if (L->contains(PN->getIncomingBlock(i))) { 4754 if (!BEValueV) { 4755 BEValueV = V; 4756 } else if (BEValueV != V) { 4757 BEValueV = nullptr; 4758 break; 4759 } 4760 } else if (!StartValueV) { 4761 StartValueV = V; 4762 } else if (StartValueV != V) { 4763 StartValueV = nullptr; 4764 break; 4765 } 4766 } 4767 if (!BEValueV || !StartValueV) 4768 return None; 4769 4770 const SCEV *BEValue = getSCEV(BEValueV); 4771 4772 // If the value coming around the backedge is an add with the symbolic 4773 // value we just inserted, possibly with casts that we can ignore under 4774 // an appropriate runtime guard, then we found a simple induction variable! 4775 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4776 if (!Add) 4777 return None; 4778 4779 // If there is a single occurrence of the symbolic value, possibly 4780 // casted, replace it with a recurrence. 4781 unsigned FoundIndex = Add->getNumOperands(); 4782 Type *TruncTy = nullptr; 4783 bool Signed; 4784 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4785 if ((TruncTy = 4786 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4787 if (FoundIndex == e) { 4788 FoundIndex = i; 4789 break; 4790 } 4791 4792 if (FoundIndex == Add->getNumOperands()) 4793 return None; 4794 4795 // Create an add with everything but the specified operand. 4796 SmallVector<const SCEV *, 8> Ops; 4797 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4798 if (i != FoundIndex) 4799 Ops.push_back(Add->getOperand(i)); 4800 const SCEV *Accum = getAddExpr(Ops); 4801 4802 // The runtime checks will not be valid if the step amount is 4803 // varying inside the loop. 4804 if (!isLoopInvariant(Accum, L)) 4805 return None; 4806 4807 // *** Part2: Create the predicates 4808 4809 // Analysis was successful: we have a phi-with-cast pattern for which we 4810 // can return an AddRec expression under the following predicates: 4811 // 4812 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4813 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4814 // P2: An Equal predicate that guarantees that 4815 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4816 // P3: An Equal predicate that guarantees that 4817 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4818 // 4819 // As we next prove, the above predicates guarantee that: 4820 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4821 // 4822 // 4823 // More formally, we want to prove that: 4824 // Expr(i+1) = Start + (i+1) * Accum 4825 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4826 // 4827 // Given that: 4828 // 1) Expr(0) = Start 4829 // 2) Expr(1) = Start + Accum 4830 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4831 // 3) Induction hypothesis (step i): 4832 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4833 // 4834 // Proof: 4835 // Expr(i+1) = 4836 // = Start + (i+1)*Accum 4837 // = (Start + i*Accum) + Accum 4838 // = Expr(i) + Accum 4839 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4840 // :: from step i 4841 // 4842 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4843 // 4844 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4845 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4846 // + Accum :: from P3 4847 // 4848 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4849 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4850 // 4851 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4852 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4853 // 4854 // By induction, the same applies to all iterations 1<=i<n: 4855 // 4856 4857 // Create a truncated addrec for which we will add a no overflow check (P1). 4858 const SCEV *StartVal = getSCEV(StartValueV); 4859 const SCEV *PHISCEV = 4860 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4861 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4862 4863 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4864 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4865 // will be constant. 4866 // 4867 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4868 // add P1. 4869 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4870 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4871 Signed ? SCEVWrapPredicate::IncrementNSSW 4872 : SCEVWrapPredicate::IncrementNUSW; 4873 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4874 Predicates.push_back(AddRecPred); 4875 } 4876 4877 // Create the Equal Predicates P2,P3: 4878 4879 // It is possible that the predicates P2 and/or P3 are computable at 4880 // compile time due to StartVal and/or Accum being constants. 4881 // If either one is, then we can check that now and escape if either P2 4882 // or P3 is false. 4883 4884 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4885 // for each of StartVal and Accum 4886 auto getExtendedExpr = [&](const SCEV *Expr, 4887 bool CreateSignExtend) -> const SCEV * { 4888 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4889 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4890 const SCEV *ExtendedExpr = 4891 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4892 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4893 return ExtendedExpr; 4894 }; 4895 4896 // Given: 4897 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4898 // = getExtendedExpr(Expr) 4899 // Determine whether the predicate P: Expr == ExtendedExpr 4900 // is known to be false at compile time 4901 auto PredIsKnownFalse = [&](const SCEV *Expr, 4902 const SCEV *ExtendedExpr) -> bool { 4903 return Expr != ExtendedExpr && 4904 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4905 }; 4906 4907 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4908 if (PredIsKnownFalse(StartVal, StartExtended)) { 4909 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4910 return None; 4911 } 4912 4913 // The Step is always Signed (because the overflow checks are either 4914 // NSSW or NUSW) 4915 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4916 if (PredIsKnownFalse(Accum, AccumExtended)) { 4917 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4918 return None; 4919 } 4920 4921 auto AppendPredicate = [&](const SCEV *Expr, 4922 const SCEV *ExtendedExpr) -> void { 4923 if (Expr != ExtendedExpr && 4924 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4925 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4926 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4927 Predicates.push_back(Pred); 4928 } 4929 }; 4930 4931 AppendPredicate(StartVal, StartExtended); 4932 AppendPredicate(Accum, AccumExtended); 4933 4934 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4935 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4936 // into NewAR if it will also add the runtime overflow checks specified in 4937 // Predicates. 4938 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4939 4940 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4941 std::make_pair(NewAR, Predicates); 4942 // Remember the result of the analysis for this SCEV at this locayyytion. 4943 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4944 return PredRewrite; 4945 } 4946 4947 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4948 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4949 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4950 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4951 if (!L) 4952 return None; 4953 4954 // Check to see if we already analyzed this PHI. 4955 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4956 if (I != PredicatedSCEVRewrites.end()) { 4957 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4958 I->second; 4959 // Analysis was done before and failed to create an AddRec: 4960 if (Rewrite.first == SymbolicPHI) 4961 return None; 4962 // Analysis was done before and succeeded to create an AddRec under 4963 // a predicate: 4964 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4965 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4966 return Rewrite; 4967 } 4968 4969 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4970 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4971 4972 // Record in the cache that the analysis failed 4973 if (!Rewrite) { 4974 SmallVector<const SCEVPredicate *, 3> Predicates; 4975 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4976 return None; 4977 } 4978 4979 return Rewrite; 4980 } 4981 4982 // FIXME: This utility is currently required because the Rewriter currently 4983 // does not rewrite this expression: 4984 // {0, +, (sext ix (trunc iy to ix) to iy)} 4985 // into {0, +, %step}, 4986 // even when the following Equal predicate exists: 4987 // "%step == (sext ix (trunc iy to ix) to iy)". 4988 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4989 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4990 if (AR1 == AR2) 4991 return true; 4992 4993 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4994 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4995 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4996 return false; 4997 return true; 4998 }; 4999 5000 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5001 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5002 return false; 5003 return true; 5004 } 5005 5006 /// A helper function for createAddRecFromPHI to handle simple cases. 5007 /// 5008 /// This function tries to find an AddRec expression for the simplest (yet most 5009 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5010 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5011 /// technique for finding the AddRec expression. 5012 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5013 Value *BEValueV, 5014 Value *StartValueV) { 5015 const Loop *L = LI.getLoopFor(PN->getParent()); 5016 assert(L && L->getHeader() == PN->getParent()); 5017 assert(BEValueV && StartValueV); 5018 5019 auto BO = MatchBinaryOp(BEValueV, DT); 5020 if (!BO) 5021 return nullptr; 5022 5023 if (BO->Opcode != Instruction::Add) 5024 return nullptr; 5025 5026 const SCEV *Accum = nullptr; 5027 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5028 Accum = getSCEV(BO->RHS); 5029 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5030 Accum = getSCEV(BO->LHS); 5031 5032 if (!Accum) 5033 return nullptr; 5034 5035 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5036 if (BO->IsNUW) 5037 Flags = setFlags(Flags, SCEV::FlagNUW); 5038 if (BO->IsNSW) 5039 Flags = setFlags(Flags, SCEV::FlagNSW); 5040 5041 const SCEV *StartVal = getSCEV(StartValueV); 5042 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5043 5044 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5045 5046 // We can add Flags to the post-inc expression only if we 5047 // know that it is *undefined behavior* for BEValueV to 5048 // overflow. 5049 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5050 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5051 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5052 5053 return PHISCEV; 5054 } 5055 5056 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5057 const Loop *L = LI.getLoopFor(PN->getParent()); 5058 if (!L || L->getHeader() != PN->getParent()) 5059 return nullptr; 5060 5061 // The loop may have multiple entrances or multiple exits; we can analyze 5062 // this phi as an addrec if it has a unique entry value and a unique 5063 // backedge value. 5064 Value *BEValueV = nullptr, *StartValueV = nullptr; 5065 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5066 Value *V = PN->getIncomingValue(i); 5067 if (L->contains(PN->getIncomingBlock(i))) { 5068 if (!BEValueV) { 5069 BEValueV = V; 5070 } else if (BEValueV != V) { 5071 BEValueV = nullptr; 5072 break; 5073 } 5074 } else if (!StartValueV) { 5075 StartValueV = V; 5076 } else if (StartValueV != V) { 5077 StartValueV = nullptr; 5078 break; 5079 } 5080 } 5081 if (!BEValueV || !StartValueV) 5082 return nullptr; 5083 5084 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5085 "PHI node already processed?"); 5086 5087 // First, try to find AddRec expression without creating a fictituos symbolic 5088 // value for PN. 5089 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5090 return S; 5091 5092 // Handle PHI node value symbolically. 5093 const SCEV *SymbolicName = getUnknown(PN); 5094 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5095 5096 // Using this symbolic name for the PHI, analyze the value coming around 5097 // the back-edge. 5098 const SCEV *BEValue = getSCEV(BEValueV); 5099 5100 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5101 // has a special value for the first iteration of the loop. 5102 5103 // If the value coming around the backedge is an add with the symbolic 5104 // value we just inserted, then we found a simple induction variable! 5105 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5106 // If there is a single occurrence of the symbolic value, replace it 5107 // with a recurrence. 5108 unsigned FoundIndex = Add->getNumOperands(); 5109 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5110 if (Add->getOperand(i) == SymbolicName) 5111 if (FoundIndex == e) { 5112 FoundIndex = i; 5113 break; 5114 } 5115 5116 if (FoundIndex != Add->getNumOperands()) { 5117 // Create an add with everything but the specified operand. 5118 SmallVector<const SCEV *, 8> Ops; 5119 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5120 if (i != FoundIndex) 5121 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5122 L, *this)); 5123 const SCEV *Accum = getAddExpr(Ops); 5124 5125 // This is not a valid addrec if the step amount is varying each 5126 // loop iteration, but is not itself an addrec in this loop. 5127 if (isLoopInvariant(Accum, L) || 5128 (isa<SCEVAddRecExpr>(Accum) && 5129 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5130 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5131 5132 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5133 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5134 if (BO->IsNUW) 5135 Flags = setFlags(Flags, SCEV::FlagNUW); 5136 if (BO->IsNSW) 5137 Flags = setFlags(Flags, SCEV::FlagNSW); 5138 } 5139 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5140 // If the increment is an inbounds GEP, then we know the address 5141 // space cannot be wrapped around. We cannot make any guarantee 5142 // about signed or unsigned overflow because pointers are 5143 // unsigned but we may have a negative index from the base 5144 // pointer. We can guarantee that no unsigned wrap occurs if the 5145 // indices form a positive value. 5146 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5147 Flags = setFlags(Flags, SCEV::FlagNW); 5148 5149 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5150 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5151 Flags = setFlags(Flags, SCEV::FlagNUW); 5152 } 5153 5154 // We cannot transfer nuw and nsw flags from subtraction 5155 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5156 // for instance. 5157 } 5158 5159 const SCEV *StartVal = getSCEV(StartValueV); 5160 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5161 5162 // Okay, for the entire analysis of this edge we assumed the PHI 5163 // to be symbolic. We now need to go back and purge all of the 5164 // entries for the scalars that use the symbolic expression. 5165 forgetSymbolicName(PN, SymbolicName); 5166 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5167 5168 // We can add Flags to the post-inc expression only if we 5169 // know that it is *undefined behavior* for BEValueV to 5170 // overflow. 5171 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5172 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5173 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5174 5175 return PHISCEV; 5176 } 5177 } 5178 } else { 5179 // Otherwise, this could be a loop like this: 5180 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5181 // In this case, j = {1,+,1} and BEValue is j. 5182 // Because the other in-value of i (0) fits the evolution of BEValue 5183 // i really is an addrec evolution. 5184 // 5185 // We can generalize this saying that i is the shifted value of BEValue 5186 // by one iteration: 5187 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5188 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5189 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5190 if (Shifted != getCouldNotCompute() && 5191 Start != getCouldNotCompute()) { 5192 const SCEV *StartVal = getSCEV(StartValueV); 5193 if (Start == StartVal) { 5194 // Okay, for the entire analysis of this edge we assumed the PHI 5195 // to be symbolic. We now need to go back and purge all of the 5196 // entries for the scalars that use the symbolic expression. 5197 forgetSymbolicName(PN, SymbolicName); 5198 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5199 return Shifted; 5200 } 5201 } 5202 } 5203 5204 // Remove the temporary PHI node SCEV that has been inserted while intending 5205 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5206 // as it will prevent later (possibly simpler) SCEV expressions to be added 5207 // to the ValueExprMap. 5208 eraseValueFromMap(PN); 5209 5210 return nullptr; 5211 } 5212 5213 // Checks if the SCEV S is available at BB. S is considered available at BB 5214 // if S can be materialized at BB without introducing a fault. 5215 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5216 BasicBlock *BB) { 5217 struct CheckAvailable { 5218 bool TraversalDone = false; 5219 bool Available = true; 5220 5221 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5222 BasicBlock *BB = nullptr; 5223 DominatorTree &DT; 5224 5225 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5226 : L(L), BB(BB), DT(DT) {} 5227 5228 bool setUnavailable() { 5229 TraversalDone = true; 5230 Available = false; 5231 return false; 5232 } 5233 5234 bool follow(const SCEV *S) { 5235 switch (S->getSCEVType()) { 5236 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5237 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5238 case scUMinExpr: 5239 case scSMinExpr: 5240 // These expressions are available if their operand(s) is/are. 5241 return true; 5242 5243 case scAddRecExpr: { 5244 // We allow add recurrences that are on the loop BB is in, or some 5245 // outer loop. This guarantees availability because the value of the 5246 // add recurrence at BB is simply the "current" value of the induction 5247 // variable. We can relax this in the future; for instance an add 5248 // recurrence on a sibling dominating loop is also available at BB. 5249 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5250 if (L && (ARLoop == L || ARLoop->contains(L))) 5251 return true; 5252 5253 return setUnavailable(); 5254 } 5255 5256 case scUnknown: { 5257 // For SCEVUnknown, we check for simple dominance. 5258 const auto *SU = cast<SCEVUnknown>(S); 5259 Value *V = SU->getValue(); 5260 5261 if (isa<Argument>(V)) 5262 return false; 5263 5264 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5265 return false; 5266 5267 return setUnavailable(); 5268 } 5269 5270 case scUDivExpr: 5271 case scCouldNotCompute: 5272 // We do not try to smart about these at all. 5273 return setUnavailable(); 5274 } 5275 llvm_unreachable("switch should be fully covered!"); 5276 } 5277 5278 bool isDone() { return TraversalDone; } 5279 }; 5280 5281 CheckAvailable CA(L, BB, DT); 5282 SCEVTraversal<CheckAvailable> ST(CA); 5283 5284 ST.visitAll(S); 5285 return CA.Available; 5286 } 5287 5288 // Try to match a control flow sequence that branches out at BI and merges back 5289 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5290 // match. 5291 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5292 Value *&C, Value *&LHS, Value *&RHS) { 5293 C = BI->getCondition(); 5294 5295 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5296 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5297 5298 if (!LeftEdge.isSingleEdge()) 5299 return false; 5300 5301 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5302 5303 Use &LeftUse = Merge->getOperandUse(0); 5304 Use &RightUse = Merge->getOperandUse(1); 5305 5306 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5307 LHS = LeftUse; 5308 RHS = RightUse; 5309 return true; 5310 } 5311 5312 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5313 LHS = RightUse; 5314 RHS = LeftUse; 5315 return true; 5316 } 5317 5318 return false; 5319 } 5320 5321 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5322 auto IsReachable = 5323 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5324 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5325 const Loop *L = LI.getLoopFor(PN->getParent()); 5326 5327 // We don't want to break LCSSA, even in a SCEV expression tree. 5328 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5329 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5330 return nullptr; 5331 5332 // Try to match 5333 // 5334 // br %cond, label %left, label %right 5335 // left: 5336 // br label %merge 5337 // right: 5338 // br label %merge 5339 // merge: 5340 // V = phi [ %x, %left ], [ %y, %right ] 5341 // 5342 // as "select %cond, %x, %y" 5343 5344 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5345 assert(IDom && "At least the entry block should dominate PN"); 5346 5347 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5348 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5349 5350 if (BI && BI->isConditional() && 5351 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5352 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5353 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5354 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5355 } 5356 5357 return nullptr; 5358 } 5359 5360 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5361 if (const SCEV *S = createAddRecFromPHI(PN)) 5362 return S; 5363 5364 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5365 return S; 5366 5367 // If the PHI has a single incoming value, follow that value, unless the 5368 // PHI's incoming blocks are in a different loop, in which case doing so 5369 // risks breaking LCSSA form. Instcombine would normally zap these, but 5370 // it doesn't have DominatorTree information, so it may miss cases. 5371 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5372 if (LI.replacementPreservesLCSSAForm(PN, V)) 5373 return getSCEV(V); 5374 5375 // If it's not a loop phi, we can't handle it yet. 5376 return getUnknown(PN); 5377 } 5378 5379 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5380 Value *Cond, 5381 Value *TrueVal, 5382 Value *FalseVal) { 5383 // Handle "constant" branch or select. This can occur for instance when a 5384 // loop pass transforms an inner loop and moves on to process the outer loop. 5385 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5386 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5387 5388 // Try to match some simple smax or umax patterns. 5389 auto *ICI = dyn_cast<ICmpInst>(Cond); 5390 if (!ICI) 5391 return getUnknown(I); 5392 5393 Value *LHS = ICI->getOperand(0); 5394 Value *RHS = ICI->getOperand(1); 5395 5396 switch (ICI->getPredicate()) { 5397 case ICmpInst::ICMP_SLT: 5398 case ICmpInst::ICMP_SLE: 5399 std::swap(LHS, RHS); 5400 LLVM_FALLTHROUGH; 5401 case ICmpInst::ICMP_SGT: 5402 case ICmpInst::ICMP_SGE: 5403 // a >s b ? a+x : b+x -> smax(a, b)+x 5404 // a >s b ? b+x : a+x -> smin(a, b)+x 5405 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5406 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5407 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5408 const SCEV *LA = getSCEV(TrueVal); 5409 const SCEV *RA = getSCEV(FalseVal); 5410 const SCEV *LDiff = getMinusSCEV(LA, LS); 5411 const SCEV *RDiff = getMinusSCEV(RA, RS); 5412 if (LDiff == RDiff) 5413 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5414 LDiff = getMinusSCEV(LA, RS); 5415 RDiff = getMinusSCEV(RA, LS); 5416 if (LDiff == RDiff) 5417 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5418 } 5419 break; 5420 case ICmpInst::ICMP_ULT: 5421 case ICmpInst::ICMP_ULE: 5422 std::swap(LHS, RHS); 5423 LLVM_FALLTHROUGH; 5424 case ICmpInst::ICMP_UGT: 5425 case ICmpInst::ICMP_UGE: 5426 // a >u b ? a+x : b+x -> umax(a, b)+x 5427 // a >u b ? b+x : a+x -> umin(a, b)+x 5428 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5429 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5430 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5431 const SCEV *LA = getSCEV(TrueVal); 5432 const SCEV *RA = getSCEV(FalseVal); 5433 const SCEV *LDiff = getMinusSCEV(LA, LS); 5434 const SCEV *RDiff = getMinusSCEV(RA, RS); 5435 if (LDiff == RDiff) 5436 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5437 LDiff = getMinusSCEV(LA, RS); 5438 RDiff = getMinusSCEV(RA, LS); 5439 if (LDiff == RDiff) 5440 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5441 } 5442 break; 5443 case ICmpInst::ICMP_NE: 5444 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5445 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5446 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5447 const SCEV *One = getOne(I->getType()); 5448 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5449 const SCEV *LA = getSCEV(TrueVal); 5450 const SCEV *RA = getSCEV(FalseVal); 5451 const SCEV *LDiff = getMinusSCEV(LA, LS); 5452 const SCEV *RDiff = getMinusSCEV(RA, One); 5453 if (LDiff == RDiff) 5454 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5455 } 5456 break; 5457 case ICmpInst::ICMP_EQ: 5458 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5459 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5460 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5461 const SCEV *One = getOne(I->getType()); 5462 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5463 const SCEV *LA = getSCEV(TrueVal); 5464 const SCEV *RA = getSCEV(FalseVal); 5465 const SCEV *LDiff = getMinusSCEV(LA, One); 5466 const SCEV *RDiff = getMinusSCEV(RA, LS); 5467 if (LDiff == RDiff) 5468 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5469 } 5470 break; 5471 default: 5472 break; 5473 } 5474 5475 return getUnknown(I); 5476 } 5477 5478 /// Expand GEP instructions into add and multiply operations. This allows them 5479 /// to be analyzed by regular SCEV code. 5480 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5481 // Don't attempt to analyze GEPs over unsized objects. 5482 if (!GEP->getSourceElementType()->isSized()) 5483 return getUnknown(GEP); 5484 5485 SmallVector<const SCEV *, 4> IndexExprs; 5486 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5487 IndexExprs.push_back(getSCEV(*Index)); 5488 return getGEPExpr(GEP, IndexExprs); 5489 } 5490 5491 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5492 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5493 return C->getAPInt().countTrailingZeros(); 5494 5495 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5496 return std::min(GetMinTrailingZeros(T->getOperand()), 5497 (uint32_t)getTypeSizeInBits(T->getType())); 5498 5499 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5500 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5501 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5502 ? getTypeSizeInBits(E->getType()) 5503 : OpRes; 5504 } 5505 5506 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5507 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5508 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5509 ? getTypeSizeInBits(E->getType()) 5510 : OpRes; 5511 } 5512 5513 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5514 // The result is the min of all operands results. 5515 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5516 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5517 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5518 return MinOpRes; 5519 } 5520 5521 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5522 // The result is the sum of all operands results. 5523 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5524 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5525 for (unsigned i = 1, e = M->getNumOperands(); 5526 SumOpRes != BitWidth && i != e; ++i) 5527 SumOpRes = 5528 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5529 return SumOpRes; 5530 } 5531 5532 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5533 // The result is the min of all operands results. 5534 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5535 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5536 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5537 return MinOpRes; 5538 } 5539 5540 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5541 // The result is the min of all operands results. 5542 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5543 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5544 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5545 return MinOpRes; 5546 } 5547 5548 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5549 // The result is the min of all operands results. 5550 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5551 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5552 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5553 return MinOpRes; 5554 } 5555 5556 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5557 // For a SCEVUnknown, ask ValueTracking. 5558 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5559 return Known.countMinTrailingZeros(); 5560 } 5561 5562 // SCEVUDivExpr 5563 return 0; 5564 } 5565 5566 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5567 auto I = MinTrailingZerosCache.find(S); 5568 if (I != MinTrailingZerosCache.end()) 5569 return I->second; 5570 5571 uint32_t Result = GetMinTrailingZerosImpl(S); 5572 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5573 assert(InsertPair.second && "Should insert a new key"); 5574 return InsertPair.first->second; 5575 } 5576 5577 /// Helper method to assign a range to V from metadata present in the IR. 5578 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5579 if (Instruction *I = dyn_cast<Instruction>(V)) 5580 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5581 return getConstantRangeFromMetadata(*MD); 5582 5583 return None; 5584 } 5585 5586 /// Determine the range for a particular SCEV. If SignHint is 5587 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5588 /// with a "cleaner" unsigned (resp. signed) representation. 5589 const ConstantRange & 5590 ScalarEvolution::getRangeRef(const SCEV *S, 5591 ScalarEvolution::RangeSignHint SignHint) { 5592 DenseMap<const SCEV *, ConstantRange> &Cache = 5593 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5594 : SignedRanges; 5595 ConstantRange::PreferredRangeType RangeType = 5596 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5597 ? ConstantRange::Unsigned : ConstantRange::Signed; 5598 5599 // See if we've computed this range already. 5600 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5601 if (I != Cache.end()) 5602 return I->second; 5603 5604 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5605 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5606 5607 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5608 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5609 using OBO = OverflowingBinaryOperator; 5610 5611 // If the value has known zeros, the maximum value will have those known zeros 5612 // as well. 5613 uint32_t TZ = GetMinTrailingZeros(S); 5614 if (TZ != 0) { 5615 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5616 ConservativeResult = 5617 ConstantRange(APInt::getMinValue(BitWidth), 5618 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5619 else 5620 ConservativeResult = ConstantRange( 5621 APInt::getSignedMinValue(BitWidth), 5622 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5623 } 5624 5625 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5626 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5627 unsigned WrapType = OBO::AnyWrap; 5628 if (Add->hasNoSignedWrap()) 5629 WrapType |= OBO::NoSignedWrap; 5630 if (Add->hasNoUnsignedWrap()) 5631 WrapType |= OBO::NoUnsignedWrap; 5632 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5633 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5634 WrapType, RangeType); 5635 return setRange(Add, SignHint, 5636 ConservativeResult.intersectWith(X, RangeType)); 5637 } 5638 5639 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5640 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5641 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5642 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5643 return setRange(Mul, SignHint, 5644 ConservativeResult.intersectWith(X, RangeType)); 5645 } 5646 5647 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5648 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5649 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5650 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5651 return setRange(SMax, SignHint, 5652 ConservativeResult.intersectWith(X, RangeType)); 5653 } 5654 5655 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5656 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5657 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5658 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5659 return setRange(UMax, SignHint, 5660 ConservativeResult.intersectWith(X, RangeType)); 5661 } 5662 5663 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5664 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5665 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5666 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5667 return setRange(SMin, SignHint, 5668 ConservativeResult.intersectWith(X, RangeType)); 5669 } 5670 5671 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5672 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5673 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5674 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5675 return setRange(UMin, SignHint, 5676 ConservativeResult.intersectWith(X, RangeType)); 5677 } 5678 5679 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5680 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5681 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5682 return setRange(UDiv, SignHint, 5683 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5684 } 5685 5686 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5687 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5688 return setRange(ZExt, SignHint, 5689 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5690 RangeType)); 5691 } 5692 5693 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5694 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5695 return setRange(SExt, SignHint, 5696 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5697 RangeType)); 5698 } 5699 5700 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5701 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5702 return setRange(Trunc, SignHint, 5703 ConservativeResult.intersectWith(X.truncate(BitWidth), 5704 RangeType)); 5705 } 5706 5707 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5708 // If there's no unsigned wrap, the value will never be less than its 5709 // initial value. 5710 if (AddRec->hasNoUnsignedWrap()) { 5711 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5712 if (!UnsignedMinValue.isNullValue()) 5713 ConservativeResult = ConservativeResult.intersectWith( 5714 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5715 } 5716 5717 // If there's no signed wrap, and all the operands except initial value have 5718 // the same sign or zero, the value won't ever be: 5719 // 1: smaller than initial value if operands are non negative, 5720 // 2: bigger than initial value if operands are non positive. 5721 // For both cases, value can not cross signed min/max boundary. 5722 if (AddRec->hasNoSignedWrap()) { 5723 bool AllNonNeg = true; 5724 bool AllNonPos = true; 5725 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5726 if (!isKnownNonNegative(AddRec->getOperand(i))) 5727 AllNonNeg = false; 5728 if (!isKnownNonPositive(AddRec->getOperand(i))) 5729 AllNonPos = false; 5730 } 5731 if (AllNonNeg) 5732 ConservativeResult = ConservativeResult.intersectWith( 5733 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5734 APInt::getSignedMinValue(BitWidth)), 5735 RangeType); 5736 else if (AllNonPos) 5737 ConservativeResult = ConservativeResult.intersectWith( 5738 ConstantRange::getNonEmpty( 5739 APInt::getSignedMinValue(BitWidth), 5740 getSignedRangeMax(AddRec->getStart()) + 1), 5741 RangeType); 5742 } 5743 5744 // TODO: non-affine addrec 5745 if (AddRec->isAffine()) { 5746 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5747 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5748 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5749 auto RangeFromAffine = getRangeForAffineAR( 5750 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5751 BitWidth); 5752 if (!RangeFromAffine.isFullSet()) 5753 ConservativeResult = 5754 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5755 5756 auto RangeFromFactoring = getRangeViaFactoring( 5757 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5758 BitWidth); 5759 if (!RangeFromFactoring.isFullSet()) 5760 ConservativeResult = 5761 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5762 } 5763 } 5764 5765 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5766 } 5767 5768 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5769 // Check if the IR explicitly contains !range metadata. 5770 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5771 if (MDRange.hasValue()) 5772 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5773 RangeType); 5774 5775 // Split here to avoid paying the compile-time cost of calling both 5776 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5777 // if needed. 5778 const DataLayout &DL = getDataLayout(); 5779 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5780 // For a SCEVUnknown, ask ValueTracking. 5781 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5782 if (Known.getBitWidth() != BitWidth) 5783 Known = Known.zextOrTrunc(BitWidth); 5784 // If Known does not result in full-set, intersect with it. 5785 if (Known.getMinValue() != Known.getMaxValue() + 1) 5786 ConservativeResult = ConservativeResult.intersectWith( 5787 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5788 RangeType); 5789 } else { 5790 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5791 "generalize as needed!"); 5792 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5793 // If the pointer size is larger than the index size type, this can cause 5794 // NS to be larger than BitWidth. So compensate for this. 5795 if (U->getType()->isPointerTy()) { 5796 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5797 int ptrIdxDiff = ptrSize - BitWidth; 5798 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5799 NS -= ptrIdxDiff; 5800 } 5801 5802 if (NS > 1) 5803 ConservativeResult = ConservativeResult.intersectWith( 5804 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5805 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5806 RangeType); 5807 } 5808 5809 // A range of Phi is a subset of union of all ranges of its input. 5810 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5811 // Make sure that we do not run over cycled Phis. 5812 if (PendingPhiRanges.insert(Phi).second) { 5813 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5814 for (auto &Op : Phi->operands()) { 5815 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5816 RangeFromOps = RangeFromOps.unionWith(OpRange); 5817 // No point to continue if we already have a full set. 5818 if (RangeFromOps.isFullSet()) 5819 break; 5820 } 5821 ConservativeResult = 5822 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5823 bool Erased = PendingPhiRanges.erase(Phi); 5824 assert(Erased && "Failed to erase Phi properly?"); 5825 (void) Erased; 5826 } 5827 } 5828 5829 return setRange(U, SignHint, std::move(ConservativeResult)); 5830 } 5831 5832 return setRange(S, SignHint, std::move(ConservativeResult)); 5833 } 5834 5835 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5836 // values that the expression can take. Initially, the expression has a value 5837 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5838 // argument defines if we treat Step as signed or unsigned. 5839 static ConstantRange getRangeForAffineARHelper(APInt Step, 5840 const ConstantRange &StartRange, 5841 const APInt &MaxBECount, 5842 unsigned BitWidth, bool Signed) { 5843 // If either Step or MaxBECount is 0, then the expression won't change, and we 5844 // just need to return the initial range. 5845 if (Step == 0 || MaxBECount == 0) 5846 return StartRange; 5847 5848 // If we don't know anything about the initial value (i.e. StartRange is 5849 // FullRange), then we don't know anything about the final range either. 5850 // Return FullRange. 5851 if (StartRange.isFullSet()) 5852 return ConstantRange::getFull(BitWidth); 5853 5854 // If Step is signed and negative, then we use its absolute value, but we also 5855 // note that we're moving in the opposite direction. 5856 bool Descending = Signed && Step.isNegative(); 5857 5858 if (Signed) 5859 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5860 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5861 // This equations hold true due to the well-defined wrap-around behavior of 5862 // APInt. 5863 Step = Step.abs(); 5864 5865 // Check if Offset is more than full span of BitWidth. If it is, the 5866 // expression is guaranteed to overflow. 5867 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5868 return ConstantRange::getFull(BitWidth); 5869 5870 // Offset is by how much the expression can change. Checks above guarantee no 5871 // overflow here. 5872 APInt Offset = Step * MaxBECount; 5873 5874 // Minimum value of the final range will match the minimal value of StartRange 5875 // if the expression is increasing and will be decreased by Offset otherwise. 5876 // Maximum value of the final range will match the maximal value of StartRange 5877 // if the expression is decreasing and will be increased by Offset otherwise. 5878 APInt StartLower = StartRange.getLower(); 5879 APInt StartUpper = StartRange.getUpper() - 1; 5880 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5881 : (StartUpper + std::move(Offset)); 5882 5883 // It's possible that the new minimum/maximum value will fall into the initial 5884 // range (due to wrap around). This means that the expression can take any 5885 // value in this bitwidth, and we have to return full range. 5886 if (StartRange.contains(MovedBoundary)) 5887 return ConstantRange::getFull(BitWidth); 5888 5889 APInt NewLower = 5890 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5891 APInt NewUpper = 5892 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5893 NewUpper += 1; 5894 5895 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5896 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5897 } 5898 5899 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5900 const SCEV *Step, 5901 const SCEV *MaxBECount, 5902 unsigned BitWidth) { 5903 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5904 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5905 "Precondition!"); 5906 5907 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5908 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5909 5910 // First, consider step signed. 5911 ConstantRange StartSRange = getSignedRange(Start); 5912 ConstantRange StepSRange = getSignedRange(Step); 5913 5914 // If Step can be both positive and negative, we need to find ranges for the 5915 // maximum absolute step values in both directions and union them. 5916 ConstantRange SR = 5917 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5918 MaxBECountValue, BitWidth, /* Signed = */ true); 5919 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5920 StartSRange, MaxBECountValue, 5921 BitWidth, /* Signed = */ true)); 5922 5923 // Next, consider step unsigned. 5924 ConstantRange UR = getRangeForAffineARHelper( 5925 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5926 MaxBECountValue, BitWidth, /* Signed = */ false); 5927 5928 // Finally, intersect signed and unsigned ranges. 5929 return SR.intersectWith(UR, ConstantRange::Smallest); 5930 } 5931 5932 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5933 const SCEV *Step, 5934 const SCEV *MaxBECount, 5935 unsigned BitWidth) { 5936 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5937 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5938 5939 struct SelectPattern { 5940 Value *Condition = nullptr; 5941 APInt TrueValue; 5942 APInt FalseValue; 5943 5944 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5945 const SCEV *S) { 5946 Optional<unsigned> CastOp; 5947 APInt Offset(BitWidth, 0); 5948 5949 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5950 "Should be!"); 5951 5952 // Peel off a constant offset: 5953 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5954 // In the future we could consider being smarter here and handle 5955 // {Start+Step,+,Step} too. 5956 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5957 return; 5958 5959 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5960 S = SA->getOperand(1); 5961 } 5962 5963 // Peel off a cast operation 5964 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5965 CastOp = SCast->getSCEVType(); 5966 S = SCast->getOperand(); 5967 } 5968 5969 using namespace llvm::PatternMatch; 5970 5971 auto *SU = dyn_cast<SCEVUnknown>(S); 5972 const APInt *TrueVal, *FalseVal; 5973 if (!SU || 5974 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5975 m_APInt(FalseVal)))) { 5976 Condition = nullptr; 5977 return; 5978 } 5979 5980 TrueValue = *TrueVal; 5981 FalseValue = *FalseVal; 5982 5983 // Re-apply the cast we peeled off earlier 5984 if (CastOp.hasValue()) 5985 switch (*CastOp) { 5986 default: 5987 llvm_unreachable("Unknown SCEV cast type!"); 5988 5989 case scTruncate: 5990 TrueValue = TrueValue.trunc(BitWidth); 5991 FalseValue = FalseValue.trunc(BitWidth); 5992 break; 5993 case scZeroExtend: 5994 TrueValue = TrueValue.zext(BitWidth); 5995 FalseValue = FalseValue.zext(BitWidth); 5996 break; 5997 case scSignExtend: 5998 TrueValue = TrueValue.sext(BitWidth); 5999 FalseValue = FalseValue.sext(BitWidth); 6000 break; 6001 } 6002 6003 // Re-apply the constant offset we peeled off earlier 6004 TrueValue += Offset; 6005 FalseValue += Offset; 6006 } 6007 6008 bool isRecognized() { return Condition != nullptr; } 6009 }; 6010 6011 SelectPattern StartPattern(*this, BitWidth, Start); 6012 if (!StartPattern.isRecognized()) 6013 return ConstantRange::getFull(BitWidth); 6014 6015 SelectPattern StepPattern(*this, BitWidth, Step); 6016 if (!StepPattern.isRecognized()) 6017 return ConstantRange::getFull(BitWidth); 6018 6019 if (StartPattern.Condition != StepPattern.Condition) { 6020 // We don't handle this case today; but we could, by considering four 6021 // possibilities below instead of two. I'm not sure if there are cases where 6022 // that will help over what getRange already does, though. 6023 return ConstantRange::getFull(BitWidth); 6024 } 6025 6026 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6027 // construct arbitrary general SCEV expressions here. This function is called 6028 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6029 // say) can end up caching a suboptimal value. 6030 6031 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6032 // C2352 and C2512 (otherwise it isn't needed). 6033 6034 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6035 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6036 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6037 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6038 6039 ConstantRange TrueRange = 6040 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6041 ConstantRange FalseRange = 6042 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6043 6044 return TrueRange.unionWith(FalseRange); 6045 } 6046 6047 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6048 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6049 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6050 6051 // Return early if there are no flags to propagate to the SCEV. 6052 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6053 if (BinOp->hasNoUnsignedWrap()) 6054 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6055 if (BinOp->hasNoSignedWrap()) 6056 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6057 if (Flags == SCEV::FlagAnyWrap) 6058 return SCEV::FlagAnyWrap; 6059 6060 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6061 } 6062 6063 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6064 // Here we check that I is in the header of the innermost loop containing I, 6065 // since we only deal with instructions in the loop header. The actual loop we 6066 // need to check later will come from an add recurrence, but getting that 6067 // requires computing the SCEV of the operands, which can be expensive. This 6068 // check we can do cheaply to rule out some cases early. 6069 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6070 if (InnermostContainingLoop == nullptr || 6071 InnermostContainingLoop->getHeader() != I->getParent()) 6072 return false; 6073 6074 // Only proceed if we can prove that I does not yield poison. 6075 if (!programUndefinedIfPoison(I)) 6076 return false; 6077 6078 // At this point we know that if I is executed, then it does not wrap 6079 // according to at least one of NSW or NUW. If I is not executed, then we do 6080 // not know if the calculation that I represents would wrap. Multiple 6081 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6082 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6083 // derived from other instructions that map to the same SCEV. We cannot make 6084 // that guarantee for cases where I is not executed. So we need to find the 6085 // loop that I is considered in relation to and prove that I is executed for 6086 // every iteration of that loop. That implies that the value that I 6087 // calculates does not wrap anywhere in the loop, so then we can apply the 6088 // flags to the SCEV. 6089 // 6090 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6091 // from different loops, so that we know which loop to prove that I is 6092 // executed in. 6093 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6094 // I could be an extractvalue from a call to an overflow intrinsic. 6095 // TODO: We can do better here in some cases. 6096 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6097 return false; 6098 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6099 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6100 bool AllOtherOpsLoopInvariant = true; 6101 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6102 ++OtherOpIndex) { 6103 if (OtherOpIndex != OpIndex) { 6104 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6105 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6106 AllOtherOpsLoopInvariant = false; 6107 break; 6108 } 6109 } 6110 } 6111 if (AllOtherOpsLoopInvariant && 6112 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6113 return true; 6114 } 6115 } 6116 return false; 6117 } 6118 6119 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6120 // If we know that \c I can never be poison period, then that's enough. 6121 if (isSCEVExprNeverPoison(I)) 6122 return true; 6123 6124 // For an add recurrence specifically, we assume that infinite loops without 6125 // side effects are undefined behavior, and then reason as follows: 6126 // 6127 // If the add recurrence is poison in any iteration, it is poison on all 6128 // future iterations (since incrementing poison yields poison). If the result 6129 // of the add recurrence is fed into the loop latch condition and the loop 6130 // does not contain any throws or exiting blocks other than the latch, we now 6131 // have the ability to "choose" whether the backedge is taken or not (by 6132 // choosing a sufficiently evil value for the poison feeding into the branch) 6133 // for every iteration including and after the one in which \p I first became 6134 // poison. There are two possibilities (let's call the iteration in which \p 6135 // I first became poison as K): 6136 // 6137 // 1. In the set of iterations including and after K, the loop body executes 6138 // no side effects. In this case executing the backege an infinte number 6139 // of times will yield undefined behavior. 6140 // 6141 // 2. In the set of iterations including and after K, the loop body executes 6142 // at least one side effect. In this case, that specific instance of side 6143 // effect is control dependent on poison, which also yields undefined 6144 // behavior. 6145 6146 auto *ExitingBB = L->getExitingBlock(); 6147 auto *LatchBB = L->getLoopLatch(); 6148 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6149 return false; 6150 6151 SmallPtrSet<const Instruction *, 16> Pushed; 6152 SmallVector<const Instruction *, 8> PoisonStack; 6153 6154 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6155 // things that are known to be poison under that assumption go on the 6156 // PoisonStack. 6157 Pushed.insert(I); 6158 PoisonStack.push_back(I); 6159 6160 bool LatchControlDependentOnPoison = false; 6161 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6162 const Instruction *Poison = PoisonStack.pop_back_val(); 6163 6164 for (auto *PoisonUser : Poison->users()) { 6165 if (propagatesPoison(cast<Instruction>(PoisonUser))) { 6166 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6167 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6168 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6169 assert(BI->isConditional() && "Only possibility!"); 6170 if (BI->getParent() == LatchBB) { 6171 LatchControlDependentOnPoison = true; 6172 break; 6173 } 6174 } 6175 } 6176 } 6177 6178 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6179 } 6180 6181 ScalarEvolution::LoopProperties 6182 ScalarEvolution::getLoopProperties(const Loop *L) { 6183 using LoopProperties = ScalarEvolution::LoopProperties; 6184 6185 auto Itr = LoopPropertiesCache.find(L); 6186 if (Itr == LoopPropertiesCache.end()) { 6187 auto HasSideEffects = [](Instruction *I) { 6188 if (auto *SI = dyn_cast<StoreInst>(I)) 6189 return !SI->isSimple(); 6190 6191 return I->mayHaveSideEffects(); 6192 }; 6193 6194 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6195 /*HasNoSideEffects*/ true}; 6196 6197 for (auto *BB : L->getBlocks()) 6198 for (auto &I : *BB) { 6199 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6200 LP.HasNoAbnormalExits = false; 6201 if (HasSideEffects(&I)) 6202 LP.HasNoSideEffects = false; 6203 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6204 break; // We're already as pessimistic as we can get. 6205 } 6206 6207 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6208 assert(InsertPair.second && "We just checked!"); 6209 Itr = InsertPair.first; 6210 } 6211 6212 return Itr->second; 6213 } 6214 6215 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6216 if (!isSCEVable(V->getType())) 6217 return getUnknown(V); 6218 6219 if (Instruction *I = dyn_cast<Instruction>(V)) { 6220 // Don't attempt to analyze instructions in blocks that aren't 6221 // reachable. Such instructions don't matter, and they aren't required 6222 // to obey basic rules for definitions dominating uses which this 6223 // analysis depends on. 6224 if (!DT.isReachableFromEntry(I->getParent())) 6225 return getUnknown(UndefValue::get(V->getType())); 6226 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6227 return getConstant(CI); 6228 else if (isa<ConstantPointerNull>(V)) 6229 return getZero(V->getType()); 6230 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6231 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6232 else if (!isa<ConstantExpr>(V)) 6233 return getUnknown(V); 6234 6235 Operator *U = cast<Operator>(V); 6236 if (auto BO = MatchBinaryOp(U, DT)) { 6237 switch (BO->Opcode) { 6238 case Instruction::Add: { 6239 // The simple thing to do would be to just call getSCEV on both operands 6240 // and call getAddExpr with the result. However if we're looking at a 6241 // bunch of things all added together, this can be quite inefficient, 6242 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6243 // Instead, gather up all the operands and make a single getAddExpr call. 6244 // LLVM IR canonical form means we need only traverse the left operands. 6245 SmallVector<const SCEV *, 4> AddOps; 6246 do { 6247 if (BO->Op) { 6248 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6249 AddOps.push_back(OpSCEV); 6250 break; 6251 } 6252 6253 // If a NUW or NSW flag can be applied to the SCEV for this 6254 // addition, then compute the SCEV for this addition by itself 6255 // with a separate call to getAddExpr. We need to do that 6256 // instead of pushing the operands of the addition onto AddOps, 6257 // since the flags are only known to apply to this particular 6258 // addition - they may not apply to other additions that can be 6259 // formed with operands from AddOps. 6260 const SCEV *RHS = getSCEV(BO->RHS); 6261 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6262 if (Flags != SCEV::FlagAnyWrap) { 6263 const SCEV *LHS = getSCEV(BO->LHS); 6264 if (BO->Opcode == Instruction::Sub) 6265 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6266 else 6267 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6268 break; 6269 } 6270 } 6271 6272 if (BO->Opcode == Instruction::Sub) 6273 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6274 else 6275 AddOps.push_back(getSCEV(BO->RHS)); 6276 6277 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6278 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6279 NewBO->Opcode != Instruction::Sub)) { 6280 AddOps.push_back(getSCEV(BO->LHS)); 6281 break; 6282 } 6283 BO = NewBO; 6284 } while (true); 6285 6286 return getAddExpr(AddOps); 6287 } 6288 6289 case Instruction::Mul: { 6290 SmallVector<const SCEV *, 4> MulOps; 6291 do { 6292 if (BO->Op) { 6293 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6294 MulOps.push_back(OpSCEV); 6295 break; 6296 } 6297 6298 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6299 if (Flags != SCEV::FlagAnyWrap) { 6300 MulOps.push_back( 6301 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6302 break; 6303 } 6304 } 6305 6306 MulOps.push_back(getSCEV(BO->RHS)); 6307 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6308 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6309 MulOps.push_back(getSCEV(BO->LHS)); 6310 break; 6311 } 6312 BO = NewBO; 6313 } while (true); 6314 6315 return getMulExpr(MulOps); 6316 } 6317 case Instruction::UDiv: 6318 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6319 case Instruction::URem: 6320 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6321 case Instruction::Sub: { 6322 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6323 if (BO->Op) 6324 Flags = getNoWrapFlagsFromUB(BO->Op); 6325 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6326 } 6327 case Instruction::And: 6328 // For an expression like x&255 that merely masks off the high bits, 6329 // use zext(trunc(x)) as the SCEV expression. 6330 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6331 if (CI->isZero()) 6332 return getSCEV(BO->RHS); 6333 if (CI->isMinusOne()) 6334 return getSCEV(BO->LHS); 6335 const APInt &A = CI->getValue(); 6336 6337 // Instcombine's ShrinkDemandedConstant may strip bits out of 6338 // constants, obscuring what would otherwise be a low-bits mask. 6339 // Use computeKnownBits to compute what ShrinkDemandedConstant 6340 // knew about to reconstruct a low-bits mask value. 6341 unsigned LZ = A.countLeadingZeros(); 6342 unsigned TZ = A.countTrailingZeros(); 6343 unsigned BitWidth = A.getBitWidth(); 6344 KnownBits Known(BitWidth); 6345 computeKnownBits(BO->LHS, Known, getDataLayout(), 6346 0, &AC, nullptr, &DT); 6347 6348 APInt EffectiveMask = 6349 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6350 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6351 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6352 const SCEV *LHS = getSCEV(BO->LHS); 6353 const SCEV *ShiftedLHS = nullptr; 6354 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6355 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6356 // For an expression like (x * 8) & 8, simplify the multiply. 6357 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6358 unsigned GCD = std::min(MulZeros, TZ); 6359 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6360 SmallVector<const SCEV*, 4> MulOps; 6361 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6362 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6363 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6364 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6365 } 6366 } 6367 if (!ShiftedLHS) 6368 ShiftedLHS = getUDivExpr(LHS, MulCount); 6369 return getMulExpr( 6370 getZeroExtendExpr( 6371 getTruncateExpr(ShiftedLHS, 6372 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6373 BO->LHS->getType()), 6374 MulCount); 6375 } 6376 } 6377 break; 6378 6379 case Instruction::Or: 6380 // If the RHS of the Or is a constant, we may have something like: 6381 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6382 // optimizations will transparently handle this case. 6383 // 6384 // In order for this transformation to be safe, the LHS must be of the 6385 // form X*(2^n) and the Or constant must be less than 2^n. 6386 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6387 const SCEV *LHS = getSCEV(BO->LHS); 6388 const APInt &CIVal = CI->getValue(); 6389 if (GetMinTrailingZeros(LHS) >= 6390 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6391 // Build a plain add SCEV. 6392 return getAddExpr(LHS, getSCEV(CI), 6393 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6394 } 6395 } 6396 break; 6397 6398 case Instruction::Xor: 6399 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6400 // If the RHS of xor is -1, then this is a not operation. 6401 if (CI->isMinusOne()) 6402 return getNotSCEV(getSCEV(BO->LHS)); 6403 6404 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6405 // This is a variant of the check for xor with -1, and it handles 6406 // the case where instcombine has trimmed non-demanded bits out 6407 // of an xor with -1. 6408 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6409 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6410 if (LBO->getOpcode() == Instruction::And && 6411 LCI->getValue() == CI->getValue()) 6412 if (const SCEVZeroExtendExpr *Z = 6413 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6414 Type *UTy = BO->LHS->getType(); 6415 const SCEV *Z0 = Z->getOperand(); 6416 Type *Z0Ty = Z0->getType(); 6417 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6418 6419 // If C is a low-bits mask, the zero extend is serving to 6420 // mask off the high bits. Complement the operand and 6421 // re-apply the zext. 6422 if (CI->getValue().isMask(Z0TySize)) 6423 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6424 6425 // If C is a single bit, it may be in the sign-bit position 6426 // before the zero-extend. In this case, represent the xor 6427 // using an add, which is equivalent, and re-apply the zext. 6428 APInt Trunc = CI->getValue().trunc(Z0TySize); 6429 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6430 Trunc.isSignMask()) 6431 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6432 UTy); 6433 } 6434 } 6435 break; 6436 6437 case Instruction::Shl: 6438 // Turn shift left of a constant amount into a multiply. 6439 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6440 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6441 6442 // If the shift count is not less than the bitwidth, the result of 6443 // the shift is undefined. Don't try to analyze it, because the 6444 // resolution chosen here may differ from the resolution chosen in 6445 // other parts of the compiler. 6446 if (SA->getValue().uge(BitWidth)) 6447 break; 6448 6449 // We can safely preserve the nuw flag in all cases. It's also safe to 6450 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6451 // requires special handling. It can be preserved as long as we're not 6452 // left shifting by bitwidth - 1. 6453 auto Flags = SCEV::FlagAnyWrap; 6454 if (BO->Op) { 6455 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6456 if ((MulFlags & SCEV::FlagNSW) && 6457 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6458 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6459 if (MulFlags & SCEV::FlagNUW) 6460 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6461 } 6462 6463 Constant *X = ConstantInt::get( 6464 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6465 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6466 } 6467 break; 6468 6469 case Instruction::AShr: { 6470 // AShr X, C, where C is a constant. 6471 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6472 if (!CI) 6473 break; 6474 6475 Type *OuterTy = BO->LHS->getType(); 6476 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6477 // If the shift count is not less than the bitwidth, the result of 6478 // the shift is undefined. Don't try to analyze it, because the 6479 // resolution chosen here may differ from the resolution chosen in 6480 // other parts of the compiler. 6481 if (CI->getValue().uge(BitWidth)) 6482 break; 6483 6484 if (CI->isZero()) 6485 return getSCEV(BO->LHS); // shift by zero --> noop 6486 6487 uint64_t AShrAmt = CI->getZExtValue(); 6488 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6489 6490 Operator *L = dyn_cast<Operator>(BO->LHS); 6491 if (L && L->getOpcode() == Instruction::Shl) { 6492 // X = Shl A, n 6493 // Y = AShr X, m 6494 // Both n and m are constant. 6495 6496 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6497 if (L->getOperand(1) == BO->RHS) 6498 // For a two-shift sext-inreg, i.e. n = m, 6499 // use sext(trunc(x)) as the SCEV expression. 6500 return getSignExtendExpr( 6501 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6502 6503 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6504 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6505 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6506 if (ShlAmt > AShrAmt) { 6507 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6508 // expression. We already checked that ShlAmt < BitWidth, so 6509 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6510 // ShlAmt - AShrAmt < Amt. 6511 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6512 ShlAmt - AShrAmt); 6513 return getSignExtendExpr( 6514 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6515 getConstant(Mul)), OuterTy); 6516 } 6517 } 6518 } 6519 break; 6520 } 6521 } 6522 } 6523 6524 switch (U->getOpcode()) { 6525 case Instruction::Trunc: 6526 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6527 6528 case Instruction::ZExt: 6529 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6530 6531 case Instruction::SExt: 6532 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6533 // The NSW flag of a subtract does not always survive the conversion to 6534 // A + (-1)*B. By pushing sign extension onto its operands we are much 6535 // more likely to preserve NSW and allow later AddRec optimisations. 6536 // 6537 // NOTE: This is effectively duplicating this logic from getSignExtend: 6538 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6539 // but by that point the NSW information has potentially been lost. 6540 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6541 Type *Ty = U->getType(); 6542 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6543 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6544 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6545 } 6546 } 6547 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6548 6549 case Instruction::BitCast: 6550 // BitCasts are no-op casts so we just eliminate the cast. 6551 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6552 return getSCEV(U->getOperand(0)); 6553 break; 6554 6555 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6556 // lead to pointer expressions which cannot safely be expanded to GEPs, 6557 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6558 // simplifying integer expressions. 6559 6560 case Instruction::GetElementPtr: 6561 return createNodeForGEP(cast<GEPOperator>(U)); 6562 6563 case Instruction::PHI: 6564 return createNodeForPHI(cast<PHINode>(U)); 6565 6566 case Instruction::Select: 6567 // U can also be a select constant expr, which let fall through. Since 6568 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6569 // constant expressions cannot have instructions as operands, we'd have 6570 // returned getUnknown for a select constant expressions anyway. 6571 if (isa<Instruction>(U)) 6572 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6573 U->getOperand(1), U->getOperand(2)); 6574 break; 6575 6576 case Instruction::Call: 6577 case Instruction::Invoke: 6578 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6579 return getSCEV(RV); 6580 break; 6581 } 6582 6583 return getUnknown(V); 6584 } 6585 6586 //===----------------------------------------------------------------------===// 6587 // Iteration Count Computation Code 6588 // 6589 6590 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6591 if (!ExitCount) 6592 return 0; 6593 6594 ConstantInt *ExitConst = ExitCount->getValue(); 6595 6596 // Guard against huge trip counts. 6597 if (ExitConst->getValue().getActiveBits() > 32) 6598 return 0; 6599 6600 // In case of integer overflow, this returns 0, which is correct. 6601 return ((unsigned)ExitConst->getZExtValue()) + 1; 6602 } 6603 6604 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6605 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6606 return getSmallConstantTripCount(L, ExitingBB); 6607 6608 // No trip count information for multiple exits. 6609 return 0; 6610 } 6611 6612 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6613 BasicBlock *ExitingBlock) { 6614 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6615 assert(L->isLoopExiting(ExitingBlock) && 6616 "Exiting block must actually branch out of the loop!"); 6617 const SCEVConstant *ExitCount = 6618 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6619 return getConstantTripCount(ExitCount); 6620 } 6621 6622 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6623 const auto *MaxExitCount = 6624 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6625 return getConstantTripCount(MaxExitCount); 6626 } 6627 6628 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6629 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6630 return getSmallConstantTripMultiple(L, ExitingBB); 6631 6632 // No trip multiple information for multiple exits. 6633 return 0; 6634 } 6635 6636 /// Returns the largest constant divisor of the trip count of this loop as a 6637 /// normal unsigned value, if possible. This means that the actual trip count is 6638 /// always a multiple of the returned value (don't forget the trip count could 6639 /// very well be zero as well!). 6640 /// 6641 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6642 /// multiple of a constant (which is also the case if the trip count is simply 6643 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6644 /// if the trip count is very large (>= 2^32). 6645 /// 6646 /// As explained in the comments for getSmallConstantTripCount, this assumes 6647 /// that control exits the loop via ExitingBlock. 6648 unsigned 6649 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6650 BasicBlock *ExitingBlock) { 6651 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6652 assert(L->isLoopExiting(ExitingBlock) && 6653 "Exiting block must actually branch out of the loop!"); 6654 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6655 if (ExitCount == getCouldNotCompute()) 6656 return 1; 6657 6658 // Get the trip count from the BE count by adding 1. 6659 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6660 6661 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6662 if (!TC) 6663 // Attempt to factor more general cases. Returns the greatest power of 6664 // two divisor. If overflow happens, the trip count expression is still 6665 // divisible by the greatest power of 2 divisor returned. 6666 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6667 6668 ConstantInt *Result = TC->getValue(); 6669 6670 // Guard against huge trip counts (this requires checking 6671 // for zero to handle the case where the trip count == -1 and the 6672 // addition wraps). 6673 if (!Result || Result->getValue().getActiveBits() > 32 || 6674 Result->getValue().getActiveBits() == 0) 6675 return 1; 6676 6677 return (unsigned)Result->getZExtValue(); 6678 } 6679 6680 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6681 BasicBlock *ExitingBlock, 6682 ExitCountKind Kind) { 6683 switch (Kind) { 6684 case Exact: 6685 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6686 case ConstantMaximum: 6687 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6688 }; 6689 llvm_unreachable("Invalid ExitCountKind!"); 6690 } 6691 6692 const SCEV * 6693 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6694 SCEVUnionPredicate &Preds) { 6695 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6696 } 6697 6698 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6699 ExitCountKind Kind) { 6700 switch (Kind) { 6701 case Exact: 6702 return getBackedgeTakenInfo(L).getExact(L, this); 6703 case ConstantMaximum: 6704 return getBackedgeTakenInfo(L).getMax(this); 6705 }; 6706 llvm_unreachable("Invalid ExitCountKind!"); 6707 } 6708 6709 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6710 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6711 } 6712 6713 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6714 static void 6715 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6716 BasicBlock *Header = L->getHeader(); 6717 6718 // Push all Loop-header PHIs onto the Worklist stack. 6719 for (PHINode &PN : Header->phis()) 6720 Worklist.push_back(&PN); 6721 } 6722 6723 const ScalarEvolution::BackedgeTakenInfo & 6724 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6725 auto &BTI = getBackedgeTakenInfo(L); 6726 if (BTI.hasFullInfo()) 6727 return BTI; 6728 6729 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6730 6731 if (!Pair.second) 6732 return Pair.first->second; 6733 6734 BackedgeTakenInfo Result = 6735 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6736 6737 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6738 } 6739 6740 const ScalarEvolution::BackedgeTakenInfo & 6741 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6742 // Initially insert an invalid entry for this loop. If the insertion 6743 // succeeds, proceed to actually compute a backedge-taken count and 6744 // update the value. The temporary CouldNotCompute value tells SCEV 6745 // code elsewhere that it shouldn't attempt to request a new 6746 // backedge-taken count, which could result in infinite recursion. 6747 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6748 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6749 if (!Pair.second) 6750 return Pair.first->second; 6751 6752 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6753 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6754 // must be cleared in this scope. 6755 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6756 6757 // In product build, there are no usage of statistic. 6758 (void)NumTripCountsComputed; 6759 (void)NumTripCountsNotComputed; 6760 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6761 const SCEV *BEExact = Result.getExact(L, this); 6762 if (BEExact != getCouldNotCompute()) { 6763 assert(isLoopInvariant(BEExact, L) && 6764 isLoopInvariant(Result.getMax(this), L) && 6765 "Computed backedge-taken count isn't loop invariant for loop!"); 6766 ++NumTripCountsComputed; 6767 } 6768 else if (Result.getMax(this) == getCouldNotCompute() && 6769 isa<PHINode>(L->getHeader()->begin())) { 6770 // Only count loops that have phi nodes as not being computable. 6771 ++NumTripCountsNotComputed; 6772 } 6773 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6774 6775 // Now that we know more about the trip count for this loop, forget any 6776 // existing SCEV values for PHI nodes in this loop since they are only 6777 // conservative estimates made without the benefit of trip count 6778 // information. This is similar to the code in forgetLoop, except that 6779 // it handles SCEVUnknown PHI nodes specially. 6780 if (Result.hasAnyInfo()) { 6781 SmallVector<Instruction *, 16> Worklist; 6782 PushLoopPHIs(L, Worklist); 6783 6784 SmallPtrSet<Instruction *, 8> Discovered; 6785 while (!Worklist.empty()) { 6786 Instruction *I = Worklist.pop_back_val(); 6787 6788 ValueExprMapType::iterator It = 6789 ValueExprMap.find_as(static_cast<Value *>(I)); 6790 if (It != ValueExprMap.end()) { 6791 const SCEV *Old = It->second; 6792 6793 // SCEVUnknown for a PHI either means that it has an unrecognized 6794 // structure, or it's a PHI that's in the progress of being computed 6795 // by createNodeForPHI. In the former case, additional loop trip 6796 // count information isn't going to change anything. In the later 6797 // case, createNodeForPHI will perform the necessary updates on its 6798 // own when it gets to that point. 6799 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6800 eraseValueFromMap(It->first); 6801 forgetMemoizedResults(Old); 6802 } 6803 if (PHINode *PN = dyn_cast<PHINode>(I)) 6804 ConstantEvolutionLoopExitValue.erase(PN); 6805 } 6806 6807 // Since we don't need to invalidate anything for correctness and we're 6808 // only invalidating to make SCEV's results more precise, we get to stop 6809 // early to avoid invalidating too much. This is especially important in 6810 // cases like: 6811 // 6812 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6813 // loop0: 6814 // %pn0 = phi 6815 // ... 6816 // loop1: 6817 // %pn1 = phi 6818 // ... 6819 // 6820 // where both loop0 and loop1's backedge taken count uses the SCEV 6821 // expression for %v. If we don't have the early stop below then in cases 6822 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6823 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6824 // count for loop1, effectively nullifying SCEV's trip count cache. 6825 for (auto *U : I->users()) 6826 if (auto *I = dyn_cast<Instruction>(U)) { 6827 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6828 if (LoopForUser && L->contains(LoopForUser) && 6829 Discovered.insert(I).second) 6830 Worklist.push_back(I); 6831 } 6832 } 6833 } 6834 6835 // Re-lookup the insert position, since the call to 6836 // computeBackedgeTakenCount above could result in a 6837 // recusive call to getBackedgeTakenInfo (on a different 6838 // loop), which would invalidate the iterator computed 6839 // earlier. 6840 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6841 } 6842 6843 void ScalarEvolution::forgetAllLoops() { 6844 // This method is intended to forget all info about loops. It should 6845 // invalidate caches as if the following happened: 6846 // - The trip counts of all loops have changed arbitrarily 6847 // - Every llvm::Value has been updated in place to produce a different 6848 // result. 6849 BackedgeTakenCounts.clear(); 6850 PredicatedBackedgeTakenCounts.clear(); 6851 LoopPropertiesCache.clear(); 6852 ConstantEvolutionLoopExitValue.clear(); 6853 ValueExprMap.clear(); 6854 ValuesAtScopes.clear(); 6855 LoopDispositions.clear(); 6856 BlockDispositions.clear(); 6857 UnsignedRanges.clear(); 6858 SignedRanges.clear(); 6859 ExprValueMap.clear(); 6860 HasRecMap.clear(); 6861 MinTrailingZerosCache.clear(); 6862 PredicatedSCEVRewrites.clear(); 6863 } 6864 6865 void ScalarEvolution::forgetLoop(const Loop *L) { 6866 // Drop any stored trip count value. 6867 auto RemoveLoopFromBackedgeMap = 6868 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6869 auto BTCPos = Map.find(L); 6870 if (BTCPos != Map.end()) { 6871 BTCPos->second.clear(); 6872 Map.erase(BTCPos); 6873 } 6874 }; 6875 6876 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6877 SmallVector<Instruction *, 32> Worklist; 6878 SmallPtrSet<Instruction *, 16> Visited; 6879 6880 // Iterate over all the loops and sub-loops to drop SCEV information. 6881 while (!LoopWorklist.empty()) { 6882 auto *CurrL = LoopWorklist.pop_back_val(); 6883 6884 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6885 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6886 6887 // Drop information about predicated SCEV rewrites for this loop. 6888 for (auto I = PredicatedSCEVRewrites.begin(); 6889 I != PredicatedSCEVRewrites.end();) { 6890 std::pair<const SCEV *, const Loop *> Entry = I->first; 6891 if (Entry.second == CurrL) 6892 PredicatedSCEVRewrites.erase(I++); 6893 else 6894 ++I; 6895 } 6896 6897 auto LoopUsersItr = LoopUsers.find(CurrL); 6898 if (LoopUsersItr != LoopUsers.end()) { 6899 for (auto *S : LoopUsersItr->second) 6900 forgetMemoizedResults(S); 6901 LoopUsers.erase(LoopUsersItr); 6902 } 6903 6904 // Drop information about expressions based on loop-header PHIs. 6905 PushLoopPHIs(CurrL, Worklist); 6906 6907 while (!Worklist.empty()) { 6908 Instruction *I = Worklist.pop_back_val(); 6909 if (!Visited.insert(I).second) 6910 continue; 6911 6912 ValueExprMapType::iterator It = 6913 ValueExprMap.find_as(static_cast<Value *>(I)); 6914 if (It != ValueExprMap.end()) { 6915 eraseValueFromMap(It->first); 6916 forgetMemoizedResults(It->second); 6917 if (PHINode *PN = dyn_cast<PHINode>(I)) 6918 ConstantEvolutionLoopExitValue.erase(PN); 6919 } 6920 6921 PushDefUseChildren(I, Worklist); 6922 } 6923 6924 LoopPropertiesCache.erase(CurrL); 6925 // Forget all contained loops too, to avoid dangling entries in the 6926 // ValuesAtScopes map. 6927 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6928 } 6929 } 6930 6931 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6932 while (Loop *Parent = L->getParentLoop()) 6933 L = Parent; 6934 forgetLoop(L); 6935 } 6936 6937 void ScalarEvolution::forgetValue(Value *V) { 6938 Instruction *I = dyn_cast<Instruction>(V); 6939 if (!I) return; 6940 6941 // Drop information about expressions based on loop-header PHIs. 6942 SmallVector<Instruction *, 16> Worklist; 6943 Worklist.push_back(I); 6944 6945 SmallPtrSet<Instruction *, 8> Visited; 6946 while (!Worklist.empty()) { 6947 I = Worklist.pop_back_val(); 6948 if (!Visited.insert(I).second) 6949 continue; 6950 6951 ValueExprMapType::iterator It = 6952 ValueExprMap.find_as(static_cast<Value *>(I)); 6953 if (It != ValueExprMap.end()) { 6954 eraseValueFromMap(It->first); 6955 forgetMemoizedResults(It->second); 6956 if (PHINode *PN = dyn_cast<PHINode>(I)) 6957 ConstantEvolutionLoopExitValue.erase(PN); 6958 } 6959 6960 PushDefUseChildren(I, Worklist); 6961 } 6962 } 6963 6964 /// Get the exact loop backedge taken count considering all loop exits. A 6965 /// computable result can only be returned for loops with all exiting blocks 6966 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6967 /// is never skipped. This is a valid assumption as long as the loop exits via 6968 /// that test. For precise results, it is the caller's responsibility to specify 6969 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6970 const SCEV * 6971 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6972 SCEVUnionPredicate *Preds) const { 6973 // If any exits were not computable, the loop is not computable. 6974 if (!isComplete() || ExitNotTaken.empty()) 6975 return SE->getCouldNotCompute(); 6976 6977 const BasicBlock *Latch = L->getLoopLatch(); 6978 // All exiting blocks we have collected must dominate the only backedge. 6979 if (!Latch) 6980 return SE->getCouldNotCompute(); 6981 6982 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6983 // count is simply a minimum out of all these calculated exit counts. 6984 SmallVector<const SCEV *, 2> Ops; 6985 for (auto &ENT : ExitNotTaken) { 6986 const SCEV *BECount = ENT.ExactNotTaken; 6987 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6988 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6989 "We should only have known counts for exiting blocks that dominate " 6990 "latch!"); 6991 6992 Ops.push_back(BECount); 6993 6994 if (Preds && !ENT.hasAlwaysTruePredicate()) 6995 Preds->add(ENT.Predicate.get()); 6996 6997 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6998 "Predicate should be always true!"); 6999 } 7000 7001 return SE->getUMinFromMismatchedTypes(Ops); 7002 } 7003 7004 /// Get the exact not taken count for this loop exit. 7005 const SCEV * 7006 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 7007 ScalarEvolution *SE) const { 7008 for (auto &ENT : ExitNotTaken) 7009 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7010 return ENT.ExactNotTaken; 7011 7012 return SE->getCouldNotCompute(); 7013 } 7014 7015 const SCEV * 7016 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 7017 ScalarEvolution *SE) const { 7018 for (auto &ENT : ExitNotTaken) 7019 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7020 return ENT.MaxNotTaken; 7021 7022 return SE->getCouldNotCompute(); 7023 } 7024 7025 /// getMax - Get the max backedge taken count for the loop. 7026 const SCEV * 7027 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 7028 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7029 return !ENT.hasAlwaysTruePredicate(); 7030 }; 7031 7032 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 7033 return SE->getCouldNotCompute(); 7034 7035 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 7036 "No point in having a non-constant max backedge taken count!"); 7037 return getMax(); 7038 } 7039 7040 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 7041 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7042 return !ENT.hasAlwaysTruePredicate(); 7043 }; 7044 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7045 } 7046 7047 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7048 ScalarEvolution *SE) const { 7049 if (getMax() && getMax() != SE->getCouldNotCompute() && 7050 SE->hasOperand(getMax(), S)) 7051 return true; 7052 7053 for (auto &ENT : ExitNotTaken) 7054 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7055 SE->hasOperand(ENT.ExactNotTaken, S)) 7056 return true; 7057 7058 return false; 7059 } 7060 7061 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7062 : ExactNotTaken(E), MaxNotTaken(E) { 7063 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7064 isa<SCEVConstant>(MaxNotTaken)) && 7065 "No point in having a non-constant max backedge taken count!"); 7066 } 7067 7068 ScalarEvolution::ExitLimit::ExitLimit( 7069 const SCEV *E, const SCEV *M, bool MaxOrZero, 7070 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7071 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7072 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7073 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7074 "Exact is not allowed to be less precise than Max"); 7075 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7076 isa<SCEVConstant>(MaxNotTaken)) && 7077 "No point in having a non-constant max backedge taken count!"); 7078 for (auto *PredSet : PredSetList) 7079 for (auto *P : *PredSet) 7080 addPredicate(P); 7081 } 7082 7083 ScalarEvolution::ExitLimit::ExitLimit( 7084 const SCEV *E, const SCEV *M, bool MaxOrZero, 7085 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7086 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7087 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7088 isa<SCEVConstant>(MaxNotTaken)) && 7089 "No point in having a non-constant max backedge taken count!"); 7090 } 7091 7092 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7093 bool MaxOrZero) 7094 : ExitLimit(E, M, MaxOrZero, None) { 7095 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7096 isa<SCEVConstant>(MaxNotTaken)) && 7097 "No point in having a non-constant max backedge taken count!"); 7098 } 7099 7100 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7101 /// computable exit into a persistent ExitNotTakenInfo array. 7102 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7103 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7104 ExitCounts, 7105 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7106 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7107 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7108 7109 ExitNotTaken.reserve(ExitCounts.size()); 7110 std::transform( 7111 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7112 [&](const EdgeExitInfo &EEI) { 7113 BasicBlock *ExitBB = EEI.first; 7114 const ExitLimit &EL = EEI.second; 7115 if (EL.Predicates.empty()) 7116 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7117 nullptr); 7118 7119 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7120 for (auto *Pred : EL.Predicates) 7121 Predicate->add(Pred); 7122 7123 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7124 std::move(Predicate)); 7125 }); 7126 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7127 "No point in having a non-constant max backedge taken count!"); 7128 } 7129 7130 /// Invalidate this result and free the ExitNotTakenInfo array. 7131 void ScalarEvolution::BackedgeTakenInfo::clear() { 7132 ExitNotTaken.clear(); 7133 } 7134 7135 /// Compute the number of times the backedge of the specified loop will execute. 7136 ScalarEvolution::BackedgeTakenInfo 7137 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7138 bool AllowPredicates) { 7139 SmallVector<BasicBlock *, 8> ExitingBlocks; 7140 L->getExitingBlocks(ExitingBlocks); 7141 7142 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7143 7144 SmallVector<EdgeExitInfo, 4> ExitCounts; 7145 bool CouldComputeBECount = true; 7146 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7147 const SCEV *MustExitMaxBECount = nullptr; 7148 const SCEV *MayExitMaxBECount = nullptr; 7149 bool MustExitMaxOrZero = false; 7150 7151 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7152 // and compute maxBECount. 7153 // Do a union of all the predicates here. 7154 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7155 BasicBlock *ExitBB = ExitingBlocks[i]; 7156 7157 // We canonicalize untaken exits to br (constant), ignore them so that 7158 // proving an exit untaken doesn't negatively impact our ability to reason 7159 // about the loop as whole. 7160 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7161 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7162 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7163 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7164 continue; 7165 } 7166 7167 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7168 7169 assert((AllowPredicates || EL.Predicates.empty()) && 7170 "Predicated exit limit when predicates are not allowed!"); 7171 7172 // 1. For each exit that can be computed, add an entry to ExitCounts. 7173 // CouldComputeBECount is true only if all exits can be computed. 7174 if (EL.ExactNotTaken == getCouldNotCompute()) 7175 // We couldn't compute an exact value for this exit, so 7176 // we won't be able to compute an exact value for the loop. 7177 CouldComputeBECount = false; 7178 else 7179 ExitCounts.emplace_back(ExitBB, EL); 7180 7181 // 2. Derive the loop's MaxBECount from each exit's max number of 7182 // non-exiting iterations. Partition the loop exits into two kinds: 7183 // LoopMustExits and LoopMayExits. 7184 // 7185 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7186 // is a LoopMayExit. If any computable LoopMustExit is found, then 7187 // MaxBECount is the minimum EL.MaxNotTaken of computable 7188 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7189 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7190 // computable EL.MaxNotTaken. 7191 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7192 DT.dominates(ExitBB, Latch)) { 7193 if (!MustExitMaxBECount) { 7194 MustExitMaxBECount = EL.MaxNotTaken; 7195 MustExitMaxOrZero = EL.MaxOrZero; 7196 } else { 7197 MustExitMaxBECount = 7198 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7199 } 7200 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7201 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7202 MayExitMaxBECount = EL.MaxNotTaken; 7203 else { 7204 MayExitMaxBECount = 7205 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7206 } 7207 } 7208 } 7209 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7210 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7211 // The loop backedge will be taken the maximum or zero times if there's 7212 // a single exit that must be taken the maximum or zero times. 7213 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7214 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7215 MaxBECount, MaxOrZero); 7216 } 7217 7218 ScalarEvolution::ExitLimit 7219 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7220 bool AllowPredicates) { 7221 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7222 // If our exiting block does not dominate the latch, then its connection with 7223 // loop's exit limit may be far from trivial. 7224 const BasicBlock *Latch = L->getLoopLatch(); 7225 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7226 return getCouldNotCompute(); 7227 7228 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7229 Instruction *Term = ExitingBlock->getTerminator(); 7230 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7231 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7232 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7233 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7234 "It should have one successor in loop and one exit block!"); 7235 // Proceed to the next level to examine the exit condition expression. 7236 return computeExitLimitFromCond( 7237 L, BI->getCondition(), ExitIfTrue, 7238 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7239 } 7240 7241 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7242 // For switch, make sure that there is a single exit from the loop. 7243 BasicBlock *Exit = nullptr; 7244 for (auto *SBB : successors(ExitingBlock)) 7245 if (!L->contains(SBB)) { 7246 if (Exit) // Multiple exit successors. 7247 return getCouldNotCompute(); 7248 Exit = SBB; 7249 } 7250 assert(Exit && "Exiting block must have at least one exit"); 7251 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7252 /*ControlsExit=*/IsOnlyExit); 7253 } 7254 7255 return getCouldNotCompute(); 7256 } 7257 7258 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7259 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7260 bool ControlsExit, bool AllowPredicates) { 7261 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7262 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7263 ControlsExit, AllowPredicates); 7264 } 7265 7266 Optional<ScalarEvolution::ExitLimit> 7267 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7268 bool ExitIfTrue, bool ControlsExit, 7269 bool AllowPredicates) { 7270 (void)this->L; 7271 (void)this->ExitIfTrue; 7272 (void)this->AllowPredicates; 7273 7274 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7275 this->AllowPredicates == AllowPredicates && 7276 "Variance in assumed invariant key components!"); 7277 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7278 if (Itr == TripCountMap.end()) 7279 return None; 7280 return Itr->second; 7281 } 7282 7283 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7284 bool ExitIfTrue, 7285 bool ControlsExit, 7286 bool AllowPredicates, 7287 const ExitLimit &EL) { 7288 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7289 this->AllowPredicates == AllowPredicates && 7290 "Variance in assumed invariant key components!"); 7291 7292 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7293 assert(InsertResult.second && "Expected successful insertion!"); 7294 (void)InsertResult; 7295 (void)ExitIfTrue; 7296 } 7297 7298 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7299 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7300 bool ControlsExit, bool AllowPredicates) { 7301 7302 if (auto MaybeEL = 7303 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7304 return *MaybeEL; 7305 7306 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7307 ControlsExit, AllowPredicates); 7308 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7309 return EL; 7310 } 7311 7312 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7313 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7314 bool ControlsExit, bool AllowPredicates) { 7315 // Check if the controlling expression for this loop is an And or Or. 7316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7317 if (BO->getOpcode() == Instruction::And) { 7318 // Recurse on the operands of the and. 7319 bool EitherMayExit = !ExitIfTrue; 7320 ExitLimit EL0 = computeExitLimitFromCondCached( 7321 Cache, L, BO->getOperand(0), ExitIfTrue, 7322 ControlsExit && !EitherMayExit, AllowPredicates); 7323 ExitLimit EL1 = computeExitLimitFromCondCached( 7324 Cache, L, BO->getOperand(1), ExitIfTrue, 7325 ControlsExit && !EitherMayExit, AllowPredicates); 7326 // Be robust against unsimplified IR for the form "and i1 X, true" 7327 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7328 return CI->isOne() ? EL0 : EL1; 7329 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7330 return CI->isOne() ? EL1 : EL0; 7331 const SCEV *BECount = getCouldNotCompute(); 7332 const SCEV *MaxBECount = getCouldNotCompute(); 7333 if (EitherMayExit) { 7334 // Both conditions must be true for the loop to continue executing. 7335 // Choose the less conservative count. 7336 if (EL0.ExactNotTaken == getCouldNotCompute() || 7337 EL1.ExactNotTaken == getCouldNotCompute()) 7338 BECount = getCouldNotCompute(); 7339 else 7340 BECount = 7341 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7342 if (EL0.MaxNotTaken == getCouldNotCompute()) 7343 MaxBECount = EL1.MaxNotTaken; 7344 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7345 MaxBECount = EL0.MaxNotTaken; 7346 else 7347 MaxBECount = 7348 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7349 } else { 7350 // Both conditions must be true at the same time for the loop to exit. 7351 // For now, be conservative. 7352 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7353 MaxBECount = EL0.MaxNotTaken; 7354 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7355 BECount = EL0.ExactNotTaken; 7356 } 7357 7358 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7359 // to be more aggressive when computing BECount than when computing 7360 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7361 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7362 // to not. 7363 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7364 !isa<SCEVCouldNotCompute>(BECount)) 7365 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7366 7367 return ExitLimit(BECount, MaxBECount, false, 7368 {&EL0.Predicates, &EL1.Predicates}); 7369 } 7370 if (BO->getOpcode() == Instruction::Or) { 7371 // Recurse on the operands of the or. 7372 bool EitherMayExit = ExitIfTrue; 7373 ExitLimit EL0 = computeExitLimitFromCondCached( 7374 Cache, L, BO->getOperand(0), ExitIfTrue, 7375 ControlsExit && !EitherMayExit, AllowPredicates); 7376 ExitLimit EL1 = computeExitLimitFromCondCached( 7377 Cache, L, BO->getOperand(1), ExitIfTrue, 7378 ControlsExit && !EitherMayExit, AllowPredicates); 7379 // Be robust against unsimplified IR for the form "or i1 X, true" 7380 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7381 return CI->isZero() ? EL0 : EL1; 7382 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7383 return CI->isZero() ? EL1 : EL0; 7384 const SCEV *BECount = getCouldNotCompute(); 7385 const SCEV *MaxBECount = getCouldNotCompute(); 7386 if (EitherMayExit) { 7387 // Both conditions must be false for the loop to continue executing. 7388 // Choose the less conservative count. 7389 if (EL0.ExactNotTaken == getCouldNotCompute() || 7390 EL1.ExactNotTaken == getCouldNotCompute()) 7391 BECount = getCouldNotCompute(); 7392 else 7393 BECount = 7394 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7395 if (EL0.MaxNotTaken == getCouldNotCompute()) 7396 MaxBECount = EL1.MaxNotTaken; 7397 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7398 MaxBECount = EL0.MaxNotTaken; 7399 else 7400 MaxBECount = 7401 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7402 } else { 7403 // Both conditions must be false at the same time for the loop to exit. 7404 // For now, be conservative. 7405 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7406 MaxBECount = EL0.MaxNotTaken; 7407 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7408 BECount = EL0.ExactNotTaken; 7409 } 7410 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7411 // to be more aggressive when computing BECount than when computing 7412 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7413 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7414 // to not. 7415 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7416 !isa<SCEVCouldNotCompute>(BECount)) 7417 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7418 7419 return ExitLimit(BECount, MaxBECount, false, 7420 {&EL0.Predicates, &EL1.Predicates}); 7421 } 7422 } 7423 7424 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7425 // Proceed to the next level to examine the icmp. 7426 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7427 ExitLimit EL = 7428 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7429 if (EL.hasFullInfo() || !AllowPredicates) 7430 return EL; 7431 7432 // Try again, but use SCEV predicates this time. 7433 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7434 /*AllowPredicates=*/true); 7435 } 7436 7437 // Check for a constant condition. These are normally stripped out by 7438 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7439 // preserve the CFG and is temporarily leaving constant conditions 7440 // in place. 7441 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7442 if (ExitIfTrue == !CI->getZExtValue()) 7443 // The backedge is always taken. 7444 return getCouldNotCompute(); 7445 else 7446 // The backedge is never taken. 7447 return getZero(CI->getType()); 7448 } 7449 7450 // If it's not an integer or pointer comparison then compute it the hard way. 7451 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7452 } 7453 7454 ScalarEvolution::ExitLimit 7455 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7456 ICmpInst *ExitCond, 7457 bool ExitIfTrue, 7458 bool ControlsExit, 7459 bool AllowPredicates) { 7460 // If the condition was exit on true, convert the condition to exit on false 7461 ICmpInst::Predicate Pred; 7462 if (!ExitIfTrue) 7463 Pred = ExitCond->getPredicate(); 7464 else 7465 Pred = ExitCond->getInversePredicate(); 7466 const ICmpInst::Predicate OriginalPred = Pred; 7467 7468 // Handle common loops like: for (X = "string"; *X; ++X) 7469 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7470 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7471 ExitLimit ItCnt = 7472 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7473 if (ItCnt.hasAnyInfo()) 7474 return ItCnt; 7475 } 7476 7477 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7478 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7479 7480 // Try to evaluate any dependencies out of the loop. 7481 LHS = getSCEVAtScope(LHS, L); 7482 RHS = getSCEVAtScope(RHS, L); 7483 7484 // At this point, we would like to compute how many iterations of the 7485 // loop the predicate will return true for these inputs. 7486 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7487 // If there is a loop-invariant, force it into the RHS. 7488 std::swap(LHS, RHS); 7489 Pred = ICmpInst::getSwappedPredicate(Pred); 7490 } 7491 7492 // Simplify the operands before analyzing them. 7493 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7494 7495 // If we have a comparison of a chrec against a constant, try to use value 7496 // ranges to answer this query. 7497 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7498 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7499 if (AddRec->getLoop() == L) { 7500 // Form the constant range. 7501 ConstantRange CompRange = 7502 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7503 7504 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7505 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7506 } 7507 7508 switch (Pred) { 7509 case ICmpInst::ICMP_NE: { // while (X != Y) 7510 // Convert to: while (X-Y != 0) 7511 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7512 AllowPredicates); 7513 if (EL.hasAnyInfo()) return EL; 7514 break; 7515 } 7516 case ICmpInst::ICMP_EQ: { // while (X == Y) 7517 // Convert to: while (X-Y == 0) 7518 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7519 if (EL.hasAnyInfo()) return EL; 7520 break; 7521 } 7522 case ICmpInst::ICMP_SLT: 7523 case ICmpInst::ICMP_ULT: { // while (X < Y) 7524 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7525 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7526 AllowPredicates); 7527 if (EL.hasAnyInfo()) return EL; 7528 break; 7529 } 7530 case ICmpInst::ICMP_SGT: 7531 case ICmpInst::ICMP_UGT: { // while (X > Y) 7532 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7533 ExitLimit EL = 7534 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7535 AllowPredicates); 7536 if (EL.hasAnyInfo()) return EL; 7537 break; 7538 } 7539 default: 7540 break; 7541 } 7542 7543 auto *ExhaustiveCount = 7544 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7545 7546 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7547 return ExhaustiveCount; 7548 7549 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7550 ExitCond->getOperand(1), L, OriginalPred); 7551 } 7552 7553 ScalarEvolution::ExitLimit 7554 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7555 SwitchInst *Switch, 7556 BasicBlock *ExitingBlock, 7557 bool ControlsExit) { 7558 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7559 7560 // Give up if the exit is the default dest of a switch. 7561 if (Switch->getDefaultDest() == ExitingBlock) 7562 return getCouldNotCompute(); 7563 7564 assert(L->contains(Switch->getDefaultDest()) && 7565 "Default case must not exit the loop!"); 7566 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7567 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7568 7569 // while (X != Y) --> while (X-Y != 0) 7570 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7571 if (EL.hasAnyInfo()) 7572 return EL; 7573 7574 return getCouldNotCompute(); 7575 } 7576 7577 static ConstantInt * 7578 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7579 ScalarEvolution &SE) { 7580 const SCEV *InVal = SE.getConstant(C); 7581 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7582 assert(isa<SCEVConstant>(Val) && 7583 "Evaluation of SCEV at constant didn't fold correctly?"); 7584 return cast<SCEVConstant>(Val)->getValue(); 7585 } 7586 7587 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7588 /// compute the backedge execution count. 7589 ScalarEvolution::ExitLimit 7590 ScalarEvolution::computeLoadConstantCompareExitLimit( 7591 LoadInst *LI, 7592 Constant *RHS, 7593 const Loop *L, 7594 ICmpInst::Predicate predicate) { 7595 if (LI->isVolatile()) return getCouldNotCompute(); 7596 7597 // Check to see if the loaded pointer is a getelementptr of a global. 7598 // TODO: Use SCEV instead of manually grubbing with GEPs. 7599 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7600 if (!GEP) return getCouldNotCompute(); 7601 7602 // Make sure that it is really a constant global we are gepping, with an 7603 // initializer, and make sure the first IDX is really 0. 7604 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7605 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7606 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7607 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7608 return getCouldNotCompute(); 7609 7610 // Okay, we allow one non-constant index into the GEP instruction. 7611 Value *VarIdx = nullptr; 7612 std::vector<Constant*> Indexes; 7613 unsigned VarIdxNum = 0; 7614 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7615 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7616 Indexes.push_back(CI); 7617 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7618 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7619 VarIdx = GEP->getOperand(i); 7620 VarIdxNum = i-2; 7621 Indexes.push_back(nullptr); 7622 } 7623 7624 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7625 if (!VarIdx) 7626 return getCouldNotCompute(); 7627 7628 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7629 // Check to see if X is a loop variant variable value now. 7630 const SCEV *Idx = getSCEV(VarIdx); 7631 Idx = getSCEVAtScope(Idx, L); 7632 7633 // We can only recognize very limited forms of loop index expressions, in 7634 // particular, only affine AddRec's like {C1,+,C2}. 7635 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7636 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7637 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7638 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7639 return getCouldNotCompute(); 7640 7641 unsigned MaxSteps = MaxBruteForceIterations; 7642 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7643 ConstantInt *ItCst = ConstantInt::get( 7644 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7645 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7646 7647 // Form the GEP offset. 7648 Indexes[VarIdxNum] = Val; 7649 7650 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7651 Indexes); 7652 if (!Result) break; // Cannot compute! 7653 7654 // Evaluate the condition for this iteration. 7655 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7656 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7657 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7658 ++NumArrayLenItCounts; 7659 return getConstant(ItCst); // Found terminating iteration! 7660 } 7661 } 7662 return getCouldNotCompute(); 7663 } 7664 7665 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7666 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7667 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7668 if (!RHS) 7669 return getCouldNotCompute(); 7670 7671 const BasicBlock *Latch = L->getLoopLatch(); 7672 if (!Latch) 7673 return getCouldNotCompute(); 7674 7675 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7676 if (!Predecessor) 7677 return getCouldNotCompute(); 7678 7679 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7680 // Return LHS in OutLHS and shift_opt in OutOpCode. 7681 auto MatchPositiveShift = 7682 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7683 7684 using namespace PatternMatch; 7685 7686 ConstantInt *ShiftAmt; 7687 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7688 OutOpCode = Instruction::LShr; 7689 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7690 OutOpCode = Instruction::AShr; 7691 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7692 OutOpCode = Instruction::Shl; 7693 else 7694 return false; 7695 7696 return ShiftAmt->getValue().isStrictlyPositive(); 7697 }; 7698 7699 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7700 // 7701 // loop: 7702 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7703 // %iv.shifted = lshr i32 %iv, <positive constant> 7704 // 7705 // Return true on a successful match. Return the corresponding PHI node (%iv 7706 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7707 auto MatchShiftRecurrence = 7708 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7709 Optional<Instruction::BinaryOps> PostShiftOpCode; 7710 7711 { 7712 Instruction::BinaryOps OpC; 7713 Value *V; 7714 7715 // If we encounter a shift instruction, "peel off" the shift operation, 7716 // and remember that we did so. Later when we inspect %iv's backedge 7717 // value, we will make sure that the backedge value uses the same 7718 // operation. 7719 // 7720 // Note: the peeled shift operation does not have to be the same 7721 // instruction as the one feeding into the PHI's backedge value. We only 7722 // really care about it being the same *kind* of shift instruction -- 7723 // that's all that is required for our later inferences to hold. 7724 if (MatchPositiveShift(LHS, V, OpC)) { 7725 PostShiftOpCode = OpC; 7726 LHS = V; 7727 } 7728 } 7729 7730 PNOut = dyn_cast<PHINode>(LHS); 7731 if (!PNOut || PNOut->getParent() != L->getHeader()) 7732 return false; 7733 7734 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7735 Value *OpLHS; 7736 7737 return 7738 // The backedge value for the PHI node must be a shift by a positive 7739 // amount 7740 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7741 7742 // of the PHI node itself 7743 OpLHS == PNOut && 7744 7745 // and the kind of shift should be match the kind of shift we peeled 7746 // off, if any. 7747 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7748 }; 7749 7750 PHINode *PN; 7751 Instruction::BinaryOps OpCode; 7752 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7753 return getCouldNotCompute(); 7754 7755 const DataLayout &DL = getDataLayout(); 7756 7757 // The key rationale for this optimization is that for some kinds of shift 7758 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7759 // within a finite number of iterations. If the condition guarding the 7760 // backedge (in the sense that the backedge is taken if the condition is true) 7761 // is false for the value the shift recurrence stabilizes to, then we know 7762 // that the backedge is taken only a finite number of times. 7763 7764 ConstantInt *StableValue = nullptr; 7765 switch (OpCode) { 7766 default: 7767 llvm_unreachable("Impossible case!"); 7768 7769 case Instruction::AShr: { 7770 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7771 // bitwidth(K) iterations. 7772 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7773 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7774 Predecessor->getTerminator(), &DT); 7775 auto *Ty = cast<IntegerType>(RHS->getType()); 7776 if (Known.isNonNegative()) 7777 StableValue = ConstantInt::get(Ty, 0); 7778 else if (Known.isNegative()) 7779 StableValue = ConstantInt::get(Ty, -1, true); 7780 else 7781 return getCouldNotCompute(); 7782 7783 break; 7784 } 7785 case Instruction::LShr: 7786 case Instruction::Shl: 7787 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7788 // stabilize to 0 in at most bitwidth(K) iterations. 7789 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7790 break; 7791 } 7792 7793 auto *Result = 7794 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7795 assert(Result->getType()->isIntegerTy(1) && 7796 "Otherwise cannot be an operand to a branch instruction"); 7797 7798 if (Result->isZeroValue()) { 7799 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7800 const SCEV *UpperBound = 7801 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7802 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7803 } 7804 7805 return getCouldNotCompute(); 7806 } 7807 7808 /// Return true if we can constant fold an instruction of the specified type, 7809 /// assuming that all operands were constants. 7810 static bool CanConstantFold(const Instruction *I) { 7811 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7812 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7813 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7814 return true; 7815 7816 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7817 if (const Function *F = CI->getCalledFunction()) 7818 return canConstantFoldCallTo(CI, F); 7819 return false; 7820 } 7821 7822 /// Determine whether this instruction can constant evolve within this loop 7823 /// assuming its operands can all constant evolve. 7824 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7825 // An instruction outside of the loop can't be derived from a loop PHI. 7826 if (!L->contains(I)) return false; 7827 7828 if (isa<PHINode>(I)) { 7829 // We don't currently keep track of the control flow needed to evaluate 7830 // PHIs, so we cannot handle PHIs inside of loops. 7831 return L->getHeader() == I->getParent(); 7832 } 7833 7834 // If we won't be able to constant fold this expression even if the operands 7835 // are constants, bail early. 7836 return CanConstantFold(I); 7837 } 7838 7839 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7840 /// recursing through each instruction operand until reaching a loop header phi. 7841 static PHINode * 7842 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7843 DenseMap<Instruction *, PHINode *> &PHIMap, 7844 unsigned Depth) { 7845 if (Depth > MaxConstantEvolvingDepth) 7846 return nullptr; 7847 7848 // Otherwise, we can evaluate this instruction if all of its operands are 7849 // constant or derived from a PHI node themselves. 7850 PHINode *PHI = nullptr; 7851 for (Value *Op : UseInst->operands()) { 7852 if (isa<Constant>(Op)) continue; 7853 7854 Instruction *OpInst = dyn_cast<Instruction>(Op); 7855 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7856 7857 PHINode *P = dyn_cast<PHINode>(OpInst); 7858 if (!P) 7859 // If this operand is already visited, reuse the prior result. 7860 // We may have P != PHI if this is the deepest point at which the 7861 // inconsistent paths meet. 7862 P = PHIMap.lookup(OpInst); 7863 if (!P) { 7864 // Recurse and memoize the results, whether a phi is found or not. 7865 // This recursive call invalidates pointers into PHIMap. 7866 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7867 PHIMap[OpInst] = P; 7868 } 7869 if (!P) 7870 return nullptr; // Not evolving from PHI 7871 if (PHI && PHI != P) 7872 return nullptr; // Evolving from multiple different PHIs. 7873 PHI = P; 7874 } 7875 // This is a expression evolving from a constant PHI! 7876 return PHI; 7877 } 7878 7879 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7880 /// in the loop that V is derived from. We allow arbitrary operations along the 7881 /// way, but the operands of an operation must either be constants or a value 7882 /// derived from a constant PHI. If this expression does not fit with these 7883 /// constraints, return null. 7884 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7885 Instruction *I = dyn_cast<Instruction>(V); 7886 if (!I || !canConstantEvolve(I, L)) return nullptr; 7887 7888 if (PHINode *PN = dyn_cast<PHINode>(I)) 7889 return PN; 7890 7891 // Record non-constant instructions contained by the loop. 7892 DenseMap<Instruction *, PHINode *> PHIMap; 7893 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7894 } 7895 7896 /// EvaluateExpression - Given an expression that passes the 7897 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7898 /// in the loop has the value PHIVal. If we can't fold this expression for some 7899 /// reason, return null. 7900 static Constant *EvaluateExpression(Value *V, const Loop *L, 7901 DenseMap<Instruction *, Constant *> &Vals, 7902 const DataLayout &DL, 7903 const TargetLibraryInfo *TLI) { 7904 // Convenient constant check, but redundant for recursive calls. 7905 if (Constant *C = dyn_cast<Constant>(V)) return C; 7906 Instruction *I = dyn_cast<Instruction>(V); 7907 if (!I) return nullptr; 7908 7909 if (Constant *C = Vals.lookup(I)) return C; 7910 7911 // An instruction inside the loop depends on a value outside the loop that we 7912 // weren't given a mapping for, or a value such as a call inside the loop. 7913 if (!canConstantEvolve(I, L)) return nullptr; 7914 7915 // An unmapped PHI can be due to a branch or another loop inside this loop, 7916 // or due to this not being the initial iteration through a loop where we 7917 // couldn't compute the evolution of this particular PHI last time. 7918 if (isa<PHINode>(I)) return nullptr; 7919 7920 std::vector<Constant*> Operands(I->getNumOperands()); 7921 7922 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7923 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7924 if (!Operand) { 7925 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7926 if (!Operands[i]) return nullptr; 7927 continue; 7928 } 7929 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7930 Vals[Operand] = C; 7931 if (!C) return nullptr; 7932 Operands[i] = C; 7933 } 7934 7935 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7936 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7937 Operands[1], DL, TLI); 7938 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7939 if (!LI->isVolatile()) 7940 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7941 } 7942 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7943 } 7944 7945 7946 // If every incoming value to PN except the one for BB is a specific Constant, 7947 // return that, else return nullptr. 7948 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7949 Constant *IncomingVal = nullptr; 7950 7951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7952 if (PN->getIncomingBlock(i) == BB) 7953 continue; 7954 7955 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7956 if (!CurrentVal) 7957 return nullptr; 7958 7959 if (IncomingVal != CurrentVal) { 7960 if (IncomingVal) 7961 return nullptr; 7962 IncomingVal = CurrentVal; 7963 } 7964 } 7965 7966 return IncomingVal; 7967 } 7968 7969 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7970 /// in the header of its containing loop, we know the loop executes a 7971 /// constant number of times, and the PHI node is just a recurrence 7972 /// involving constants, fold it. 7973 Constant * 7974 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7975 const APInt &BEs, 7976 const Loop *L) { 7977 auto I = ConstantEvolutionLoopExitValue.find(PN); 7978 if (I != ConstantEvolutionLoopExitValue.end()) 7979 return I->second; 7980 7981 if (BEs.ugt(MaxBruteForceIterations)) 7982 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7983 7984 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7985 7986 DenseMap<Instruction *, Constant *> CurrentIterVals; 7987 BasicBlock *Header = L->getHeader(); 7988 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7989 7990 BasicBlock *Latch = L->getLoopLatch(); 7991 if (!Latch) 7992 return nullptr; 7993 7994 for (PHINode &PHI : Header->phis()) { 7995 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7996 CurrentIterVals[&PHI] = StartCST; 7997 } 7998 if (!CurrentIterVals.count(PN)) 7999 return RetVal = nullptr; 8000 8001 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8002 8003 // Execute the loop symbolically to determine the exit value. 8004 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8005 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8006 8007 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8008 unsigned IterationNum = 0; 8009 const DataLayout &DL = getDataLayout(); 8010 for (; ; ++IterationNum) { 8011 if (IterationNum == NumIterations) 8012 return RetVal = CurrentIterVals[PN]; // Got exit value! 8013 8014 // Compute the value of the PHIs for the next iteration. 8015 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8016 DenseMap<Instruction *, Constant *> NextIterVals; 8017 Constant *NextPHI = 8018 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8019 if (!NextPHI) 8020 return nullptr; // Couldn't evaluate! 8021 NextIterVals[PN] = NextPHI; 8022 8023 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8024 8025 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8026 // cease to be able to evaluate one of them or if they stop evolving, 8027 // because that doesn't necessarily prevent us from computing PN. 8028 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8029 for (const auto &I : CurrentIterVals) { 8030 PHINode *PHI = dyn_cast<PHINode>(I.first); 8031 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8032 PHIsToCompute.emplace_back(PHI, I.second); 8033 } 8034 // We use two distinct loops because EvaluateExpression may invalidate any 8035 // iterators into CurrentIterVals. 8036 for (const auto &I : PHIsToCompute) { 8037 PHINode *PHI = I.first; 8038 Constant *&NextPHI = NextIterVals[PHI]; 8039 if (!NextPHI) { // Not already computed. 8040 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8041 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8042 } 8043 if (NextPHI != I.second) 8044 StoppedEvolving = false; 8045 } 8046 8047 // If all entries in CurrentIterVals == NextIterVals then we can stop 8048 // iterating, the loop can't continue to change. 8049 if (StoppedEvolving) 8050 return RetVal = CurrentIterVals[PN]; 8051 8052 CurrentIterVals.swap(NextIterVals); 8053 } 8054 } 8055 8056 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8057 Value *Cond, 8058 bool ExitWhen) { 8059 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8060 if (!PN) return getCouldNotCompute(); 8061 8062 // If the loop is canonicalized, the PHI will have exactly two entries. 8063 // That's the only form we support here. 8064 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8065 8066 DenseMap<Instruction *, Constant *> CurrentIterVals; 8067 BasicBlock *Header = L->getHeader(); 8068 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8069 8070 BasicBlock *Latch = L->getLoopLatch(); 8071 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8072 8073 for (PHINode &PHI : Header->phis()) { 8074 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8075 CurrentIterVals[&PHI] = StartCST; 8076 } 8077 if (!CurrentIterVals.count(PN)) 8078 return getCouldNotCompute(); 8079 8080 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8081 // the loop symbolically to determine when the condition gets a value of 8082 // "ExitWhen". 8083 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8084 const DataLayout &DL = getDataLayout(); 8085 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8086 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8087 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8088 8089 // Couldn't symbolically evaluate. 8090 if (!CondVal) return getCouldNotCompute(); 8091 8092 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8093 ++NumBruteForceTripCountsComputed; 8094 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8095 } 8096 8097 // Update all the PHI nodes for the next iteration. 8098 DenseMap<Instruction *, Constant *> NextIterVals; 8099 8100 // Create a list of which PHIs we need to compute. We want to do this before 8101 // calling EvaluateExpression on them because that may invalidate iterators 8102 // into CurrentIterVals. 8103 SmallVector<PHINode *, 8> PHIsToCompute; 8104 for (const auto &I : CurrentIterVals) { 8105 PHINode *PHI = dyn_cast<PHINode>(I.first); 8106 if (!PHI || PHI->getParent() != Header) continue; 8107 PHIsToCompute.push_back(PHI); 8108 } 8109 for (PHINode *PHI : PHIsToCompute) { 8110 Constant *&NextPHI = NextIterVals[PHI]; 8111 if (NextPHI) continue; // Already computed! 8112 8113 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8114 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8115 } 8116 CurrentIterVals.swap(NextIterVals); 8117 } 8118 8119 // Too many iterations were needed to evaluate. 8120 return getCouldNotCompute(); 8121 } 8122 8123 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8124 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8125 ValuesAtScopes[V]; 8126 // Check to see if we've folded this expression at this loop before. 8127 for (auto &LS : Values) 8128 if (LS.first == L) 8129 return LS.second ? LS.second : V; 8130 8131 Values.emplace_back(L, nullptr); 8132 8133 // Otherwise compute it. 8134 const SCEV *C = computeSCEVAtScope(V, L); 8135 for (auto &LS : reverse(ValuesAtScopes[V])) 8136 if (LS.first == L) { 8137 LS.second = C; 8138 break; 8139 } 8140 return C; 8141 } 8142 8143 /// This builds up a Constant using the ConstantExpr interface. That way, we 8144 /// will return Constants for objects which aren't represented by a 8145 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8146 /// Returns NULL if the SCEV isn't representable as a Constant. 8147 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8148 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8149 case scCouldNotCompute: 8150 case scAddRecExpr: 8151 break; 8152 case scConstant: 8153 return cast<SCEVConstant>(V)->getValue(); 8154 case scUnknown: 8155 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8156 case scSignExtend: { 8157 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8158 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8159 return ConstantExpr::getSExt(CastOp, SS->getType()); 8160 break; 8161 } 8162 case scZeroExtend: { 8163 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8164 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8165 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8166 break; 8167 } 8168 case scTruncate: { 8169 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8170 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8171 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8172 break; 8173 } 8174 case scAddExpr: { 8175 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8176 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8177 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8178 unsigned AS = PTy->getAddressSpace(); 8179 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8180 C = ConstantExpr::getBitCast(C, DestPtrTy); 8181 } 8182 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8183 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8184 if (!C2) return nullptr; 8185 8186 // First pointer! 8187 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8188 unsigned AS = C2->getType()->getPointerAddressSpace(); 8189 std::swap(C, C2); 8190 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8191 // The offsets have been converted to bytes. We can add bytes to an 8192 // i8* by GEP with the byte count in the first index. 8193 C = ConstantExpr::getBitCast(C, DestPtrTy); 8194 } 8195 8196 // Don't bother trying to sum two pointers. We probably can't 8197 // statically compute a load that results from it anyway. 8198 if (C2->getType()->isPointerTy()) 8199 return nullptr; 8200 8201 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8202 if (PTy->getElementType()->isStructTy()) 8203 C2 = ConstantExpr::getIntegerCast( 8204 C2, Type::getInt32Ty(C->getContext()), true); 8205 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8206 } else 8207 C = ConstantExpr::getAdd(C, C2); 8208 } 8209 return C; 8210 } 8211 break; 8212 } 8213 case scMulExpr: { 8214 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8215 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8216 // Don't bother with pointers at all. 8217 if (C->getType()->isPointerTy()) return nullptr; 8218 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8219 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8220 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8221 C = ConstantExpr::getMul(C, C2); 8222 } 8223 return C; 8224 } 8225 break; 8226 } 8227 case scUDivExpr: { 8228 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8229 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8230 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8231 if (LHS->getType() == RHS->getType()) 8232 return ConstantExpr::getUDiv(LHS, RHS); 8233 break; 8234 } 8235 case scSMaxExpr: 8236 case scUMaxExpr: 8237 case scSMinExpr: 8238 case scUMinExpr: 8239 break; // TODO: smax, umax, smin, umax. 8240 } 8241 return nullptr; 8242 } 8243 8244 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8245 if (isa<SCEVConstant>(V)) return V; 8246 8247 // If this instruction is evolved from a constant-evolving PHI, compute the 8248 // exit value from the loop without using SCEVs. 8249 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8250 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8251 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8252 const Loop *LI = this->LI[I->getParent()]; 8253 // Looking for loop exit value. 8254 if (LI && LI->getParentLoop() == L && 8255 PN->getParent() == LI->getHeader()) { 8256 // Okay, there is no closed form solution for the PHI node. Check 8257 // to see if the loop that contains it has a known backedge-taken 8258 // count. If so, we may be able to force computation of the exit 8259 // value. 8260 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8261 // This trivial case can show up in some degenerate cases where 8262 // the incoming IR has not yet been fully simplified. 8263 if (BackedgeTakenCount->isZero()) { 8264 Value *InitValue = nullptr; 8265 bool MultipleInitValues = false; 8266 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8267 if (!LI->contains(PN->getIncomingBlock(i))) { 8268 if (!InitValue) 8269 InitValue = PN->getIncomingValue(i); 8270 else if (InitValue != PN->getIncomingValue(i)) { 8271 MultipleInitValues = true; 8272 break; 8273 } 8274 } 8275 } 8276 if (!MultipleInitValues && InitValue) 8277 return getSCEV(InitValue); 8278 } 8279 // Do we have a loop invariant value flowing around the backedge 8280 // for a loop which must execute the backedge? 8281 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8282 isKnownPositive(BackedgeTakenCount) && 8283 PN->getNumIncomingValues() == 2) { 8284 8285 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8286 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8287 if (LI->isLoopInvariant(BackedgeVal)) 8288 return getSCEV(BackedgeVal); 8289 } 8290 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8291 // Okay, we know how many times the containing loop executes. If 8292 // this is a constant evolving PHI node, get the final value at 8293 // the specified iteration number. 8294 Constant *RV = 8295 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8296 if (RV) return getSCEV(RV); 8297 } 8298 } 8299 8300 // If there is a single-input Phi, evaluate it at our scope. If we can 8301 // prove that this replacement does not break LCSSA form, use new value. 8302 if (PN->getNumOperands() == 1) { 8303 const SCEV *Input = getSCEV(PN->getOperand(0)); 8304 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8305 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8306 // for the simplest case just support constants. 8307 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8308 } 8309 } 8310 8311 // Okay, this is an expression that we cannot symbolically evaluate 8312 // into a SCEV. Check to see if it's possible to symbolically evaluate 8313 // the arguments into constants, and if so, try to constant propagate the 8314 // result. This is particularly useful for computing loop exit values. 8315 if (CanConstantFold(I)) { 8316 SmallVector<Constant *, 4> Operands; 8317 bool MadeImprovement = false; 8318 for (Value *Op : I->operands()) { 8319 if (Constant *C = dyn_cast<Constant>(Op)) { 8320 Operands.push_back(C); 8321 continue; 8322 } 8323 8324 // If any of the operands is non-constant and if they are 8325 // non-integer and non-pointer, don't even try to analyze them 8326 // with scev techniques. 8327 if (!isSCEVable(Op->getType())) 8328 return V; 8329 8330 const SCEV *OrigV = getSCEV(Op); 8331 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8332 MadeImprovement |= OrigV != OpV; 8333 8334 Constant *C = BuildConstantFromSCEV(OpV); 8335 if (!C) return V; 8336 if (C->getType() != Op->getType()) 8337 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8338 Op->getType(), 8339 false), 8340 C, Op->getType()); 8341 Operands.push_back(C); 8342 } 8343 8344 // Check to see if getSCEVAtScope actually made an improvement. 8345 if (MadeImprovement) { 8346 Constant *C = nullptr; 8347 const DataLayout &DL = getDataLayout(); 8348 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8349 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8350 Operands[1], DL, &TLI); 8351 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8352 if (!LI->isVolatile()) 8353 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8354 } else 8355 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8356 if (!C) return V; 8357 return getSCEV(C); 8358 } 8359 } 8360 } 8361 8362 // This is some other type of SCEVUnknown, just return it. 8363 return V; 8364 } 8365 8366 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8367 // Avoid performing the look-up in the common case where the specified 8368 // expression has no loop-variant portions. 8369 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8370 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8371 if (OpAtScope != Comm->getOperand(i)) { 8372 // Okay, at least one of these operands is loop variant but might be 8373 // foldable. Build a new instance of the folded commutative expression. 8374 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8375 Comm->op_begin()+i); 8376 NewOps.push_back(OpAtScope); 8377 8378 for (++i; i != e; ++i) { 8379 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8380 NewOps.push_back(OpAtScope); 8381 } 8382 if (isa<SCEVAddExpr>(Comm)) 8383 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8384 if (isa<SCEVMulExpr>(Comm)) 8385 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8386 if (isa<SCEVMinMaxExpr>(Comm)) 8387 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8388 llvm_unreachable("Unknown commutative SCEV type!"); 8389 } 8390 } 8391 // If we got here, all operands are loop invariant. 8392 return Comm; 8393 } 8394 8395 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8396 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8397 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8398 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8399 return Div; // must be loop invariant 8400 return getUDivExpr(LHS, RHS); 8401 } 8402 8403 // If this is a loop recurrence for a loop that does not contain L, then we 8404 // are dealing with the final value computed by the loop. 8405 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8406 // First, attempt to evaluate each operand. 8407 // Avoid performing the look-up in the common case where the specified 8408 // expression has no loop-variant portions. 8409 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8410 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8411 if (OpAtScope == AddRec->getOperand(i)) 8412 continue; 8413 8414 // Okay, at least one of these operands is loop variant but might be 8415 // foldable. Build a new instance of the folded commutative expression. 8416 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8417 AddRec->op_begin()+i); 8418 NewOps.push_back(OpAtScope); 8419 for (++i; i != e; ++i) 8420 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8421 8422 const SCEV *FoldedRec = 8423 getAddRecExpr(NewOps, AddRec->getLoop(), 8424 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8425 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8426 // The addrec may be folded to a nonrecurrence, for example, if the 8427 // induction variable is multiplied by zero after constant folding. Go 8428 // ahead and return the folded value. 8429 if (!AddRec) 8430 return FoldedRec; 8431 break; 8432 } 8433 8434 // If the scope is outside the addrec's loop, evaluate it by using the 8435 // loop exit value of the addrec. 8436 if (!AddRec->getLoop()->contains(L)) { 8437 // To evaluate this recurrence, we need to know how many times the AddRec 8438 // loop iterates. Compute this now. 8439 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8440 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8441 8442 // Then, evaluate the AddRec. 8443 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8444 } 8445 8446 return AddRec; 8447 } 8448 8449 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8450 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8451 if (Op == Cast->getOperand()) 8452 return Cast; // must be loop invariant 8453 return getZeroExtendExpr(Op, Cast->getType()); 8454 } 8455 8456 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8457 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8458 if (Op == Cast->getOperand()) 8459 return Cast; // must be loop invariant 8460 return getSignExtendExpr(Op, Cast->getType()); 8461 } 8462 8463 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8464 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8465 if (Op == Cast->getOperand()) 8466 return Cast; // must be loop invariant 8467 return getTruncateExpr(Op, Cast->getType()); 8468 } 8469 8470 llvm_unreachable("Unknown SCEV type!"); 8471 } 8472 8473 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8474 return getSCEVAtScope(getSCEV(V), L); 8475 } 8476 8477 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8478 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8479 return stripInjectiveFunctions(ZExt->getOperand()); 8480 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8481 return stripInjectiveFunctions(SExt->getOperand()); 8482 return S; 8483 } 8484 8485 /// Finds the minimum unsigned root of the following equation: 8486 /// 8487 /// A * X = B (mod N) 8488 /// 8489 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8490 /// A and B isn't important. 8491 /// 8492 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8493 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8494 ScalarEvolution &SE) { 8495 uint32_t BW = A.getBitWidth(); 8496 assert(BW == SE.getTypeSizeInBits(B->getType())); 8497 assert(A != 0 && "A must be non-zero."); 8498 8499 // 1. D = gcd(A, N) 8500 // 8501 // The gcd of A and N may have only one prime factor: 2. The number of 8502 // trailing zeros in A is its multiplicity 8503 uint32_t Mult2 = A.countTrailingZeros(); 8504 // D = 2^Mult2 8505 8506 // 2. Check if B is divisible by D. 8507 // 8508 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8509 // is not less than multiplicity of this prime factor for D. 8510 if (SE.GetMinTrailingZeros(B) < Mult2) 8511 return SE.getCouldNotCompute(); 8512 8513 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8514 // modulo (N / D). 8515 // 8516 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8517 // (N / D) in general. The inverse itself always fits into BW bits, though, 8518 // so we immediately truncate it. 8519 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8520 APInt Mod(BW + 1, 0); 8521 Mod.setBit(BW - Mult2); // Mod = N / D 8522 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8523 8524 // 4. Compute the minimum unsigned root of the equation: 8525 // I * (B / D) mod (N / D) 8526 // To simplify the computation, we factor out the divide by D: 8527 // (I * B mod N) / D 8528 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8529 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8530 } 8531 8532 /// For a given quadratic addrec, generate coefficients of the corresponding 8533 /// quadratic equation, multiplied by a common value to ensure that they are 8534 /// integers. 8535 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8536 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8537 /// were multiplied by, and BitWidth is the bit width of the original addrec 8538 /// coefficients. 8539 /// This function returns None if the addrec coefficients are not compile- 8540 /// time constants. 8541 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8542 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8543 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8544 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8545 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8546 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8547 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8548 << *AddRec << '\n'); 8549 8550 // We currently can only solve this if the coefficients are constants. 8551 if (!LC || !MC || !NC) { 8552 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8553 return None; 8554 } 8555 8556 APInt L = LC->getAPInt(); 8557 APInt M = MC->getAPInt(); 8558 APInt N = NC->getAPInt(); 8559 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8560 8561 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8562 unsigned NewWidth = BitWidth + 1; 8563 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8564 << BitWidth << '\n'); 8565 // The sign-extension (as opposed to a zero-extension) here matches the 8566 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8567 N = N.sext(NewWidth); 8568 M = M.sext(NewWidth); 8569 L = L.sext(NewWidth); 8570 8571 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8572 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8573 // L+M, L+2M+N, L+3M+3N, ... 8574 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8575 // 8576 // The equation Acc = 0 is then 8577 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8578 // In a quadratic form it becomes: 8579 // N n^2 + (2M-N) n + 2L = 0. 8580 8581 APInt A = N; 8582 APInt B = 2 * M - A; 8583 APInt C = 2 * L; 8584 APInt T = APInt(NewWidth, 2); 8585 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8586 << "x + " << C << ", coeff bw: " << NewWidth 8587 << ", multiplied by " << T << '\n'); 8588 return std::make_tuple(A, B, C, T, BitWidth); 8589 } 8590 8591 /// Helper function to compare optional APInts: 8592 /// (a) if X and Y both exist, return min(X, Y), 8593 /// (b) if neither X nor Y exist, return None, 8594 /// (c) if exactly one of X and Y exists, return that value. 8595 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8596 if (X.hasValue() && Y.hasValue()) { 8597 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8598 APInt XW = X->sextOrSelf(W); 8599 APInt YW = Y->sextOrSelf(W); 8600 return XW.slt(YW) ? *X : *Y; 8601 } 8602 if (!X.hasValue() && !Y.hasValue()) 8603 return None; 8604 return X.hasValue() ? *X : *Y; 8605 } 8606 8607 /// Helper function to truncate an optional APInt to a given BitWidth. 8608 /// When solving addrec-related equations, it is preferable to return a value 8609 /// that has the same bit width as the original addrec's coefficients. If the 8610 /// solution fits in the original bit width, truncate it (except for i1). 8611 /// Returning a value of a different bit width may inhibit some optimizations. 8612 /// 8613 /// In general, a solution to a quadratic equation generated from an addrec 8614 /// may require BW+1 bits, where BW is the bit width of the addrec's 8615 /// coefficients. The reason is that the coefficients of the quadratic 8616 /// equation are BW+1 bits wide (to avoid truncation when converting from 8617 /// the addrec to the equation). 8618 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8619 if (!X.hasValue()) 8620 return None; 8621 unsigned W = X->getBitWidth(); 8622 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8623 return X->trunc(BitWidth); 8624 return X; 8625 } 8626 8627 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8628 /// iterations. The values L, M, N are assumed to be signed, and they 8629 /// should all have the same bit widths. 8630 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8631 /// where BW is the bit width of the addrec's coefficients. 8632 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8633 /// returned as such, otherwise the bit width of the returned value may 8634 /// be greater than BW. 8635 /// 8636 /// This function returns None if 8637 /// (a) the addrec coefficients are not constant, or 8638 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8639 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8640 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8641 static Optional<APInt> 8642 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8643 APInt A, B, C, M; 8644 unsigned BitWidth; 8645 auto T = GetQuadraticEquation(AddRec); 8646 if (!T.hasValue()) 8647 return None; 8648 8649 std::tie(A, B, C, M, BitWidth) = *T; 8650 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8651 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8652 if (!X.hasValue()) 8653 return None; 8654 8655 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8656 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8657 if (!V->isZero()) 8658 return None; 8659 8660 return TruncIfPossible(X, BitWidth); 8661 } 8662 8663 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8664 /// iterations. The values M, N are assumed to be signed, and they 8665 /// should all have the same bit widths. 8666 /// Find the least n such that c(n) does not belong to the given range, 8667 /// while c(n-1) does. 8668 /// 8669 /// This function returns None if 8670 /// (a) the addrec coefficients are not constant, or 8671 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8672 /// bounds of the range. 8673 static Optional<APInt> 8674 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8675 const ConstantRange &Range, ScalarEvolution &SE) { 8676 assert(AddRec->getOperand(0)->isZero() && 8677 "Starting value of addrec should be 0"); 8678 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8679 << Range << ", addrec " << *AddRec << '\n'); 8680 // This case is handled in getNumIterationsInRange. Here we can assume that 8681 // we start in the range. 8682 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8683 "Addrec's initial value should be in range"); 8684 8685 APInt A, B, C, M; 8686 unsigned BitWidth; 8687 auto T = GetQuadraticEquation(AddRec); 8688 if (!T.hasValue()) 8689 return None; 8690 8691 // Be careful about the return value: there can be two reasons for not 8692 // returning an actual number. First, if no solutions to the equations 8693 // were found, and second, if the solutions don't leave the given range. 8694 // The first case means that the actual solution is "unknown", the second 8695 // means that it's known, but not valid. If the solution is unknown, we 8696 // cannot make any conclusions. 8697 // Return a pair: the optional solution and a flag indicating if the 8698 // solution was found. 8699 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8700 // Solve for signed overflow and unsigned overflow, pick the lower 8701 // solution. 8702 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8703 << Bound << " (before multiplying by " << M << ")\n"); 8704 Bound *= M; // The quadratic equation multiplier. 8705 8706 Optional<APInt> SO = None; 8707 if (BitWidth > 1) { 8708 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8709 "signed overflow\n"); 8710 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8711 } 8712 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8713 "unsigned overflow\n"); 8714 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8715 BitWidth+1); 8716 8717 auto LeavesRange = [&] (const APInt &X) { 8718 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8719 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8720 if (Range.contains(V0->getValue())) 8721 return false; 8722 // X should be at least 1, so X-1 is non-negative. 8723 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8724 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8725 if (Range.contains(V1->getValue())) 8726 return true; 8727 return false; 8728 }; 8729 8730 // If SolveQuadraticEquationWrap returns None, it means that there can 8731 // be a solution, but the function failed to find it. We cannot treat it 8732 // as "no solution". 8733 if (!SO.hasValue() || !UO.hasValue()) 8734 return { None, false }; 8735 8736 // Check the smaller value first to see if it leaves the range. 8737 // At this point, both SO and UO must have values. 8738 Optional<APInt> Min = MinOptional(SO, UO); 8739 if (LeavesRange(*Min)) 8740 return { Min, true }; 8741 Optional<APInt> Max = Min == SO ? UO : SO; 8742 if (LeavesRange(*Max)) 8743 return { Max, true }; 8744 8745 // Solutions were found, but were eliminated, hence the "true". 8746 return { None, true }; 8747 }; 8748 8749 std::tie(A, B, C, M, BitWidth) = *T; 8750 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8751 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8752 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8753 auto SL = SolveForBoundary(Lower); 8754 auto SU = SolveForBoundary(Upper); 8755 // If any of the solutions was unknown, no meaninigful conclusions can 8756 // be made. 8757 if (!SL.second || !SU.second) 8758 return None; 8759 8760 // Claim: The correct solution is not some value between Min and Max. 8761 // 8762 // Justification: Assuming that Min and Max are different values, one of 8763 // them is when the first signed overflow happens, the other is when the 8764 // first unsigned overflow happens. Crossing the range boundary is only 8765 // possible via an overflow (treating 0 as a special case of it, modeling 8766 // an overflow as crossing k*2^W for some k). 8767 // 8768 // The interesting case here is when Min was eliminated as an invalid 8769 // solution, but Max was not. The argument is that if there was another 8770 // overflow between Min and Max, it would also have been eliminated if 8771 // it was considered. 8772 // 8773 // For a given boundary, it is possible to have two overflows of the same 8774 // type (signed/unsigned) without having the other type in between: this 8775 // can happen when the vertex of the parabola is between the iterations 8776 // corresponding to the overflows. This is only possible when the two 8777 // overflows cross k*2^W for the same k. In such case, if the second one 8778 // left the range (and was the first one to do so), the first overflow 8779 // would have to enter the range, which would mean that either we had left 8780 // the range before or that we started outside of it. Both of these cases 8781 // are contradictions. 8782 // 8783 // Claim: In the case where SolveForBoundary returns None, the correct 8784 // solution is not some value between the Max for this boundary and the 8785 // Min of the other boundary. 8786 // 8787 // Justification: Assume that we had such Max_A and Min_B corresponding 8788 // to range boundaries A and B and such that Max_A < Min_B. If there was 8789 // a solution between Max_A and Min_B, it would have to be caused by an 8790 // overflow corresponding to either A or B. It cannot correspond to B, 8791 // since Min_B is the first occurrence of such an overflow. If it 8792 // corresponded to A, it would have to be either a signed or an unsigned 8793 // overflow that is larger than both eliminated overflows for A. But 8794 // between the eliminated overflows and this overflow, the values would 8795 // cover the entire value space, thus crossing the other boundary, which 8796 // is a contradiction. 8797 8798 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8799 } 8800 8801 ScalarEvolution::ExitLimit 8802 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8803 bool AllowPredicates) { 8804 8805 // This is only used for loops with a "x != y" exit test. The exit condition 8806 // is now expressed as a single expression, V = x-y. So the exit test is 8807 // effectively V != 0. We know and take advantage of the fact that this 8808 // expression only being used in a comparison by zero context. 8809 8810 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8811 // If the value is a constant 8812 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8813 // If the value is already zero, the branch will execute zero times. 8814 if (C->getValue()->isZero()) return C; 8815 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8816 } 8817 8818 const SCEVAddRecExpr *AddRec = 8819 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8820 8821 if (!AddRec && AllowPredicates) 8822 // Try to make this an AddRec using runtime tests, in the first X 8823 // iterations of this loop, where X is the SCEV expression found by the 8824 // algorithm below. 8825 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8826 8827 if (!AddRec || AddRec->getLoop() != L) 8828 return getCouldNotCompute(); 8829 8830 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8831 // the quadratic equation to solve it. 8832 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8833 // We can only use this value if the chrec ends up with an exact zero 8834 // value at this index. When solving for "X*X != 5", for example, we 8835 // should not accept a root of 2. 8836 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8837 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8838 return ExitLimit(R, R, false, Predicates); 8839 } 8840 return getCouldNotCompute(); 8841 } 8842 8843 // Otherwise we can only handle this if it is affine. 8844 if (!AddRec->isAffine()) 8845 return getCouldNotCompute(); 8846 8847 // If this is an affine expression, the execution count of this branch is 8848 // the minimum unsigned root of the following equation: 8849 // 8850 // Start + Step*N = 0 (mod 2^BW) 8851 // 8852 // equivalent to: 8853 // 8854 // Step*N = -Start (mod 2^BW) 8855 // 8856 // where BW is the common bit width of Start and Step. 8857 8858 // Get the initial value for the loop. 8859 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8860 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8861 8862 // For now we handle only constant steps. 8863 // 8864 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8865 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8866 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8867 // We have not yet seen any such cases. 8868 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8869 if (!StepC || StepC->getValue()->isZero()) 8870 return getCouldNotCompute(); 8871 8872 // For positive steps (counting up until unsigned overflow): 8873 // N = -Start/Step (as unsigned) 8874 // For negative steps (counting down to zero): 8875 // N = Start/-Step 8876 // First compute the unsigned distance from zero in the direction of Step. 8877 bool CountDown = StepC->getAPInt().isNegative(); 8878 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8879 8880 // Handle unitary steps, which cannot wraparound. 8881 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8882 // N = Distance (as unsigned) 8883 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8884 APInt MaxBECount = getUnsignedRangeMax(Distance); 8885 8886 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8887 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8888 // case, and see if we can improve the bound. 8889 // 8890 // Explicitly handling this here is necessary because getUnsignedRange 8891 // isn't context-sensitive; it doesn't know that we only care about the 8892 // range inside the loop. 8893 const SCEV *Zero = getZero(Distance->getType()); 8894 const SCEV *One = getOne(Distance->getType()); 8895 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8896 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8897 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8898 // as "unsigned_max(Distance + 1) - 1". 8899 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8900 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8901 } 8902 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8903 } 8904 8905 // If the condition controls loop exit (the loop exits only if the expression 8906 // is true) and the addition is no-wrap we can use unsigned divide to 8907 // compute the backedge count. In this case, the step may not divide the 8908 // distance, but we don't care because if the condition is "missed" the loop 8909 // will have undefined behavior due to wrapping. 8910 if (ControlsExit && AddRec->hasNoSelfWrap() && 8911 loopHasNoAbnormalExits(AddRec->getLoop())) { 8912 const SCEV *Exact = 8913 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8914 const SCEV *Max = 8915 Exact == getCouldNotCompute() 8916 ? Exact 8917 : getConstant(getUnsignedRangeMax(Exact)); 8918 return ExitLimit(Exact, Max, false, Predicates); 8919 } 8920 8921 // Solve the general equation. 8922 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8923 getNegativeSCEV(Start), *this); 8924 const SCEV *M = E == getCouldNotCompute() 8925 ? E 8926 : getConstant(getUnsignedRangeMax(E)); 8927 return ExitLimit(E, M, false, Predicates); 8928 } 8929 8930 ScalarEvolution::ExitLimit 8931 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8932 // Loops that look like: while (X == 0) are very strange indeed. We don't 8933 // handle them yet except for the trivial case. This could be expanded in the 8934 // future as needed. 8935 8936 // If the value is a constant, check to see if it is known to be non-zero 8937 // already. If so, the backedge will execute zero times. 8938 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8939 if (!C->getValue()->isZero()) 8940 return getZero(C->getType()); 8941 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8942 } 8943 8944 // We could implement others, but I really doubt anyone writes loops like 8945 // this, and if they did, they would already be constant folded. 8946 return getCouldNotCompute(); 8947 } 8948 8949 std::pair<BasicBlock *, BasicBlock *> 8950 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8951 // If the block has a unique predecessor, then there is no path from the 8952 // predecessor to the block that does not go through the direct edge 8953 // from the predecessor to the block. 8954 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8955 return {Pred, BB}; 8956 8957 // A loop's header is defined to be a block that dominates the loop. 8958 // If the header has a unique predecessor outside the loop, it must be 8959 // a block that has exactly one successor that can reach the loop. 8960 if (Loop *L = LI.getLoopFor(BB)) 8961 return {L->getLoopPredecessor(), L->getHeader()}; 8962 8963 return {nullptr, nullptr}; 8964 } 8965 8966 /// SCEV structural equivalence is usually sufficient for testing whether two 8967 /// expressions are equal, however for the purposes of looking for a condition 8968 /// guarding a loop, it can be useful to be a little more general, since a 8969 /// front-end may have replicated the controlling expression. 8970 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8971 // Quick check to see if they are the same SCEV. 8972 if (A == B) return true; 8973 8974 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8975 // Not all instructions that are "identical" compute the same value. For 8976 // instance, two distinct alloca instructions allocating the same type are 8977 // identical and do not read memory; but compute distinct values. 8978 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8979 }; 8980 8981 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8982 // two different instructions with the same value. Check for this case. 8983 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8984 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8985 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8986 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8987 if (ComputesEqualValues(AI, BI)) 8988 return true; 8989 8990 // Otherwise assume they may have a different value. 8991 return false; 8992 } 8993 8994 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8995 const SCEV *&LHS, const SCEV *&RHS, 8996 unsigned Depth) { 8997 bool Changed = false; 8998 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8999 // '0 != 0'. 9000 auto TrivialCase = [&](bool TriviallyTrue) { 9001 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9002 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9003 return true; 9004 }; 9005 // If we hit the max recursion limit bail out. 9006 if (Depth >= 3) 9007 return false; 9008 9009 // Canonicalize a constant to the right side. 9010 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9011 // Check for both operands constant. 9012 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9013 if (ConstantExpr::getICmp(Pred, 9014 LHSC->getValue(), 9015 RHSC->getValue())->isNullValue()) 9016 return TrivialCase(false); 9017 else 9018 return TrivialCase(true); 9019 } 9020 // Otherwise swap the operands to put the constant on the right. 9021 std::swap(LHS, RHS); 9022 Pred = ICmpInst::getSwappedPredicate(Pred); 9023 Changed = true; 9024 } 9025 9026 // If we're comparing an addrec with a value which is loop-invariant in the 9027 // addrec's loop, put the addrec on the left. Also make a dominance check, 9028 // as both operands could be addrecs loop-invariant in each other's loop. 9029 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9030 const Loop *L = AR->getLoop(); 9031 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9032 std::swap(LHS, RHS); 9033 Pred = ICmpInst::getSwappedPredicate(Pred); 9034 Changed = true; 9035 } 9036 } 9037 9038 // If there's a constant operand, canonicalize comparisons with boundary 9039 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9040 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9041 const APInt &RA = RC->getAPInt(); 9042 9043 bool SimplifiedByConstantRange = false; 9044 9045 if (!ICmpInst::isEquality(Pred)) { 9046 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9047 if (ExactCR.isFullSet()) 9048 return TrivialCase(true); 9049 else if (ExactCR.isEmptySet()) 9050 return TrivialCase(false); 9051 9052 APInt NewRHS; 9053 CmpInst::Predicate NewPred; 9054 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9055 ICmpInst::isEquality(NewPred)) { 9056 // We were able to convert an inequality to an equality. 9057 Pred = NewPred; 9058 RHS = getConstant(NewRHS); 9059 Changed = SimplifiedByConstantRange = true; 9060 } 9061 } 9062 9063 if (!SimplifiedByConstantRange) { 9064 switch (Pred) { 9065 default: 9066 break; 9067 case ICmpInst::ICMP_EQ: 9068 case ICmpInst::ICMP_NE: 9069 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9070 if (!RA) 9071 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9072 if (const SCEVMulExpr *ME = 9073 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9074 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9075 ME->getOperand(0)->isAllOnesValue()) { 9076 RHS = AE->getOperand(1); 9077 LHS = ME->getOperand(1); 9078 Changed = true; 9079 } 9080 break; 9081 9082 9083 // The "Should have been caught earlier!" messages refer to the fact 9084 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9085 // should have fired on the corresponding cases, and canonicalized the 9086 // check to trivial case. 9087 9088 case ICmpInst::ICMP_UGE: 9089 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9090 Pred = ICmpInst::ICMP_UGT; 9091 RHS = getConstant(RA - 1); 9092 Changed = true; 9093 break; 9094 case ICmpInst::ICMP_ULE: 9095 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9096 Pred = ICmpInst::ICMP_ULT; 9097 RHS = getConstant(RA + 1); 9098 Changed = true; 9099 break; 9100 case ICmpInst::ICMP_SGE: 9101 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9102 Pred = ICmpInst::ICMP_SGT; 9103 RHS = getConstant(RA - 1); 9104 Changed = true; 9105 break; 9106 case ICmpInst::ICMP_SLE: 9107 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9108 Pred = ICmpInst::ICMP_SLT; 9109 RHS = getConstant(RA + 1); 9110 Changed = true; 9111 break; 9112 } 9113 } 9114 } 9115 9116 // Check for obvious equality. 9117 if (HasSameValue(LHS, RHS)) { 9118 if (ICmpInst::isTrueWhenEqual(Pred)) 9119 return TrivialCase(true); 9120 if (ICmpInst::isFalseWhenEqual(Pred)) 9121 return TrivialCase(false); 9122 } 9123 9124 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9125 // adding or subtracting 1 from one of the operands. 9126 switch (Pred) { 9127 case ICmpInst::ICMP_SLE: 9128 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9129 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9130 SCEV::FlagNSW); 9131 Pred = ICmpInst::ICMP_SLT; 9132 Changed = true; 9133 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9134 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9135 SCEV::FlagNSW); 9136 Pred = ICmpInst::ICMP_SLT; 9137 Changed = true; 9138 } 9139 break; 9140 case ICmpInst::ICMP_SGE: 9141 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9142 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9143 SCEV::FlagNSW); 9144 Pred = ICmpInst::ICMP_SGT; 9145 Changed = true; 9146 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9147 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9148 SCEV::FlagNSW); 9149 Pred = ICmpInst::ICMP_SGT; 9150 Changed = true; 9151 } 9152 break; 9153 case ICmpInst::ICMP_ULE: 9154 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9155 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9156 SCEV::FlagNUW); 9157 Pred = ICmpInst::ICMP_ULT; 9158 Changed = true; 9159 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9160 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9161 Pred = ICmpInst::ICMP_ULT; 9162 Changed = true; 9163 } 9164 break; 9165 case ICmpInst::ICMP_UGE: 9166 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9167 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9168 Pred = ICmpInst::ICMP_UGT; 9169 Changed = true; 9170 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9171 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9172 SCEV::FlagNUW); 9173 Pred = ICmpInst::ICMP_UGT; 9174 Changed = true; 9175 } 9176 break; 9177 default: 9178 break; 9179 } 9180 9181 // TODO: More simplifications are possible here. 9182 9183 // Recursively simplify until we either hit a recursion limit or nothing 9184 // changes. 9185 if (Changed) 9186 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9187 9188 return Changed; 9189 } 9190 9191 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9192 return getSignedRangeMax(S).isNegative(); 9193 } 9194 9195 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9196 return getSignedRangeMin(S).isStrictlyPositive(); 9197 } 9198 9199 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9200 return !getSignedRangeMin(S).isNegative(); 9201 } 9202 9203 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9204 return !getSignedRangeMax(S).isStrictlyPositive(); 9205 } 9206 9207 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9208 return isKnownNegative(S) || isKnownPositive(S); 9209 } 9210 9211 std::pair<const SCEV *, const SCEV *> 9212 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9213 // Compute SCEV on entry of loop L. 9214 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9215 if (Start == getCouldNotCompute()) 9216 return { Start, Start }; 9217 // Compute post increment SCEV for loop L. 9218 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9219 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9220 return { Start, PostInc }; 9221 } 9222 9223 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9224 const SCEV *LHS, const SCEV *RHS) { 9225 // First collect all loops. 9226 SmallPtrSet<const Loop *, 8> LoopsUsed; 9227 getUsedLoops(LHS, LoopsUsed); 9228 getUsedLoops(RHS, LoopsUsed); 9229 9230 if (LoopsUsed.empty()) 9231 return false; 9232 9233 // Domination relationship must be a linear order on collected loops. 9234 #ifndef NDEBUG 9235 for (auto *L1 : LoopsUsed) 9236 for (auto *L2 : LoopsUsed) 9237 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9238 DT.dominates(L2->getHeader(), L1->getHeader())) && 9239 "Domination relationship is not a linear order"); 9240 #endif 9241 9242 const Loop *MDL = 9243 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9244 [&](const Loop *L1, const Loop *L2) { 9245 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9246 }); 9247 9248 // Get init and post increment value for LHS. 9249 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9250 // if LHS contains unknown non-invariant SCEV then bail out. 9251 if (SplitLHS.first == getCouldNotCompute()) 9252 return false; 9253 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9254 // Get init and post increment value for RHS. 9255 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9256 // if RHS contains unknown non-invariant SCEV then bail out. 9257 if (SplitRHS.first == getCouldNotCompute()) 9258 return false; 9259 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9260 // It is possible that init SCEV contains an invariant load but it does 9261 // not dominate MDL and is not available at MDL loop entry, so we should 9262 // check it here. 9263 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9264 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9265 return false; 9266 9267 // It seems backedge guard check is faster than entry one so in some cases 9268 // it can speed up whole estimation by short circuit 9269 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9270 SplitRHS.second) && 9271 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9272 } 9273 9274 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9275 const SCEV *LHS, const SCEV *RHS) { 9276 // Canonicalize the inputs first. 9277 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9278 9279 if (isKnownViaInduction(Pred, LHS, RHS)) 9280 return true; 9281 9282 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9283 return true; 9284 9285 // Otherwise see what can be done with some simple reasoning. 9286 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9287 } 9288 9289 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9290 const SCEVAddRecExpr *LHS, 9291 const SCEV *RHS) { 9292 const Loop *L = LHS->getLoop(); 9293 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9294 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9295 } 9296 9297 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9298 ICmpInst::Predicate Pred, 9299 bool &Increasing) { 9300 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9301 9302 #ifndef NDEBUG 9303 // Verify an invariant: inverting the predicate should turn a monotonically 9304 // increasing change to a monotonically decreasing one, and vice versa. 9305 bool IncreasingSwapped; 9306 bool ResultSwapped = isMonotonicPredicateImpl( 9307 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9308 9309 assert(Result == ResultSwapped && "should be able to analyze both!"); 9310 if (ResultSwapped) 9311 assert(Increasing == !IncreasingSwapped && 9312 "monotonicity should flip as we flip the predicate"); 9313 #endif 9314 9315 return Result; 9316 } 9317 9318 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9319 ICmpInst::Predicate Pred, 9320 bool &Increasing) { 9321 9322 // A zero step value for LHS means the induction variable is essentially a 9323 // loop invariant value. We don't really depend on the predicate actually 9324 // flipping from false to true (for increasing predicates, and the other way 9325 // around for decreasing predicates), all we care about is that *if* the 9326 // predicate changes then it only changes from false to true. 9327 // 9328 // A zero step value in itself is not very useful, but there may be places 9329 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9330 // as general as possible. 9331 9332 switch (Pred) { 9333 default: 9334 return false; // Conservative answer 9335 9336 case ICmpInst::ICMP_UGT: 9337 case ICmpInst::ICMP_UGE: 9338 case ICmpInst::ICMP_ULT: 9339 case ICmpInst::ICMP_ULE: 9340 if (!LHS->hasNoUnsignedWrap()) 9341 return false; 9342 9343 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9344 return true; 9345 9346 case ICmpInst::ICMP_SGT: 9347 case ICmpInst::ICMP_SGE: 9348 case ICmpInst::ICMP_SLT: 9349 case ICmpInst::ICMP_SLE: { 9350 if (!LHS->hasNoSignedWrap()) 9351 return false; 9352 9353 const SCEV *Step = LHS->getStepRecurrence(*this); 9354 9355 if (isKnownNonNegative(Step)) { 9356 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9357 return true; 9358 } 9359 9360 if (isKnownNonPositive(Step)) { 9361 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9362 return true; 9363 } 9364 9365 return false; 9366 } 9367 9368 } 9369 9370 llvm_unreachable("switch has default clause!"); 9371 } 9372 9373 bool ScalarEvolution::isLoopInvariantPredicate( 9374 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9375 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9376 const SCEV *&InvariantRHS) { 9377 9378 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9379 if (!isLoopInvariant(RHS, L)) { 9380 if (!isLoopInvariant(LHS, L)) 9381 return false; 9382 9383 std::swap(LHS, RHS); 9384 Pred = ICmpInst::getSwappedPredicate(Pred); 9385 } 9386 9387 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9388 if (!ArLHS || ArLHS->getLoop() != L) 9389 return false; 9390 9391 bool Increasing; 9392 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9393 return false; 9394 9395 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9396 // true as the loop iterates, and the backedge is control dependent on 9397 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9398 // 9399 // * if the predicate was false in the first iteration then the predicate 9400 // is never evaluated again, since the loop exits without taking the 9401 // backedge. 9402 // * if the predicate was true in the first iteration then it will 9403 // continue to be true for all future iterations since it is 9404 // monotonically increasing. 9405 // 9406 // For both the above possibilities, we can replace the loop varying 9407 // predicate with its value on the first iteration of the loop (which is 9408 // loop invariant). 9409 // 9410 // A similar reasoning applies for a monotonically decreasing predicate, by 9411 // replacing true with false and false with true in the above two bullets. 9412 9413 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9414 9415 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9416 return false; 9417 9418 InvariantPred = Pred; 9419 InvariantLHS = ArLHS->getStart(); 9420 InvariantRHS = RHS; 9421 return true; 9422 } 9423 9424 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9425 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9426 if (HasSameValue(LHS, RHS)) 9427 return ICmpInst::isTrueWhenEqual(Pred); 9428 9429 // This code is split out from isKnownPredicate because it is called from 9430 // within isLoopEntryGuardedByCond. 9431 9432 auto CheckRanges = 9433 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9434 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9435 .contains(RangeLHS); 9436 }; 9437 9438 // The check at the top of the function catches the case where the values are 9439 // known to be equal. 9440 if (Pred == CmpInst::ICMP_EQ) 9441 return false; 9442 9443 if (Pred == CmpInst::ICMP_NE) 9444 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9445 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9446 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9447 9448 if (CmpInst::isSigned(Pred)) 9449 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9450 9451 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9452 } 9453 9454 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9455 const SCEV *LHS, 9456 const SCEV *RHS) { 9457 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9458 // Return Y via OutY. 9459 auto MatchBinaryAddToConst = 9460 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9461 SCEV::NoWrapFlags ExpectedFlags) { 9462 const SCEV *NonConstOp, *ConstOp; 9463 SCEV::NoWrapFlags FlagsPresent; 9464 9465 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9466 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9467 return false; 9468 9469 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9470 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9471 }; 9472 9473 APInt C; 9474 9475 switch (Pred) { 9476 default: 9477 break; 9478 9479 case ICmpInst::ICMP_SGE: 9480 std::swap(LHS, RHS); 9481 LLVM_FALLTHROUGH; 9482 case ICmpInst::ICMP_SLE: 9483 // X s<= (X + C)<nsw> if C >= 0 9484 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9485 return true; 9486 9487 // (X + C)<nsw> s<= X if C <= 0 9488 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9489 !C.isStrictlyPositive()) 9490 return true; 9491 break; 9492 9493 case ICmpInst::ICMP_SGT: 9494 std::swap(LHS, RHS); 9495 LLVM_FALLTHROUGH; 9496 case ICmpInst::ICMP_SLT: 9497 // X s< (X + C)<nsw> if C > 0 9498 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9499 C.isStrictlyPositive()) 9500 return true; 9501 9502 // (X + C)<nsw> s< X if C < 0 9503 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9504 return true; 9505 break; 9506 } 9507 9508 return false; 9509 } 9510 9511 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9512 const SCEV *LHS, 9513 const SCEV *RHS) { 9514 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9515 return false; 9516 9517 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9518 // the stack can result in exponential time complexity. 9519 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9520 9521 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9522 // 9523 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9524 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9525 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9526 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9527 // use isKnownPredicate later if needed. 9528 return isKnownNonNegative(RHS) && 9529 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9530 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9531 } 9532 9533 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9534 ICmpInst::Predicate Pred, 9535 const SCEV *LHS, const SCEV *RHS) { 9536 // No need to even try if we know the module has no guards. 9537 if (!HasGuards) 9538 return false; 9539 9540 return any_of(*BB, [&](Instruction &I) { 9541 using namespace llvm::PatternMatch; 9542 9543 Value *Condition; 9544 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9545 m_Value(Condition))) && 9546 isImpliedCond(Pred, LHS, RHS, Condition, false); 9547 }); 9548 } 9549 9550 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9551 /// protected by a conditional between LHS and RHS. This is used to 9552 /// to eliminate casts. 9553 bool 9554 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9555 ICmpInst::Predicate Pred, 9556 const SCEV *LHS, const SCEV *RHS) { 9557 // Interpret a null as meaning no loop, where there is obviously no guard 9558 // (interprocedural conditions notwithstanding). 9559 if (!L) return true; 9560 9561 if (VerifyIR) 9562 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9563 "This cannot be done on broken IR!"); 9564 9565 9566 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9567 return true; 9568 9569 BasicBlock *Latch = L->getLoopLatch(); 9570 if (!Latch) 9571 return false; 9572 9573 BranchInst *LoopContinuePredicate = 9574 dyn_cast<BranchInst>(Latch->getTerminator()); 9575 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9576 isImpliedCond(Pred, LHS, RHS, 9577 LoopContinuePredicate->getCondition(), 9578 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9579 return true; 9580 9581 // We don't want more than one activation of the following loops on the stack 9582 // -- that can lead to O(n!) time complexity. 9583 if (WalkingBEDominatingConds) 9584 return false; 9585 9586 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9587 9588 // See if we can exploit a trip count to prove the predicate. 9589 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9590 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9591 if (LatchBECount != getCouldNotCompute()) { 9592 // We know that Latch branches back to the loop header exactly 9593 // LatchBECount times. This means the backdege condition at Latch is 9594 // equivalent to "{0,+,1} u< LatchBECount". 9595 Type *Ty = LatchBECount->getType(); 9596 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9597 const SCEV *LoopCounter = 9598 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9599 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9600 LatchBECount)) 9601 return true; 9602 } 9603 9604 // Check conditions due to any @llvm.assume intrinsics. 9605 for (auto &AssumeVH : AC.assumptions()) { 9606 if (!AssumeVH) 9607 continue; 9608 auto *CI = cast<CallInst>(AssumeVH); 9609 if (!DT.dominates(CI, Latch->getTerminator())) 9610 continue; 9611 9612 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9613 return true; 9614 } 9615 9616 // If the loop is not reachable from the entry block, we risk running into an 9617 // infinite loop as we walk up into the dom tree. These loops do not matter 9618 // anyway, so we just return a conservative answer when we see them. 9619 if (!DT.isReachableFromEntry(L->getHeader())) 9620 return false; 9621 9622 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9623 return true; 9624 9625 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9626 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9627 assert(DTN && "should reach the loop header before reaching the root!"); 9628 9629 BasicBlock *BB = DTN->getBlock(); 9630 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9631 return true; 9632 9633 BasicBlock *PBB = BB->getSinglePredecessor(); 9634 if (!PBB) 9635 continue; 9636 9637 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9638 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9639 continue; 9640 9641 Value *Condition = ContinuePredicate->getCondition(); 9642 9643 // If we have an edge `E` within the loop body that dominates the only 9644 // latch, the condition guarding `E` also guards the backedge. This 9645 // reasoning works only for loops with a single latch. 9646 9647 BasicBlockEdge DominatingEdge(PBB, BB); 9648 if (DominatingEdge.isSingleEdge()) { 9649 // We're constructively (and conservatively) enumerating edges within the 9650 // loop body that dominate the latch. The dominator tree better agree 9651 // with us on this: 9652 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9653 9654 if (isImpliedCond(Pred, LHS, RHS, Condition, 9655 BB != ContinuePredicate->getSuccessor(0))) 9656 return true; 9657 } 9658 } 9659 9660 return false; 9661 } 9662 9663 bool 9664 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9665 ICmpInst::Predicate Pred, 9666 const SCEV *LHS, const SCEV *RHS) { 9667 // Interpret a null as meaning no loop, where there is obviously no guard 9668 // (interprocedural conditions notwithstanding). 9669 if (!L) return false; 9670 9671 if (VerifyIR) 9672 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9673 "This cannot be done on broken IR!"); 9674 9675 // Both LHS and RHS must be available at loop entry. 9676 assert(isAvailableAtLoopEntry(LHS, L) && 9677 "LHS is not available at Loop Entry"); 9678 assert(isAvailableAtLoopEntry(RHS, L) && 9679 "RHS is not available at Loop Entry"); 9680 9681 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9682 return true; 9683 9684 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9685 // the facts (a >= b && a != b) separately. A typical situation is when the 9686 // non-strict comparison is known from ranges and non-equality is known from 9687 // dominating predicates. If we are proving strict comparison, we always try 9688 // to prove non-equality and non-strict comparison separately. 9689 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9690 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9691 bool ProvedNonStrictComparison = false; 9692 bool ProvedNonEquality = false; 9693 9694 if (ProvingStrictComparison) { 9695 ProvedNonStrictComparison = 9696 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9697 ProvedNonEquality = 9698 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9699 if (ProvedNonStrictComparison && ProvedNonEquality) 9700 return true; 9701 } 9702 9703 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9704 auto ProveViaGuard = [&](BasicBlock *Block) { 9705 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9706 return true; 9707 if (ProvingStrictComparison) { 9708 if (!ProvedNonStrictComparison) 9709 ProvedNonStrictComparison = 9710 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9711 if (!ProvedNonEquality) 9712 ProvedNonEquality = 9713 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9714 if (ProvedNonStrictComparison && ProvedNonEquality) 9715 return true; 9716 } 9717 return false; 9718 }; 9719 9720 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9721 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9722 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9723 return true; 9724 if (ProvingStrictComparison) { 9725 if (!ProvedNonStrictComparison) 9726 ProvedNonStrictComparison = 9727 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9728 if (!ProvedNonEquality) 9729 ProvedNonEquality = 9730 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9731 if (ProvedNonStrictComparison && ProvedNonEquality) 9732 return true; 9733 } 9734 return false; 9735 }; 9736 9737 // Starting at the loop predecessor, climb up the predecessor chain, as long 9738 // as there are predecessors that can be found that have unique successors 9739 // leading to the original header. 9740 for (std::pair<BasicBlock *, BasicBlock *> 9741 Pair(L->getLoopPredecessor(), L->getHeader()); 9742 Pair.first; 9743 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9744 9745 if (ProveViaGuard(Pair.first)) 9746 return true; 9747 9748 BranchInst *LoopEntryPredicate = 9749 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9750 if (!LoopEntryPredicate || 9751 LoopEntryPredicate->isUnconditional()) 9752 continue; 9753 9754 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9755 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9756 return true; 9757 } 9758 9759 // Check conditions due to any @llvm.assume intrinsics. 9760 for (auto &AssumeVH : AC.assumptions()) { 9761 if (!AssumeVH) 9762 continue; 9763 auto *CI = cast<CallInst>(AssumeVH); 9764 if (!DT.dominates(CI, L->getHeader())) 9765 continue; 9766 9767 if (ProveViaCond(CI->getArgOperand(0), false)) 9768 return true; 9769 } 9770 9771 return false; 9772 } 9773 9774 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9775 const SCEV *LHS, const SCEV *RHS, 9776 Value *FoundCondValue, 9777 bool Inverse) { 9778 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9779 return false; 9780 9781 auto ClearOnExit = 9782 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9783 9784 // Recursively handle And and Or conditions. 9785 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9786 if (BO->getOpcode() == Instruction::And) { 9787 if (!Inverse) 9788 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9789 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9790 } else if (BO->getOpcode() == Instruction::Or) { 9791 if (Inverse) 9792 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9793 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9794 } 9795 } 9796 9797 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9798 if (!ICI) return false; 9799 9800 // Now that we found a conditional branch that dominates the loop or controls 9801 // the loop latch. Check to see if it is the comparison we are looking for. 9802 ICmpInst::Predicate FoundPred; 9803 if (Inverse) 9804 FoundPred = ICI->getInversePredicate(); 9805 else 9806 FoundPred = ICI->getPredicate(); 9807 9808 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9809 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9810 9811 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9812 } 9813 9814 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9815 const SCEV *RHS, 9816 ICmpInst::Predicate FoundPred, 9817 const SCEV *FoundLHS, 9818 const SCEV *FoundRHS) { 9819 // Balance the types. 9820 if (getTypeSizeInBits(LHS->getType()) < 9821 getTypeSizeInBits(FoundLHS->getType())) { 9822 if (CmpInst::isSigned(Pred)) { 9823 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9824 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9825 } else { 9826 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9827 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9828 } 9829 } else if (getTypeSizeInBits(LHS->getType()) > 9830 getTypeSizeInBits(FoundLHS->getType())) { 9831 if (CmpInst::isSigned(FoundPred)) { 9832 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9833 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9834 } else { 9835 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9836 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9837 } 9838 } 9839 9840 // Canonicalize the query to match the way instcombine will have 9841 // canonicalized the comparison. 9842 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9843 if (LHS == RHS) 9844 return CmpInst::isTrueWhenEqual(Pred); 9845 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9846 if (FoundLHS == FoundRHS) 9847 return CmpInst::isFalseWhenEqual(FoundPred); 9848 9849 // Check to see if we can make the LHS or RHS match. 9850 if (LHS == FoundRHS || RHS == FoundLHS) { 9851 if (isa<SCEVConstant>(RHS)) { 9852 std::swap(FoundLHS, FoundRHS); 9853 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9854 } else { 9855 std::swap(LHS, RHS); 9856 Pred = ICmpInst::getSwappedPredicate(Pred); 9857 } 9858 } 9859 9860 // Check whether the found predicate is the same as the desired predicate. 9861 if (FoundPred == Pred) 9862 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9863 9864 // Check whether swapping the found predicate makes it the same as the 9865 // desired predicate. 9866 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9867 if (isa<SCEVConstant>(RHS)) 9868 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9869 else 9870 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9871 RHS, LHS, FoundLHS, FoundRHS); 9872 } 9873 9874 // Unsigned comparison is the same as signed comparison when both the operands 9875 // are non-negative. 9876 if (CmpInst::isUnsigned(FoundPred) && 9877 CmpInst::getSignedPredicate(FoundPred) == Pred && 9878 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9879 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9880 9881 // Check if we can make progress by sharpening ranges. 9882 if (FoundPred == ICmpInst::ICMP_NE && 9883 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9884 9885 const SCEVConstant *C = nullptr; 9886 const SCEV *V = nullptr; 9887 9888 if (isa<SCEVConstant>(FoundLHS)) { 9889 C = cast<SCEVConstant>(FoundLHS); 9890 V = FoundRHS; 9891 } else { 9892 C = cast<SCEVConstant>(FoundRHS); 9893 V = FoundLHS; 9894 } 9895 9896 // The guarding predicate tells us that C != V. If the known range 9897 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9898 // range we consider has to correspond to same signedness as the 9899 // predicate we're interested in folding. 9900 9901 APInt Min = ICmpInst::isSigned(Pred) ? 9902 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9903 9904 if (Min == C->getAPInt()) { 9905 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9906 // This is true even if (Min + 1) wraps around -- in case of 9907 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9908 9909 APInt SharperMin = Min + 1; 9910 9911 switch (Pred) { 9912 case ICmpInst::ICMP_SGE: 9913 case ICmpInst::ICMP_UGE: 9914 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9915 // RHS, we're done. 9916 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9917 getConstant(SharperMin))) 9918 return true; 9919 LLVM_FALLTHROUGH; 9920 9921 case ICmpInst::ICMP_SGT: 9922 case ICmpInst::ICMP_UGT: 9923 // We know from the range information that (V `Pred` Min || 9924 // V == Min). We know from the guarding condition that !(V 9925 // == Min). This gives us 9926 // 9927 // V `Pred` Min || V == Min && !(V == Min) 9928 // => V `Pred` Min 9929 // 9930 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9931 9932 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9933 return true; 9934 LLVM_FALLTHROUGH; 9935 9936 default: 9937 // No change 9938 break; 9939 } 9940 } 9941 } 9942 9943 // Check whether the actual condition is beyond sufficient. 9944 if (FoundPred == ICmpInst::ICMP_EQ) 9945 if (ICmpInst::isTrueWhenEqual(Pred)) 9946 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9947 return true; 9948 if (Pred == ICmpInst::ICMP_NE) 9949 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9950 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9951 return true; 9952 9953 // Otherwise assume the worst. 9954 return false; 9955 } 9956 9957 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9958 const SCEV *&L, const SCEV *&R, 9959 SCEV::NoWrapFlags &Flags) { 9960 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9961 if (!AE || AE->getNumOperands() != 2) 9962 return false; 9963 9964 L = AE->getOperand(0); 9965 R = AE->getOperand(1); 9966 Flags = AE->getNoWrapFlags(); 9967 return true; 9968 } 9969 9970 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9971 const SCEV *Less) { 9972 // We avoid subtracting expressions here because this function is usually 9973 // fairly deep in the call stack (i.e. is called many times). 9974 9975 // X - X = 0. 9976 if (More == Less) 9977 return APInt(getTypeSizeInBits(More->getType()), 0); 9978 9979 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9980 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9981 const auto *MAR = cast<SCEVAddRecExpr>(More); 9982 9983 if (LAR->getLoop() != MAR->getLoop()) 9984 return None; 9985 9986 // We look at affine expressions only; not for correctness but to keep 9987 // getStepRecurrence cheap. 9988 if (!LAR->isAffine() || !MAR->isAffine()) 9989 return None; 9990 9991 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9992 return None; 9993 9994 Less = LAR->getStart(); 9995 More = MAR->getStart(); 9996 9997 // fall through 9998 } 9999 10000 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10001 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10002 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10003 return M - L; 10004 } 10005 10006 SCEV::NoWrapFlags Flags; 10007 const SCEV *LLess = nullptr, *RLess = nullptr; 10008 const SCEV *LMore = nullptr, *RMore = nullptr; 10009 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10010 // Compare (X + C1) vs X. 10011 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10012 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10013 if (RLess == More) 10014 return -(C1->getAPInt()); 10015 10016 // Compare X vs (X + C2). 10017 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10018 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10019 if (RMore == Less) 10020 return C2->getAPInt(); 10021 10022 // Compare (X + C1) vs (X + C2). 10023 if (C1 && C2 && RLess == RMore) 10024 return C2->getAPInt() - C1->getAPInt(); 10025 10026 return None; 10027 } 10028 10029 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10030 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10031 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10032 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10033 return false; 10034 10035 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10036 if (!AddRecLHS) 10037 return false; 10038 10039 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10040 if (!AddRecFoundLHS) 10041 return false; 10042 10043 // We'd like to let SCEV reason about control dependencies, so we constrain 10044 // both the inequalities to be about add recurrences on the same loop. This 10045 // way we can use isLoopEntryGuardedByCond later. 10046 10047 const Loop *L = AddRecFoundLHS->getLoop(); 10048 if (L != AddRecLHS->getLoop()) 10049 return false; 10050 10051 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10052 // 10053 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10054 // ... (2) 10055 // 10056 // Informal proof for (2), assuming (1) [*]: 10057 // 10058 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10059 // 10060 // Then 10061 // 10062 // FoundLHS s< FoundRHS s< INT_MIN - C 10063 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10064 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10065 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10066 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10067 // <=> FoundLHS + C s< FoundRHS + C 10068 // 10069 // [*]: (1) can be proved by ruling out overflow. 10070 // 10071 // [**]: This can be proved by analyzing all the four possibilities: 10072 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10073 // (A s>= 0, B s>= 0). 10074 // 10075 // Note: 10076 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10077 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10078 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10079 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10080 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10081 // C)". 10082 10083 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10084 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10085 if (!LDiff || !RDiff || *LDiff != *RDiff) 10086 return false; 10087 10088 if (LDiff->isMinValue()) 10089 return true; 10090 10091 APInt FoundRHSLimit; 10092 10093 if (Pred == CmpInst::ICMP_ULT) { 10094 FoundRHSLimit = -(*RDiff); 10095 } else { 10096 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10097 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10098 } 10099 10100 // Try to prove (1) or (2), as needed. 10101 return isAvailableAtLoopEntry(FoundRHS, L) && 10102 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10103 getConstant(FoundRHSLimit)); 10104 } 10105 10106 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10107 const SCEV *LHS, const SCEV *RHS, 10108 const SCEV *FoundLHS, 10109 const SCEV *FoundRHS, unsigned Depth) { 10110 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10111 10112 auto ClearOnExit = make_scope_exit([&]() { 10113 if (LPhi) { 10114 bool Erased = PendingMerges.erase(LPhi); 10115 assert(Erased && "Failed to erase LPhi!"); 10116 (void)Erased; 10117 } 10118 if (RPhi) { 10119 bool Erased = PendingMerges.erase(RPhi); 10120 assert(Erased && "Failed to erase RPhi!"); 10121 (void)Erased; 10122 } 10123 }); 10124 10125 // Find respective Phis and check that they are not being pending. 10126 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10127 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10128 if (!PendingMerges.insert(Phi).second) 10129 return false; 10130 LPhi = Phi; 10131 } 10132 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10133 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10134 // If we detect a loop of Phi nodes being processed by this method, for 10135 // example: 10136 // 10137 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10138 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10139 // 10140 // we don't want to deal with a case that complex, so return conservative 10141 // answer false. 10142 if (!PendingMerges.insert(Phi).second) 10143 return false; 10144 RPhi = Phi; 10145 } 10146 10147 // If none of LHS, RHS is a Phi, nothing to do here. 10148 if (!LPhi && !RPhi) 10149 return false; 10150 10151 // If there is a SCEVUnknown Phi we are interested in, make it left. 10152 if (!LPhi) { 10153 std::swap(LHS, RHS); 10154 std::swap(FoundLHS, FoundRHS); 10155 std::swap(LPhi, RPhi); 10156 Pred = ICmpInst::getSwappedPredicate(Pred); 10157 } 10158 10159 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10160 const BasicBlock *LBB = LPhi->getParent(); 10161 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10162 10163 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10164 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10165 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10166 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10167 }; 10168 10169 if (RPhi && RPhi->getParent() == LBB) { 10170 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10171 // If we compare two Phis from the same block, and for each entry block 10172 // the predicate is true for incoming values from this block, then the 10173 // predicate is also true for the Phis. 10174 for (const BasicBlock *IncBB : predecessors(LBB)) { 10175 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10176 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10177 if (!ProvedEasily(L, R)) 10178 return false; 10179 } 10180 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10181 // Case two: RHS is also a Phi from the same basic block, and it is an 10182 // AddRec. It means that there is a loop which has both AddRec and Unknown 10183 // PHIs, for it we can compare incoming values of AddRec from above the loop 10184 // and latch with their respective incoming values of LPhi. 10185 // TODO: Generalize to handle loops with many inputs in a header. 10186 if (LPhi->getNumIncomingValues() != 2) return false; 10187 10188 auto *RLoop = RAR->getLoop(); 10189 auto *Predecessor = RLoop->getLoopPredecessor(); 10190 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10191 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10192 if (!ProvedEasily(L1, RAR->getStart())) 10193 return false; 10194 auto *Latch = RLoop->getLoopLatch(); 10195 assert(Latch && "Loop with AddRec with no latch?"); 10196 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10197 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10198 return false; 10199 } else { 10200 // In all other cases go over inputs of LHS and compare each of them to RHS, 10201 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10202 // At this point RHS is either a non-Phi, or it is a Phi from some block 10203 // different from LBB. 10204 for (const BasicBlock *IncBB : predecessors(LBB)) { 10205 // Check that RHS is available in this block. 10206 if (!dominates(RHS, IncBB)) 10207 return false; 10208 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10209 if (!ProvedEasily(L, RHS)) 10210 return false; 10211 } 10212 } 10213 return true; 10214 } 10215 10216 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10217 const SCEV *LHS, const SCEV *RHS, 10218 const SCEV *FoundLHS, 10219 const SCEV *FoundRHS) { 10220 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10221 return true; 10222 10223 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10224 return true; 10225 10226 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10227 FoundLHS, FoundRHS) || 10228 // ~x < ~y --> x > y 10229 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10230 getNotSCEV(FoundRHS), 10231 getNotSCEV(FoundLHS)); 10232 } 10233 10234 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10235 template <typename MinMaxExprType> 10236 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10237 const SCEV *Candidate) { 10238 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10239 if (!MinMaxExpr) 10240 return false; 10241 10242 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10243 } 10244 10245 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10246 ICmpInst::Predicate Pred, 10247 const SCEV *LHS, const SCEV *RHS) { 10248 // If both sides are affine addrecs for the same loop, with equal 10249 // steps, and we know the recurrences don't wrap, then we only 10250 // need to check the predicate on the starting values. 10251 10252 if (!ICmpInst::isRelational(Pred)) 10253 return false; 10254 10255 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10256 if (!LAR) 10257 return false; 10258 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10259 if (!RAR) 10260 return false; 10261 if (LAR->getLoop() != RAR->getLoop()) 10262 return false; 10263 if (!LAR->isAffine() || !RAR->isAffine()) 10264 return false; 10265 10266 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10267 return false; 10268 10269 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10270 SCEV::FlagNSW : SCEV::FlagNUW; 10271 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10272 return false; 10273 10274 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10275 } 10276 10277 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10278 /// expression? 10279 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10280 ICmpInst::Predicate Pred, 10281 const SCEV *LHS, const SCEV *RHS) { 10282 switch (Pred) { 10283 default: 10284 return false; 10285 10286 case ICmpInst::ICMP_SGE: 10287 std::swap(LHS, RHS); 10288 LLVM_FALLTHROUGH; 10289 case ICmpInst::ICMP_SLE: 10290 return 10291 // min(A, ...) <= A 10292 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10293 // A <= max(A, ...) 10294 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10295 10296 case ICmpInst::ICMP_UGE: 10297 std::swap(LHS, RHS); 10298 LLVM_FALLTHROUGH; 10299 case ICmpInst::ICMP_ULE: 10300 return 10301 // min(A, ...) <= A 10302 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10303 // A <= max(A, ...) 10304 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10305 } 10306 10307 llvm_unreachable("covered switch fell through?!"); 10308 } 10309 10310 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10311 const SCEV *LHS, const SCEV *RHS, 10312 const SCEV *FoundLHS, 10313 const SCEV *FoundRHS, 10314 unsigned Depth) { 10315 assert(getTypeSizeInBits(LHS->getType()) == 10316 getTypeSizeInBits(RHS->getType()) && 10317 "LHS and RHS have different sizes?"); 10318 assert(getTypeSizeInBits(FoundLHS->getType()) == 10319 getTypeSizeInBits(FoundRHS->getType()) && 10320 "FoundLHS and FoundRHS have different sizes?"); 10321 // We want to avoid hurting the compile time with analysis of too big trees. 10322 if (Depth > MaxSCEVOperationsImplicationDepth) 10323 return false; 10324 // We only want to work with ICMP_SGT comparison so far. 10325 // TODO: Extend to ICMP_UGT? 10326 if (Pred == ICmpInst::ICMP_SLT) { 10327 Pred = ICmpInst::ICMP_SGT; 10328 std::swap(LHS, RHS); 10329 std::swap(FoundLHS, FoundRHS); 10330 } 10331 if (Pred != ICmpInst::ICMP_SGT) 10332 return false; 10333 10334 auto GetOpFromSExt = [&](const SCEV *S) { 10335 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10336 return Ext->getOperand(); 10337 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10338 // the constant in some cases. 10339 return S; 10340 }; 10341 10342 // Acquire values from extensions. 10343 auto *OrigLHS = LHS; 10344 auto *OrigFoundLHS = FoundLHS; 10345 LHS = GetOpFromSExt(LHS); 10346 FoundLHS = GetOpFromSExt(FoundLHS); 10347 10348 // Is the SGT predicate can be proved trivially or using the found context. 10349 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10350 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10351 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10352 FoundRHS, Depth + 1); 10353 }; 10354 10355 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10356 // We want to avoid creation of any new non-constant SCEV. Since we are 10357 // going to compare the operands to RHS, we should be certain that we don't 10358 // need any size extensions for this. So let's decline all cases when the 10359 // sizes of types of LHS and RHS do not match. 10360 // TODO: Maybe try to get RHS from sext to catch more cases? 10361 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10362 return false; 10363 10364 // Should not overflow. 10365 if (!LHSAddExpr->hasNoSignedWrap()) 10366 return false; 10367 10368 auto *LL = LHSAddExpr->getOperand(0); 10369 auto *LR = LHSAddExpr->getOperand(1); 10370 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10371 10372 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10373 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10374 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10375 }; 10376 // Try to prove the following rule: 10377 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10378 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10379 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10380 return true; 10381 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10382 Value *LL, *LR; 10383 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10384 10385 using namespace llvm::PatternMatch; 10386 10387 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10388 // Rules for division. 10389 // We are going to perform some comparisons with Denominator and its 10390 // derivative expressions. In general case, creating a SCEV for it may 10391 // lead to a complex analysis of the entire graph, and in particular it 10392 // can request trip count recalculation for the same loop. This would 10393 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10394 // this, we only want to create SCEVs that are constants in this section. 10395 // So we bail if Denominator is not a constant. 10396 if (!isa<ConstantInt>(LR)) 10397 return false; 10398 10399 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10400 10401 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10402 // then a SCEV for the numerator already exists and matches with FoundLHS. 10403 auto *Numerator = getExistingSCEV(LL); 10404 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10405 return false; 10406 10407 // Make sure that the numerator matches with FoundLHS and the denominator 10408 // is positive. 10409 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10410 return false; 10411 10412 auto *DTy = Denominator->getType(); 10413 auto *FRHSTy = FoundRHS->getType(); 10414 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10415 // One of types is a pointer and another one is not. We cannot extend 10416 // them properly to a wider type, so let us just reject this case. 10417 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10418 // to avoid this check. 10419 return false; 10420 10421 // Given that: 10422 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10423 auto *WTy = getWiderType(DTy, FRHSTy); 10424 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10425 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10426 10427 // Try to prove the following rule: 10428 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10429 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10430 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10431 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10432 if (isKnownNonPositive(RHS) && 10433 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10434 return true; 10435 10436 // Try to prove the following rule: 10437 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10438 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10439 // If we divide it by Denominator > 2, then: 10440 // 1. If FoundLHS is negative, then the result is 0. 10441 // 2. If FoundLHS is non-negative, then the result is non-negative. 10442 // Anyways, the result is non-negative. 10443 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10444 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10445 if (isKnownNegative(RHS) && 10446 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10447 return true; 10448 } 10449 } 10450 10451 // If our expression contained SCEVUnknown Phis, and we split it down and now 10452 // need to prove something for them, try to prove the predicate for every 10453 // possible incoming values of those Phis. 10454 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10455 return true; 10456 10457 return false; 10458 } 10459 10460 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10461 const SCEV *LHS, const SCEV *RHS) { 10462 // zext x u<= sext x, sext x s<= zext x 10463 switch (Pred) { 10464 case ICmpInst::ICMP_SGE: 10465 std::swap(LHS, RHS); 10466 LLVM_FALLTHROUGH; 10467 case ICmpInst::ICMP_SLE: { 10468 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10469 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10470 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10471 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10472 return true; 10473 break; 10474 } 10475 case ICmpInst::ICMP_UGE: 10476 std::swap(LHS, RHS); 10477 LLVM_FALLTHROUGH; 10478 case ICmpInst::ICMP_ULE: { 10479 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10480 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10481 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10482 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10483 return true; 10484 break; 10485 } 10486 default: 10487 break; 10488 }; 10489 return false; 10490 } 10491 10492 bool 10493 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10494 const SCEV *LHS, const SCEV *RHS) { 10495 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10496 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10497 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10498 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10499 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10500 } 10501 10502 bool 10503 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10504 const SCEV *LHS, const SCEV *RHS, 10505 const SCEV *FoundLHS, 10506 const SCEV *FoundRHS) { 10507 switch (Pred) { 10508 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10509 case ICmpInst::ICMP_EQ: 10510 case ICmpInst::ICMP_NE: 10511 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10512 return true; 10513 break; 10514 case ICmpInst::ICMP_SLT: 10515 case ICmpInst::ICMP_SLE: 10516 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10517 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10518 return true; 10519 break; 10520 case ICmpInst::ICMP_SGT: 10521 case ICmpInst::ICMP_SGE: 10522 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10523 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10524 return true; 10525 break; 10526 case ICmpInst::ICMP_ULT: 10527 case ICmpInst::ICMP_ULE: 10528 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10529 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10530 return true; 10531 break; 10532 case ICmpInst::ICMP_UGT: 10533 case ICmpInst::ICMP_UGE: 10534 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10535 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10536 return true; 10537 break; 10538 } 10539 10540 // Maybe it can be proved via operations? 10541 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10542 return true; 10543 10544 return false; 10545 } 10546 10547 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10548 const SCEV *LHS, 10549 const SCEV *RHS, 10550 const SCEV *FoundLHS, 10551 const SCEV *FoundRHS) { 10552 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10553 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10554 // reduce the compile time impact of this optimization. 10555 return false; 10556 10557 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10558 if (!Addend) 10559 return false; 10560 10561 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10562 10563 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10564 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10565 ConstantRange FoundLHSRange = 10566 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10567 10568 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10569 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10570 10571 // We can also compute the range of values for `LHS` that satisfy the 10572 // consequent, "`LHS` `Pred` `RHS`": 10573 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10574 ConstantRange SatisfyingLHSRange = 10575 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10576 10577 // The antecedent implies the consequent if every value of `LHS` that 10578 // satisfies the antecedent also satisfies the consequent. 10579 return SatisfyingLHSRange.contains(LHSRange); 10580 } 10581 10582 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10583 bool IsSigned, bool NoWrap) { 10584 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10585 10586 if (NoWrap) return false; 10587 10588 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10589 const SCEV *One = getOne(Stride->getType()); 10590 10591 if (IsSigned) { 10592 APInt MaxRHS = getSignedRangeMax(RHS); 10593 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10594 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10595 10596 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10597 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10598 } 10599 10600 APInt MaxRHS = getUnsignedRangeMax(RHS); 10601 APInt MaxValue = APInt::getMaxValue(BitWidth); 10602 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10603 10604 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10605 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10606 } 10607 10608 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10609 bool IsSigned, bool NoWrap) { 10610 if (NoWrap) return false; 10611 10612 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10613 const SCEV *One = getOne(Stride->getType()); 10614 10615 if (IsSigned) { 10616 APInt MinRHS = getSignedRangeMin(RHS); 10617 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10618 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10619 10620 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10621 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10622 } 10623 10624 APInt MinRHS = getUnsignedRangeMin(RHS); 10625 APInt MinValue = APInt::getMinValue(BitWidth); 10626 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10627 10628 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10629 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10630 } 10631 10632 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10633 bool Equality) { 10634 const SCEV *One = getOne(Step->getType()); 10635 Delta = Equality ? getAddExpr(Delta, Step) 10636 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10637 return getUDivExpr(Delta, Step); 10638 } 10639 10640 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10641 const SCEV *Stride, 10642 const SCEV *End, 10643 unsigned BitWidth, 10644 bool IsSigned) { 10645 10646 assert(!isKnownNonPositive(Stride) && 10647 "Stride is expected strictly positive!"); 10648 // Calculate the maximum backedge count based on the range of values 10649 // permitted by Start, End, and Stride. 10650 const SCEV *MaxBECount; 10651 APInt MinStart = 10652 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10653 10654 APInt StrideForMaxBECount = 10655 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10656 10657 // We already know that the stride is positive, so we paper over conservatism 10658 // in our range computation by forcing StrideForMaxBECount to be at least one. 10659 // In theory this is unnecessary, but we expect MaxBECount to be a 10660 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10661 // is nothing to constant fold it to). 10662 APInt One(BitWidth, 1, IsSigned); 10663 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10664 10665 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10666 : APInt::getMaxValue(BitWidth); 10667 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10668 10669 // Although End can be a MAX expression we estimate MaxEnd considering only 10670 // the case End = RHS of the loop termination condition. This is safe because 10671 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10672 // taken count. 10673 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10674 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10675 10676 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10677 getConstant(StrideForMaxBECount) /* Step */, 10678 false /* Equality */); 10679 10680 return MaxBECount; 10681 } 10682 10683 ScalarEvolution::ExitLimit 10684 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10685 const Loop *L, bool IsSigned, 10686 bool ControlsExit, bool AllowPredicates) { 10687 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10688 10689 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10690 bool PredicatedIV = false; 10691 10692 if (!IV && AllowPredicates) { 10693 // Try to make this an AddRec using runtime tests, in the first X 10694 // iterations of this loop, where X is the SCEV expression found by the 10695 // algorithm below. 10696 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10697 PredicatedIV = true; 10698 } 10699 10700 // Avoid weird loops 10701 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10702 return getCouldNotCompute(); 10703 10704 bool NoWrap = ControlsExit && 10705 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10706 10707 const SCEV *Stride = IV->getStepRecurrence(*this); 10708 10709 bool PositiveStride = isKnownPositive(Stride); 10710 10711 // Avoid negative or zero stride values. 10712 if (!PositiveStride) { 10713 // We can compute the correct backedge taken count for loops with unknown 10714 // strides if we can prove that the loop is not an infinite loop with side 10715 // effects. Here's the loop structure we are trying to handle - 10716 // 10717 // i = start 10718 // do { 10719 // A[i] = i; 10720 // i += s; 10721 // } while (i < end); 10722 // 10723 // The backedge taken count for such loops is evaluated as - 10724 // (max(end, start + stride) - start - 1) /u stride 10725 // 10726 // The additional preconditions that we need to check to prove correctness 10727 // of the above formula is as follows - 10728 // 10729 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10730 // NoWrap flag). 10731 // b) loop is single exit with no side effects. 10732 // 10733 // 10734 // Precondition a) implies that if the stride is negative, this is a single 10735 // trip loop. The backedge taken count formula reduces to zero in this case. 10736 // 10737 // Precondition b) implies that the unknown stride cannot be zero otherwise 10738 // we have UB. 10739 // 10740 // The positive stride case is the same as isKnownPositive(Stride) returning 10741 // true (original behavior of the function). 10742 // 10743 // We want to make sure that the stride is truly unknown as there are edge 10744 // cases where ScalarEvolution propagates no wrap flags to the 10745 // post-increment/decrement IV even though the increment/decrement operation 10746 // itself is wrapping. The computed backedge taken count may be wrong in 10747 // such cases. This is prevented by checking that the stride is not known to 10748 // be either positive or non-positive. For example, no wrap flags are 10749 // propagated to the post-increment IV of this loop with a trip count of 2 - 10750 // 10751 // unsigned char i; 10752 // for(i=127; i<128; i+=129) 10753 // A[i] = i; 10754 // 10755 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10756 !loopHasNoSideEffects(L)) 10757 return getCouldNotCompute(); 10758 } else if (!Stride->isOne() && 10759 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10760 // Avoid proven overflow cases: this will ensure that the backedge taken 10761 // count will not generate any unsigned overflow. Relaxed no-overflow 10762 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10763 // undefined behaviors like the case of C language. 10764 return getCouldNotCompute(); 10765 10766 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10767 : ICmpInst::ICMP_ULT; 10768 const SCEV *Start = IV->getStart(); 10769 const SCEV *End = RHS; 10770 // When the RHS is not invariant, we do not know the end bound of the loop and 10771 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10772 // calculate the MaxBECount, given the start, stride and max value for the end 10773 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10774 // checked above). 10775 if (!isLoopInvariant(RHS, L)) { 10776 const SCEV *MaxBECount = computeMaxBECountForLT( 10777 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10778 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10779 false /*MaxOrZero*/, Predicates); 10780 } 10781 // If the backedge is taken at least once, then it will be taken 10782 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10783 // is the LHS value of the less-than comparison the first time it is evaluated 10784 // and End is the RHS. 10785 const SCEV *BECountIfBackedgeTaken = 10786 computeBECount(getMinusSCEV(End, Start), Stride, false); 10787 // If the loop entry is guarded by the result of the backedge test of the 10788 // first loop iteration, then we know the backedge will be taken at least 10789 // once and so the backedge taken count is as above. If not then we use the 10790 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10791 // as if the backedge is taken at least once max(End,Start) is End and so the 10792 // result is as above, and if not max(End,Start) is Start so we get a backedge 10793 // count of zero. 10794 const SCEV *BECount; 10795 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10796 BECount = BECountIfBackedgeTaken; 10797 else { 10798 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10799 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10800 } 10801 10802 const SCEV *MaxBECount; 10803 bool MaxOrZero = false; 10804 if (isa<SCEVConstant>(BECount)) 10805 MaxBECount = BECount; 10806 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10807 // If we know exactly how many times the backedge will be taken if it's 10808 // taken at least once, then the backedge count will either be that or 10809 // zero. 10810 MaxBECount = BECountIfBackedgeTaken; 10811 MaxOrZero = true; 10812 } else { 10813 MaxBECount = computeMaxBECountForLT( 10814 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10815 } 10816 10817 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10818 !isa<SCEVCouldNotCompute>(BECount)) 10819 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10820 10821 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10822 } 10823 10824 ScalarEvolution::ExitLimit 10825 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10826 const Loop *L, bool IsSigned, 10827 bool ControlsExit, bool AllowPredicates) { 10828 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10829 // We handle only IV > Invariant 10830 if (!isLoopInvariant(RHS, L)) 10831 return getCouldNotCompute(); 10832 10833 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10834 if (!IV && AllowPredicates) 10835 // Try to make this an AddRec using runtime tests, in the first X 10836 // iterations of this loop, where X is the SCEV expression found by the 10837 // algorithm below. 10838 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10839 10840 // Avoid weird loops 10841 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10842 return getCouldNotCompute(); 10843 10844 bool NoWrap = ControlsExit && 10845 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10846 10847 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10848 10849 // Avoid negative or zero stride values 10850 if (!isKnownPositive(Stride)) 10851 return getCouldNotCompute(); 10852 10853 // Avoid proven overflow cases: this will ensure that the backedge taken count 10854 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10855 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10856 // behaviors like the case of C language. 10857 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10858 return getCouldNotCompute(); 10859 10860 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10861 : ICmpInst::ICMP_UGT; 10862 10863 const SCEV *Start = IV->getStart(); 10864 const SCEV *End = RHS; 10865 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10866 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10867 10868 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10869 10870 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10871 : getUnsignedRangeMax(Start); 10872 10873 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10874 : getUnsignedRangeMin(Stride); 10875 10876 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10877 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10878 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10879 10880 // Although End can be a MIN expression we estimate MinEnd considering only 10881 // the case End = RHS. This is safe because in the other case (Start - End) 10882 // is zero, leading to a zero maximum backedge taken count. 10883 APInt MinEnd = 10884 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10885 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10886 10887 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10888 ? BECount 10889 : computeBECount(getConstant(MaxStart - MinEnd), 10890 getConstant(MinStride), false); 10891 10892 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10893 MaxBECount = BECount; 10894 10895 return ExitLimit(BECount, MaxBECount, false, Predicates); 10896 } 10897 10898 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10899 ScalarEvolution &SE) const { 10900 if (Range.isFullSet()) // Infinite loop. 10901 return SE.getCouldNotCompute(); 10902 10903 // If the start is a non-zero constant, shift the range to simplify things. 10904 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10905 if (!SC->getValue()->isZero()) { 10906 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10907 Operands[0] = SE.getZero(SC->getType()); 10908 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10909 getNoWrapFlags(FlagNW)); 10910 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10911 return ShiftedAddRec->getNumIterationsInRange( 10912 Range.subtract(SC->getAPInt()), SE); 10913 // This is strange and shouldn't happen. 10914 return SE.getCouldNotCompute(); 10915 } 10916 10917 // The only time we can solve this is when we have all constant indices. 10918 // Otherwise, we cannot determine the overflow conditions. 10919 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10920 return SE.getCouldNotCompute(); 10921 10922 // Okay at this point we know that all elements of the chrec are constants and 10923 // that the start element is zero. 10924 10925 // First check to see if the range contains zero. If not, the first 10926 // iteration exits. 10927 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10928 if (!Range.contains(APInt(BitWidth, 0))) 10929 return SE.getZero(getType()); 10930 10931 if (isAffine()) { 10932 // If this is an affine expression then we have this situation: 10933 // Solve {0,+,A} in Range === Ax in Range 10934 10935 // We know that zero is in the range. If A is positive then we know that 10936 // the upper value of the range must be the first possible exit value. 10937 // If A is negative then the lower of the range is the last possible loop 10938 // value. Also note that we already checked for a full range. 10939 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10940 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10941 10942 // The exit value should be (End+A)/A. 10943 APInt ExitVal = (End + A).udiv(A); 10944 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10945 10946 // Evaluate at the exit value. If we really did fall out of the valid 10947 // range, then we computed our trip count, otherwise wrap around or other 10948 // things must have happened. 10949 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10950 if (Range.contains(Val->getValue())) 10951 return SE.getCouldNotCompute(); // Something strange happened 10952 10953 // Ensure that the previous value is in the range. This is a sanity check. 10954 assert(Range.contains( 10955 EvaluateConstantChrecAtConstant(this, 10956 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10957 "Linear scev computation is off in a bad way!"); 10958 return SE.getConstant(ExitValue); 10959 } 10960 10961 if (isQuadratic()) { 10962 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10963 return SE.getConstant(S.getValue()); 10964 } 10965 10966 return SE.getCouldNotCompute(); 10967 } 10968 10969 const SCEVAddRecExpr * 10970 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10971 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10972 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10973 // but in this case we cannot guarantee that the value returned will be an 10974 // AddRec because SCEV does not have a fixed point where it stops 10975 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10976 // may happen if we reach arithmetic depth limit while simplifying. So we 10977 // construct the returned value explicitly. 10978 SmallVector<const SCEV *, 3> Ops; 10979 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10980 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10981 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10982 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10983 // We know that the last operand is not a constant zero (otherwise it would 10984 // have been popped out earlier). This guarantees us that if the result has 10985 // the same last operand, then it will also not be popped out, meaning that 10986 // the returned value will be an AddRec. 10987 const SCEV *Last = getOperand(getNumOperands() - 1); 10988 assert(!Last->isZero() && "Recurrency with zero step?"); 10989 Ops.push_back(Last); 10990 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10991 SCEV::FlagAnyWrap)); 10992 } 10993 10994 // Return true when S contains at least an undef value. 10995 static inline bool containsUndefs(const SCEV *S) { 10996 return SCEVExprContains(S, [](const SCEV *S) { 10997 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10998 return isa<UndefValue>(SU->getValue()); 10999 return false; 11000 }); 11001 } 11002 11003 namespace { 11004 11005 // Collect all steps of SCEV expressions. 11006 struct SCEVCollectStrides { 11007 ScalarEvolution &SE; 11008 SmallVectorImpl<const SCEV *> &Strides; 11009 11010 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11011 : SE(SE), Strides(S) {} 11012 11013 bool follow(const SCEV *S) { 11014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11015 Strides.push_back(AR->getStepRecurrence(SE)); 11016 return true; 11017 } 11018 11019 bool isDone() const { return false; } 11020 }; 11021 11022 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11023 struct SCEVCollectTerms { 11024 SmallVectorImpl<const SCEV *> &Terms; 11025 11026 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11027 11028 bool follow(const SCEV *S) { 11029 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11030 isa<SCEVSignExtendExpr>(S)) { 11031 if (!containsUndefs(S)) 11032 Terms.push_back(S); 11033 11034 // Stop recursion: once we collected a term, do not walk its operands. 11035 return false; 11036 } 11037 11038 // Keep looking. 11039 return true; 11040 } 11041 11042 bool isDone() const { return false; } 11043 }; 11044 11045 // Check if a SCEV contains an AddRecExpr. 11046 struct SCEVHasAddRec { 11047 bool &ContainsAddRec; 11048 11049 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11050 ContainsAddRec = false; 11051 } 11052 11053 bool follow(const SCEV *S) { 11054 if (isa<SCEVAddRecExpr>(S)) { 11055 ContainsAddRec = true; 11056 11057 // Stop recursion: once we collected a term, do not walk its operands. 11058 return false; 11059 } 11060 11061 // Keep looking. 11062 return true; 11063 } 11064 11065 bool isDone() const { return false; } 11066 }; 11067 11068 // Find factors that are multiplied with an expression that (possibly as a 11069 // subexpression) contains an AddRecExpr. In the expression: 11070 // 11071 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11072 // 11073 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11074 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11075 // parameters as they form a product with an induction variable. 11076 // 11077 // This collector expects all array size parameters to be in the same MulExpr. 11078 // It might be necessary to later add support for collecting parameters that are 11079 // spread over different nested MulExpr. 11080 struct SCEVCollectAddRecMultiplies { 11081 SmallVectorImpl<const SCEV *> &Terms; 11082 ScalarEvolution &SE; 11083 11084 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11085 : Terms(T), SE(SE) {} 11086 11087 bool follow(const SCEV *S) { 11088 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11089 bool HasAddRec = false; 11090 SmallVector<const SCEV *, 0> Operands; 11091 for (auto Op : Mul->operands()) { 11092 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11093 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11094 Operands.push_back(Op); 11095 } else if (Unknown) { 11096 HasAddRec = true; 11097 } else { 11098 bool ContainsAddRec = false; 11099 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11100 visitAll(Op, ContiansAddRec); 11101 HasAddRec |= ContainsAddRec; 11102 } 11103 } 11104 if (Operands.size() == 0) 11105 return true; 11106 11107 if (!HasAddRec) 11108 return false; 11109 11110 Terms.push_back(SE.getMulExpr(Operands)); 11111 // Stop recursion: once we collected a term, do not walk its operands. 11112 return false; 11113 } 11114 11115 // Keep looking. 11116 return true; 11117 } 11118 11119 bool isDone() const { return false; } 11120 }; 11121 11122 } // end anonymous namespace 11123 11124 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11125 /// two places: 11126 /// 1) The strides of AddRec expressions. 11127 /// 2) Unknowns that are multiplied with AddRec expressions. 11128 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11129 SmallVectorImpl<const SCEV *> &Terms) { 11130 SmallVector<const SCEV *, 4> Strides; 11131 SCEVCollectStrides StrideCollector(*this, Strides); 11132 visitAll(Expr, StrideCollector); 11133 11134 LLVM_DEBUG({ 11135 dbgs() << "Strides:\n"; 11136 for (const SCEV *S : Strides) 11137 dbgs() << *S << "\n"; 11138 }); 11139 11140 for (const SCEV *S : Strides) { 11141 SCEVCollectTerms TermCollector(Terms); 11142 visitAll(S, TermCollector); 11143 } 11144 11145 LLVM_DEBUG({ 11146 dbgs() << "Terms:\n"; 11147 for (const SCEV *T : Terms) 11148 dbgs() << *T << "\n"; 11149 }); 11150 11151 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11152 visitAll(Expr, MulCollector); 11153 } 11154 11155 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11156 SmallVectorImpl<const SCEV *> &Terms, 11157 SmallVectorImpl<const SCEV *> &Sizes) { 11158 int Last = Terms.size() - 1; 11159 const SCEV *Step = Terms[Last]; 11160 11161 // End of recursion. 11162 if (Last == 0) { 11163 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11164 SmallVector<const SCEV *, 2> Qs; 11165 for (const SCEV *Op : M->operands()) 11166 if (!isa<SCEVConstant>(Op)) 11167 Qs.push_back(Op); 11168 11169 Step = SE.getMulExpr(Qs); 11170 } 11171 11172 Sizes.push_back(Step); 11173 return true; 11174 } 11175 11176 for (const SCEV *&Term : Terms) { 11177 // Normalize the terms before the next call to findArrayDimensionsRec. 11178 const SCEV *Q, *R; 11179 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11180 11181 // Bail out when GCD does not evenly divide one of the terms. 11182 if (!R->isZero()) 11183 return false; 11184 11185 Term = Q; 11186 } 11187 11188 // Remove all SCEVConstants. 11189 Terms.erase( 11190 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11191 Terms.end()); 11192 11193 if (Terms.size() > 0) 11194 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11195 return false; 11196 11197 Sizes.push_back(Step); 11198 return true; 11199 } 11200 11201 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11202 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11203 for (const SCEV *T : Terms) 11204 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11205 return true; 11206 return false; 11207 } 11208 11209 // Return the number of product terms in S. 11210 static inline int numberOfTerms(const SCEV *S) { 11211 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11212 return Expr->getNumOperands(); 11213 return 1; 11214 } 11215 11216 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11217 if (isa<SCEVConstant>(T)) 11218 return nullptr; 11219 11220 if (isa<SCEVUnknown>(T)) 11221 return T; 11222 11223 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11224 SmallVector<const SCEV *, 2> Factors; 11225 for (const SCEV *Op : M->operands()) 11226 if (!isa<SCEVConstant>(Op)) 11227 Factors.push_back(Op); 11228 11229 return SE.getMulExpr(Factors); 11230 } 11231 11232 return T; 11233 } 11234 11235 /// Return the size of an element read or written by Inst. 11236 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11237 Type *Ty; 11238 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11239 Ty = Store->getValueOperand()->getType(); 11240 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11241 Ty = Load->getType(); 11242 else 11243 return nullptr; 11244 11245 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11246 return getSizeOfExpr(ETy, Ty); 11247 } 11248 11249 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11250 SmallVectorImpl<const SCEV *> &Sizes, 11251 const SCEV *ElementSize) { 11252 if (Terms.size() < 1 || !ElementSize) 11253 return; 11254 11255 // Early return when Terms do not contain parameters: we do not delinearize 11256 // non parametric SCEVs. 11257 if (!containsParameters(Terms)) 11258 return; 11259 11260 LLVM_DEBUG({ 11261 dbgs() << "Terms:\n"; 11262 for (const SCEV *T : Terms) 11263 dbgs() << *T << "\n"; 11264 }); 11265 11266 // Remove duplicates. 11267 array_pod_sort(Terms.begin(), Terms.end()); 11268 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11269 11270 // Put larger terms first. 11271 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11272 return numberOfTerms(LHS) > numberOfTerms(RHS); 11273 }); 11274 11275 // Try to divide all terms by the element size. If term is not divisible by 11276 // element size, proceed with the original term. 11277 for (const SCEV *&Term : Terms) { 11278 const SCEV *Q, *R; 11279 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11280 if (!Q->isZero()) 11281 Term = Q; 11282 } 11283 11284 SmallVector<const SCEV *, 4> NewTerms; 11285 11286 // Remove constant factors. 11287 for (const SCEV *T : Terms) 11288 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11289 NewTerms.push_back(NewT); 11290 11291 LLVM_DEBUG({ 11292 dbgs() << "Terms after sorting:\n"; 11293 for (const SCEV *T : NewTerms) 11294 dbgs() << *T << "\n"; 11295 }); 11296 11297 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11298 Sizes.clear(); 11299 return; 11300 } 11301 11302 // The last element to be pushed into Sizes is the size of an element. 11303 Sizes.push_back(ElementSize); 11304 11305 LLVM_DEBUG({ 11306 dbgs() << "Sizes:\n"; 11307 for (const SCEV *S : Sizes) 11308 dbgs() << *S << "\n"; 11309 }); 11310 } 11311 11312 void ScalarEvolution::computeAccessFunctions( 11313 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11314 SmallVectorImpl<const SCEV *> &Sizes) { 11315 // Early exit in case this SCEV is not an affine multivariate function. 11316 if (Sizes.empty()) 11317 return; 11318 11319 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11320 if (!AR->isAffine()) 11321 return; 11322 11323 const SCEV *Res = Expr; 11324 int Last = Sizes.size() - 1; 11325 for (int i = Last; i >= 0; i--) { 11326 const SCEV *Q, *R; 11327 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11328 11329 LLVM_DEBUG({ 11330 dbgs() << "Res: " << *Res << "\n"; 11331 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11332 dbgs() << "Res divided by Sizes[i]:\n"; 11333 dbgs() << "Quotient: " << *Q << "\n"; 11334 dbgs() << "Remainder: " << *R << "\n"; 11335 }); 11336 11337 Res = Q; 11338 11339 // Do not record the last subscript corresponding to the size of elements in 11340 // the array. 11341 if (i == Last) { 11342 11343 // Bail out if the remainder is too complex. 11344 if (isa<SCEVAddRecExpr>(R)) { 11345 Subscripts.clear(); 11346 Sizes.clear(); 11347 return; 11348 } 11349 11350 continue; 11351 } 11352 11353 // Record the access function for the current subscript. 11354 Subscripts.push_back(R); 11355 } 11356 11357 // Also push in last position the remainder of the last division: it will be 11358 // the access function of the innermost dimension. 11359 Subscripts.push_back(Res); 11360 11361 std::reverse(Subscripts.begin(), Subscripts.end()); 11362 11363 LLVM_DEBUG({ 11364 dbgs() << "Subscripts:\n"; 11365 for (const SCEV *S : Subscripts) 11366 dbgs() << *S << "\n"; 11367 }); 11368 } 11369 11370 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11371 /// sizes of an array access. Returns the remainder of the delinearization that 11372 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11373 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11374 /// expressions in the stride and base of a SCEV corresponding to the 11375 /// computation of a GCD (greatest common divisor) of base and stride. When 11376 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11377 /// 11378 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11379 /// 11380 /// void foo(long n, long m, long o, double A[n][m][o]) { 11381 /// 11382 /// for (long i = 0; i < n; i++) 11383 /// for (long j = 0; j < m; j++) 11384 /// for (long k = 0; k < o; k++) 11385 /// A[i][j][k] = 1.0; 11386 /// } 11387 /// 11388 /// the delinearization input is the following AddRec SCEV: 11389 /// 11390 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11391 /// 11392 /// From this SCEV, we are able to say that the base offset of the access is %A 11393 /// because it appears as an offset that does not divide any of the strides in 11394 /// the loops: 11395 /// 11396 /// CHECK: Base offset: %A 11397 /// 11398 /// and then SCEV->delinearize determines the size of some of the dimensions of 11399 /// the array as these are the multiples by which the strides are happening: 11400 /// 11401 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11402 /// 11403 /// Note that the outermost dimension remains of UnknownSize because there are 11404 /// no strides that would help identifying the size of the last dimension: when 11405 /// the array has been statically allocated, one could compute the size of that 11406 /// dimension by dividing the overall size of the array by the size of the known 11407 /// dimensions: %m * %o * 8. 11408 /// 11409 /// Finally delinearize provides the access functions for the array reference 11410 /// that does correspond to A[i][j][k] of the above C testcase: 11411 /// 11412 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11413 /// 11414 /// The testcases are checking the output of a function pass: 11415 /// DelinearizationPass that walks through all loads and stores of a function 11416 /// asking for the SCEV of the memory access with respect to all enclosing 11417 /// loops, calling SCEV->delinearize on that and printing the results. 11418 void ScalarEvolution::delinearize(const SCEV *Expr, 11419 SmallVectorImpl<const SCEV *> &Subscripts, 11420 SmallVectorImpl<const SCEV *> &Sizes, 11421 const SCEV *ElementSize) { 11422 // First step: collect parametric terms. 11423 SmallVector<const SCEV *, 4> Terms; 11424 collectParametricTerms(Expr, Terms); 11425 11426 if (Terms.empty()) 11427 return; 11428 11429 // Second step: find subscript sizes. 11430 findArrayDimensions(Terms, Sizes, ElementSize); 11431 11432 if (Sizes.empty()) 11433 return; 11434 11435 // Third step: compute the access functions for each subscript. 11436 computeAccessFunctions(Expr, Subscripts, Sizes); 11437 11438 if (Subscripts.empty()) 11439 return; 11440 11441 LLVM_DEBUG({ 11442 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11443 dbgs() << "ArrayDecl[UnknownSize]"; 11444 for (const SCEV *S : Sizes) 11445 dbgs() << "[" << *S << "]"; 11446 11447 dbgs() << "\nArrayRef"; 11448 for (const SCEV *S : Subscripts) 11449 dbgs() << "[" << *S << "]"; 11450 dbgs() << "\n"; 11451 }); 11452 } 11453 11454 bool ScalarEvolution::getIndexExpressionsFromGEP( 11455 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11456 SmallVectorImpl<int> &Sizes) { 11457 assert(Subscripts.empty() && Sizes.empty() && 11458 "Expected output lists to be empty on entry to this function."); 11459 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11460 Type *Ty = GEP->getPointerOperandType(); 11461 bool DroppedFirstDim = false; 11462 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11463 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11464 if (i == 1) { 11465 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11466 Ty = PtrTy->getElementType(); 11467 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11468 Ty = ArrayTy->getElementType(); 11469 } else { 11470 Subscripts.clear(); 11471 Sizes.clear(); 11472 return false; 11473 } 11474 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11475 if (Const->getValue()->isZero()) { 11476 DroppedFirstDim = true; 11477 continue; 11478 } 11479 Subscripts.push_back(Expr); 11480 continue; 11481 } 11482 11483 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11484 if (!ArrayTy) { 11485 Subscripts.clear(); 11486 Sizes.clear(); 11487 return false; 11488 } 11489 11490 Subscripts.push_back(Expr); 11491 if (!(DroppedFirstDim && i == 2)) 11492 Sizes.push_back(ArrayTy->getNumElements()); 11493 11494 Ty = ArrayTy->getElementType(); 11495 } 11496 return !Subscripts.empty(); 11497 } 11498 11499 //===----------------------------------------------------------------------===// 11500 // SCEVCallbackVH Class Implementation 11501 //===----------------------------------------------------------------------===// 11502 11503 void ScalarEvolution::SCEVCallbackVH::deleted() { 11504 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11505 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11506 SE->ConstantEvolutionLoopExitValue.erase(PN); 11507 SE->eraseValueFromMap(getValPtr()); 11508 // this now dangles! 11509 } 11510 11511 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11512 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11513 11514 // Forget all the expressions associated with users of the old value, 11515 // so that future queries will recompute the expressions using the new 11516 // value. 11517 Value *Old = getValPtr(); 11518 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11519 SmallPtrSet<User *, 8> Visited; 11520 while (!Worklist.empty()) { 11521 User *U = Worklist.pop_back_val(); 11522 // Deleting the Old value will cause this to dangle. Postpone 11523 // that until everything else is done. 11524 if (U == Old) 11525 continue; 11526 if (!Visited.insert(U).second) 11527 continue; 11528 if (PHINode *PN = dyn_cast<PHINode>(U)) 11529 SE->ConstantEvolutionLoopExitValue.erase(PN); 11530 SE->eraseValueFromMap(U); 11531 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11532 } 11533 // Delete the Old value. 11534 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11535 SE->ConstantEvolutionLoopExitValue.erase(PN); 11536 SE->eraseValueFromMap(Old); 11537 // this now dangles! 11538 } 11539 11540 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11541 : CallbackVH(V), SE(se) {} 11542 11543 //===----------------------------------------------------------------------===// 11544 // ScalarEvolution Class Implementation 11545 //===----------------------------------------------------------------------===// 11546 11547 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11548 AssumptionCache &AC, DominatorTree &DT, 11549 LoopInfo &LI) 11550 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11551 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11552 LoopDispositions(64), BlockDispositions(64) { 11553 // To use guards for proving predicates, we need to scan every instruction in 11554 // relevant basic blocks, and not just terminators. Doing this is a waste of 11555 // time if the IR does not actually contain any calls to 11556 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11557 // 11558 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11559 // to _add_ guards to the module when there weren't any before, and wants 11560 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11561 // efficient in lieu of being smart in that rather obscure case. 11562 11563 auto *GuardDecl = F.getParent()->getFunction( 11564 Intrinsic::getName(Intrinsic::experimental_guard)); 11565 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11566 } 11567 11568 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11569 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11570 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11571 ValueExprMap(std::move(Arg.ValueExprMap)), 11572 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11573 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11574 PendingMerges(std::move(Arg.PendingMerges)), 11575 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11576 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11577 PredicatedBackedgeTakenCounts( 11578 std::move(Arg.PredicatedBackedgeTakenCounts)), 11579 ConstantEvolutionLoopExitValue( 11580 std::move(Arg.ConstantEvolutionLoopExitValue)), 11581 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11582 LoopDispositions(std::move(Arg.LoopDispositions)), 11583 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11584 BlockDispositions(std::move(Arg.BlockDispositions)), 11585 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11586 SignedRanges(std::move(Arg.SignedRanges)), 11587 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11588 UniquePreds(std::move(Arg.UniquePreds)), 11589 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11590 LoopUsers(std::move(Arg.LoopUsers)), 11591 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11592 FirstUnknown(Arg.FirstUnknown) { 11593 Arg.FirstUnknown = nullptr; 11594 } 11595 11596 ScalarEvolution::~ScalarEvolution() { 11597 // Iterate through all the SCEVUnknown instances and call their 11598 // destructors, so that they release their references to their values. 11599 for (SCEVUnknown *U = FirstUnknown; U;) { 11600 SCEVUnknown *Tmp = U; 11601 U = U->Next; 11602 Tmp->~SCEVUnknown(); 11603 } 11604 FirstUnknown = nullptr; 11605 11606 ExprValueMap.clear(); 11607 ValueExprMap.clear(); 11608 HasRecMap.clear(); 11609 11610 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11611 // that a loop had multiple computable exits. 11612 for (auto &BTCI : BackedgeTakenCounts) 11613 BTCI.second.clear(); 11614 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11615 BTCI.second.clear(); 11616 11617 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11618 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11619 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11620 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11621 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11622 } 11623 11624 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11625 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11626 } 11627 11628 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11629 const Loop *L) { 11630 // Print all inner loops first 11631 for (Loop *I : *L) 11632 PrintLoopInfo(OS, SE, I); 11633 11634 OS << "Loop "; 11635 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11636 OS << ": "; 11637 11638 SmallVector<BasicBlock *, 8> ExitingBlocks; 11639 L->getExitingBlocks(ExitingBlocks); 11640 if (ExitingBlocks.size() != 1) 11641 OS << "<multiple exits> "; 11642 11643 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11644 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11645 else 11646 OS << "Unpredictable backedge-taken count.\n"; 11647 11648 if (ExitingBlocks.size() > 1) 11649 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11650 OS << " exit count for " << ExitingBlock->getName() << ": " 11651 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11652 } 11653 11654 OS << "Loop "; 11655 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11656 OS << ": "; 11657 11658 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11659 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11660 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11661 OS << ", actual taken count either this or zero."; 11662 } else { 11663 OS << "Unpredictable max backedge-taken count. "; 11664 } 11665 11666 OS << "\n" 11667 "Loop "; 11668 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11669 OS << ": "; 11670 11671 SCEVUnionPredicate Pred; 11672 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11673 if (!isa<SCEVCouldNotCompute>(PBT)) { 11674 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11675 OS << " Predicates:\n"; 11676 Pred.print(OS, 4); 11677 } else { 11678 OS << "Unpredictable predicated backedge-taken count. "; 11679 } 11680 OS << "\n"; 11681 11682 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11683 OS << "Loop "; 11684 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11685 OS << ": "; 11686 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11687 } 11688 } 11689 11690 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11691 switch (LD) { 11692 case ScalarEvolution::LoopVariant: 11693 return "Variant"; 11694 case ScalarEvolution::LoopInvariant: 11695 return "Invariant"; 11696 case ScalarEvolution::LoopComputable: 11697 return "Computable"; 11698 } 11699 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11700 } 11701 11702 void ScalarEvolution::print(raw_ostream &OS) const { 11703 // ScalarEvolution's implementation of the print method is to print 11704 // out SCEV values of all instructions that are interesting. Doing 11705 // this potentially causes it to create new SCEV objects though, 11706 // which technically conflicts with the const qualifier. This isn't 11707 // observable from outside the class though, so casting away the 11708 // const isn't dangerous. 11709 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11710 11711 if (ClassifyExpressions) { 11712 OS << "Classifying expressions for: "; 11713 F.printAsOperand(OS, /*PrintType=*/false); 11714 OS << "\n"; 11715 for (Instruction &I : instructions(F)) 11716 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11717 OS << I << '\n'; 11718 OS << " --> "; 11719 const SCEV *SV = SE.getSCEV(&I); 11720 SV->print(OS); 11721 if (!isa<SCEVCouldNotCompute>(SV)) { 11722 OS << " U: "; 11723 SE.getUnsignedRange(SV).print(OS); 11724 OS << " S: "; 11725 SE.getSignedRange(SV).print(OS); 11726 } 11727 11728 const Loop *L = LI.getLoopFor(I.getParent()); 11729 11730 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11731 if (AtUse != SV) { 11732 OS << " --> "; 11733 AtUse->print(OS); 11734 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11735 OS << " U: "; 11736 SE.getUnsignedRange(AtUse).print(OS); 11737 OS << " S: "; 11738 SE.getSignedRange(AtUse).print(OS); 11739 } 11740 } 11741 11742 if (L) { 11743 OS << "\t\t" "Exits: "; 11744 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11745 if (!SE.isLoopInvariant(ExitValue, L)) { 11746 OS << "<<Unknown>>"; 11747 } else { 11748 OS << *ExitValue; 11749 } 11750 11751 bool First = true; 11752 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11753 if (First) { 11754 OS << "\t\t" "LoopDispositions: { "; 11755 First = false; 11756 } else { 11757 OS << ", "; 11758 } 11759 11760 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11761 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11762 } 11763 11764 for (auto *InnerL : depth_first(L)) { 11765 if (InnerL == L) 11766 continue; 11767 if (First) { 11768 OS << "\t\t" "LoopDispositions: { "; 11769 First = false; 11770 } else { 11771 OS << ", "; 11772 } 11773 11774 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11775 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11776 } 11777 11778 OS << " }"; 11779 } 11780 11781 OS << "\n"; 11782 } 11783 } 11784 11785 OS << "Determining loop execution counts for: "; 11786 F.printAsOperand(OS, /*PrintType=*/false); 11787 OS << "\n"; 11788 for (Loop *I : LI) 11789 PrintLoopInfo(OS, &SE, I); 11790 } 11791 11792 ScalarEvolution::LoopDisposition 11793 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11794 auto &Values = LoopDispositions[S]; 11795 for (auto &V : Values) { 11796 if (V.getPointer() == L) 11797 return V.getInt(); 11798 } 11799 Values.emplace_back(L, LoopVariant); 11800 LoopDisposition D = computeLoopDisposition(S, L); 11801 auto &Values2 = LoopDispositions[S]; 11802 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11803 if (V.getPointer() == L) { 11804 V.setInt(D); 11805 break; 11806 } 11807 } 11808 return D; 11809 } 11810 11811 ScalarEvolution::LoopDisposition 11812 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11813 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11814 case scConstant: 11815 return LoopInvariant; 11816 case scTruncate: 11817 case scZeroExtend: 11818 case scSignExtend: 11819 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11820 case scAddRecExpr: { 11821 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11822 11823 // If L is the addrec's loop, it's computable. 11824 if (AR->getLoop() == L) 11825 return LoopComputable; 11826 11827 // Add recurrences are never invariant in the function-body (null loop). 11828 if (!L) 11829 return LoopVariant; 11830 11831 // Everything that is not defined at loop entry is variant. 11832 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11833 return LoopVariant; 11834 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11835 " dominate the contained loop's header?"); 11836 11837 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11838 if (AR->getLoop()->contains(L)) 11839 return LoopInvariant; 11840 11841 // This recurrence is variant w.r.t. L if any of its operands 11842 // are variant. 11843 for (auto *Op : AR->operands()) 11844 if (!isLoopInvariant(Op, L)) 11845 return LoopVariant; 11846 11847 // Otherwise it's loop-invariant. 11848 return LoopInvariant; 11849 } 11850 case scAddExpr: 11851 case scMulExpr: 11852 case scUMaxExpr: 11853 case scSMaxExpr: 11854 case scUMinExpr: 11855 case scSMinExpr: { 11856 bool HasVarying = false; 11857 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11858 LoopDisposition D = getLoopDisposition(Op, L); 11859 if (D == LoopVariant) 11860 return LoopVariant; 11861 if (D == LoopComputable) 11862 HasVarying = true; 11863 } 11864 return HasVarying ? LoopComputable : LoopInvariant; 11865 } 11866 case scUDivExpr: { 11867 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11868 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11869 if (LD == LoopVariant) 11870 return LoopVariant; 11871 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11872 if (RD == LoopVariant) 11873 return LoopVariant; 11874 return (LD == LoopInvariant && RD == LoopInvariant) ? 11875 LoopInvariant : LoopComputable; 11876 } 11877 case scUnknown: 11878 // All non-instruction values are loop invariant. All instructions are loop 11879 // invariant if they are not contained in the specified loop. 11880 // Instructions are never considered invariant in the function body 11881 // (null loop) because they are defined within the "loop". 11882 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11883 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11884 return LoopInvariant; 11885 case scCouldNotCompute: 11886 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11887 } 11888 llvm_unreachable("Unknown SCEV kind!"); 11889 } 11890 11891 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11892 return getLoopDisposition(S, L) == LoopInvariant; 11893 } 11894 11895 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11896 return getLoopDisposition(S, L) == LoopComputable; 11897 } 11898 11899 ScalarEvolution::BlockDisposition 11900 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11901 auto &Values = BlockDispositions[S]; 11902 for (auto &V : Values) { 11903 if (V.getPointer() == BB) 11904 return V.getInt(); 11905 } 11906 Values.emplace_back(BB, DoesNotDominateBlock); 11907 BlockDisposition D = computeBlockDisposition(S, BB); 11908 auto &Values2 = BlockDispositions[S]; 11909 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11910 if (V.getPointer() == BB) { 11911 V.setInt(D); 11912 break; 11913 } 11914 } 11915 return D; 11916 } 11917 11918 ScalarEvolution::BlockDisposition 11919 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11920 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11921 case scConstant: 11922 return ProperlyDominatesBlock; 11923 case scTruncate: 11924 case scZeroExtend: 11925 case scSignExtend: 11926 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11927 case scAddRecExpr: { 11928 // This uses a "dominates" query instead of "properly dominates" query 11929 // to test for proper dominance too, because the instruction which 11930 // produces the addrec's value is a PHI, and a PHI effectively properly 11931 // dominates its entire containing block. 11932 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11933 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11934 return DoesNotDominateBlock; 11935 11936 // Fall through into SCEVNAryExpr handling. 11937 LLVM_FALLTHROUGH; 11938 } 11939 case scAddExpr: 11940 case scMulExpr: 11941 case scUMaxExpr: 11942 case scSMaxExpr: 11943 case scUMinExpr: 11944 case scSMinExpr: { 11945 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11946 bool Proper = true; 11947 for (const SCEV *NAryOp : NAry->operands()) { 11948 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11949 if (D == DoesNotDominateBlock) 11950 return DoesNotDominateBlock; 11951 if (D == DominatesBlock) 11952 Proper = false; 11953 } 11954 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11955 } 11956 case scUDivExpr: { 11957 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11958 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11959 BlockDisposition LD = getBlockDisposition(LHS, BB); 11960 if (LD == DoesNotDominateBlock) 11961 return DoesNotDominateBlock; 11962 BlockDisposition RD = getBlockDisposition(RHS, BB); 11963 if (RD == DoesNotDominateBlock) 11964 return DoesNotDominateBlock; 11965 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11966 ProperlyDominatesBlock : DominatesBlock; 11967 } 11968 case scUnknown: 11969 if (Instruction *I = 11970 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11971 if (I->getParent() == BB) 11972 return DominatesBlock; 11973 if (DT.properlyDominates(I->getParent(), BB)) 11974 return ProperlyDominatesBlock; 11975 return DoesNotDominateBlock; 11976 } 11977 return ProperlyDominatesBlock; 11978 case scCouldNotCompute: 11979 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11980 } 11981 llvm_unreachable("Unknown SCEV kind!"); 11982 } 11983 11984 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11985 return getBlockDisposition(S, BB) >= DominatesBlock; 11986 } 11987 11988 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11989 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11990 } 11991 11992 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11993 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11994 } 11995 11996 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11997 auto IsS = [&](const SCEV *X) { return S == X; }; 11998 auto ContainsS = [&](const SCEV *X) { 11999 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12000 }; 12001 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12002 } 12003 12004 void 12005 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12006 ValuesAtScopes.erase(S); 12007 LoopDispositions.erase(S); 12008 BlockDispositions.erase(S); 12009 UnsignedRanges.erase(S); 12010 SignedRanges.erase(S); 12011 ExprValueMap.erase(S); 12012 HasRecMap.erase(S); 12013 MinTrailingZerosCache.erase(S); 12014 12015 for (auto I = PredicatedSCEVRewrites.begin(); 12016 I != PredicatedSCEVRewrites.end();) { 12017 std::pair<const SCEV *, const Loop *> Entry = I->first; 12018 if (Entry.first == S) 12019 PredicatedSCEVRewrites.erase(I++); 12020 else 12021 ++I; 12022 } 12023 12024 auto RemoveSCEVFromBackedgeMap = 12025 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12026 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12027 BackedgeTakenInfo &BEInfo = I->second; 12028 if (BEInfo.hasOperand(S, this)) { 12029 BEInfo.clear(); 12030 Map.erase(I++); 12031 } else 12032 ++I; 12033 } 12034 }; 12035 12036 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12037 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12038 } 12039 12040 void 12041 ScalarEvolution::getUsedLoops(const SCEV *S, 12042 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12043 struct FindUsedLoops { 12044 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12045 : LoopsUsed(LoopsUsed) {} 12046 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12047 bool follow(const SCEV *S) { 12048 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12049 LoopsUsed.insert(AR->getLoop()); 12050 return true; 12051 } 12052 12053 bool isDone() const { return false; } 12054 }; 12055 12056 FindUsedLoops F(LoopsUsed); 12057 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12058 } 12059 12060 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12061 SmallPtrSet<const Loop *, 8> LoopsUsed; 12062 getUsedLoops(S, LoopsUsed); 12063 for (auto *L : LoopsUsed) 12064 LoopUsers[L].push_back(S); 12065 } 12066 12067 void ScalarEvolution::verify() const { 12068 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12069 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12070 12071 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12072 12073 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12074 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12075 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12076 12077 const SCEV *visitConstant(const SCEVConstant *Constant) { 12078 return SE.getConstant(Constant->getAPInt()); 12079 } 12080 12081 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12082 return SE.getUnknown(Expr->getValue()); 12083 } 12084 12085 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12086 return SE.getCouldNotCompute(); 12087 } 12088 }; 12089 12090 SCEVMapper SCM(SE2); 12091 12092 while (!LoopStack.empty()) { 12093 auto *L = LoopStack.pop_back_val(); 12094 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12095 12096 auto *CurBECount = SCM.visit( 12097 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12098 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12099 12100 if (CurBECount == SE2.getCouldNotCompute() || 12101 NewBECount == SE2.getCouldNotCompute()) { 12102 // NB! This situation is legal, but is very suspicious -- whatever pass 12103 // change the loop to make a trip count go from could not compute to 12104 // computable or vice-versa *should have* invalidated SCEV. However, we 12105 // choose not to assert here (for now) since we don't want false 12106 // positives. 12107 continue; 12108 } 12109 12110 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12111 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12112 // not propagate undef aggressively). This means we can (and do) fail 12113 // verification in cases where a transform makes the trip count of a loop 12114 // go from "undef" to "undef+1" (say). The transform is fine, since in 12115 // both cases the loop iterates "undef" times, but SCEV thinks we 12116 // increased the trip count of the loop by 1 incorrectly. 12117 continue; 12118 } 12119 12120 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12121 SE.getTypeSizeInBits(NewBECount->getType())) 12122 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12123 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12124 SE.getTypeSizeInBits(NewBECount->getType())) 12125 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12126 12127 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12128 12129 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12130 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12131 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12132 dbgs() << "Old: " << *CurBECount << "\n"; 12133 dbgs() << "New: " << *NewBECount << "\n"; 12134 dbgs() << "Delta: " << *Delta << "\n"; 12135 std::abort(); 12136 } 12137 } 12138 } 12139 12140 bool ScalarEvolution::invalidate( 12141 Function &F, const PreservedAnalyses &PA, 12142 FunctionAnalysisManager::Invalidator &Inv) { 12143 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12144 // of its dependencies is invalidated. 12145 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12146 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12147 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12148 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12149 Inv.invalidate<LoopAnalysis>(F, PA); 12150 } 12151 12152 AnalysisKey ScalarEvolutionAnalysis::Key; 12153 12154 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12155 FunctionAnalysisManager &AM) { 12156 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12157 AM.getResult<AssumptionAnalysis>(F), 12158 AM.getResult<DominatorTreeAnalysis>(F), 12159 AM.getResult<LoopAnalysis>(F)); 12160 } 12161 12162 PreservedAnalyses 12163 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12164 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12165 return PreservedAnalyses::all(); 12166 } 12167 12168 PreservedAnalyses 12169 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12170 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12171 return PreservedAnalyses::all(); 12172 } 12173 12174 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12175 "Scalar Evolution Analysis", false, true) 12176 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12177 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12178 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12179 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12180 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12181 "Scalar Evolution Analysis", false, true) 12182 12183 char ScalarEvolutionWrapperPass::ID = 0; 12184 12185 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12186 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12187 } 12188 12189 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12190 SE.reset(new ScalarEvolution( 12191 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12192 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12193 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12194 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12195 return false; 12196 } 12197 12198 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12199 12200 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12201 SE->print(OS); 12202 } 12203 12204 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12205 if (!VerifySCEV) 12206 return; 12207 12208 SE->verify(); 12209 } 12210 12211 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12212 AU.setPreservesAll(); 12213 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12214 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12215 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12216 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12217 } 12218 12219 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12220 const SCEV *RHS) { 12221 FoldingSetNodeID ID; 12222 assert(LHS->getType() == RHS->getType() && 12223 "Type mismatch between LHS and RHS"); 12224 // Unique this node based on the arguments 12225 ID.AddInteger(SCEVPredicate::P_Equal); 12226 ID.AddPointer(LHS); 12227 ID.AddPointer(RHS); 12228 void *IP = nullptr; 12229 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12230 return S; 12231 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12232 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12233 UniquePreds.InsertNode(Eq, IP); 12234 return Eq; 12235 } 12236 12237 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12238 const SCEVAddRecExpr *AR, 12239 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12240 FoldingSetNodeID ID; 12241 // Unique this node based on the arguments 12242 ID.AddInteger(SCEVPredicate::P_Wrap); 12243 ID.AddPointer(AR); 12244 ID.AddInteger(AddedFlags); 12245 void *IP = nullptr; 12246 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12247 return S; 12248 auto *OF = new (SCEVAllocator) 12249 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12250 UniquePreds.InsertNode(OF, IP); 12251 return OF; 12252 } 12253 12254 namespace { 12255 12256 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12257 public: 12258 12259 /// Rewrites \p S in the context of a loop L and the SCEV predication 12260 /// infrastructure. 12261 /// 12262 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12263 /// equivalences present in \p Pred. 12264 /// 12265 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12266 /// \p NewPreds such that the result will be an AddRecExpr. 12267 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12268 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12269 SCEVUnionPredicate *Pred) { 12270 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12271 return Rewriter.visit(S); 12272 } 12273 12274 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12275 if (Pred) { 12276 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12277 for (auto *Pred : ExprPreds) 12278 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12279 if (IPred->getLHS() == Expr) 12280 return IPred->getRHS(); 12281 } 12282 return convertToAddRecWithPreds(Expr); 12283 } 12284 12285 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12286 const SCEV *Operand = visit(Expr->getOperand()); 12287 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12288 if (AR && AR->getLoop() == L && AR->isAffine()) { 12289 // This couldn't be folded because the operand didn't have the nuw 12290 // flag. Add the nusw flag as an assumption that we could make. 12291 const SCEV *Step = AR->getStepRecurrence(SE); 12292 Type *Ty = Expr->getType(); 12293 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12294 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12295 SE.getSignExtendExpr(Step, Ty), L, 12296 AR->getNoWrapFlags()); 12297 } 12298 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12299 } 12300 12301 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12302 const SCEV *Operand = visit(Expr->getOperand()); 12303 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12304 if (AR && AR->getLoop() == L && AR->isAffine()) { 12305 // This couldn't be folded because the operand didn't have the nsw 12306 // flag. Add the nssw flag as an assumption that we could make. 12307 const SCEV *Step = AR->getStepRecurrence(SE); 12308 Type *Ty = Expr->getType(); 12309 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12310 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12311 SE.getSignExtendExpr(Step, Ty), L, 12312 AR->getNoWrapFlags()); 12313 } 12314 return SE.getSignExtendExpr(Operand, Expr->getType()); 12315 } 12316 12317 private: 12318 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12319 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12320 SCEVUnionPredicate *Pred) 12321 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12322 12323 bool addOverflowAssumption(const SCEVPredicate *P) { 12324 if (!NewPreds) { 12325 // Check if we've already made this assumption. 12326 return Pred && Pred->implies(P); 12327 } 12328 NewPreds->insert(P); 12329 return true; 12330 } 12331 12332 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12333 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12334 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12335 return addOverflowAssumption(A); 12336 } 12337 12338 // If \p Expr represents a PHINode, we try to see if it can be represented 12339 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12340 // to add this predicate as a runtime overflow check, we return the AddRec. 12341 // If \p Expr does not meet these conditions (is not a PHI node, or we 12342 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12343 // return \p Expr. 12344 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12345 if (!isa<PHINode>(Expr->getValue())) 12346 return Expr; 12347 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12348 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12349 if (!PredicatedRewrite) 12350 return Expr; 12351 for (auto *P : PredicatedRewrite->second){ 12352 // Wrap predicates from outer loops are not supported. 12353 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12354 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12355 if (L != AR->getLoop()) 12356 return Expr; 12357 } 12358 if (!addOverflowAssumption(P)) 12359 return Expr; 12360 } 12361 return PredicatedRewrite->first; 12362 } 12363 12364 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12365 SCEVUnionPredicate *Pred; 12366 const Loop *L; 12367 }; 12368 12369 } // end anonymous namespace 12370 12371 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12372 SCEVUnionPredicate &Preds) { 12373 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12374 } 12375 12376 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12377 const SCEV *S, const Loop *L, 12378 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12379 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12380 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12381 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12382 12383 if (!AddRec) 12384 return nullptr; 12385 12386 // Since the transformation was successful, we can now transfer the SCEV 12387 // predicates. 12388 for (auto *P : TransformPreds) 12389 Preds.insert(P); 12390 12391 return AddRec; 12392 } 12393 12394 /// SCEV predicates 12395 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12396 SCEVPredicateKind Kind) 12397 : FastID(ID), Kind(Kind) {} 12398 12399 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12400 const SCEV *LHS, const SCEV *RHS) 12401 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12402 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12403 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12404 } 12405 12406 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12407 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12408 12409 if (!Op) 12410 return false; 12411 12412 return Op->LHS == LHS && Op->RHS == RHS; 12413 } 12414 12415 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12416 12417 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12418 12419 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12420 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12421 } 12422 12423 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12424 const SCEVAddRecExpr *AR, 12425 IncrementWrapFlags Flags) 12426 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12427 12428 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12429 12430 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12431 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12432 12433 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12434 } 12435 12436 bool SCEVWrapPredicate::isAlwaysTrue() const { 12437 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12438 IncrementWrapFlags IFlags = Flags; 12439 12440 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12441 IFlags = clearFlags(IFlags, IncrementNSSW); 12442 12443 return IFlags == IncrementAnyWrap; 12444 } 12445 12446 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12447 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12448 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12449 OS << "<nusw>"; 12450 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12451 OS << "<nssw>"; 12452 OS << "\n"; 12453 } 12454 12455 SCEVWrapPredicate::IncrementWrapFlags 12456 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12457 ScalarEvolution &SE) { 12458 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12459 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12460 12461 // We can safely transfer the NSW flag as NSSW. 12462 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12463 ImpliedFlags = IncrementNSSW; 12464 12465 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12466 // If the increment is positive, the SCEV NUW flag will also imply the 12467 // WrapPredicate NUSW flag. 12468 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12469 if (Step->getValue()->getValue().isNonNegative()) 12470 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12471 } 12472 12473 return ImpliedFlags; 12474 } 12475 12476 /// Union predicates don't get cached so create a dummy set ID for it. 12477 SCEVUnionPredicate::SCEVUnionPredicate() 12478 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12479 12480 bool SCEVUnionPredicate::isAlwaysTrue() const { 12481 return all_of(Preds, 12482 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12483 } 12484 12485 ArrayRef<const SCEVPredicate *> 12486 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12487 auto I = SCEVToPreds.find(Expr); 12488 if (I == SCEVToPreds.end()) 12489 return ArrayRef<const SCEVPredicate *>(); 12490 return I->second; 12491 } 12492 12493 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12494 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12495 return all_of(Set->Preds, 12496 [this](const SCEVPredicate *I) { return this->implies(I); }); 12497 12498 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12499 if (ScevPredsIt == SCEVToPreds.end()) 12500 return false; 12501 auto &SCEVPreds = ScevPredsIt->second; 12502 12503 return any_of(SCEVPreds, 12504 [N](const SCEVPredicate *I) { return I->implies(N); }); 12505 } 12506 12507 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12508 12509 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12510 for (auto Pred : Preds) 12511 Pred->print(OS, Depth); 12512 } 12513 12514 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12515 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12516 for (auto Pred : Set->Preds) 12517 add(Pred); 12518 return; 12519 } 12520 12521 if (implies(N)) 12522 return; 12523 12524 const SCEV *Key = N->getExpr(); 12525 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12526 " associated expression!"); 12527 12528 SCEVToPreds[Key].push_back(N); 12529 Preds.push_back(N); 12530 } 12531 12532 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12533 Loop &L) 12534 : SE(SE), L(L) {} 12535 12536 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12537 const SCEV *Expr = SE.getSCEV(V); 12538 RewriteEntry &Entry = RewriteMap[Expr]; 12539 12540 // If we already have an entry and the version matches, return it. 12541 if (Entry.second && Generation == Entry.first) 12542 return Entry.second; 12543 12544 // We found an entry but it's stale. Rewrite the stale entry 12545 // according to the current predicate. 12546 if (Entry.second) 12547 Expr = Entry.second; 12548 12549 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12550 Entry = {Generation, NewSCEV}; 12551 12552 return NewSCEV; 12553 } 12554 12555 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12556 if (!BackedgeCount) { 12557 SCEVUnionPredicate BackedgePred; 12558 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12559 addPredicate(BackedgePred); 12560 } 12561 return BackedgeCount; 12562 } 12563 12564 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12565 if (Preds.implies(&Pred)) 12566 return; 12567 Preds.add(&Pred); 12568 updateGeneration(); 12569 } 12570 12571 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12572 return Preds; 12573 } 12574 12575 void PredicatedScalarEvolution::updateGeneration() { 12576 // If the generation number wrapped recompute everything. 12577 if (++Generation == 0) { 12578 for (auto &II : RewriteMap) { 12579 const SCEV *Rewritten = II.second.second; 12580 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12581 } 12582 } 12583 } 12584 12585 void PredicatedScalarEvolution::setNoOverflow( 12586 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12587 const SCEV *Expr = getSCEV(V); 12588 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12589 12590 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12591 12592 // Clear the statically implied flags. 12593 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12594 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12595 12596 auto II = FlagsMap.insert({V, Flags}); 12597 if (!II.second) 12598 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12599 } 12600 12601 bool PredicatedScalarEvolution::hasNoOverflow( 12602 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12603 const SCEV *Expr = getSCEV(V); 12604 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12605 12606 Flags = SCEVWrapPredicate::clearFlags( 12607 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12608 12609 auto II = FlagsMap.find(V); 12610 12611 if (II != FlagsMap.end()) 12612 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12613 12614 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12615 } 12616 12617 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12618 const SCEV *Expr = this->getSCEV(V); 12619 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12620 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12621 12622 if (!New) 12623 return nullptr; 12624 12625 for (auto *P : NewPreds) 12626 Preds.add(P); 12627 12628 updateGeneration(); 12629 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12630 return New; 12631 } 12632 12633 PredicatedScalarEvolution::PredicatedScalarEvolution( 12634 const PredicatedScalarEvolution &Init) 12635 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12636 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12637 for (auto I : Init.FlagsMap) 12638 FlagsMap.insert(I); 12639 } 12640 12641 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12642 // For each block. 12643 for (auto *BB : L.getBlocks()) 12644 for (auto &I : *BB) { 12645 if (!SE.isSCEVable(I.getType())) 12646 continue; 12647 12648 auto *Expr = SE.getSCEV(&I); 12649 auto II = RewriteMap.find(Expr); 12650 12651 if (II == RewriteMap.end()) 12652 continue; 12653 12654 // Don't print things that are not interesting. 12655 if (II->second.second == Expr) 12656 continue; 12657 12658 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12659 OS.indent(Depth + 2) << *Expr << "\n"; 12660 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12661 } 12662 } 12663 12664 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12665 // arbitrary expressions. 12666 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12667 // 4, A / B becomes X / 8). 12668 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12669 const SCEV *&RHS) { 12670 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12671 if (Add == nullptr || Add->getNumOperands() != 2) 12672 return false; 12673 12674 const SCEV *A = Add->getOperand(1); 12675 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12676 12677 if (Mul == nullptr) 12678 return false; 12679 12680 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12681 // (SomeExpr + (-(SomeExpr / B) * B)). 12682 if (Expr == getURemExpr(A, B)) { 12683 LHS = A; 12684 RHS = B; 12685 return true; 12686 } 12687 return false; 12688 }; 12689 12690 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12691 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12692 return MatchURemWithDivisor(Mul->getOperand(1)) || 12693 MatchURemWithDivisor(Mul->getOperand(2)); 12694 12695 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12696 if (Mul->getNumOperands() == 2) 12697 return MatchURemWithDivisor(Mul->getOperand(1)) || 12698 MatchURemWithDivisor(Mul->getOperand(0)) || 12699 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12700 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12701 return false; 12702 } 12703