1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/KnownBits.h" 93 #include "llvm/Support/MathExtras.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include <algorithm> 97 using namespace llvm; 98 99 #define DEBUG_TYPE "scalar-evolution" 100 101 STATISTIC(NumArrayLenItCounts, 102 "Number of trip counts computed with array length"); 103 STATISTIC(NumTripCountsComputed, 104 "Number of loops with predictable loop counts"); 105 STATISTIC(NumTripCountsNotComputed, 106 "Number of loops without predictable loop counts"); 107 STATISTIC(NumBruteForceTripCountsComputed, 108 "Number of loops with trip counts computed by force"); 109 110 static cl::opt<unsigned> 111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 112 cl::desc("Maximum number of iterations SCEV will " 113 "symbolically execute a constant " 114 "derived loop"), 115 cl::init(100)); 116 117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 118 static cl::opt<bool> 119 VerifySCEV("verify-scev", 120 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 121 static cl::opt<bool> 122 VerifySCEVMap("verify-scev-maps", 123 cl::desc("Verify no dangling value in ScalarEvolution's " 124 "ExprValueMap (slow)")); 125 126 static cl::opt<unsigned> MulOpsInlineThreshold( 127 "scev-mulops-inline-threshold", cl::Hidden, 128 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 129 cl::init(32)); 130 131 static cl::opt<unsigned> AddOpsInlineThreshold( 132 "scev-addops-inline-threshold", cl::Hidden, 133 cl::desc("Threshold for inlining addition operands into a SCEV"), 134 cl::init(500)); 135 136 static cl::opt<unsigned> MaxSCEVCompareDepth( 137 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 138 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 139 cl::init(32)); 140 141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 142 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 143 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 144 cl::init(2)); 145 146 static cl::opt<unsigned> MaxValueCompareDepth( 147 "scalar-evolution-max-value-compare-depth", cl::Hidden, 148 cl::desc("Maximum depth of recursive value complexity comparisons"), 149 cl::init(2)); 150 151 static cl::opt<unsigned> 152 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 153 cl::desc("Maximum depth of recursive arithmetics"), 154 cl::init(32)); 155 156 static cl::opt<unsigned> MaxConstantEvolvingDepth( 157 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 158 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 159 160 static cl::opt<unsigned> 161 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 162 cl::desc("Maximum depth of recursive SExt/ZExt"), 163 cl::init(8)); 164 165 //===----------------------------------------------------------------------===// 166 // SCEV class definitions 167 //===----------------------------------------------------------------------===// 168 169 //===----------------------------------------------------------------------===// 170 // Implementation of the SCEV class. 171 // 172 173 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 174 LLVM_DUMP_METHOD void SCEV::dump() const { 175 print(dbgs()); 176 dbgs() << '\n'; 177 } 178 #endif 179 180 void SCEV::print(raw_ostream &OS) const { 181 switch (static_cast<SCEVTypes>(getSCEVType())) { 182 case scConstant: 183 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 184 return; 185 case scTruncate: { 186 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 187 const SCEV *Op = Trunc->getOperand(); 188 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 189 << *Trunc->getType() << ")"; 190 return; 191 } 192 case scZeroExtend: { 193 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 194 const SCEV *Op = ZExt->getOperand(); 195 OS << "(zext " << *Op->getType() << " " << *Op << " to " 196 << *ZExt->getType() << ")"; 197 return; 198 } 199 case scSignExtend: { 200 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 201 const SCEV *Op = SExt->getOperand(); 202 OS << "(sext " << *Op->getType() << " " << *Op << " to " 203 << *SExt->getType() << ")"; 204 return; 205 } 206 case scAddRecExpr: { 207 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 208 OS << "{" << *AR->getOperand(0); 209 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 210 OS << ",+," << *AR->getOperand(i); 211 OS << "}<"; 212 if (AR->hasNoUnsignedWrap()) 213 OS << "nuw><"; 214 if (AR->hasNoSignedWrap()) 215 OS << "nsw><"; 216 if (AR->hasNoSelfWrap() && 217 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 218 OS << "nw><"; 219 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 220 OS << ">"; 221 return; 222 } 223 case scAddExpr: 224 case scMulExpr: 225 case scUMaxExpr: 226 case scSMaxExpr: { 227 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 228 const char *OpStr = nullptr; 229 switch (NAry->getSCEVType()) { 230 case scAddExpr: OpStr = " + "; break; 231 case scMulExpr: OpStr = " * "; break; 232 case scUMaxExpr: OpStr = " umax "; break; 233 case scSMaxExpr: OpStr = " smax "; break; 234 } 235 OS << "("; 236 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 237 I != E; ++I) { 238 OS << **I; 239 if (std::next(I) != E) 240 OS << OpStr; 241 } 242 OS << ")"; 243 switch (NAry->getSCEVType()) { 244 case scAddExpr: 245 case scMulExpr: 246 if (NAry->hasNoUnsignedWrap()) 247 OS << "<nuw>"; 248 if (NAry->hasNoSignedWrap()) 249 OS << "<nsw>"; 250 } 251 return; 252 } 253 case scUDivExpr: { 254 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 255 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 256 return; 257 } 258 case scUnknown: { 259 const SCEVUnknown *U = cast<SCEVUnknown>(this); 260 Type *AllocTy; 261 if (U->isSizeOf(AllocTy)) { 262 OS << "sizeof(" << *AllocTy << ")"; 263 return; 264 } 265 if (U->isAlignOf(AllocTy)) { 266 OS << "alignof(" << *AllocTy << ")"; 267 return; 268 } 269 270 Type *CTy; 271 Constant *FieldNo; 272 if (U->isOffsetOf(CTy, FieldNo)) { 273 OS << "offsetof(" << *CTy << ", "; 274 FieldNo->printAsOperand(OS, false); 275 OS << ")"; 276 return; 277 } 278 279 // Otherwise just print it normally. 280 U->getValue()->printAsOperand(OS, false); 281 return; 282 } 283 case scCouldNotCompute: 284 OS << "***COULDNOTCOMPUTE***"; 285 return; 286 } 287 llvm_unreachable("Unknown SCEV kind!"); 288 } 289 290 Type *SCEV::getType() const { 291 switch (static_cast<SCEVTypes>(getSCEVType())) { 292 case scConstant: 293 return cast<SCEVConstant>(this)->getType(); 294 case scTruncate: 295 case scZeroExtend: 296 case scSignExtend: 297 return cast<SCEVCastExpr>(this)->getType(); 298 case scAddRecExpr: 299 case scMulExpr: 300 case scUMaxExpr: 301 case scSMaxExpr: 302 return cast<SCEVNAryExpr>(this)->getType(); 303 case scAddExpr: 304 return cast<SCEVAddExpr>(this)->getType(); 305 case scUDivExpr: 306 return cast<SCEVUDivExpr>(this)->getType(); 307 case scUnknown: 308 return cast<SCEVUnknown>(this)->getType(); 309 case scCouldNotCompute: 310 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 311 } 312 llvm_unreachable("Unknown SCEV kind!"); 313 } 314 315 bool SCEV::isZero() const { 316 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 317 return SC->getValue()->isZero(); 318 return false; 319 } 320 321 bool SCEV::isOne() const { 322 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 323 return SC->getValue()->isOne(); 324 return false; 325 } 326 327 bool SCEV::isAllOnesValue() const { 328 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 329 return SC->getValue()->isMinusOne(); 330 return false; 331 } 332 333 bool SCEV::isNonConstantNegative() const { 334 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 335 if (!Mul) return false; 336 337 // If there is a constant factor, it will be first. 338 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 339 if (!SC) return false; 340 341 // Return true if the value is negative, this matches things like (-42 * V). 342 return SC->getAPInt().isNegative(); 343 } 344 345 SCEVCouldNotCompute::SCEVCouldNotCompute() : 346 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 347 348 bool SCEVCouldNotCompute::classof(const SCEV *S) { 349 return S->getSCEVType() == scCouldNotCompute; 350 } 351 352 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 353 FoldingSetNodeID ID; 354 ID.AddInteger(scConstant); 355 ID.AddPointer(V); 356 void *IP = nullptr; 357 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 358 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 359 UniqueSCEVs.InsertNode(S, IP); 360 return S; 361 } 362 363 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 364 return getConstant(ConstantInt::get(getContext(), Val)); 365 } 366 367 const SCEV * 368 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 369 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 370 return getConstant(ConstantInt::get(ITy, V, isSigned)); 371 } 372 373 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 374 unsigned SCEVTy, const SCEV *op, Type *ty) 375 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 376 377 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 378 const SCEV *op, Type *ty) 379 : SCEVCastExpr(ID, scTruncate, op, ty) { 380 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 381 (Ty->isIntegerTy() || Ty->isPointerTy()) && 382 "Cannot truncate non-integer value!"); 383 } 384 385 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 386 const SCEV *op, Type *ty) 387 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 388 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 389 (Ty->isIntegerTy() || Ty->isPointerTy()) && 390 "Cannot zero extend non-integer value!"); 391 } 392 393 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 394 const SCEV *op, Type *ty) 395 : SCEVCastExpr(ID, scSignExtend, op, ty) { 396 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 397 (Ty->isIntegerTy() || Ty->isPointerTy()) && 398 "Cannot sign extend non-integer value!"); 399 } 400 401 void SCEVUnknown::deleted() { 402 // Clear this SCEVUnknown from various maps. 403 SE->forgetMemoizedResults(this); 404 405 // Remove this SCEVUnknown from the uniquing map. 406 SE->UniqueSCEVs.RemoveNode(this); 407 408 // Release the value. 409 setValPtr(nullptr); 410 } 411 412 void SCEVUnknown::allUsesReplacedWith(Value *New) { 413 // Clear this SCEVUnknown from various maps. 414 SE->forgetMemoizedResults(this); 415 416 // Remove this SCEVUnknown from the uniquing map. 417 SE->UniqueSCEVs.RemoveNode(this); 418 419 // Update this SCEVUnknown to point to the new value. This is needed 420 // because there may still be outstanding SCEVs which still point to 421 // this SCEVUnknown. 422 setValPtr(New); 423 } 424 425 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 426 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 427 if (VCE->getOpcode() == Instruction::PtrToInt) 428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 429 if (CE->getOpcode() == Instruction::GetElementPtr && 430 CE->getOperand(0)->isNullValue() && 431 CE->getNumOperands() == 2) 432 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 433 if (CI->isOne()) { 434 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 435 ->getElementType(); 436 return true; 437 } 438 439 return false; 440 } 441 442 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 443 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 444 if (VCE->getOpcode() == Instruction::PtrToInt) 445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 446 if (CE->getOpcode() == Instruction::GetElementPtr && 447 CE->getOperand(0)->isNullValue()) { 448 Type *Ty = 449 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 450 if (StructType *STy = dyn_cast<StructType>(Ty)) 451 if (!STy->isPacked() && 452 CE->getNumOperands() == 3 && 453 CE->getOperand(1)->isNullValue()) { 454 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 455 if (CI->isOne() && 456 STy->getNumElements() == 2 && 457 STy->getElementType(0)->isIntegerTy(1)) { 458 AllocTy = STy->getElementType(1); 459 return true; 460 } 461 } 462 } 463 464 return false; 465 } 466 467 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 468 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 469 if (VCE->getOpcode() == Instruction::PtrToInt) 470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 471 if (CE->getOpcode() == Instruction::GetElementPtr && 472 CE->getNumOperands() == 3 && 473 CE->getOperand(0)->isNullValue() && 474 CE->getOperand(1)->isNullValue()) { 475 Type *Ty = 476 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 477 // Ignore vector types here so that ScalarEvolutionExpander doesn't 478 // emit getelementptrs that index into vectors. 479 if (Ty->isStructTy() || Ty->isArrayTy()) { 480 CTy = Ty; 481 FieldNo = CE->getOperand(2); 482 return true; 483 } 484 } 485 486 return false; 487 } 488 489 //===----------------------------------------------------------------------===// 490 // SCEV Utilities 491 //===----------------------------------------------------------------------===// 492 493 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 494 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 495 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 496 /// have been previously deemed to be "equally complex" by this routine. It is 497 /// intended to avoid exponential time complexity in cases like: 498 /// 499 /// %a = f(%x, %y) 500 /// %b = f(%a, %a) 501 /// %c = f(%b, %b) 502 /// 503 /// %d = f(%x, %y) 504 /// %e = f(%d, %d) 505 /// %f = f(%e, %e) 506 /// 507 /// CompareValueComplexity(%f, %c) 508 /// 509 /// Since we do not continue running this routine on expression trees once we 510 /// have seen unequal values, there is no need to track them in the cache. 511 static int 512 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 513 const LoopInfo *const LI, Value *LV, Value *RV, 514 unsigned Depth) { 515 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV})) 516 return 0; 517 518 // Order pointer values after integer values. This helps SCEVExpander form 519 // GEPs. 520 bool LIsPointer = LV->getType()->isPointerTy(), 521 RIsPointer = RV->getType()->isPointerTy(); 522 if (LIsPointer != RIsPointer) 523 return (int)LIsPointer - (int)RIsPointer; 524 525 // Compare getValueID values. 526 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 527 if (LID != RID) 528 return (int)LID - (int)RID; 529 530 // Sort arguments by their position. 531 if (const auto *LA = dyn_cast<Argument>(LV)) { 532 const auto *RA = cast<Argument>(RV); 533 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 534 return (int)LArgNo - (int)RArgNo; 535 } 536 537 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 538 const auto *RGV = cast<GlobalValue>(RV); 539 540 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 541 auto LT = GV->getLinkage(); 542 return !(GlobalValue::isPrivateLinkage(LT) || 543 GlobalValue::isInternalLinkage(LT)); 544 }; 545 546 // Use the names to distinguish the two values, but only if the 547 // names are semantically important. 548 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 549 return LGV->getName().compare(RGV->getName()); 550 } 551 552 // For instructions, compare their loop depth, and their operand count. This 553 // is pretty loose. 554 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 555 const auto *RInst = cast<Instruction>(RV); 556 557 // Compare loop depths. 558 const BasicBlock *LParent = LInst->getParent(), 559 *RParent = RInst->getParent(); 560 if (LParent != RParent) { 561 unsigned LDepth = LI->getLoopDepth(LParent), 562 RDepth = LI->getLoopDepth(RParent); 563 if (LDepth != RDepth) 564 return (int)LDepth - (int)RDepth; 565 } 566 567 // Compare the number of operands. 568 unsigned LNumOps = LInst->getNumOperands(), 569 RNumOps = RInst->getNumOperands(); 570 if (LNumOps != RNumOps) 571 return (int)LNumOps - (int)RNumOps; 572 573 for (unsigned Idx : seq(0u, LNumOps)) { 574 int Result = 575 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 576 RInst->getOperand(Idx), Depth + 1); 577 if (Result != 0) 578 return Result; 579 } 580 } 581 582 EqCache.insert({LV, RV}); 583 return 0; 584 } 585 586 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 587 // than RHS, respectively. A three-way result allows recursive comparisons to be 588 // more efficient. 589 static int CompareSCEVComplexity( 590 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 591 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 592 DominatorTree &DT, unsigned Depth = 0) { 593 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 594 if (LHS == RHS) 595 return 0; 596 597 // Primarily, sort the SCEVs by their getSCEVType(). 598 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 599 if (LType != RType) 600 return (int)LType - (int)RType; 601 602 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS})) 603 return 0; 604 // Aside from the getSCEVType() ordering, the particular ordering 605 // isn't very important except that it's beneficial to be consistent, 606 // so that (a + b) and (b + a) don't end up as different expressions. 607 switch (static_cast<SCEVTypes>(LType)) { 608 case scUnknown: { 609 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 610 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 611 612 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 613 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 614 Depth + 1); 615 if (X == 0) 616 EqCacheSCEV.insert({LHS, RHS}); 617 return X; 618 } 619 620 case scConstant: { 621 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 622 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 623 624 // Compare constant values. 625 const APInt &LA = LC->getAPInt(); 626 const APInt &RA = RC->getAPInt(); 627 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 628 if (LBitWidth != RBitWidth) 629 return (int)LBitWidth - (int)RBitWidth; 630 return LA.ult(RA) ? -1 : 1; 631 } 632 633 case scAddRecExpr: { 634 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 635 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 636 637 // There is always a dominance between two recs that are used by one SCEV, 638 // so we can safely sort recs by loop header dominance. We require such 639 // order in getAddExpr. 640 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 641 if (LLoop != RLoop) { 642 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 643 assert(LHead != RHead && "Two loops share the same header?"); 644 if (DT.dominates(LHead, RHead)) 645 return 1; 646 else 647 assert(DT.dominates(RHead, LHead) && 648 "No dominance between recurrences used by one SCEV?"); 649 return -1; 650 } 651 652 // Addrec complexity grows with operand count. 653 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 654 if (LNumOps != RNumOps) 655 return (int)LNumOps - (int)RNumOps; 656 657 // Lexicographically compare. 658 for (unsigned i = 0; i != LNumOps; ++i) { 659 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 660 RA->getOperand(i), DT, Depth + 1); 661 if (X != 0) 662 return X; 663 } 664 EqCacheSCEV.insert({LHS, RHS}); 665 return 0; 666 } 667 668 case scAddExpr: 669 case scMulExpr: 670 case scSMaxExpr: 671 case scUMaxExpr: { 672 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 673 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 674 675 // Lexicographically compare n-ary expressions. 676 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 677 if (LNumOps != RNumOps) 678 return (int)LNumOps - (int)RNumOps; 679 680 for (unsigned i = 0; i != LNumOps; ++i) { 681 if (i >= RNumOps) 682 return 1; 683 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 684 RC->getOperand(i), DT, Depth + 1); 685 if (X != 0) 686 return X; 687 } 688 EqCacheSCEV.insert({LHS, RHS}); 689 return 0; 690 } 691 692 case scUDivExpr: { 693 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 694 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 695 696 // Lexicographically compare udiv expressions. 697 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 698 DT, Depth + 1); 699 if (X != 0) 700 return X; 701 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT, 702 Depth + 1); 703 if (X == 0) 704 EqCacheSCEV.insert({LHS, RHS}); 705 return X; 706 } 707 708 case scTruncate: 709 case scZeroExtend: 710 case scSignExtend: { 711 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 712 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 713 714 // Compare cast expressions by operand. 715 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 716 RC->getOperand(), DT, Depth + 1); 717 if (X == 0) 718 EqCacheSCEV.insert({LHS, RHS}); 719 return X; 720 } 721 722 case scCouldNotCompute: 723 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 724 } 725 llvm_unreachable("Unknown SCEV kind!"); 726 } 727 728 /// Given a list of SCEV objects, order them by their complexity, and group 729 /// objects of the same complexity together by value. When this routine is 730 /// finished, we know that any duplicates in the vector are consecutive and that 731 /// complexity is monotonically increasing. 732 /// 733 /// Note that we go take special precautions to ensure that we get deterministic 734 /// results from this routine. In other words, we don't want the results of 735 /// this to depend on where the addresses of various SCEV objects happened to 736 /// land in memory. 737 /// 738 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 739 LoopInfo *LI, DominatorTree &DT) { 740 if (Ops.size() < 2) return; // Noop 741 742 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 743 if (Ops.size() == 2) { 744 // This is the common case, which also happens to be trivially simple. 745 // Special case it. 746 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 747 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0) 748 std::swap(LHS, RHS); 749 return; 750 } 751 752 // Do the rough sort by complexity. 753 std::stable_sort(Ops.begin(), Ops.end(), 754 [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) { 755 return 756 CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0; 757 }); 758 759 // Now that we are sorted by complexity, group elements of the same 760 // complexity. Note that this is, at worst, N^2, but the vector is likely to 761 // be extremely short in practice. Note that we take this approach because we 762 // do not want to depend on the addresses of the objects we are grouping. 763 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 764 const SCEV *S = Ops[i]; 765 unsigned Complexity = S->getSCEVType(); 766 767 // If there are any objects of the same complexity and same value as this 768 // one, group them. 769 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 770 if (Ops[j] == S) { // Found a duplicate. 771 // Move it to immediately after i'th element. 772 std::swap(Ops[i+1], Ops[j]); 773 ++i; // no need to rescan it. 774 if (i == e-2) return; // Done! 775 } 776 } 777 } 778 } 779 780 // Returns the size of the SCEV S. 781 static inline int sizeOfSCEV(const SCEV *S) { 782 struct FindSCEVSize { 783 int Size; 784 FindSCEVSize() : Size(0) {} 785 786 bool follow(const SCEV *S) { 787 ++Size; 788 // Keep looking at all operands of S. 789 return true; 790 } 791 bool isDone() const { 792 return false; 793 } 794 }; 795 796 FindSCEVSize F; 797 SCEVTraversal<FindSCEVSize> ST(F); 798 ST.visitAll(S); 799 return F.Size; 800 } 801 802 namespace { 803 804 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 805 public: 806 // Computes the Quotient and Remainder of the division of Numerator by 807 // Denominator. 808 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 809 const SCEV *Denominator, const SCEV **Quotient, 810 const SCEV **Remainder) { 811 assert(Numerator && Denominator && "Uninitialized SCEV"); 812 813 SCEVDivision D(SE, Numerator, Denominator); 814 815 // Check for the trivial case here to avoid having to check for it in the 816 // rest of the code. 817 if (Numerator == Denominator) { 818 *Quotient = D.One; 819 *Remainder = D.Zero; 820 return; 821 } 822 823 if (Numerator->isZero()) { 824 *Quotient = D.Zero; 825 *Remainder = D.Zero; 826 return; 827 } 828 829 // A simple case when N/1. The quotient is N. 830 if (Denominator->isOne()) { 831 *Quotient = Numerator; 832 *Remainder = D.Zero; 833 return; 834 } 835 836 // Split the Denominator when it is a product. 837 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 838 const SCEV *Q, *R; 839 *Quotient = Numerator; 840 for (const SCEV *Op : T->operands()) { 841 divide(SE, *Quotient, Op, &Q, &R); 842 *Quotient = Q; 843 844 // Bail out when the Numerator is not divisible by one of the terms of 845 // the Denominator. 846 if (!R->isZero()) { 847 *Quotient = D.Zero; 848 *Remainder = Numerator; 849 return; 850 } 851 } 852 *Remainder = D.Zero; 853 return; 854 } 855 856 D.visit(Numerator); 857 *Quotient = D.Quotient; 858 *Remainder = D.Remainder; 859 } 860 861 // Except in the trivial case described above, we do not know how to divide 862 // Expr by Denominator for the following functions with empty implementation. 863 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 864 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 865 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 866 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 867 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 868 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 869 void visitUnknown(const SCEVUnknown *Numerator) {} 870 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 871 872 void visitConstant(const SCEVConstant *Numerator) { 873 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 874 APInt NumeratorVal = Numerator->getAPInt(); 875 APInt DenominatorVal = D->getAPInt(); 876 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 877 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 878 879 if (NumeratorBW > DenominatorBW) 880 DenominatorVal = DenominatorVal.sext(NumeratorBW); 881 else if (NumeratorBW < DenominatorBW) 882 NumeratorVal = NumeratorVal.sext(DenominatorBW); 883 884 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 885 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 886 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 887 Quotient = SE.getConstant(QuotientVal); 888 Remainder = SE.getConstant(RemainderVal); 889 return; 890 } 891 } 892 893 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 894 const SCEV *StartQ, *StartR, *StepQ, *StepR; 895 if (!Numerator->isAffine()) 896 return cannotDivide(Numerator); 897 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 898 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 899 // Bail out if the types do not match. 900 Type *Ty = Denominator->getType(); 901 if (Ty != StartQ->getType() || Ty != StartR->getType() || 902 Ty != StepQ->getType() || Ty != StepR->getType()) 903 return cannotDivide(Numerator); 904 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 905 Numerator->getNoWrapFlags()); 906 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 907 Numerator->getNoWrapFlags()); 908 } 909 910 void visitAddExpr(const SCEVAddExpr *Numerator) { 911 SmallVector<const SCEV *, 2> Qs, Rs; 912 Type *Ty = Denominator->getType(); 913 914 for (const SCEV *Op : Numerator->operands()) { 915 const SCEV *Q, *R; 916 divide(SE, Op, Denominator, &Q, &R); 917 918 // Bail out if types do not match. 919 if (Ty != Q->getType() || Ty != R->getType()) 920 return cannotDivide(Numerator); 921 922 Qs.push_back(Q); 923 Rs.push_back(R); 924 } 925 926 if (Qs.size() == 1) { 927 Quotient = Qs[0]; 928 Remainder = Rs[0]; 929 return; 930 } 931 932 Quotient = SE.getAddExpr(Qs); 933 Remainder = SE.getAddExpr(Rs); 934 } 935 936 void visitMulExpr(const SCEVMulExpr *Numerator) { 937 SmallVector<const SCEV *, 2> Qs; 938 Type *Ty = Denominator->getType(); 939 940 bool FoundDenominatorTerm = false; 941 for (const SCEV *Op : Numerator->operands()) { 942 // Bail out if types do not match. 943 if (Ty != Op->getType()) 944 return cannotDivide(Numerator); 945 946 if (FoundDenominatorTerm) { 947 Qs.push_back(Op); 948 continue; 949 } 950 951 // Check whether Denominator divides one of the product operands. 952 const SCEV *Q, *R; 953 divide(SE, Op, Denominator, &Q, &R); 954 if (!R->isZero()) { 955 Qs.push_back(Op); 956 continue; 957 } 958 959 // Bail out if types do not match. 960 if (Ty != Q->getType()) 961 return cannotDivide(Numerator); 962 963 FoundDenominatorTerm = true; 964 Qs.push_back(Q); 965 } 966 967 if (FoundDenominatorTerm) { 968 Remainder = Zero; 969 if (Qs.size() == 1) 970 Quotient = Qs[0]; 971 else 972 Quotient = SE.getMulExpr(Qs); 973 return; 974 } 975 976 if (!isa<SCEVUnknown>(Denominator)) 977 return cannotDivide(Numerator); 978 979 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 980 ValueToValueMap RewriteMap; 981 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 982 cast<SCEVConstant>(Zero)->getValue(); 983 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 984 985 if (Remainder->isZero()) { 986 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 987 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 988 cast<SCEVConstant>(One)->getValue(); 989 Quotient = 990 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 991 return; 992 } 993 994 // Quotient is (Numerator - Remainder) divided by Denominator. 995 const SCEV *Q, *R; 996 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 997 // This SCEV does not seem to simplify: fail the division here. 998 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 999 return cannotDivide(Numerator); 1000 divide(SE, Diff, Denominator, &Q, &R); 1001 if (R != Zero) 1002 return cannotDivide(Numerator); 1003 Quotient = Q; 1004 } 1005 1006 private: 1007 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1008 const SCEV *Denominator) 1009 : SE(S), Denominator(Denominator) { 1010 Zero = SE.getZero(Denominator->getType()); 1011 One = SE.getOne(Denominator->getType()); 1012 1013 // We generally do not know how to divide Expr by Denominator. We 1014 // initialize the division to a "cannot divide" state to simplify the rest 1015 // of the code. 1016 cannotDivide(Numerator); 1017 } 1018 1019 // Convenience function for giving up on the division. We set the quotient to 1020 // be equal to zero and the remainder to be equal to the numerator. 1021 void cannotDivide(const SCEV *Numerator) { 1022 Quotient = Zero; 1023 Remainder = Numerator; 1024 } 1025 1026 ScalarEvolution &SE; 1027 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1028 }; 1029 1030 } 1031 1032 //===----------------------------------------------------------------------===// 1033 // Simple SCEV method implementations 1034 //===----------------------------------------------------------------------===// 1035 1036 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1037 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1038 ScalarEvolution &SE, 1039 Type *ResultTy) { 1040 // Handle the simplest case efficiently. 1041 if (K == 1) 1042 return SE.getTruncateOrZeroExtend(It, ResultTy); 1043 1044 // We are using the following formula for BC(It, K): 1045 // 1046 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1047 // 1048 // Suppose, W is the bitwidth of the return value. We must be prepared for 1049 // overflow. Hence, we must assure that the result of our computation is 1050 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1051 // safe in modular arithmetic. 1052 // 1053 // However, this code doesn't use exactly that formula; the formula it uses 1054 // is something like the following, where T is the number of factors of 2 in 1055 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1056 // exponentiation: 1057 // 1058 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1059 // 1060 // This formula is trivially equivalent to the previous formula. However, 1061 // this formula can be implemented much more efficiently. The trick is that 1062 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1063 // arithmetic. To do exact division in modular arithmetic, all we have 1064 // to do is multiply by the inverse. Therefore, this step can be done at 1065 // width W. 1066 // 1067 // The next issue is how to safely do the division by 2^T. The way this 1068 // is done is by doing the multiplication step at a width of at least W + T 1069 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1070 // when we perform the division by 2^T (which is equivalent to a right shift 1071 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1072 // truncated out after the division by 2^T. 1073 // 1074 // In comparison to just directly using the first formula, this technique 1075 // is much more efficient; using the first formula requires W * K bits, 1076 // but this formula less than W + K bits. Also, the first formula requires 1077 // a division step, whereas this formula only requires multiplies and shifts. 1078 // 1079 // It doesn't matter whether the subtraction step is done in the calculation 1080 // width or the input iteration count's width; if the subtraction overflows, 1081 // the result must be zero anyway. We prefer here to do it in the width of 1082 // the induction variable because it helps a lot for certain cases; CodeGen 1083 // isn't smart enough to ignore the overflow, which leads to much less 1084 // efficient code if the width of the subtraction is wider than the native 1085 // register width. 1086 // 1087 // (It's possible to not widen at all by pulling out factors of 2 before 1088 // the multiplication; for example, K=2 can be calculated as 1089 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1090 // extra arithmetic, so it's not an obvious win, and it gets 1091 // much more complicated for K > 3.) 1092 1093 // Protection from insane SCEVs; this bound is conservative, 1094 // but it probably doesn't matter. 1095 if (K > 1000) 1096 return SE.getCouldNotCompute(); 1097 1098 unsigned W = SE.getTypeSizeInBits(ResultTy); 1099 1100 // Calculate K! / 2^T and T; we divide out the factors of two before 1101 // multiplying for calculating K! / 2^T to avoid overflow. 1102 // Other overflow doesn't matter because we only care about the bottom 1103 // W bits of the result. 1104 APInt OddFactorial(W, 1); 1105 unsigned T = 1; 1106 for (unsigned i = 3; i <= K; ++i) { 1107 APInt Mult(W, i); 1108 unsigned TwoFactors = Mult.countTrailingZeros(); 1109 T += TwoFactors; 1110 Mult.lshrInPlace(TwoFactors); 1111 OddFactorial *= Mult; 1112 } 1113 1114 // We need at least W + T bits for the multiplication step 1115 unsigned CalculationBits = W + T; 1116 1117 // Calculate 2^T, at width T+W. 1118 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1119 1120 // Calculate the multiplicative inverse of K! / 2^T; 1121 // this multiplication factor will perform the exact division by 1122 // K! / 2^T. 1123 APInt Mod = APInt::getSignedMinValue(W+1); 1124 APInt MultiplyFactor = OddFactorial.zext(W+1); 1125 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1126 MultiplyFactor = MultiplyFactor.trunc(W); 1127 1128 // Calculate the product, at width T+W 1129 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1130 CalculationBits); 1131 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1132 for (unsigned i = 1; i != K; ++i) { 1133 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1134 Dividend = SE.getMulExpr(Dividend, 1135 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1136 } 1137 1138 // Divide by 2^T 1139 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1140 1141 // Truncate the result, and divide by K! / 2^T. 1142 1143 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1144 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1145 } 1146 1147 /// Return the value of this chain of recurrences at the specified iteration 1148 /// number. We can evaluate this recurrence by multiplying each element in the 1149 /// chain by the binomial coefficient corresponding to it. In other words, we 1150 /// can evaluate {A,+,B,+,C,+,D} as: 1151 /// 1152 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1153 /// 1154 /// where BC(It, k) stands for binomial coefficient. 1155 /// 1156 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1157 ScalarEvolution &SE) const { 1158 const SCEV *Result = getStart(); 1159 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1160 // The computation is correct in the face of overflow provided that the 1161 // multiplication is performed _after_ the evaluation of the binomial 1162 // coefficient. 1163 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1164 if (isa<SCEVCouldNotCompute>(Coeff)) 1165 return Coeff; 1166 1167 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1168 } 1169 return Result; 1170 } 1171 1172 //===----------------------------------------------------------------------===// 1173 // SCEV Expression folder implementations 1174 //===----------------------------------------------------------------------===// 1175 1176 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1177 Type *Ty) { 1178 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1179 "This is not a truncating conversion!"); 1180 assert(isSCEVable(Ty) && 1181 "This is not a conversion to a SCEVable type!"); 1182 Ty = getEffectiveSCEVType(Ty); 1183 1184 FoldingSetNodeID ID; 1185 ID.AddInteger(scTruncate); 1186 ID.AddPointer(Op); 1187 ID.AddPointer(Ty); 1188 void *IP = nullptr; 1189 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1190 1191 // Fold if the operand is constant. 1192 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1193 return getConstant( 1194 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1195 1196 // trunc(trunc(x)) --> trunc(x) 1197 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1198 return getTruncateExpr(ST->getOperand(), Ty); 1199 1200 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1201 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1202 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1203 1204 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1205 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1206 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1207 1208 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1209 // eliminate all the truncates, or we replace other casts with truncates. 1210 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1211 SmallVector<const SCEV *, 4> Operands; 1212 bool hasTrunc = false; 1213 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1214 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1215 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1216 hasTrunc = isa<SCEVTruncateExpr>(S); 1217 Operands.push_back(S); 1218 } 1219 if (!hasTrunc) 1220 return getAddExpr(Operands); 1221 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1222 } 1223 1224 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1225 // eliminate all the truncates, or we replace other casts with truncates. 1226 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1227 SmallVector<const SCEV *, 4> Operands; 1228 bool hasTrunc = false; 1229 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1230 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1231 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1232 hasTrunc = isa<SCEVTruncateExpr>(S); 1233 Operands.push_back(S); 1234 } 1235 if (!hasTrunc) 1236 return getMulExpr(Operands); 1237 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1238 } 1239 1240 // If the input value is a chrec scev, truncate the chrec's operands. 1241 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1242 SmallVector<const SCEV *, 4> Operands; 1243 for (const SCEV *Op : AddRec->operands()) 1244 Operands.push_back(getTruncateExpr(Op, Ty)); 1245 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1246 } 1247 1248 // The cast wasn't folded; create an explicit cast node. We can reuse 1249 // the existing insert position since if we get here, we won't have 1250 // made any changes which would invalidate it. 1251 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1252 Op, Ty); 1253 UniqueSCEVs.InsertNode(S, IP); 1254 return S; 1255 } 1256 1257 // Get the limit of a recurrence such that incrementing by Step cannot cause 1258 // signed overflow as long as the value of the recurrence within the 1259 // loop does not exceed this limit before incrementing. 1260 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1261 ICmpInst::Predicate *Pred, 1262 ScalarEvolution *SE) { 1263 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1264 if (SE->isKnownPositive(Step)) { 1265 *Pred = ICmpInst::ICMP_SLT; 1266 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1267 SE->getSignedRangeMax(Step)); 1268 } 1269 if (SE->isKnownNegative(Step)) { 1270 *Pred = ICmpInst::ICMP_SGT; 1271 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1272 SE->getSignedRangeMin(Step)); 1273 } 1274 return nullptr; 1275 } 1276 1277 // Get the limit of a recurrence such that incrementing by Step cannot cause 1278 // unsigned overflow as long as the value of the recurrence within the loop does 1279 // not exceed this limit before incrementing. 1280 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1281 ICmpInst::Predicate *Pred, 1282 ScalarEvolution *SE) { 1283 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1284 *Pred = ICmpInst::ICMP_ULT; 1285 1286 return SE->getConstant(APInt::getMinValue(BitWidth) - 1287 SE->getUnsignedRangeMax(Step)); 1288 } 1289 1290 namespace { 1291 1292 struct ExtendOpTraitsBase { 1293 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1294 unsigned); 1295 }; 1296 1297 // Used to make code generic over signed and unsigned overflow. 1298 template <typename ExtendOp> struct ExtendOpTraits { 1299 // Members present: 1300 // 1301 // static const SCEV::NoWrapFlags WrapType; 1302 // 1303 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1304 // 1305 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1306 // ICmpInst::Predicate *Pred, 1307 // ScalarEvolution *SE); 1308 }; 1309 1310 template <> 1311 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1312 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1313 1314 static const GetExtendExprTy GetExtendExpr; 1315 1316 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1317 ICmpInst::Predicate *Pred, 1318 ScalarEvolution *SE) { 1319 return getSignedOverflowLimitForStep(Step, Pred, SE); 1320 } 1321 }; 1322 1323 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1324 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1325 1326 template <> 1327 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1328 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1329 1330 static const GetExtendExprTy GetExtendExpr; 1331 1332 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1333 ICmpInst::Predicate *Pred, 1334 ScalarEvolution *SE) { 1335 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1336 } 1337 }; 1338 1339 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1340 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1341 } 1342 1343 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1344 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1345 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1346 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1347 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1348 // expression "Step + sext/zext(PreIncAR)" is congruent with 1349 // "sext/zext(PostIncAR)" 1350 template <typename ExtendOpTy> 1351 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1352 ScalarEvolution *SE, unsigned Depth) { 1353 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1354 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1355 1356 const Loop *L = AR->getLoop(); 1357 const SCEV *Start = AR->getStart(); 1358 const SCEV *Step = AR->getStepRecurrence(*SE); 1359 1360 // Check for a simple looking step prior to loop entry. 1361 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1362 if (!SA) 1363 return nullptr; 1364 1365 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1366 // subtraction is expensive. For this purpose, perform a quick and dirty 1367 // difference, by checking for Step in the operand list. 1368 SmallVector<const SCEV *, 4> DiffOps; 1369 for (const SCEV *Op : SA->operands()) 1370 if (Op != Step) 1371 DiffOps.push_back(Op); 1372 1373 if (DiffOps.size() == SA->getNumOperands()) 1374 return nullptr; 1375 1376 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1377 // `Step`: 1378 1379 // 1. NSW/NUW flags on the step increment. 1380 auto PreStartFlags = 1381 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1382 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1383 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1384 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1385 1386 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1387 // "S+X does not sign/unsign-overflow". 1388 // 1389 1390 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1391 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1392 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1393 return PreStart; 1394 1395 // 2. Direct overflow check on the step operation's expression. 1396 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1397 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1398 const SCEV *OperandExtendedStart = 1399 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1400 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1401 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1402 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1403 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1404 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1405 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1406 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1407 } 1408 return PreStart; 1409 } 1410 1411 // 3. Loop precondition. 1412 ICmpInst::Predicate Pred; 1413 const SCEV *OverflowLimit = 1414 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1415 1416 if (OverflowLimit && 1417 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1418 return PreStart; 1419 1420 return nullptr; 1421 } 1422 1423 // Get the normalized zero or sign extended expression for this AddRec's Start. 1424 template <typename ExtendOpTy> 1425 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1426 ScalarEvolution *SE, 1427 unsigned Depth) { 1428 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1429 1430 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1431 if (!PreStart) 1432 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1433 1434 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1435 Depth), 1436 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1437 } 1438 1439 // Try to prove away overflow by looking at "nearby" add recurrences. A 1440 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1441 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1442 // 1443 // Formally: 1444 // 1445 // {S,+,X} == {S-T,+,X} + T 1446 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1447 // 1448 // If ({S-T,+,X} + T) does not overflow ... (1) 1449 // 1450 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1451 // 1452 // If {S-T,+,X} does not overflow ... (2) 1453 // 1454 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1455 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1456 // 1457 // If (S-T)+T does not overflow ... (3) 1458 // 1459 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1460 // == {Ext(S),+,Ext(X)} == LHS 1461 // 1462 // Thus, if (1), (2) and (3) are true for some T, then 1463 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1464 // 1465 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1466 // does not overflow" restricted to the 0th iteration. Therefore we only need 1467 // to check for (1) and (2). 1468 // 1469 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1470 // is `Delta` (defined below). 1471 // 1472 template <typename ExtendOpTy> 1473 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1474 const SCEV *Step, 1475 const Loop *L) { 1476 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1477 1478 // We restrict `Start` to a constant to prevent SCEV from spending too much 1479 // time here. It is correct (but more expensive) to continue with a 1480 // non-constant `Start` and do a general SCEV subtraction to compute 1481 // `PreStart` below. 1482 // 1483 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1484 if (!StartC) 1485 return false; 1486 1487 APInt StartAI = StartC->getAPInt(); 1488 1489 for (unsigned Delta : {-2, -1, 1, 2}) { 1490 const SCEV *PreStart = getConstant(StartAI - Delta); 1491 1492 FoldingSetNodeID ID; 1493 ID.AddInteger(scAddRecExpr); 1494 ID.AddPointer(PreStart); 1495 ID.AddPointer(Step); 1496 ID.AddPointer(L); 1497 void *IP = nullptr; 1498 const auto *PreAR = 1499 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1500 1501 // Give up if we don't already have the add recurrence we need because 1502 // actually constructing an add recurrence is relatively expensive. 1503 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1504 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1505 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1506 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1507 DeltaS, &Pred, this); 1508 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1509 return true; 1510 } 1511 } 1512 1513 return false; 1514 } 1515 1516 const SCEV * 1517 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1518 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1519 "This is not an extending conversion!"); 1520 assert(isSCEVable(Ty) && 1521 "This is not a conversion to a SCEVable type!"); 1522 Ty = getEffectiveSCEVType(Ty); 1523 1524 // Fold if the operand is constant. 1525 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1526 return getConstant( 1527 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1528 1529 // zext(zext(x)) --> zext(x) 1530 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1531 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1532 1533 // Before doing any expensive analysis, check to see if we've already 1534 // computed a SCEV for this Op and Ty. 1535 FoldingSetNodeID ID; 1536 ID.AddInteger(scZeroExtend); 1537 ID.AddPointer(Op); 1538 ID.AddPointer(Ty); 1539 void *IP = nullptr; 1540 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1541 if (Depth > MaxExtDepth) { 1542 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1543 Op, Ty); 1544 UniqueSCEVs.InsertNode(S, IP); 1545 return S; 1546 } 1547 1548 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1549 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1550 // It's possible the bits taken off by the truncate were all zero bits. If 1551 // so, we should be able to simplify this further. 1552 const SCEV *X = ST->getOperand(); 1553 ConstantRange CR = getUnsignedRange(X); 1554 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1555 unsigned NewBits = getTypeSizeInBits(Ty); 1556 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1557 CR.zextOrTrunc(NewBits))) 1558 return getTruncateOrZeroExtend(X, Ty); 1559 } 1560 1561 // If the input value is a chrec scev, and we can prove that the value 1562 // did not overflow the old, smaller, value, we can zero extend all of the 1563 // operands (often constants). This allows analysis of something like 1564 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1565 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1566 if (AR->isAffine()) { 1567 const SCEV *Start = AR->getStart(); 1568 const SCEV *Step = AR->getStepRecurrence(*this); 1569 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1570 const Loop *L = AR->getLoop(); 1571 1572 if (!AR->hasNoUnsignedWrap()) { 1573 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1574 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1575 } 1576 1577 // If we have special knowledge that this addrec won't overflow, 1578 // we don't need to do any further analysis. 1579 if (AR->hasNoUnsignedWrap()) 1580 return getAddRecExpr( 1581 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1582 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1583 1584 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1585 // Note that this serves two purposes: It filters out loops that are 1586 // simply not analyzable, and it covers the case where this code is 1587 // being called from within backedge-taken count analysis, such that 1588 // attempting to ask for the backedge-taken count would likely result 1589 // in infinite recursion. In the later case, the analysis code will 1590 // cope with a conservative value, and it will take care to purge 1591 // that value once it has finished. 1592 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1593 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1594 // Manually compute the final value for AR, checking for 1595 // overflow. 1596 1597 // Check whether the backedge-taken count can be losslessly casted to 1598 // the addrec's type. The count is always unsigned. 1599 const SCEV *CastedMaxBECount = 1600 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1601 const SCEV *RecastedMaxBECount = 1602 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1603 if (MaxBECount == RecastedMaxBECount) { 1604 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1605 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1606 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1607 SCEV::FlagAnyWrap, Depth + 1); 1608 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1609 SCEV::FlagAnyWrap, 1610 Depth + 1), 1611 WideTy, Depth + 1); 1612 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1613 const SCEV *WideMaxBECount = 1614 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1615 const SCEV *OperandExtendedAdd = 1616 getAddExpr(WideStart, 1617 getMulExpr(WideMaxBECount, 1618 getZeroExtendExpr(Step, WideTy, Depth + 1), 1619 SCEV::FlagAnyWrap, Depth + 1), 1620 SCEV::FlagAnyWrap, Depth + 1); 1621 if (ZAdd == OperandExtendedAdd) { 1622 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1623 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1624 // Return the expression with the addrec on the outside. 1625 return getAddRecExpr( 1626 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1627 Depth + 1), 1628 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1629 AR->getNoWrapFlags()); 1630 } 1631 // Similar to above, only this time treat the step value as signed. 1632 // This covers loops that count down. 1633 OperandExtendedAdd = 1634 getAddExpr(WideStart, 1635 getMulExpr(WideMaxBECount, 1636 getSignExtendExpr(Step, WideTy, Depth + 1), 1637 SCEV::FlagAnyWrap, Depth + 1), 1638 SCEV::FlagAnyWrap, Depth + 1); 1639 if (ZAdd == OperandExtendedAdd) { 1640 // Cache knowledge of AR NW, which is propagated to this AddRec. 1641 // Negative step causes unsigned wrap, but it still can't self-wrap. 1642 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1643 // Return the expression with the addrec on the outside. 1644 return getAddRecExpr( 1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1646 Depth + 1), 1647 getSignExtendExpr(Step, Ty, Depth + 1), L, 1648 AR->getNoWrapFlags()); 1649 } 1650 } 1651 } 1652 1653 // Normally, in the cases we can prove no-overflow via a 1654 // backedge guarding condition, we can also compute a backedge 1655 // taken count for the loop. The exceptions are assumptions and 1656 // guards present in the loop -- SCEV is not great at exploiting 1657 // these to compute max backedge taken counts, but can still use 1658 // these to prove lack of overflow. Use this fact to avoid 1659 // doing extra work that may not pay off. 1660 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1661 !AC.assumptions().empty()) { 1662 // If the backedge is guarded by a comparison with the pre-inc 1663 // value the addrec is safe. Also, if the entry is guarded by 1664 // a comparison with the start value and the backedge is 1665 // guarded by a comparison with the post-inc value, the addrec 1666 // is safe. 1667 if (isKnownPositive(Step)) { 1668 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1669 getUnsignedRangeMax(Step)); 1670 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1671 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1672 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1673 AR->getPostIncExpr(*this), N))) { 1674 // Cache knowledge of AR NUW, which is propagated to this 1675 // AddRec. 1676 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1677 // Return the expression with the addrec on the outside. 1678 return getAddRecExpr( 1679 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1680 Depth + 1), 1681 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1682 AR->getNoWrapFlags()); 1683 } 1684 } else if (isKnownNegative(Step)) { 1685 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1686 getSignedRangeMin(Step)); 1687 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1688 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1689 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1690 AR->getPostIncExpr(*this), N))) { 1691 // Cache knowledge of AR NW, which is propagated to this 1692 // AddRec. Negative step causes unsigned wrap, but it 1693 // still can't self-wrap. 1694 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1695 // Return the expression with the addrec on the outside. 1696 return getAddRecExpr( 1697 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1698 Depth + 1), 1699 getSignExtendExpr(Step, Ty, Depth + 1), L, 1700 AR->getNoWrapFlags()); 1701 } 1702 } 1703 } 1704 1705 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1706 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1707 return getAddRecExpr( 1708 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1709 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1710 } 1711 } 1712 1713 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1714 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1715 if (SA->hasNoUnsignedWrap()) { 1716 // If the addition does not unsign overflow then we can, by definition, 1717 // commute the zero extension with the addition operation. 1718 SmallVector<const SCEV *, 4> Ops; 1719 for (const auto *Op : SA->operands()) 1720 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1721 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1722 } 1723 } 1724 1725 // The cast wasn't folded; create an explicit cast node. 1726 // Recompute the insert position, as it may have been invalidated. 1727 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1728 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1729 Op, Ty); 1730 UniqueSCEVs.InsertNode(S, IP); 1731 return S; 1732 } 1733 1734 const SCEV * 1735 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1736 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1737 "This is not an extending conversion!"); 1738 assert(isSCEVable(Ty) && 1739 "This is not a conversion to a SCEVable type!"); 1740 Ty = getEffectiveSCEVType(Ty); 1741 1742 // Fold if the operand is constant. 1743 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1744 return getConstant( 1745 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1746 1747 // sext(sext(x)) --> sext(x) 1748 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1749 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1750 1751 // sext(zext(x)) --> zext(x) 1752 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1753 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1754 1755 // Before doing any expensive analysis, check to see if we've already 1756 // computed a SCEV for this Op and Ty. 1757 FoldingSetNodeID ID; 1758 ID.AddInteger(scSignExtend); 1759 ID.AddPointer(Op); 1760 ID.AddPointer(Ty); 1761 void *IP = nullptr; 1762 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1763 // Limit recursion depth. 1764 if (Depth > MaxExtDepth) { 1765 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1766 Op, Ty); 1767 UniqueSCEVs.InsertNode(S, IP); 1768 return S; 1769 } 1770 1771 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1772 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1773 // It's possible the bits taken off by the truncate were all sign bits. If 1774 // so, we should be able to simplify this further. 1775 const SCEV *X = ST->getOperand(); 1776 ConstantRange CR = getSignedRange(X); 1777 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1778 unsigned NewBits = getTypeSizeInBits(Ty); 1779 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1780 CR.sextOrTrunc(NewBits))) 1781 return getTruncateOrSignExtend(X, Ty); 1782 } 1783 1784 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1785 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1786 if (SA->getNumOperands() == 2) { 1787 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1788 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1789 if (SMul && SC1) { 1790 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1791 const APInt &C1 = SC1->getAPInt(); 1792 const APInt &C2 = SC2->getAPInt(); 1793 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1794 C2.ugt(C1) && C2.isPowerOf2()) 1795 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1796 getSignExtendExpr(SMul, Ty, Depth + 1), 1797 SCEV::FlagAnyWrap, Depth + 1); 1798 } 1799 } 1800 } 1801 1802 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1803 if (SA->hasNoSignedWrap()) { 1804 // If the addition does not sign overflow then we can, by definition, 1805 // commute the sign extension with the addition operation. 1806 SmallVector<const SCEV *, 4> Ops; 1807 for (const auto *Op : SA->operands()) 1808 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1809 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1810 } 1811 } 1812 // If the input value is a chrec scev, and we can prove that the value 1813 // did not overflow the old, smaller, value, we can sign extend all of the 1814 // operands (often constants). This allows analysis of something like 1815 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1816 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1817 if (AR->isAffine()) { 1818 const SCEV *Start = AR->getStart(); 1819 const SCEV *Step = AR->getStepRecurrence(*this); 1820 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1821 const Loop *L = AR->getLoop(); 1822 1823 if (!AR->hasNoSignedWrap()) { 1824 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1825 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1826 } 1827 1828 // If we have special knowledge that this addrec won't overflow, 1829 // we don't need to do any further analysis. 1830 if (AR->hasNoSignedWrap()) 1831 return getAddRecExpr( 1832 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1833 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1834 1835 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1836 // Note that this serves two purposes: It filters out loops that are 1837 // simply not analyzable, and it covers the case where this code is 1838 // being called from within backedge-taken count analysis, such that 1839 // attempting to ask for the backedge-taken count would likely result 1840 // in infinite recursion. In the later case, the analysis code will 1841 // cope with a conservative value, and it will take care to purge 1842 // that value once it has finished. 1843 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1844 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1845 // Manually compute the final value for AR, checking for 1846 // overflow. 1847 1848 // Check whether the backedge-taken count can be losslessly casted to 1849 // the addrec's type. The count is always unsigned. 1850 const SCEV *CastedMaxBECount = 1851 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1852 const SCEV *RecastedMaxBECount = 1853 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1854 if (MaxBECount == RecastedMaxBECount) { 1855 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1856 // Check whether Start+Step*MaxBECount has no signed overflow. 1857 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1858 SCEV::FlagAnyWrap, Depth + 1); 1859 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1860 SCEV::FlagAnyWrap, 1861 Depth + 1), 1862 WideTy, Depth + 1); 1863 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1864 const SCEV *WideMaxBECount = 1865 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1866 const SCEV *OperandExtendedAdd = 1867 getAddExpr(WideStart, 1868 getMulExpr(WideMaxBECount, 1869 getSignExtendExpr(Step, WideTy, Depth + 1), 1870 SCEV::FlagAnyWrap, Depth + 1), 1871 SCEV::FlagAnyWrap, Depth + 1); 1872 if (SAdd == OperandExtendedAdd) { 1873 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1874 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1875 // Return the expression with the addrec on the outside. 1876 return getAddRecExpr( 1877 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1878 Depth + 1), 1879 getSignExtendExpr(Step, Ty, Depth + 1), L, 1880 AR->getNoWrapFlags()); 1881 } 1882 // Similar to above, only this time treat the step value as unsigned. 1883 // This covers loops that count up with an unsigned step. 1884 OperandExtendedAdd = 1885 getAddExpr(WideStart, 1886 getMulExpr(WideMaxBECount, 1887 getZeroExtendExpr(Step, WideTy, Depth + 1), 1888 SCEV::FlagAnyWrap, Depth + 1), 1889 SCEV::FlagAnyWrap, Depth + 1); 1890 if (SAdd == OperandExtendedAdd) { 1891 // If AR wraps around then 1892 // 1893 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1894 // => SAdd != OperandExtendedAdd 1895 // 1896 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1897 // (SAdd == OperandExtendedAdd => AR is NW) 1898 1899 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1900 1901 // Return the expression with the addrec on the outside. 1902 return getAddRecExpr( 1903 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1904 Depth + 1), 1905 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1906 AR->getNoWrapFlags()); 1907 } 1908 } 1909 } 1910 1911 // Normally, in the cases we can prove no-overflow via a 1912 // backedge guarding condition, we can also compute a backedge 1913 // taken count for the loop. The exceptions are assumptions and 1914 // guards present in the loop -- SCEV is not great at exploiting 1915 // these to compute max backedge taken counts, but can still use 1916 // these to prove lack of overflow. Use this fact to avoid 1917 // doing extra work that may not pay off. 1918 1919 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1920 !AC.assumptions().empty()) { 1921 // If the backedge is guarded by a comparison with the pre-inc 1922 // value the addrec is safe. Also, if the entry is guarded by 1923 // a comparison with the start value and the backedge is 1924 // guarded by a comparison with the post-inc value, the addrec 1925 // is safe. 1926 ICmpInst::Predicate Pred; 1927 const SCEV *OverflowLimit = 1928 getSignedOverflowLimitForStep(Step, &Pred, this); 1929 if (OverflowLimit && 1930 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1931 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1932 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1933 OverflowLimit)))) { 1934 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1935 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1936 return getAddRecExpr( 1937 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1938 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1939 } 1940 } 1941 1942 // If Start and Step are constants, check if we can apply this 1943 // transformation: 1944 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1945 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1946 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1947 if (SC1 && SC2) { 1948 const APInt &C1 = SC1->getAPInt(); 1949 const APInt &C2 = SC2->getAPInt(); 1950 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1951 C2.isPowerOf2()) { 1952 Start = getSignExtendExpr(Start, Ty, Depth + 1); 1953 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1954 AR->getNoWrapFlags()); 1955 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 1956 SCEV::FlagAnyWrap, Depth + 1); 1957 } 1958 } 1959 1960 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1961 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1962 return getAddRecExpr( 1963 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1964 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1965 } 1966 } 1967 1968 // If the input value is provably positive and we could not simplify 1969 // away the sext build a zext instead. 1970 if (isKnownNonNegative(Op)) 1971 return getZeroExtendExpr(Op, Ty, Depth + 1); 1972 1973 // The cast wasn't folded; create an explicit cast node. 1974 // Recompute the insert position, as it may have been invalidated. 1975 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1976 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1977 Op, Ty); 1978 UniqueSCEVs.InsertNode(S, IP); 1979 return S; 1980 } 1981 1982 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1983 /// unspecified bits out to the given type. 1984 /// 1985 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1986 Type *Ty) { 1987 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1988 "This is not an extending conversion!"); 1989 assert(isSCEVable(Ty) && 1990 "This is not a conversion to a SCEVable type!"); 1991 Ty = getEffectiveSCEVType(Ty); 1992 1993 // Sign-extend negative constants. 1994 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1995 if (SC->getAPInt().isNegative()) 1996 return getSignExtendExpr(Op, Ty); 1997 1998 // Peel off a truncate cast. 1999 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2000 const SCEV *NewOp = T->getOperand(); 2001 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2002 return getAnyExtendExpr(NewOp, Ty); 2003 return getTruncateOrNoop(NewOp, Ty); 2004 } 2005 2006 // Next try a zext cast. If the cast is folded, use it. 2007 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2008 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2009 return ZExt; 2010 2011 // Next try a sext cast. If the cast is folded, use it. 2012 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2013 if (!isa<SCEVSignExtendExpr>(SExt)) 2014 return SExt; 2015 2016 // Force the cast to be folded into the operands of an addrec. 2017 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2018 SmallVector<const SCEV *, 4> Ops; 2019 for (const SCEV *Op : AR->operands()) 2020 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2021 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2022 } 2023 2024 // If the expression is obviously signed, use the sext cast value. 2025 if (isa<SCEVSMaxExpr>(Op)) 2026 return SExt; 2027 2028 // Absent any other information, use the zext cast value. 2029 return ZExt; 2030 } 2031 2032 /// Process the given Ops list, which is a list of operands to be added under 2033 /// the given scale, update the given map. This is a helper function for 2034 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2035 /// that would form an add expression like this: 2036 /// 2037 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2038 /// 2039 /// where A and B are constants, update the map with these values: 2040 /// 2041 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2042 /// 2043 /// and add 13 + A*B*29 to AccumulatedConstant. 2044 /// This will allow getAddRecExpr to produce this: 2045 /// 2046 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2047 /// 2048 /// This form often exposes folding opportunities that are hidden in 2049 /// the original operand list. 2050 /// 2051 /// Return true iff it appears that any interesting folding opportunities 2052 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2053 /// the common case where no interesting opportunities are present, and 2054 /// is also used as a check to avoid infinite recursion. 2055 /// 2056 static bool 2057 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2058 SmallVectorImpl<const SCEV *> &NewOps, 2059 APInt &AccumulatedConstant, 2060 const SCEV *const *Ops, size_t NumOperands, 2061 const APInt &Scale, 2062 ScalarEvolution &SE) { 2063 bool Interesting = false; 2064 2065 // Iterate over the add operands. They are sorted, with constants first. 2066 unsigned i = 0; 2067 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2068 ++i; 2069 // Pull a buried constant out to the outside. 2070 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2071 Interesting = true; 2072 AccumulatedConstant += Scale * C->getAPInt(); 2073 } 2074 2075 // Next comes everything else. We're especially interested in multiplies 2076 // here, but they're in the middle, so just visit the rest with one loop. 2077 for (; i != NumOperands; ++i) { 2078 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2079 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2080 APInt NewScale = 2081 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2082 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2083 // A multiplication of a constant with another add; recurse. 2084 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2085 Interesting |= 2086 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2087 Add->op_begin(), Add->getNumOperands(), 2088 NewScale, SE); 2089 } else { 2090 // A multiplication of a constant with some other value. Update 2091 // the map. 2092 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2093 const SCEV *Key = SE.getMulExpr(MulOps); 2094 auto Pair = M.insert({Key, NewScale}); 2095 if (Pair.second) { 2096 NewOps.push_back(Pair.first->first); 2097 } else { 2098 Pair.first->second += NewScale; 2099 // The map already had an entry for this value, which may indicate 2100 // a folding opportunity. 2101 Interesting = true; 2102 } 2103 } 2104 } else { 2105 // An ordinary operand. Update the map. 2106 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2107 M.insert({Ops[i], Scale}); 2108 if (Pair.second) { 2109 NewOps.push_back(Pair.first->first); 2110 } else { 2111 Pair.first->second += Scale; 2112 // The map already had an entry for this value, which may indicate 2113 // a folding opportunity. 2114 Interesting = true; 2115 } 2116 } 2117 } 2118 2119 return Interesting; 2120 } 2121 2122 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2123 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2124 // can't-overflow flags for the operation if possible. 2125 static SCEV::NoWrapFlags 2126 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2127 const SmallVectorImpl<const SCEV *> &Ops, 2128 SCEV::NoWrapFlags Flags) { 2129 using namespace std::placeholders; 2130 typedef OverflowingBinaryOperator OBO; 2131 2132 bool CanAnalyze = 2133 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2134 (void)CanAnalyze; 2135 assert(CanAnalyze && "don't call from other places!"); 2136 2137 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2138 SCEV::NoWrapFlags SignOrUnsignWrap = 2139 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2140 2141 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2142 auto IsKnownNonNegative = [&](const SCEV *S) { 2143 return SE->isKnownNonNegative(S); 2144 }; 2145 2146 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2147 Flags = 2148 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2149 2150 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2151 2152 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2153 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2154 2155 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2156 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2157 2158 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2159 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2160 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2161 Instruction::Add, C, OBO::NoSignedWrap); 2162 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2163 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2164 } 2165 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2166 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2167 Instruction::Add, C, OBO::NoUnsignedWrap); 2168 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2169 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2170 } 2171 } 2172 2173 return Flags; 2174 } 2175 2176 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2177 if (!isLoopInvariant(S, L)) 2178 return false; 2179 // If a value depends on a SCEVUnknown which is defined after the loop, we 2180 // conservatively assume that we cannot calculate it at the loop's entry. 2181 struct FindDominatedSCEVUnknown { 2182 bool Found = false; 2183 const Loop *L; 2184 DominatorTree &DT; 2185 LoopInfo &LI; 2186 2187 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI) 2188 : L(L), DT(DT), LI(LI) {} 2189 2190 bool checkSCEVUnknown(const SCEVUnknown *SU) { 2191 if (auto *I = dyn_cast<Instruction>(SU->getValue())) { 2192 if (DT.dominates(L->getHeader(), I->getParent())) 2193 Found = true; 2194 else 2195 assert(DT.dominates(I->getParent(), L->getHeader()) && 2196 "No dominance relationship between SCEV and loop?"); 2197 } 2198 return false; 2199 } 2200 2201 bool follow(const SCEV *S) { 2202 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 2203 case scConstant: 2204 return false; 2205 case scAddRecExpr: 2206 case scTruncate: 2207 case scZeroExtend: 2208 case scSignExtend: 2209 case scAddExpr: 2210 case scMulExpr: 2211 case scUMaxExpr: 2212 case scSMaxExpr: 2213 case scUDivExpr: 2214 return true; 2215 case scUnknown: 2216 return checkSCEVUnknown(cast<SCEVUnknown>(S)); 2217 case scCouldNotCompute: 2218 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 2219 } 2220 return false; 2221 } 2222 2223 bool isDone() { return Found; } 2224 }; 2225 2226 FindDominatedSCEVUnknown FSU(L, DT, LI); 2227 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU); 2228 ST.visitAll(S); 2229 return !FSU.Found; 2230 } 2231 2232 /// Get a canonical add expression, or something simpler if possible. 2233 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2234 SCEV::NoWrapFlags Flags, 2235 unsigned Depth) { 2236 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2237 "only nuw or nsw allowed"); 2238 assert(!Ops.empty() && "Cannot get empty add!"); 2239 if (Ops.size() == 1) return Ops[0]; 2240 #ifndef NDEBUG 2241 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2242 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2243 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2244 "SCEVAddExpr operand types don't match!"); 2245 #endif 2246 2247 // Sort by complexity, this groups all similar expression types together. 2248 GroupByComplexity(Ops, &LI, DT); 2249 2250 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2251 2252 // If there are any constants, fold them together. 2253 unsigned Idx = 0; 2254 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2255 ++Idx; 2256 assert(Idx < Ops.size()); 2257 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2258 // We found two constants, fold them together! 2259 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2260 if (Ops.size() == 2) return Ops[0]; 2261 Ops.erase(Ops.begin()+1); // Erase the folded element 2262 LHSC = cast<SCEVConstant>(Ops[0]); 2263 } 2264 2265 // If we are left with a constant zero being added, strip it off. 2266 if (LHSC->getValue()->isZero()) { 2267 Ops.erase(Ops.begin()); 2268 --Idx; 2269 } 2270 2271 if (Ops.size() == 1) return Ops[0]; 2272 } 2273 2274 // Limit recursion calls depth. 2275 if (Depth > MaxArithDepth) 2276 return getOrCreateAddExpr(Ops, Flags); 2277 2278 // Okay, check to see if the same value occurs in the operand list more than 2279 // once. If so, merge them together into an multiply expression. Since we 2280 // sorted the list, these values are required to be adjacent. 2281 Type *Ty = Ops[0]->getType(); 2282 bool FoundMatch = false; 2283 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2284 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2285 // Scan ahead to count how many equal operands there are. 2286 unsigned Count = 2; 2287 while (i+Count != e && Ops[i+Count] == Ops[i]) 2288 ++Count; 2289 // Merge the values into a multiply. 2290 const SCEV *Scale = getConstant(Ty, Count); 2291 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2292 if (Ops.size() == Count) 2293 return Mul; 2294 Ops[i] = Mul; 2295 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2296 --i; e -= Count - 1; 2297 FoundMatch = true; 2298 } 2299 if (FoundMatch) 2300 return getAddExpr(Ops, Flags); 2301 2302 // Check for truncates. If all the operands are truncated from the same 2303 // type, see if factoring out the truncate would permit the result to be 2304 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2305 // if the contents of the resulting outer trunc fold to something simple. 2306 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2307 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2308 Type *DstType = Trunc->getType(); 2309 Type *SrcType = Trunc->getOperand()->getType(); 2310 SmallVector<const SCEV *, 8> LargeOps; 2311 bool Ok = true; 2312 // Check all the operands to see if they can be represented in the 2313 // source type of the truncate. 2314 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2315 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2316 if (T->getOperand()->getType() != SrcType) { 2317 Ok = false; 2318 break; 2319 } 2320 LargeOps.push_back(T->getOperand()); 2321 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2322 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2323 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2324 SmallVector<const SCEV *, 8> LargeMulOps; 2325 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2326 if (const SCEVTruncateExpr *T = 2327 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2328 if (T->getOperand()->getType() != SrcType) { 2329 Ok = false; 2330 break; 2331 } 2332 LargeMulOps.push_back(T->getOperand()); 2333 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2334 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2335 } else { 2336 Ok = false; 2337 break; 2338 } 2339 } 2340 if (Ok) 2341 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2342 } else { 2343 Ok = false; 2344 break; 2345 } 2346 } 2347 if (Ok) { 2348 // Evaluate the expression in the larger type. 2349 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2350 // If it folds to something simple, use it. Otherwise, don't. 2351 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2352 return getTruncateExpr(Fold, DstType); 2353 } 2354 } 2355 2356 // Skip past any other cast SCEVs. 2357 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2358 ++Idx; 2359 2360 // If there are add operands they would be next. 2361 if (Idx < Ops.size()) { 2362 bool DeletedAdd = false; 2363 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2364 if (Ops.size() > AddOpsInlineThreshold || 2365 Add->getNumOperands() > AddOpsInlineThreshold) 2366 break; 2367 // If we have an add, expand the add operands onto the end of the operands 2368 // list. 2369 Ops.erase(Ops.begin()+Idx); 2370 Ops.append(Add->op_begin(), Add->op_end()); 2371 DeletedAdd = true; 2372 } 2373 2374 // If we deleted at least one add, we added operands to the end of the list, 2375 // and they are not necessarily sorted. Recurse to resort and resimplify 2376 // any operands we just acquired. 2377 if (DeletedAdd) 2378 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2379 } 2380 2381 // Skip over the add expression until we get to a multiply. 2382 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2383 ++Idx; 2384 2385 // Check to see if there are any folding opportunities present with 2386 // operands multiplied by constant values. 2387 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2388 uint64_t BitWidth = getTypeSizeInBits(Ty); 2389 DenseMap<const SCEV *, APInt> M; 2390 SmallVector<const SCEV *, 8> NewOps; 2391 APInt AccumulatedConstant(BitWidth, 0); 2392 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2393 Ops.data(), Ops.size(), 2394 APInt(BitWidth, 1), *this)) { 2395 struct APIntCompare { 2396 bool operator()(const APInt &LHS, const APInt &RHS) const { 2397 return LHS.ult(RHS); 2398 } 2399 }; 2400 2401 // Some interesting folding opportunity is present, so its worthwhile to 2402 // re-generate the operands list. Group the operands by constant scale, 2403 // to avoid multiplying by the same constant scale multiple times. 2404 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2405 for (const SCEV *NewOp : NewOps) 2406 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2407 // Re-generate the operands list. 2408 Ops.clear(); 2409 if (AccumulatedConstant != 0) 2410 Ops.push_back(getConstant(AccumulatedConstant)); 2411 for (auto &MulOp : MulOpLists) 2412 if (MulOp.first != 0) 2413 Ops.push_back(getMulExpr( 2414 getConstant(MulOp.first), 2415 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2416 SCEV::FlagAnyWrap, Depth + 1)); 2417 if (Ops.empty()) 2418 return getZero(Ty); 2419 if (Ops.size() == 1) 2420 return Ops[0]; 2421 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2422 } 2423 } 2424 2425 // If we are adding something to a multiply expression, make sure the 2426 // something is not already an operand of the multiply. If so, merge it into 2427 // the multiply. 2428 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2429 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2430 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2431 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2432 if (isa<SCEVConstant>(MulOpSCEV)) 2433 continue; 2434 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2435 if (MulOpSCEV == Ops[AddOp]) { 2436 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2437 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2438 if (Mul->getNumOperands() != 2) { 2439 // If the multiply has more than two operands, we must get the 2440 // Y*Z term. 2441 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2442 Mul->op_begin()+MulOp); 2443 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2444 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2445 } 2446 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2447 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2448 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2449 SCEV::FlagAnyWrap, Depth + 1); 2450 if (Ops.size() == 2) return OuterMul; 2451 if (AddOp < Idx) { 2452 Ops.erase(Ops.begin()+AddOp); 2453 Ops.erase(Ops.begin()+Idx-1); 2454 } else { 2455 Ops.erase(Ops.begin()+Idx); 2456 Ops.erase(Ops.begin()+AddOp-1); 2457 } 2458 Ops.push_back(OuterMul); 2459 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2460 } 2461 2462 // Check this multiply against other multiplies being added together. 2463 for (unsigned OtherMulIdx = Idx+1; 2464 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2465 ++OtherMulIdx) { 2466 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2467 // If MulOp occurs in OtherMul, we can fold the two multiplies 2468 // together. 2469 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2470 OMulOp != e; ++OMulOp) 2471 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2472 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2473 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2474 if (Mul->getNumOperands() != 2) { 2475 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2476 Mul->op_begin()+MulOp); 2477 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2478 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2479 } 2480 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2481 if (OtherMul->getNumOperands() != 2) { 2482 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2483 OtherMul->op_begin()+OMulOp); 2484 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2485 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2486 } 2487 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2488 const SCEV *InnerMulSum = 2489 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2490 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2491 SCEV::FlagAnyWrap, Depth + 1); 2492 if (Ops.size() == 2) return OuterMul; 2493 Ops.erase(Ops.begin()+Idx); 2494 Ops.erase(Ops.begin()+OtherMulIdx-1); 2495 Ops.push_back(OuterMul); 2496 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2497 } 2498 } 2499 } 2500 } 2501 2502 // If there are any add recurrences in the operands list, see if any other 2503 // added values are loop invariant. If so, we can fold them into the 2504 // recurrence. 2505 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2506 ++Idx; 2507 2508 // Scan over all recurrences, trying to fold loop invariants into them. 2509 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2510 // Scan all of the other operands to this add and add them to the vector if 2511 // they are loop invariant w.r.t. the recurrence. 2512 SmallVector<const SCEV *, 8> LIOps; 2513 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2514 const Loop *AddRecLoop = AddRec->getLoop(); 2515 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2516 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2517 LIOps.push_back(Ops[i]); 2518 Ops.erase(Ops.begin()+i); 2519 --i; --e; 2520 } 2521 2522 // If we found some loop invariants, fold them into the recurrence. 2523 if (!LIOps.empty()) { 2524 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2525 LIOps.push_back(AddRec->getStart()); 2526 2527 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2528 AddRec->op_end()); 2529 // This follows from the fact that the no-wrap flags on the outer add 2530 // expression are applicable on the 0th iteration, when the add recurrence 2531 // will be equal to its start value. 2532 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2533 2534 // Build the new addrec. Propagate the NUW and NSW flags if both the 2535 // outer add and the inner addrec are guaranteed to have no overflow. 2536 // Always propagate NW. 2537 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2538 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2539 2540 // If all of the other operands were loop invariant, we are done. 2541 if (Ops.size() == 1) return NewRec; 2542 2543 // Otherwise, add the folded AddRec by the non-invariant parts. 2544 for (unsigned i = 0;; ++i) 2545 if (Ops[i] == AddRec) { 2546 Ops[i] = NewRec; 2547 break; 2548 } 2549 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2550 } 2551 2552 // Okay, if there weren't any loop invariants to be folded, check to see if 2553 // there are multiple AddRec's with the same loop induction variable being 2554 // added together. If so, we can fold them. 2555 for (unsigned OtherIdx = Idx+1; 2556 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2557 ++OtherIdx) { 2558 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2559 // so that the 1st found AddRecExpr is dominated by all others. 2560 assert(DT.dominates( 2561 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2562 AddRec->getLoop()->getHeader()) && 2563 "AddRecExprs are not sorted in reverse dominance order?"); 2564 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2565 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2566 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2567 AddRec->op_end()); 2568 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2569 ++OtherIdx) { 2570 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2571 if (OtherAddRec->getLoop() == AddRecLoop) { 2572 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2573 i != e; ++i) { 2574 if (i >= AddRecOps.size()) { 2575 AddRecOps.append(OtherAddRec->op_begin()+i, 2576 OtherAddRec->op_end()); 2577 break; 2578 } 2579 SmallVector<const SCEV *, 2> TwoOps = { 2580 AddRecOps[i], OtherAddRec->getOperand(i)}; 2581 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2582 } 2583 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2584 } 2585 } 2586 // Step size has changed, so we cannot guarantee no self-wraparound. 2587 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2588 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2589 } 2590 } 2591 2592 // Otherwise couldn't fold anything into this recurrence. Move onto the 2593 // next one. 2594 } 2595 2596 // Okay, it looks like we really DO need an add expr. Check to see if we 2597 // already have one, otherwise create a new one. 2598 return getOrCreateAddExpr(Ops, Flags); 2599 } 2600 2601 const SCEV * 2602 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2603 SCEV::NoWrapFlags Flags) { 2604 FoldingSetNodeID ID; 2605 ID.AddInteger(scAddExpr); 2606 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2607 ID.AddPointer(Ops[i]); 2608 void *IP = nullptr; 2609 SCEVAddExpr *S = 2610 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2611 if (!S) { 2612 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2613 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2614 S = new (SCEVAllocator) 2615 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2616 UniqueSCEVs.InsertNode(S, IP); 2617 } 2618 S->setNoWrapFlags(Flags); 2619 return S; 2620 } 2621 2622 const SCEV * 2623 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2624 SCEV::NoWrapFlags Flags) { 2625 FoldingSetNodeID ID; 2626 ID.AddInteger(scMulExpr); 2627 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2628 ID.AddPointer(Ops[i]); 2629 void *IP = nullptr; 2630 SCEVMulExpr *S = 2631 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2632 if (!S) { 2633 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2634 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2635 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2636 O, Ops.size()); 2637 UniqueSCEVs.InsertNode(S, IP); 2638 } 2639 S->setNoWrapFlags(Flags); 2640 return S; 2641 } 2642 2643 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2644 uint64_t k = i*j; 2645 if (j > 1 && k / j != i) Overflow = true; 2646 return k; 2647 } 2648 2649 /// Compute the result of "n choose k", the binomial coefficient. If an 2650 /// intermediate computation overflows, Overflow will be set and the return will 2651 /// be garbage. Overflow is not cleared on absence of overflow. 2652 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2653 // We use the multiplicative formula: 2654 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2655 // At each iteration, we take the n-th term of the numeral and divide by the 2656 // (k-n)th term of the denominator. This division will always produce an 2657 // integral result, and helps reduce the chance of overflow in the 2658 // intermediate computations. However, we can still overflow even when the 2659 // final result would fit. 2660 2661 if (n == 0 || n == k) return 1; 2662 if (k > n) return 0; 2663 2664 if (k > n/2) 2665 k = n-k; 2666 2667 uint64_t r = 1; 2668 for (uint64_t i = 1; i <= k; ++i) { 2669 r = umul_ov(r, n-(i-1), Overflow); 2670 r /= i; 2671 } 2672 return r; 2673 } 2674 2675 /// Determine if any of the operands in this SCEV are a constant or if 2676 /// any of the add or multiply expressions in this SCEV contain a constant. 2677 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2678 SmallVector<const SCEV *, 4> Ops; 2679 Ops.push_back(StartExpr); 2680 while (!Ops.empty()) { 2681 const SCEV *CurrentExpr = Ops.pop_back_val(); 2682 if (isa<SCEVConstant>(*CurrentExpr)) 2683 return true; 2684 2685 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2686 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2687 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2688 } 2689 } 2690 return false; 2691 } 2692 2693 /// Get a canonical multiply expression, or something simpler if possible. 2694 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2695 SCEV::NoWrapFlags Flags, 2696 unsigned Depth) { 2697 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2698 "only nuw or nsw allowed"); 2699 assert(!Ops.empty() && "Cannot get empty mul!"); 2700 if (Ops.size() == 1) return Ops[0]; 2701 #ifndef NDEBUG 2702 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2703 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2704 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2705 "SCEVMulExpr operand types don't match!"); 2706 #endif 2707 2708 // Sort by complexity, this groups all similar expression types together. 2709 GroupByComplexity(Ops, &LI, DT); 2710 2711 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2712 2713 // Limit recursion calls depth. 2714 if (Depth > MaxArithDepth) 2715 return getOrCreateMulExpr(Ops, Flags); 2716 2717 // If there are any constants, fold them together. 2718 unsigned Idx = 0; 2719 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2720 2721 // C1*(C2+V) -> C1*C2 + C1*V 2722 if (Ops.size() == 2) 2723 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2724 // If any of Add's ops are Adds or Muls with a constant, 2725 // apply this transformation as well. 2726 if (Add->getNumOperands() == 2) 2727 if (containsConstantSomewhere(Add)) 2728 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2729 SCEV::FlagAnyWrap, Depth + 1), 2730 getMulExpr(LHSC, Add->getOperand(1), 2731 SCEV::FlagAnyWrap, Depth + 1), 2732 SCEV::FlagAnyWrap, Depth + 1); 2733 2734 ++Idx; 2735 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2736 // We found two constants, fold them together! 2737 ConstantInt *Fold = 2738 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2739 Ops[0] = getConstant(Fold); 2740 Ops.erase(Ops.begin()+1); // Erase the folded element 2741 if (Ops.size() == 1) return Ops[0]; 2742 LHSC = cast<SCEVConstant>(Ops[0]); 2743 } 2744 2745 // If we are left with a constant one being multiplied, strip it off. 2746 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2747 Ops.erase(Ops.begin()); 2748 --Idx; 2749 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2750 // If we have a multiply of zero, it will always be zero. 2751 return Ops[0]; 2752 } else if (Ops[0]->isAllOnesValue()) { 2753 // If we have a mul by -1 of an add, try distributing the -1 among the 2754 // add operands. 2755 if (Ops.size() == 2) { 2756 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2757 SmallVector<const SCEV *, 4> NewOps; 2758 bool AnyFolded = false; 2759 for (const SCEV *AddOp : Add->operands()) { 2760 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2761 Depth + 1); 2762 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2763 NewOps.push_back(Mul); 2764 } 2765 if (AnyFolded) 2766 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2767 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2768 // Negation preserves a recurrence's no self-wrap property. 2769 SmallVector<const SCEV *, 4> Operands; 2770 for (const SCEV *AddRecOp : AddRec->operands()) 2771 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2772 Depth + 1)); 2773 2774 return getAddRecExpr(Operands, AddRec->getLoop(), 2775 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2776 } 2777 } 2778 } 2779 2780 if (Ops.size() == 1) 2781 return Ops[0]; 2782 } 2783 2784 // Skip over the add expression until we get to a multiply. 2785 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2786 ++Idx; 2787 2788 // If there are mul operands inline them all into this expression. 2789 if (Idx < Ops.size()) { 2790 bool DeletedMul = false; 2791 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2792 if (Ops.size() > MulOpsInlineThreshold) 2793 break; 2794 // If we have an mul, expand the mul operands onto the end of the 2795 // operands list. 2796 Ops.erase(Ops.begin()+Idx); 2797 Ops.append(Mul->op_begin(), Mul->op_end()); 2798 DeletedMul = true; 2799 } 2800 2801 // If we deleted at least one mul, we added operands to the end of the 2802 // list, and they are not necessarily sorted. Recurse to resort and 2803 // resimplify any operands we just acquired. 2804 if (DeletedMul) 2805 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2806 } 2807 2808 // If there are any add recurrences in the operands list, see if any other 2809 // added values are loop invariant. If so, we can fold them into the 2810 // recurrence. 2811 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2812 ++Idx; 2813 2814 // Scan over all recurrences, trying to fold loop invariants into them. 2815 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2816 // Scan all of the other operands to this mul and add them to the vector 2817 // if they are loop invariant w.r.t. the recurrence. 2818 SmallVector<const SCEV *, 8> LIOps; 2819 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2820 const Loop *AddRecLoop = AddRec->getLoop(); 2821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2822 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2823 LIOps.push_back(Ops[i]); 2824 Ops.erase(Ops.begin()+i); 2825 --i; --e; 2826 } 2827 2828 // If we found some loop invariants, fold them into the recurrence. 2829 if (!LIOps.empty()) { 2830 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2831 SmallVector<const SCEV *, 4> NewOps; 2832 NewOps.reserve(AddRec->getNumOperands()); 2833 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2834 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2835 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2836 SCEV::FlagAnyWrap, Depth + 1)); 2837 2838 // Build the new addrec. Propagate the NUW and NSW flags if both the 2839 // outer mul and the inner addrec are guaranteed to have no overflow. 2840 // 2841 // No self-wrap cannot be guaranteed after changing the step size, but 2842 // will be inferred if either NUW or NSW is true. 2843 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2844 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2845 2846 // If all of the other operands were loop invariant, we are done. 2847 if (Ops.size() == 1) return NewRec; 2848 2849 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2850 for (unsigned i = 0;; ++i) 2851 if (Ops[i] == AddRec) { 2852 Ops[i] = NewRec; 2853 break; 2854 } 2855 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2856 } 2857 2858 // Okay, if there weren't any loop invariants to be folded, check to see 2859 // if there are multiple AddRec's with the same loop induction variable 2860 // being multiplied together. If so, we can fold them. 2861 2862 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2863 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2864 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2865 // ]]],+,...up to x=2n}. 2866 // Note that the arguments to choose() are always integers with values 2867 // known at compile time, never SCEV objects. 2868 // 2869 // The implementation avoids pointless extra computations when the two 2870 // addrec's are of different length (mathematically, it's equivalent to 2871 // an infinite stream of zeros on the right). 2872 bool OpsModified = false; 2873 for (unsigned OtherIdx = Idx+1; 2874 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2875 ++OtherIdx) { 2876 const SCEVAddRecExpr *OtherAddRec = 2877 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2878 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2879 continue; 2880 2881 bool Overflow = false; 2882 Type *Ty = AddRec->getType(); 2883 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2884 SmallVector<const SCEV*, 7> AddRecOps; 2885 for (int x = 0, xe = AddRec->getNumOperands() + 2886 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2887 const SCEV *Term = getZero(Ty); 2888 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2889 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2890 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2891 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2892 z < ze && !Overflow; ++z) { 2893 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2894 uint64_t Coeff; 2895 if (LargerThan64Bits) 2896 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2897 else 2898 Coeff = Coeff1*Coeff2; 2899 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2900 const SCEV *Term1 = AddRec->getOperand(y-z); 2901 const SCEV *Term2 = OtherAddRec->getOperand(z); 2902 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2903 SCEV::FlagAnyWrap, Depth + 1), 2904 SCEV::FlagAnyWrap, Depth + 1); 2905 } 2906 } 2907 AddRecOps.push_back(Term); 2908 } 2909 if (!Overflow) { 2910 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2911 SCEV::FlagAnyWrap); 2912 if (Ops.size() == 2) return NewAddRec; 2913 Ops[Idx] = NewAddRec; 2914 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2915 OpsModified = true; 2916 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2917 if (!AddRec) 2918 break; 2919 } 2920 } 2921 if (OpsModified) 2922 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2923 2924 // Otherwise couldn't fold anything into this recurrence. Move onto the 2925 // next one. 2926 } 2927 2928 // Okay, it looks like we really DO need an mul expr. Check to see if we 2929 // already have one, otherwise create a new one. 2930 return getOrCreateMulExpr(Ops, Flags); 2931 } 2932 2933 /// Get a canonical unsigned division expression, or something simpler if 2934 /// possible. 2935 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2936 const SCEV *RHS) { 2937 assert(getEffectiveSCEVType(LHS->getType()) == 2938 getEffectiveSCEVType(RHS->getType()) && 2939 "SCEVUDivExpr operand types don't match!"); 2940 2941 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2942 if (RHSC->getValue()->isOne()) 2943 return LHS; // X udiv 1 --> x 2944 // If the denominator is zero, the result of the udiv is undefined. Don't 2945 // try to analyze it, because the resolution chosen here may differ from 2946 // the resolution chosen in other parts of the compiler. 2947 if (!RHSC->getValue()->isZero()) { 2948 // Determine if the division can be folded into the operands of 2949 // its operands. 2950 // TODO: Generalize this to non-constants by using known-bits information. 2951 Type *Ty = LHS->getType(); 2952 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2953 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2954 // For non-power-of-two values, effectively round the value up to the 2955 // nearest power of two. 2956 if (!RHSC->getAPInt().isPowerOf2()) 2957 ++MaxShiftAmt; 2958 IntegerType *ExtTy = 2959 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2960 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2961 if (const SCEVConstant *Step = 2962 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2963 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2964 const APInt &StepInt = Step->getAPInt(); 2965 const APInt &DivInt = RHSC->getAPInt(); 2966 if (!StepInt.urem(DivInt) && 2967 getZeroExtendExpr(AR, ExtTy) == 2968 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2969 getZeroExtendExpr(Step, ExtTy), 2970 AR->getLoop(), SCEV::FlagAnyWrap)) { 2971 SmallVector<const SCEV *, 4> Operands; 2972 for (const SCEV *Op : AR->operands()) 2973 Operands.push_back(getUDivExpr(Op, RHS)); 2974 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2975 } 2976 /// Get a canonical UDivExpr for a recurrence. 2977 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2978 // We can currently only fold X%N if X is constant. 2979 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2980 if (StartC && !DivInt.urem(StepInt) && 2981 getZeroExtendExpr(AR, ExtTy) == 2982 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2983 getZeroExtendExpr(Step, ExtTy), 2984 AR->getLoop(), SCEV::FlagAnyWrap)) { 2985 const APInt &StartInt = StartC->getAPInt(); 2986 const APInt &StartRem = StartInt.urem(StepInt); 2987 if (StartRem != 0) 2988 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2989 AR->getLoop(), SCEV::FlagNW); 2990 } 2991 } 2992 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2993 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2994 SmallVector<const SCEV *, 4> Operands; 2995 for (const SCEV *Op : M->operands()) 2996 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2997 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2998 // Find an operand that's safely divisible. 2999 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3000 const SCEV *Op = M->getOperand(i); 3001 const SCEV *Div = getUDivExpr(Op, RHSC); 3002 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3003 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3004 M->op_end()); 3005 Operands[i] = Div; 3006 return getMulExpr(Operands); 3007 } 3008 } 3009 } 3010 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3011 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3012 SmallVector<const SCEV *, 4> Operands; 3013 for (const SCEV *Op : A->operands()) 3014 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3015 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3016 Operands.clear(); 3017 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3018 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3019 if (isa<SCEVUDivExpr>(Op) || 3020 getMulExpr(Op, RHS) != A->getOperand(i)) 3021 break; 3022 Operands.push_back(Op); 3023 } 3024 if (Operands.size() == A->getNumOperands()) 3025 return getAddExpr(Operands); 3026 } 3027 } 3028 3029 // Fold if both operands are constant. 3030 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3031 Constant *LHSCV = LHSC->getValue(); 3032 Constant *RHSCV = RHSC->getValue(); 3033 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3034 RHSCV))); 3035 } 3036 } 3037 } 3038 3039 FoldingSetNodeID ID; 3040 ID.AddInteger(scUDivExpr); 3041 ID.AddPointer(LHS); 3042 ID.AddPointer(RHS); 3043 void *IP = nullptr; 3044 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3045 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3046 LHS, RHS); 3047 UniqueSCEVs.InsertNode(S, IP); 3048 return S; 3049 } 3050 3051 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3052 APInt A = C1->getAPInt().abs(); 3053 APInt B = C2->getAPInt().abs(); 3054 uint32_t ABW = A.getBitWidth(); 3055 uint32_t BBW = B.getBitWidth(); 3056 3057 if (ABW > BBW) 3058 B = B.zext(ABW); 3059 else if (ABW < BBW) 3060 A = A.zext(BBW); 3061 3062 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3063 } 3064 3065 /// Get a canonical unsigned division expression, or something simpler if 3066 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3067 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3068 /// it's not exact because the udiv may be clearing bits. 3069 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3070 const SCEV *RHS) { 3071 // TODO: we could try to find factors in all sorts of things, but for now we 3072 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3073 // end of this file for inspiration. 3074 3075 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3076 if (!Mul || !Mul->hasNoUnsignedWrap()) 3077 return getUDivExpr(LHS, RHS); 3078 3079 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3080 // If the mulexpr multiplies by a constant, then that constant must be the 3081 // first element of the mulexpr. 3082 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3083 if (LHSCst == RHSCst) { 3084 SmallVector<const SCEV *, 2> Operands; 3085 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3086 return getMulExpr(Operands); 3087 } 3088 3089 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3090 // that there's a factor provided by one of the other terms. We need to 3091 // check. 3092 APInt Factor = gcd(LHSCst, RHSCst); 3093 if (!Factor.isIntN(1)) { 3094 LHSCst = 3095 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3096 RHSCst = 3097 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3098 SmallVector<const SCEV *, 2> Operands; 3099 Operands.push_back(LHSCst); 3100 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3101 LHS = getMulExpr(Operands); 3102 RHS = RHSCst; 3103 Mul = dyn_cast<SCEVMulExpr>(LHS); 3104 if (!Mul) 3105 return getUDivExactExpr(LHS, RHS); 3106 } 3107 } 3108 } 3109 3110 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3111 if (Mul->getOperand(i) == RHS) { 3112 SmallVector<const SCEV *, 2> Operands; 3113 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3114 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3115 return getMulExpr(Operands); 3116 } 3117 } 3118 3119 return getUDivExpr(LHS, RHS); 3120 } 3121 3122 /// Get an add recurrence expression for the specified loop. Simplify the 3123 /// expression as much as possible. 3124 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3125 const Loop *L, 3126 SCEV::NoWrapFlags Flags) { 3127 SmallVector<const SCEV *, 4> Operands; 3128 Operands.push_back(Start); 3129 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3130 if (StepChrec->getLoop() == L) { 3131 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3132 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3133 } 3134 3135 Operands.push_back(Step); 3136 return getAddRecExpr(Operands, L, Flags); 3137 } 3138 3139 /// Get an add recurrence expression for the specified loop. Simplify the 3140 /// expression as much as possible. 3141 const SCEV * 3142 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3143 const Loop *L, SCEV::NoWrapFlags Flags) { 3144 if (Operands.size() == 1) return Operands[0]; 3145 #ifndef NDEBUG 3146 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3147 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3148 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3149 "SCEVAddRecExpr operand types don't match!"); 3150 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3151 assert(isLoopInvariant(Operands[i], L) && 3152 "SCEVAddRecExpr operand is not loop-invariant!"); 3153 #endif 3154 3155 if (Operands.back()->isZero()) { 3156 Operands.pop_back(); 3157 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3158 } 3159 3160 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3161 // use that information to infer NUW and NSW flags. However, computing a 3162 // BE count requires calling getAddRecExpr, so we may not yet have a 3163 // meaningful BE count at this point (and if we don't, we'd be stuck 3164 // with a SCEVCouldNotCompute as the cached BE count). 3165 3166 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3167 3168 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3169 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3170 const Loop *NestedLoop = NestedAR->getLoop(); 3171 if (L->contains(NestedLoop) 3172 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3173 : (!NestedLoop->contains(L) && 3174 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3175 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3176 NestedAR->op_end()); 3177 Operands[0] = NestedAR->getStart(); 3178 // AddRecs require their operands be loop-invariant with respect to their 3179 // loops. Don't perform this transformation if it would break this 3180 // requirement. 3181 bool AllInvariant = all_of( 3182 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3183 3184 if (AllInvariant) { 3185 // Create a recurrence for the outer loop with the same step size. 3186 // 3187 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3188 // inner recurrence has the same property. 3189 SCEV::NoWrapFlags OuterFlags = 3190 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3191 3192 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3193 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3194 return isLoopInvariant(Op, NestedLoop); 3195 }); 3196 3197 if (AllInvariant) { 3198 // Ok, both add recurrences are valid after the transformation. 3199 // 3200 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3201 // the outer recurrence has the same property. 3202 SCEV::NoWrapFlags InnerFlags = 3203 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3204 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3205 } 3206 } 3207 // Reset Operands to its original state. 3208 Operands[0] = NestedAR; 3209 } 3210 } 3211 3212 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3213 // already have one, otherwise create a new one. 3214 FoldingSetNodeID ID; 3215 ID.AddInteger(scAddRecExpr); 3216 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3217 ID.AddPointer(Operands[i]); 3218 ID.AddPointer(L); 3219 void *IP = nullptr; 3220 SCEVAddRecExpr *S = 3221 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3222 if (!S) { 3223 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3224 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3225 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3226 O, Operands.size(), L); 3227 UniqueSCEVs.InsertNode(S, IP); 3228 } 3229 S->setNoWrapFlags(Flags); 3230 return S; 3231 } 3232 3233 const SCEV * 3234 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3235 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3236 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3237 // getSCEV(Base)->getType() has the same address space as Base->getType() 3238 // because SCEV::getType() preserves the address space. 3239 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3240 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3241 // instruction to its SCEV, because the Instruction may be guarded by control 3242 // flow and the no-overflow bits may not be valid for the expression in any 3243 // context. This can be fixed similarly to how these flags are handled for 3244 // adds. 3245 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3246 : SCEV::FlagAnyWrap; 3247 3248 const SCEV *TotalOffset = getZero(IntPtrTy); 3249 // The array size is unimportant. The first thing we do on CurTy is getting 3250 // its element type. 3251 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3252 for (const SCEV *IndexExpr : IndexExprs) { 3253 // Compute the (potentially symbolic) offset in bytes for this index. 3254 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3255 // For a struct, add the member offset. 3256 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3257 unsigned FieldNo = Index->getZExtValue(); 3258 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3259 3260 // Add the field offset to the running total offset. 3261 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3262 3263 // Update CurTy to the type of the field at Index. 3264 CurTy = STy->getTypeAtIndex(Index); 3265 } else { 3266 // Update CurTy to its element type. 3267 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3268 // For an array, add the element offset, explicitly scaled. 3269 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3270 // Getelementptr indices are signed. 3271 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3272 3273 // Multiply the index by the element size to compute the element offset. 3274 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3275 3276 // Add the element offset to the running total offset. 3277 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3278 } 3279 } 3280 3281 // Add the total offset from all the GEP indices to the base. 3282 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3283 } 3284 3285 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3286 const SCEV *RHS) { 3287 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3288 return getSMaxExpr(Ops); 3289 } 3290 3291 const SCEV * 3292 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3293 assert(!Ops.empty() && "Cannot get empty smax!"); 3294 if (Ops.size() == 1) return Ops[0]; 3295 #ifndef NDEBUG 3296 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3297 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3298 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3299 "SCEVSMaxExpr operand types don't match!"); 3300 #endif 3301 3302 // Sort by complexity, this groups all similar expression types together. 3303 GroupByComplexity(Ops, &LI, DT); 3304 3305 // If there are any constants, fold them together. 3306 unsigned Idx = 0; 3307 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3308 ++Idx; 3309 assert(Idx < Ops.size()); 3310 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3311 // We found two constants, fold them together! 3312 ConstantInt *Fold = ConstantInt::get( 3313 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3314 Ops[0] = getConstant(Fold); 3315 Ops.erase(Ops.begin()+1); // Erase the folded element 3316 if (Ops.size() == 1) return Ops[0]; 3317 LHSC = cast<SCEVConstant>(Ops[0]); 3318 } 3319 3320 // If we are left with a constant minimum-int, strip it off. 3321 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3322 Ops.erase(Ops.begin()); 3323 --Idx; 3324 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3325 // If we have an smax with a constant maximum-int, it will always be 3326 // maximum-int. 3327 return Ops[0]; 3328 } 3329 3330 if (Ops.size() == 1) return Ops[0]; 3331 } 3332 3333 // Find the first SMax 3334 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3335 ++Idx; 3336 3337 // Check to see if one of the operands is an SMax. If so, expand its operands 3338 // onto our operand list, and recurse to simplify. 3339 if (Idx < Ops.size()) { 3340 bool DeletedSMax = false; 3341 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3342 Ops.erase(Ops.begin()+Idx); 3343 Ops.append(SMax->op_begin(), SMax->op_end()); 3344 DeletedSMax = true; 3345 } 3346 3347 if (DeletedSMax) 3348 return getSMaxExpr(Ops); 3349 } 3350 3351 // Okay, check to see if the same value occurs in the operand list twice. If 3352 // so, delete one. Since we sorted the list, these values are required to 3353 // be adjacent. 3354 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3355 // X smax Y smax Y --> X smax Y 3356 // X smax Y --> X, if X is always greater than Y 3357 if (Ops[i] == Ops[i+1] || 3358 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3359 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3360 --i; --e; 3361 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3362 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3363 --i; --e; 3364 } 3365 3366 if (Ops.size() == 1) return Ops[0]; 3367 3368 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3369 3370 // Okay, it looks like we really DO need an smax expr. Check to see if we 3371 // already have one, otherwise create a new one. 3372 FoldingSetNodeID ID; 3373 ID.AddInteger(scSMaxExpr); 3374 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3375 ID.AddPointer(Ops[i]); 3376 void *IP = nullptr; 3377 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3378 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3379 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3380 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3381 O, Ops.size()); 3382 UniqueSCEVs.InsertNode(S, IP); 3383 return S; 3384 } 3385 3386 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3387 const SCEV *RHS) { 3388 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3389 return getUMaxExpr(Ops); 3390 } 3391 3392 const SCEV * 3393 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3394 assert(!Ops.empty() && "Cannot get empty umax!"); 3395 if (Ops.size() == 1) return Ops[0]; 3396 #ifndef NDEBUG 3397 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3398 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3399 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3400 "SCEVUMaxExpr operand types don't match!"); 3401 #endif 3402 3403 // Sort by complexity, this groups all similar expression types together. 3404 GroupByComplexity(Ops, &LI, DT); 3405 3406 // If there are any constants, fold them together. 3407 unsigned Idx = 0; 3408 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3409 ++Idx; 3410 assert(Idx < Ops.size()); 3411 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3412 // We found two constants, fold them together! 3413 ConstantInt *Fold = ConstantInt::get( 3414 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3415 Ops[0] = getConstant(Fold); 3416 Ops.erase(Ops.begin()+1); // Erase the folded element 3417 if (Ops.size() == 1) return Ops[0]; 3418 LHSC = cast<SCEVConstant>(Ops[0]); 3419 } 3420 3421 // If we are left with a constant minimum-int, strip it off. 3422 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3423 Ops.erase(Ops.begin()); 3424 --Idx; 3425 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3426 // If we have an umax with a constant maximum-int, it will always be 3427 // maximum-int. 3428 return Ops[0]; 3429 } 3430 3431 if (Ops.size() == 1) return Ops[0]; 3432 } 3433 3434 // Find the first UMax 3435 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3436 ++Idx; 3437 3438 // Check to see if one of the operands is a UMax. If so, expand its operands 3439 // onto our operand list, and recurse to simplify. 3440 if (Idx < Ops.size()) { 3441 bool DeletedUMax = false; 3442 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3443 Ops.erase(Ops.begin()+Idx); 3444 Ops.append(UMax->op_begin(), UMax->op_end()); 3445 DeletedUMax = true; 3446 } 3447 3448 if (DeletedUMax) 3449 return getUMaxExpr(Ops); 3450 } 3451 3452 // Okay, check to see if the same value occurs in the operand list twice. If 3453 // so, delete one. Since we sorted the list, these values are required to 3454 // be adjacent. 3455 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3456 // X umax Y umax Y --> X umax Y 3457 // X umax Y --> X, if X is always greater than Y 3458 if (Ops[i] == Ops[i+1] || 3459 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3460 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3461 --i; --e; 3462 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3463 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3464 --i; --e; 3465 } 3466 3467 if (Ops.size() == 1) return Ops[0]; 3468 3469 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3470 3471 // Okay, it looks like we really DO need a umax expr. Check to see if we 3472 // already have one, otherwise create a new one. 3473 FoldingSetNodeID ID; 3474 ID.AddInteger(scUMaxExpr); 3475 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3476 ID.AddPointer(Ops[i]); 3477 void *IP = nullptr; 3478 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3479 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3480 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3481 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3482 O, Ops.size()); 3483 UniqueSCEVs.InsertNode(S, IP); 3484 return S; 3485 } 3486 3487 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3488 const SCEV *RHS) { 3489 // ~smax(~x, ~y) == smin(x, y). 3490 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3491 } 3492 3493 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3494 const SCEV *RHS) { 3495 // ~umax(~x, ~y) == umin(x, y) 3496 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3497 } 3498 3499 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3500 // We can bypass creating a target-independent 3501 // constant expression and then folding it back into a ConstantInt. 3502 // This is just a compile-time optimization. 3503 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3504 } 3505 3506 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3507 StructType *STy, 3508 unsigned FieldNo) { 3509 // We can bypass creating a target-independent 3510 // constant expression and then folding it back into a ConstantInt. 3511 // This is just a compile-time optimization. 3512 return getConstant( 3513 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3514 } 3515 3516 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3517 // Don't attempt to do anything other than create a SCEVUnknown object 3518 // here. createSCEV only calls getUnknown after checking for all other 3519 // interesting possibilities, and any other code that calls getUnknown 3520 // is doing so in order to hide a value from SCEV canonicalization. 3521 3522 FoldingSetNodeID ID; 3523 ID.AddInteger(scUnknown); 3524 ID.AddPointer(V); 3525 void *IP = nullptr; 3526 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3527 assert(cast<SCEVUnknown>(S)->getValue() == V && 3528 "Stale SCEVUnknown in uniquing map!"); 3529 return S; 3530 } 3531 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3532 FirstUnknown); 3533 FirstUnknown = cast<SCEVUnknown>(S); 3534 UniqueSCEVs.InsertNode(S, IP); 3535 return S; 3536 } 3537 3538 //===----------------------------------------------------------------------===// 3539 // Basic SCEV Analysis and PHI Idiom Recognition Code 3540 // 3541 3542 /// Test if values of the given type are analyzable within the SCEV 3543 /// framework. This primarily includes integer types, and it can optionally 3544 /// include pointer types if the ScalarEvolution class has access to 3545 /// target-specific information. 3546 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3547 // Integers and pointers are always SCEVable. 3548 return Ty->isIntegerTy() || Ty->isPointerTy(); 3549 } 3550 3551 /// Return the size in bits of the specified type, for which isSCEVable must 3552 /// return true. 3553 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3554 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3555 return getDataLayout().getTypeSizeInBits(Ty); 3556 } 3557 3558 /// Return a type with the same bitwidth as the given type and which represents 3559 /// how SCEV will treat the given type, for which isSCEVable must return 3560 /// true. For pointer types, this is the pointer-sized integer type. 3561 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3562 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3563 3564 if (Ty->isIntegerTy()) 3565 return Ty; 3566 3567 // The only other support type is pointer. 3568 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3569 return getDataLayout().getIntPtrType(Ty); 3570 } 3571 3572 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3573 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3574 } 3575 3576 const SCEV *ScalarEvolution::getCouldNotCompute() { 3577 return CouldNotCompute.get(); 3578 } 3579 3580 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3581 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3582 auto *SU = dyn_cast<SCEVUnknown>(S); 3583 return SU && SU->getValue() == nullptr; 3584 }); 3585 3586 return !ContainsNulls; 3587 } 3588 3589 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3590 HasRecMapType::iterator I = HasRecMap.find(S); 3591 if (I != HasRecMap.end()) 3592 return I->second; 3593 3594 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3595 HasRecMap.insert({S, FoundAddRec}); 3596 return FoundAddRec; 3597 } 3598 3599 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3600 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3601 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3602 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3603 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3604 if (!Add) 3605 return {S, nullptr}; 3606 3607 if (Add->getNumOperands() != 2) 3608 return {S, nullptr}; 3609 3610 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3611 if (!ConstOp) 3612 return {S, nullptr}; 3613 3614 return {Add->getOperand(1), ConstOp->getValue()}; 3615 } 3616 3617 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3618 /// by the value and offset from any ValueOffsetPair in the set. 3619 SetVector<ScalarEvolution::ValueOffsetPair> * 3620 ScalarEvolution::getSCEVValues(const SCEV *S) { 3621 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3622 if (SI == ExprValueMap.end()) 3623 return nullptr; 3624 #ifndef NDEBUG 3625 if (VerifySCEVMap) { 3626 // Check there is no dangling Value in the set returned. 3627 for (const auto &VE : SI->second) 3628 assert(ValueExprMap.count(VE.first)); 3629 } 3630 #endif 3631 return &SI->second; 3632 } 3633 3634 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3635 /// cannot be used separately. eraseValueFromMap should be used to remove 3636 /// V from ValueExprMap and ExprValueMap at the same time. 3637 void ScalarEvolution::eraseValueFromMap(Value *V) { 3638 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3639 if (I != ValueExprMap.end()) { 3640 const SCEV *S = I->second; 3641 // Remove {V, 0} from the set of ExprValueMap[S] 3642 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3643 SV->remove({V, nullptr}); 3644 3645 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3646 const SCEV *Stripped; 3647 ConstantInt *Offset; 3648 std::tie(Stripped, Offset) = splitAddExpr(S); 3649 if (Offset != nullptr) { 3650 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3651 SV->remove({V, Offset}); 3652 } 3653 ValueExprMap.erase(V); 3654 } 3655 } 3656 3657 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3658 /// create a new one. 3659 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3660 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3661 3662 const SCEV *S = getExistingSCEV(V); 3663 if (S == nullptr) { 3664 S = createSCEV(V); 3665 // During PHI resolution, it is possible to create two SCEVs for the same 3666 // V, so it is needed to double check whether V->S is inserted into 3667 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3668 std::pair<ValueExprMapType::iterator, bool> Pair = 3669 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3670 if (Pair.second) { 3671 ExprValueMap[S].insert({V, nullptr}); 3672 3673 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3674 // ExprValueMap. 3675 const SCEV *Stripped = S; 3676 ConstantInt *Offset = nullptr; 3677 std::tie(Stripped, Offset) = splitAddExpr(S); 3678 // If stripped is SCEVUnknown, don't bother to save 3679 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3680 // increase the complexity of the expansion code. 3681 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3682 // because it may generate add/sub instead of GEP in SCEV expansion. 3683 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3684 !isa<GetElementPtrInst>(V)) 3685 ExprValueMap[Stripped].insert({V, Offset}); 3686 } 3687 } 3688 return S; 3689 } 3690 3691 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3692 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3693 3694 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3695 if (I != ValueExprMap.end()) { 3696 const SCEV *S = I->second; 3697 if (checkValidity(S)) 3698 return S; 3699 eraseValueFromMap(V); 3700 forgetMemoizedResults(S); 3701 } 3702 return nullptr; 3703 } 3704 3705 /// Return a SCEV corresponding to -V = -1*V 3706 /// 3707 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3708 SCEV::NoWrapFlags Flags) { 3709 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3710 return getConstant( 3711 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3712 3713 Type *Ty = V->getType(); 3714 Ty = getEffectiveSCEVType(Ty); 3715 return getMulExpr( 3716 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3717 } 3718 3719 /// Return a SCEV corresponding to ~V = -1-V 3720 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3721 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3722 return getConstant( 3723 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3724 3725 Type *Ty = V->getType(); 3726 Ty = getEffectiveSCEVType(Ty); 3727 const SCEV *AllOnes = 3728 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3729 return getMinusSCEV(AllOnes, V); 3730 } 3731 3732 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3733 SCEV::NoWrapFlags Flags, 3734 unsigned Depth) { 3735 // Fast path: X - X --> 0. 3736 if (LHS == RHS) 3737 return getZero(LHS->getType()); 3738 3739 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3740 // makes it so that we cannot make much use of NUW. 3741 auto AddFlags = SCEV::FlagAnyWrap; 3742 const bool RHSIsNotMinSigned = 3743 !getSignedRangeMin(RHS).isMinSignedValue(); 3744 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3745 // Let M be the minimum representable signed value. Then (-1)*RHS 3746 // signed-wraps if and only if RHS is M. That can happen even for 3747 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3748 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3749 // (-1)*RHS, we need to prove that RHS != M. 3750 // 3751 // If LHS is non-negative and we know that LHS - RHS does not 3752 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3753 // either by proving that RHS > M or that LHS >= 0. 3754 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3755 AddFlags = SCEV::FlagNSW; 3756 } 3757 } 3758 3759 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3760 // RHS is NSW and LHS >= 0. 3761 // 3762 // The difficulty here is that the NSW flag may have been proven 3763 // relative to a loop that is to be found in a recurrence in LHS and 3764 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3765 // larger scope than intended. 3766 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3767 3768 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3769 } 3770 3771 const SCEV * 3772 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3773 Type *SrcTy = V->getType(); 3774 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3775 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3776 "Cannot truncate or zero extend with non-integer arguments!"); 3777 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3778 return V; // No conversion 3779 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3780 return getTruncateExpr(V, Ty); 3781 return getZeroExtendExpr(V, Ty); 3782 } 3783 3784 const SCEV * 3785 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3786 Type *Ty) { 3787 Type *SrcTy = V->getType(); 3788 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3789 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3790 "Cannot truncate or zero extend with non-integer arguments!"); 3791 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3792 return V; // No conversion 3793 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3794 return getTruncateExpr(V, Ty); 3795 return getSignExtendExpr(V, Ty); 3796 } 3797 3798 const SCEV * 3799 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3800 Type *SrcTy = V->getType(); 3801 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3802 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3803 "Cannot noop or zero extend with non-integer arguments!"); 3804 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3805 "getNoopOrZeroExtend cannot truncate!"); 3806 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3807 return V; // No conversion 3808 return getZeroExtendExpr(V, Ty); 3809 } 3810 3811 const SCEV * 3812 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3813 Type *SrcTy = V->getType(); 3814 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3815 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3816 "Cannot noop or sign extend with non-integer arguments!"); 3817 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3818 "getNoopOrSignExtend cannot truncate!"); 3819 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3820 return V; // No conversion 3821 return getSignExtendExpr(V, Ty); 3822 } 3823 3824 const SCEV * 3825 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3826 Type *SrcTy = V->getType(); 3827 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3828 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3829 "Cannot noop or any extend with non-integer arguments!"); 3830 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3831 "getNoopOrAnyExtend cannot truncate!"); 3832 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3833 return V; // No conversion 3834 return getAnyExtendExpr(V, Ty); 3835 } 3836 3837 const SCEV * 3838 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3839 Type *SrcTy = V->getType(); 3840 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3841 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3842 "Cannot truncate or noop with non-integer arguments!"); 3843 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3844 "getTruncateOrNoop cannot extend!"); 3845 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3846 return V; // No conversion 3847 return getTruncateExpr(V, Ty); 3848 } 3849 3850 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3851 const SCEV *RHS) { 3852 const SCEV *PromotedLHS = LHS; 3853 const SCEV *PromotedRHS = RHS; 3854 3855 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3856 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3857 else 3858 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3859 3860 return getUMaxExpr(PromotedLHS, PromotedRHS); 3861 } 3862 3863 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3864 const SCEV *RHS) { 3865 const SCEV *PromotedLHS = LHS; 3866 const SCEV *PromotedRHS = RHS; 3867 3868 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3869 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3870 else 3871 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3872 3873 return getUMinExpr(PromotedLHS, PromotedRHS); 3874 } 3875 3876 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3877 // A pointer operand may evaluate to a nonpointer expression, such as null. 3878 if (!V->getType()->isPointerTy()) 3879 return V; 3880 3881 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3882 return getPointerBase(Cast->getOperand()); 3883 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3884 const SCEV *PtrOp = nullptr; 3885 for (const SCEV *NAryOp : NAry->operands()) { 3886 if (NAryOp->getType()->isPointerTy()) { 3887 // Cannot find the base of an expression with multiple pointer operands. 3888 if (PtrOp) 3889 return V; 3890 PtrOp = NAryOp; 3891 } 3892 } 3893 if (!PtrOp) 3894 return V; 3895 return getPointerBase(PtrOp); 3896 } 3897 return V; 3898 } 3899 3900 /// Push users of the given Instruction onto the given Worklist. 3901 static void 3902 PushDefUseChildren(Instruction *I, 3903 SmallVectorImpl<Instruction *> &Worklist) { 3904 // Push the def-use children onto the Worklist stack. 3905 for (User *U : I->users()) 3906 Worklist.push_back(cast<Instruction>(U)); 3907 } 3908 3909 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3910 SmallVector<Instruction *, 16> Worklist; 3911 PushDefUseChildren(PN, Worklist); 3912 3913 SmallPtrSet<Instruction *, 8> Visited; 3914 Visited.insert(PN); 3915 while (!Worklist.empty()) { 3916 Instruction *I = Worklist.pop_back_val(); 3917 if (!Visited.insert(I).second) 3918 continue; 3919 3920 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3921 if (It != ValueExprMap.end()) { 3922 const SCEV *Old = It->second; 3923 3924 // Short-circuit the def-use traversal if the symbolic name 3925 // ceases to appear in expressions. 3926 if (Old != SymName && !hasOperand(Old, SymName)) 3927 continue; 3928 3929 // SCEVUnknown for a PHI either means that it has an unrecognized 3930 // structure, it's a PHI that's in the progress of being computed 3931 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3932 // additional loop trip count information isn't going to change anything. 3933 // In the second case, createNodeForPHI will perform the necessary 3934 // updates on its own when it gets to that point. In the third, we do 3935 // want to forget the SCEVUnknown. 3936 if (!isa<PHINode>(I) || 3937 !isa<SCEVUnknown>(Old) || 3938 (I != PN && Old == SymName)) { 3939 eraseValueFromMap(It->first); 3940 forgetMemoizedResults(Old); 3941 } 3942 } 3943 3944 PushDefUseChildren(I, Worklist); 3945 } 3946 } 3947 3948 namespace { 3949 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3950 public: 3951 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3952 ScalarEvolution &SE) { 3953 SCEVInitRewriter Rewriter(L, SE); 3954 const SCEV *Result = Rewriter.visit(S); 3955 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3956 } 3957 3958 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3959 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3960 3961 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3962 if (!SE.isLoopInvariant(Expr, L)) 3963 Valid = false; 3964 return Expr; 3965 } 3966 3967 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3968 // Only allow AddRecExprs for this loop. 3969 if (Expr->getLoop() == L) 3970 return Expr->getStart(); 3971 Valid = false; 3972 return Expr; 3973 } 3974 3975 bool isValid() { return Valid; } 3976 3977 private: 3978 const Loop *L; 3979 bool Valid; 3980 }; 3981 3982 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3983 public: 3984 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3985 ScalarEvolution &SE) { 3986 SCEVShiftRewriter Rewriter(L, SE); 3987 const SCEV *Result = Rewriter.visit(S); 3988 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3989 } 3990 3991 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3992 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3993 3994 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3995 // Only allow AddRecExprs for this loop. 3996 if (!SE.isLoopInvariant(Expr, L)) 3997 Valid = false; 3998 return Expr; 3999 } 4000 4001 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4002 if (Expr->getLoop() == L && Expr->isAffine()) 4003 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4004 Valid = false; 4005 return Expr; 4006 } 4007 bool isValid() { return Valid; } 4008 4009 private: 4010 const Loop *L; 4011 bool Valid; 4012 }; 4013 } // end anonymous namespace 4014 4015 SCEV::NoWrapFlags 4016 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4017 if (!AR->isAffine()) 4018 return SCEV::FlagAnyWrap; 4019 4020 typedef OverflowingBinaryOperator OBO; 4021 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4022 4023 if (!AR->hasNoSignedWrap()) { 4024 ConstantRange AddRecRange = getSignedRange(AR); 4025 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4026 4027 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4028 Instruction::Add, IncRange, OBO::NoSignedWrap); 4029 if (NSWRegion.contains(AddRecRange)) 4030 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4031 } 4032 4033 if (!AR->hasNoUnsignedWrap()) { 4034 ConstantRange AddRecRange = getUnsignedRange(AR); 4035 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4036 4037 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4038 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4039 if (NUWRegion.contains(AddRecRange)) 4040 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4041 } 4042 4043 return Result; 4044 } 4045 4046 namespace { 4047 /// Represents an abstract binary operation. This may exist as a 4048 /// normal instruction or constant expression, or may have been 4049 /// derived from an expression tree. 4050 struct BinaryOp { 4051 unsigned Opcode; 4052 Value *LHS; 4053 Value *RHS; 4054 bool IsNSW; 4055 bool IsNUW; 4056 4057 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4058 /// constant expression. 4059 Operator *Op; 4060 4061 explicit BinaryOp(Operator *Op) 4062 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4063 IsNSW(false), IsNUW(false), Op(Op) { 4064 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4065 IsNSW = OBO->hasNoSignedWrap(); 4066 IsNUW = OBO->hasNoUnsignedWrap(); 4067 } 4068 } 4069 4070 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4071 bool IsNUW = false) 4072 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4073 Op(nullptr) {} 4074 }; 4075 } 4076 4077 4078 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4079 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4080 auto *Op = dyn_cast<Operator>(V); 4081 if (!Op) 4082 return None; 4083 4084 // Implementation detail: all the cleverness here should happen without 4085 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4086 // SCEV expressions when possible, and we should not break that. 4087 4088 switch (Op->getOpcode()) { 4089 case Instruction::Add: 4090 case Instruction::Sub: 4091 case Instruction::Mul: 4092 case Instruction::UDiv: 4093 case Instruction::And: 4094 case Instruction::Or: 4095 case Instruction::AShr: 4096 case Instruction::Shl: 4097 return BinaryOp(Op); 4098 4099 case Instruction::Xor: 4100 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4101 // If the RHS of the xor is a signmask, then this is just an add. 4102 // Instcombine turns add of signmask into xor as a strength reduction step. 4103 if (RHSC->getValue().isSignMask()) 4104 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4105 return BinaryOp(Op); 4106 4107 case Instruction::LShr: 4108 // Turn logical shift right of a constant into a unsigned divide. 4109 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4110 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4111 4112 // If the shift count is not less than the bitwidth, the result of 4113 // the shift is undefined. Don't try to analyze it, because the 4114 // resolution chosen here may differ from the resolution chosen in 4115 // other parts of the compiler. 4116 if (SA->getValue().ult(BitWidth)) { 4117 Constant *X = 4118 ConstantInt::get(SA->getContext(), 4119 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4120 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4121 } 4122 } 4123 return BinaryOp(Op); 4124 4125 case Instruction::ExtractValue: { 4126 auto *EVI = cast<ExtractValueInst>(Op); 4127 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4128 break; 4129 4130 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4131 if (!CI) 4132 break; 4133 4134 if (auto *F = CI->getCalledFunction()) 4135 switch (F->getIntrinsicID()) { 4136 case Intrinsic::sadd_with_overflow: 4137 case Intrinsic::uadd_with_overflow: { 4138 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4139 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4140 CI->getArgOperand(1)); 4141 4142 // Now that we know that all uses of the arithmetic-result component of 4143 // CI are guarded by the overflow check, we can go ahead and pretend 4144 // that the arithmetic is non-overflowing. 4145 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4146 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4147 CI->getArgOperand(1), /* IsNSW = */ true, 4148 /* IsNUW = */ false); 4149 else 4150 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4151 CI->getArgOperand(1), /* IsNSW = */ false, 4152 /* IsNUW*/ true); 4153 } 4154 4155 case Intrinsic::ssub_with_overflow: 4156 case Intrinsic::usub_with_overflow: 4157 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4158 CI->getArgOperand(1)); 4159 4160 case Intrinsic::smul_with_overflow: 4161 case Intrinsic::umul_with_overflow: 4162 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4163 CI->getArgOperand(1)); 4164 default: 4165 break; 4166 } 4167 } 4168 4169 default: 4170 break; 4171 } 4172 4173 return None; 4174 } 4175 4176 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4177 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4178 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4179 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4180 /// follows one of the following patterns: 4181 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4182 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4183 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4184 /// we return the type of the truncation operation, and indicate whether the 4185 /// truncated type should be treated as signed/unsigned by setting 4186 /// \p Signed to true/false, respectively. 4187 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4188 bool &Signed, ScalarEvolution &SE) { 4189 4190 // The case where Op == SymbolicPHI (that is, with no type conversions on 4191 // the way) is handled by the regular add recurrence creating logic and 4192 // would have already been triggered in createAddRecForPHI. Reaching it here 4193 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4194 // because one of the other operands of the SCEVAddExpr updating this PHI is 4195 // not invariant). 4196 // 4197 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4198 // this case predicates that allow us to prove that Op == SymbolicPHI will 4199 // be added. 4200 if (Op == SymbolicPHI) 4201 return nullptr; 4202 4203 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4204 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4205 if (SourceBits != NewBits) 4206 return nullptr; 4207 4208 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4209 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4210 if (!SExt && !ZExt) 4211 return nullptr; 4212 const SCEVTruncateExpr *Trunc = 4213 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4214 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4215 if (!Trunc) 4216 return nullptr; 4217 const SCEV *X = Trunc->getOperand(); 4218 if (X != SymbolicPHI) 4219 return nullptr; 4220 Signed = SExt ? true : false; 4221 return Trunc->getType(); 4222 } 4223 4224 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4225 if (!PN->getType()->isIntegerTy()) 4226 return nullptr; 4227 const Loop *L = LI.getLoopFor(PN->getParent()); 4228 if (!L || L->getHeader() != PN->getParent()) 4229 return nullptr; 4230 return L; 4231 } 4232 4233 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4234 // computation that updates the phi follows the following pattern: 4235 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4236 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4237 // If so, try to see if it can be rewritten as an AddRecExpr under some 4238 // Predicates. If successful, return them as a pair. Also cache the results 4239 // of the analysis. 4240 // 4241 // Example usage scenario: 4242 // Say the Rewriter is called for the following SCEV: 4243 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4244 // where: 4245 // %X = phi i64 (%Start, %BEValue) 4246 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4247 // and call this function with %SymbolicPHI = %X. 4248 // 4249 // The analysis will find that the value coming around the backedge has 4250 // the following SCEV: 4251 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4252 // Upon concluding that this matches the desired pattern, the function 4253 // will return the pair {NewAddRec, SmallPredsVec} where: 4254 // NewAddRec = {%Start,+,%Step} 4255 // SmallPredsVec = {P1, P2, P3} as follows: 4256 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4257 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4258 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4259 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4260 // under the predicates {P1,P2,P3}. 4261 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4262 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4263 // 4264 // TODO's: 4265 // 4266 // 1) Extend the Induction descriptor to also support inductions that involve 4267 // casts: When needed (namely, when we are called in the context of the 4268 // vectorizer induction analysis), a Set of cast instructions will be 4269 // populated by this method, and provided back to isInductionPHI. This is 4270 // needed to allow the vectorizer to properly record them to be ignored by 4271 // the cost model and to avoid vectorizing them (otherwise these casts, 4272 // which are redundant under the runtime overflow checks, will be 4273 // vectorized, which can be costly). 4274 // 4275 // 2) Support additional induction/PHISCEV patterns: We also want to support 4276 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4277 // after the induction update operation (the induction increment): 4278 // 4279 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4280 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4281 // 4282 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4283 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4284 // 4285 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4286 // 4287 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4288 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4289 SmallVector<const SCEVPredicate *, 3> Predicates; 4290 4291 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4292 // return an AddRec expression under some predicate. 4293 4294 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4295 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4296 assert (L && "Expecting an integer loop header phi"); 4297 4298 // The loop may have multiple entrances or multiple exits; we can analyze 4299 // this phi as an addrec if it has a unique entry value and a unique 4300 // backedge value. 4301 Value *BEValueV = nullptr, *StartValueV = nullptr; 4302 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4303 Value *V = PN->getIncomingValue(i); 4304 if (L->contains(PN->getIncomingBlock(i))) { 4305 if (!BEValueV) { 4306 BEValueV = V; 4307 } else if (BEValueV != V) { 4308 BEValueV = nullptr; 4309 break; 4310 } 4311 } else if (!StartValueV) { 4312 StartValueV = V; 4313 } else if (StartValueV != V) { 4314 StartValueV = nullptr; 4315 break; 4316 } 4317 } 4318 if (!BEValueV || !StartValueV) 4319 return None; 4320 4321 const SCEV *BEValue = getSCEV(BEValueV); 4322 4323 // If the value coming around the backedge is an add with the symbolic 4324 // value we just inserted, possibly with casts that we can ignore under 4325 // an appropriate runtime guard, then we found a simple induction variable! 4326 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4327 if (!Add) 4328 return None; 4329 4330 // If there is a single occurrence of the symbolic value, possibly 4331 // casted, replace it with a recurrence. 4332 unsigned FoundIndex = Add->getNumOperands(); 4333 Type *TruncTy = nullptr; 4334 bool Signed; 4335 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4336 if ((TruncTy = 4337 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4338 if (FoundIndex == e) { 4339 FoundIndex = i; 4340 break; 4341 } 4342 4343 if (FoundIndex == Add->getNumOperands()) 4344 return None; 4345 4346 // Create an add with everything but the specified operand. 4347 SmallVector<const SCEV *, 8> Ops; 4348 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4349 if (i != FoundIndex) 4350 Ops.push_back(Add->getOperand(i)); 4351 const SCEV *Accum = getAddExpr(Ops); 4352 4353 // The runtime checks will not be valid if the step amount is 4354 // varying inside the loop. 4355 if (!isLoopInvariant(Accum, L)) 4356 return None; 4357 4358 4359 // *** Part2: Create the predicates 4360 4361 // Analysis was successful: we have a phi-with-cast pattern for which we 4362 // can return an AddRec expression under the following predicates: 4363 // 4364 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4365 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4366 // P2: An Equal predicate that guarantees that 4367 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4368 // P3: An Equal predicate that guarantees that 4369 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4370 // 4371 // As we next prove, the above predicates guarantee that: 4372 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4373 // 4374 // 4375 // More formally, we want to prove that: 4376 // Expr(i+1) = Start + (i+1) * Accum 4377 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4378 // 4379 // Given that: 4380 // 1) Expr(0) = Start 4381 // 2) Expr(1) = Start + Accum 4382 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4383 // 3) Induction hypothesis (step i): 4384 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4385 // 4386 // Proof: 4387 // Expr(i+1) = 4388 // = Start + (i+1)*Accum 4389 // = (Start + i*Accum) + Accum 4390 // = Expr(i) + Accum 4391 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4392 // :: from step i 4393 // 4394 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4395 // 4396 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4397 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4398 // + Accum :: from P3 4399 // 4400 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4401 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4402 // 4403 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4404 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4405 // 4406 // By induction, the same applies to all iterations 1<=i<n: 4407 // 4408 4409 // Create a truncated addrec for which we will add a no overflow check (P1). 4410 const SCEV *StartVal = getSCEV(StartValueV); 4411 const SCEV *PHISCEV = 4412 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4413 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4414 const auto *AR = cast<SCEVAddRecExpr>(PHISCEV); 4415 4416 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4417 Signed ? SCEVWrapPredicate::IncrementNSSW 4418 : SCEVWrapPredicate::IncrementNUSW; 4419 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4420 Predicates.push_back(AddRecPred); 4421 4422 // Create the Equal Predicates P2,P3: 4423 auto AppendPredicate = [&](const SCEV *Expr) -> void { 4424 assert (isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4425 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4426 const SCEV *ExtendedExpr = 4427 Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4428 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4429 if (Expr != ExtendedExpr && 4430 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4431 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4432 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4433 Predicates.push_back(Pred); 4434 } 4435 }; 4436 4437 AppendPredicate(StartVal); 4438 AppendPredicate(Accum); 4439 4440 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4441 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4442 // into NewAR if it will also add the runtime overflow checks specified in 4443 // Predicates. 4444 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4445 4446 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4447 std::make_pair(NewAR, Predicates); 4448 // Remember the result of the analysis for this SCEV at this locayyytion. 4449 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4450 return PredRewrite; 4451 } 4452 4453 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4454 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4455 4456 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4457 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4458 if (!L) 4459 return None; 4460 4461 // Check to see if we already analyzed this PHI. 4462 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4463 if (I != PredicatedSCEVRewrites.end()) { 4464 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4465 I->second; 4466 // Analysis was done before and failed to create an AddRec: 4467 if (Rewrite.first == SymbolicPHI) 4468 return None; 4469 // Analysis was done before and succeeded to create an AddRec under 4470 // a predicate: 4471 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4472 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4473 return Rewrite; 4474 } 4475 4476 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4477 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4478 4479 // Record in the cache that the analysis failed 4480 if (!Rewrite) { 4481 SmallVector<const SCEVPredicate *, 3> Predicates; 4482 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4483 return None; 4484 } 4485 4486 return Rewrite; 4487 } 4488 4489 /// A helper function for createAddRecFromPHI to handle simple cases. 4490 /// 4491 /// This function tries to find an AddRec expression for the simplest (yet most 4492 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4493 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4494 /// technique for finding the AddRec expression. 4495 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4496 Value *BEValueV, 4497 Value *StartValueV) { 4498 const Loop *L = LI.getLoopFor(PN->getParent()); 4499 assert(L && L->getHeader() == PN->getParent()); 4500 assert(BEValueV && StartValueV); 4501 4502 auto BO = MatchBinaryOp(BEValueV, DT); 4503 if (!BO) 4504 return nullptr; 4505 4506 if (BO->Opcode != Instruction::Add) 4507 return nullptr; 4508 4509 const SCEV *Accum = nullptr; 4510 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4511 Accum = getSCEV(BO->RHS); 4512 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4513 Accum = getSCEV(BO->LHS); 4514 4515 if (!Accum) 4516 return nullptr; 4517 4518 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4519 if (BO->IsNUW) 4520 Flags = setFlags(Flags, SCEV::FlagNUW); 4521 if (BO->IsNSW) 4522 Flags = setFlags(Flags, SCEV::FlagNSW); 4523 4524 const SCEV *StartVal = getSCEV(StartValueV); 4525 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4526 4527 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4528 4529 // We can add Flags to the post-inc expression only if we 4530 // know that it is *undefined behavior* for BEValueV to 4531 // overflow. 4532 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4533 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4534 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4535 4536 return PHISCEV; 4537 } 4538 4539 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4540 const Loop *L = LI.getLoopFor(PN->getParent()); 4541 if (!L || L->getHeader() != PN->getParent()) 4542 return nullptr; 4543 4544 // The loop may have multiple entrances or multiple exits; we can analyze 4545 // this phi as an addrec if it has a unique entry value and a unique 4546 // backedge value. 4547 Value *BEValueV = nullptr, *StartValueV = nullptr; 4548 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4549 Value *V = PN->getIncomingValue(i); 4550 if (L->contains(PN->getIncomingBlock(i))) { 4551 if (!BEValueV) { 4552 BEValueV = V; 4553 } else if (BEValueV != V) { 4554 BEValueV = nullptr; 4555 break; 4556 } 4557 } else if (!StartValueV) { 4558 StartValueV = V; 4559 } else if (StartValueV != V) { 4560 StartValueV = nullptr; 4561 break; 4562 } 4563 } 4564 if (!BEValueV || !StartValueV) 4565 return nullptr; 4566 4567 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4568 "PHI node already processed?"); 4569 4570 // First, try to find AddRec expression without creating a fictituos symbolic 4571 // value for PN. 4572 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4573 return S; 4574 4575 // Handle PHI node value symbolically. 4576 const SCEV *SymbolicName = getUnknown(PN); 4577 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4578 4579 // Using this symbolic name for the PHI, analyze the value coming around 4580 // the back-edge. 4581 const SCEV *BEValue = getSCEV(BEValueV); 4582 4583 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4584 // has a special value for the first iteration of the loop. 4585 4586 // If the value coming around the backedge is an add with the symbolic 4587 // value we just inserted, then we found a simple induction variable! 4588 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4589 // If there is a single occurrence of the symbolic value, replace it 4590 // with a recurrence. 4591 unsigned FoundIndex = Add->getNumOperands(); 4592 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4593 if (Add->getOperand(i) == SymbolicName) 4594 if (FoundIndex == e) { 4595 FoundIndex = i; 4596 break; 4597 } 4598 4599 if (FoundIndex != Add->getNumOperands()) { 4600 // Create an add with everything but the specified operand. 4601 SmallVector<const SCEV *, 8> Ops; 4602 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4603 if (i != FoundIndex) 4604 Ops.push_back(Add->getOperand(i)); 4605 const SCEV *Accum = getAddExpr(Ops); 4606 4607 // This is not a valid addrec if the step amount is varying each 4608 // loop iteration, but is not itself an addrec in this loop. 4609 if (isLoopInvariant(Accum, L) || 4610 (isa<SCEVAddRecExpr>(Accum) && 4611 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4612 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4613 4614 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4615 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4616 if (BO->IsNUW) 4617 Flags = setFlags(Flags, SCEV::FlagNUW); 4618 if (BO->IsNSW) 4619 Flags = setFlags(Flags, SCEV::FlagNSW); 4620 } 4621 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4622 // If the increment is an inbounds GEP, then we know the address 4623 // space cannot be wrapped around. We cannot make any guarantee 4624 // about signed or unsigned overflow because pointers are 4625 // unsigned but we may have a negative index from the base 4626 // pointer. We can guarantee that no unsigned wrap occurs if the 4627 // indices form a positive value. 4628 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4629 Flags = setFlags(Flags, SCEV::FlagNW); 4630 4631 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4632 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4633 Flags = setFlags(Flags, SCEV::FlagNUW); 4634 } 4635 4636 // We cannot transfer nuw and nsw flags from subtraction 4637 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4638 // for instance. 4639 } 4640 4641 const SCEV *StartVal = getSCEV(StartValueV); 4642 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4643 4644 // Okay, for the entire analysis of this edge we assumed the PHI 4645 // to be symbolic. We now need to go back and purge all of the 4646 // entries for the scalars that use the symbolic expression. 4647 forgetSymbolicName(PN, SymbolicName); 4648 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4649 4650 // We can add Flags to the post-inc expression only if we 4651 // know that it is *undefined behavior* for BEValueV to 4652 // overflow. 4653 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4654 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4655 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4656 4657 return PHISCEV; 4658 } 4659 } 4660 } else { 4661 // Otherwise, this could be a loop like this: 4662 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4663 // In this case, j = {1,+,1} and BEValue is j. 4664 // Because the other in-value of i (0) fits the evolution of BEValue 4665 // i really is an addrec evolution. 4666 // 4667 // We can generalize this saying that i is the shifted value of BEValue 4668 // by one iteration: 4669 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4670 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4671 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4672 if (Shifted != getCouldNotCompute() && 4673 Start != getCouldNotCompute()) { 4674 const SCEV *StartVal = getSCEV(StartValueV); 4675 if (Start == StartVal) { 4676 // Okay, for the entire analysis of this edge we assumed the PHI 4677 // to be symbolic. We now need to go back and purge all of the 4678 // entries for the scalars that use the symbolic expression. 4679 forgetSymbolicName(PN, SymbolicName); 4680 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4681 return Shifted; 4682 } 4683 } 4684 } 4685 4686 // Remove the temporary PHI node SCEV that has been inserted while intending 4687 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4688 // as it will prevent later (possibly simpler) SCEV expressions to be added 4689 // to the ValueExprMap. 4690 eraseValueFromMap(PN); 4691 4692 return nullptr; 4693 } 4694 4695 // Checks if the SCEV S is available at BB. S is considered available at BB 4696 // if S can be materialized at BB without introducing a fault. 4697 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4698 BasicBlock *BB) { 4699 struct CheckAvailable { 4700 bool TraversalDone = false; 4701 bool Available = true; 4702 4703 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4704 BasicBlock *BB = nullptr; 4705 DominatorTree &DT; 4706 4707 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4708 : L(L), BB(BB), DT(DT) {} 4709 4710 bool setUnavailable() { 4711 TraversalDone = true; 4712 Available = false; 4713 return false; 4714 } 4715 4716 bool follow(const SCEV *S) { 4717 switch (S->getSCEVType()) { 4718 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4719 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4720 // These expressions are available if their operand(s) is/are. 4721 return true; 4722 4723 case scAddRecExpr: { 4724 // We allow add recurrences that are on the loop BB is in, or some 4725 // outer loop. This guarantees availability because the value of the 4726 // add recurrence at BB is simply the "current" value of the induction 4727 // variable. We can relax this in the future; for instance an add 4728 // recurrence on a sibling dominating loop is also available at BB. 4729 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4730 if (L && (ARLoop == L || ARLoop->contains(L))) 4731 return true; 4732 4733 return setUnavailable(); 4734 } 4735 4736 case scUnknown: { 4737 // For SCEVUnknown, we check for simple dominance. 4738 const auto *SU = cast<SCEVUnknown>(S); 4739 Value *V = SU->getValue(); 4740 4741 if (isa<Argument>(V)) 4742 return false; 4743 4744 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4745 return false; 4746 4747 return setUnavailable(); 4748 } 4749 4750 case scUDivExpr: 4751 case scCouldNotCompute: 4752 // We do not try to smart about these at all. 4753 return setUnavailable(); 4754 } 4755 llvm_unreachable("switch should be fully covered!"); 4756 } 4757 4758 bool isDone() { return TraversalDone; } 4759 }; 4760 4761 CheckAvailable CA(L, BB, DT); 4762 SCEVTraversal<CheckAvailable> ST(CA); 4763 4764 ST.visitAll(S); 4765 return CA.Available; 4766 } 4767 4768 // Try to match a control flow sequence that branches out at BI and merges back 4769 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4770 // match. 4771 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4772 Value *&C, Value *&LHS, Value *&RHS) { 4773 C = BI->getCondition(); 4774 4775 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4776 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4777 4778 if (!LeftEdge.isSingleEdge()) 4779 return false; 4780 4781 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4782 4783 Use &LeftUse = Merge->getOperandUse(0); 4784 Use &RightUse = Merge->getOperandUse(1); 4785 4786 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4787 LHS = LeftUse; 4788 RHS = RightUse; 4789 return true; 4790 } 4791 4792 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4793 LHS = RightUse; 4794 RHS = LeftUse; 4795 return true; 4796 } 4797 4798 return false; 4799 } 4800 4801 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4802 auto IsReachable = 4803 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4804 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4805 const Loop *L = LI.getLoopFor(PN->getParent()); 4806 4807 // We don't want to break LCSSA, even in a SCEV expression tree. 4808 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4809 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4810 return nullptr; 4811 4812 // Try to match 4813 // 4814 // br %cond, label %left, label %right 4815 // left: 4816 // br label %merge 4817 // right: 4818 // br label %merge 4819 // merge: 4820 // V = phi [ %x, %left ], [ %y, %right ] 4821 // 4822 // as "select %cond, %x, %y" 4823 4824 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4825 assert(IDom && "At least the entry block should dominate PN"); 4826 4827 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4828 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4829 4830 if (BI && BI->isConditional() && 4831 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4832 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4833 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4834 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4835 } 4836 4837 return nullptr; 4838 } 4839 4840 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4841 if (const SCEV *S = createAddRecFromPHI(PN)) 4842 return S; 4843 4844 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4845 return S; 4846 4847 // If the PHI has a single incoming value, follow that value, unless the 4848 // PHI's incoming blocks are in a different loop, in which case doing so 4849 // risks breaking LCSSA form. Instcombine would normally zap these, but 4850 // it doesn't have DominatorTree information, so it may miss cases. 4851 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 4852 if (LI.replacementPreservesLCSSAForm(PN, V)) 4853 return getSCEV(V); 4854 4855 // If it's not a loop phi, we can't handle it yet. 4856 return getUnknown(PN); 4857 } 4858 4859 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4860 Value *Cond, 4861 Value *TrueVal, 4862 Value *FalseVal) { 4863 // Handle "constant" branch or select. This can occur for instance when a 4864 // loop pass transforms an inner loop and moves on to process the outer loop. 4865 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4866 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4867 4868 // Try to match some simple smax or umax patterns. 4869 auto *ICI = dyn_cast<ICmpInst>(Cond); 4870 if (!ICI) 4871 return getUnknown(I); 4872 4873 Value *LHS = ICI->getOperand(0); 4874 Value *RHS = ICI->getOperand(1); 4875 4876 switch (ICI->getPredicate()) { 4877 case ICmpInst::ICMP_SLT: 4878 case ICmpInst::ICMP_SLE: 4879 std::swap(LHS, RHS); 4880 LLVM_FALLTHROUGH; 4881 case ICmpInst::ICMP_SGT: 4882 case ICmpInst::ICMP_SGE: 4883 // a >s b ? a+x : b+x -> smax(a, b)+x 4884 // a >s b ? b+x : a+x -> smin(a, b)+x 4885 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4886 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4887 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4888 const SCEV *LA = getSCEV(TrueVal); 4889 const SCEV *RA = getSCEV(FalseVal); 4890 const SCEV *LDiff = getMinusSCEV(LA, LS); 4891 const SCEV *RDiff = getMinusSCEV(RA, RS); 4892 if (LDiff == RDiff) 4893 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4894 LDiff = getMinusSCEV(LA, RS); 4895 RDiff = getMinusSCEV(RA, LS); 4896 if (LDiff == RDiff) 4897 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4898 } 4899 break; 4900 case ICmpInst::ICMP_ULT: 4901 case ICmpInst::ICMP_ULE: 4902 std::swap(LHS, RHS); 4903 LLVM_FALLTHROUGH; 4904 case ICmpInst::ICMP_UGT: 4905 case ICmpInst::ICMP_UGE: 4906 // a >u b ? a+x : b+x -> umax(a, b)+x 4907 // a >u b ? b+x : a+x -> umin(a, b)+x 4908 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4909 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4910 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4911 const SCEV *LA = getSCEV(TrueVal); 4912 const SCEV *RA = getSCEV(FalseVal); 4913 const SCEV *LDiff = getMinusSCEV(LA, LS); 4914 const SCEV *RDiff = getMinusSCEV(RA, RS); 4915 if (LDiff == RDiff) 4916 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4917 LDiff = getMinusSCEV(LA, RS); 4918 RDiff = getMinusSCEV(RA, LS); 4919 if (LDiff == RDiff) 4920 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4921 } 4922 break; 4923 case ICmpInst::ICMP_NE: 4924 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4925 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4926 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4927 const SCEV *One = getOne(I->getType()); 4928 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4929 const SCEV *LA = getSCEV(TrueVal); 4930 const SCEV *RA = getSCEV(FalseVal); 4931 const SCEV *LDiff = getMinusSCEV(LA, LS); 4932 const SCEV *RDiff = getMinusSCEV(RA, One); 4933 if (LDiff == RDiff) 4934 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4935 } 4936 break; 4937 case ICmpInst::ICMP_EQ: 4938 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4939 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4940 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4941 const SCEV *One = getOne(I->getType()); 4942 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4943 const SCEV *LA = getSCEV(TrueVal); 4944 const SCEV *RA = getSCEV(FalseVal); 4945 const SCEV *LDiff = getMinusSCEV(LA, One); 4946 const SCEV *RDiff = getMinusSCEV(RA, LS); 4947 if (LDiff == RDiff) 4948 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4949 } 4950 break; 4951 default: 4952 break; 4953 } 4954 4955 return getUnknown(I); 4956 } 4957 4958 /// Expand GEP instructions into add and multiply operations. This allows them 4959 /// to be analyzed by regular SCEV code. 4960 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4961 // Don't attempt to analyze GEPs over unsized objects. 4962 if (!GEP->getSourceElementType()->isSized()) 4963 return getUnknown(GEP); 4964 4965 SmallVector<const SCEV *, 4> IndexExprs; 4966 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4967 IndexExprs.push_back(getSCEV(*Index)); 4968 return getGEPExpr(GEP, IndexExprs); 4969 } 4970 4971 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 4972 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4973 return C->getAPInt().countTrailingZeros(); 4974 4975 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4976 return std::min(GetMinTrailingZeros(T->getOperand()), 4977 (uint32_t)getTypeSizeInBits(T->getType())); 4978 4979 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4980 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4981 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4982 ? getTypeSizeInBits(E->getType()) 4983 : OpRes; 4984 } 4985 4986 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4987 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4988 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4989 ? getTypeSizeInBits(E->getType()) 4990 : OpRes; 4991 } 4992 4993 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4994 // The result is the min of all operands results. 4995 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4996 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4997 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4998 return MinOpRes; 4999 } 5000 5001 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5002 // The result is the sum of all operands results. 5003 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5004 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5005 for (unsigned i = 1, e = M->getNumOperands(); 5006 SumOpRes != BitWidth && i != e; ++i) 5007 SumOpRes = 5008 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5009 return SumOpRes; 5010 } 5011 5012 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5013 // The result is the min of all operands results. 5014 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5015 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5016 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5017 return MinOpRes; 5018 } 5019 5020 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5021 // The result is the min of all operands results. 5022 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5023 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5024 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5025 return MinOpRes; 5026 } 5027 5028 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5029 // The result is the min of all operands results. 5030 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5031 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5032 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5033 return MinOpRes; 5034 } 5035 5036 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5037 // For a SCEVUnknown, ask ValueTracking. 5038 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5039 return Known.countMinTrailingZeros(); 5040 } 5041 5042 // SCEVUDivExpr 5043 return 0; 5044 } 5045 5046 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5047 auto I = MinTrailingZerosCache.find(S); 5048 if (I != MinTrailingZerosCache.end()) 5049 return I->second; 5050 5051 uint32_t Result = GetMinTrailingZerosImpl(S); 5052 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5053 assert(InsertPair.second && "Should insert a new key"); 5054 return InsertPair.first->second; 5055 } 5056 5057 /// Helper method to assign a range to V from metadata present in the IR. 5058 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5059 if (Instruction *I = dyn_cast<Instruction>(V)) 5060 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5061 return getConstantRangeFromMetadata(*MD); 5062 5063 return None; 5064 } 5065 5066 /// Determine the range for a particular SCEV. If SignHint is 5067 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5068 /// with a "cleaner" unsigned (resp. signed) representation. 5069 const ConstantRange & 5070 ScalarEvolution::getRangeRef(const SCEV *S, 5071 ScalarEvolution::RangeSignHint SignHint) { 5072 DenseMap<const SCEV *, ConstantRange> &Cache = 5073 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5074 : SignedRanges; 5075 5076 // See if we've computed this range already. 5077 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5078 if (I != Cache.end()) 5079 return I->second; 5080 5081 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5082 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5083 5084 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5085 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5086 5087 // If the value has known zeros, the maximum value will have those known zeros 5088 // as well. 5089 uint32_t TZ = GetMinTrailingZeros(S); 5090 if (TZ != 0) { 5091 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5092 ConservativeResult = 5093 ConstantRange(APInt::getMinValue(BitWidth), 5094 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5095 else 5096 ConservativeResult = ConstantRange( 5097 APInt::getSignedMinValue(BitWidth), 5098 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5099 } 5100 5101 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5102 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5103 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5104 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5105 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5106 } 5107 5108 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5109 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5110 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5111 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5112 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5113 } 5114 5115 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5116 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5117 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5118 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5119 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5120 } 5121 5122 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5123 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5124 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5125 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5126 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5127 } 5128 5129 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5130 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5131 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5132 return setRange(UDiv, SignHint, 5133 ConservativeResult.intersectWith(X.udiv(Y))); 5134 } 5135 5136 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5137 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5138 return setRange(ZExt, SignHint, 5139 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5140 } 5141 5142 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5143 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5144 return setRange(SExt, SignHint, 5145 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5146 } 5147 5148 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5149 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5150 return setRange(Trunc, SignHint, 5151 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5152 } 5153 5154 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5155 // If there's no unsigned wrap, the value will never be less than its 5156 // initial value. 5157 if (AddRec->hasNoUnsignedWrap()) 5158 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5159 if (!C->getValue()->isZero()) 5160 ConservativeResult = ConservativeResult.intersectWith( 5161 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5162 5163 // If there's no signed wrap, and all the operands have the same sign or 5164 // zero, the value won't ever change sign. 5165 if (AddRec->hasNoSignedWrap()) { 5166 bool AllNonNeg = true; 5167 bool AllNonPos = true; 5168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5169 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5170 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5171 } 5172 if (AllNonNeg) 5173 ConservativeResult = ConservativeResult.intersectWith( 5174 ConstantRange(APInt(BitWidth, 0), 5175 APInt::getSignedMinValue(BitWidth))); 5176 else if (AllNonPos) 5177 ConservativeResult = ConservativeResult.intersectWith( 5178 ConstantRange(APInt::getSignedMinValue(BitWidth), 5179 APInt(BitWidth, 1))); 5180 } 5181 5182 // TODO: non-affine addrec 5183 if (AddRec->isAffine()) { 5184 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5185 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5186 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5187 auto RangeFromAffine = getRangeForAffineAR( 5188 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5189 BitWidth); 5190 if (!RangeFromAffine.isFullSet()) 5191 ConservativeResult = 5192 ConservativeResult.intersectWith(RangeFromAffine); 5193 5194 auto RangeFromFactoring = getRangeViaFactoring( 5195 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5196 BitWidth); 5197 if (!RangeFromFactoring.isFullSet()) 5198 ConservativeResult = 5199 ConservativeResult.intersectWith(RangeFromFactoring); 5200 } 5201 } 5202 5203 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5204 } 5205 5206 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5207 // Check if the IR explicitly contains !range metadata. 5208 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5209 if (MDRange.hasValue()) 5210 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5211 5212 // Split here to avoid paying the compile-time cost of calling both 5213 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5214 // if needed. 5215 const DataLayout &DL = getDataLayout(); 5216 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5217 // For a SCEVUnknown, ask ValueTracking. 5218 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5219 if (Known.One != ~Known.Zero + 1) 5220 ConservativeResult = 5221 ConservativeResult.intersectWith(ConstantRange(Known.One, 5222 ~Known.Zero + 1)); 5223 } else { 5224 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5225 "generalize as needed!"); 5226 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5227 if (NS > 1) 5228 ConservativeResult = ConservativeResult.intersectWith( 5229 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5230 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5231 } 5232 5233 return setRange(U, SignHint, std::move(ConservativeResult)); 5234 } 5235 5236 return setRange(S, SignHint, std::move(ConservativeResult)); 5237 } 5238 5239 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5240 // values that the expression can take. Initially, the expression has a value 5241 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5242 // argument defines if we treat Step as signed or unsigned. 5243 static ConstantRange getRangeForAffineARHelper(APInt Step, 5244 const ConstantRange &StartRange, 5245 const APInt &MaxBECount, 5246 unsigned BitWidth, bool Signed) { 5247 // If either Step or MaxBECount is 0, then the expression won't change, and we 5248 // just need to return the initial range. 5249 if (Step == 0 || MaxBECount == 0) 5250 return StartRange; 5251 5252 // If we don't know anything about the initial value (i.e. StartRange is 5253 // FullRange), then we don't know anything about the final range either. 5254 // Return FullRange. 5255 if (StartRange.isFullSet()) 5256 return ConstantRange(BitWidth, /* isFullSet = */ true); 5257 5258 // If Step is signed and negative, then we use its absolute value, but we also 5259 // note that we're moving in the opposite direction. 5260 bool Descending = Signed && Step.isNegative(); 5261 5262 if (Signed) 5263 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5264 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5265 // This equations hold true due to the well-defined wrap-around behavior of 5266 // APInt. 5267 Step = Step.abs(); 5268 5269 // Check if Offset is more than full span of BitWidth. If it is, the 5270 // expression is guaranteed to overflow. 5271 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5272 return ConstantRange(BitWidth, /* isFullSet = */ true); 5273 5274 // Offset is by how much the expression can change. Checks above guarantee no 5275 // overflow here. 5276 APInt Offset = Step * MaxBECount; 5277 5278 // Minimum value of the final range will match the minimal value of StartRange 5279 // if the expression is increasing and will be decreased by Offset otherwise. 5280 // Maximum value of the final range will match the maximal value of StartRange 5281 // if the expression is decreasing and will be increased by Offset otherwise. 5282 APInt StartLower = StartRange.getLower(); 5283 APInt StartUpper = StartRange.getUpper() - 1; 5284 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5285 : (StartUpper + std::move(Offset)); 5286 5287 // It's possible that the new minimum/maximum value will fall into the initial 5288 // range (due to wrap around). This means that the expression can take any 5289 // value in this bitwidth, and we have to return full range. 5290 if (StartRange.contains(MovedBoundary)) 5291 return ConstantRange(BitWidth, /* isFullSet = */ true); 5292 5293 APInt NewLower = 5294 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5295 APInt NewUpper = 5296 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5297 NewUpper += 1; 5298 5299 // If we end up with full range, return a proper full range. 5300 if (NewLower == NewUpper) 5301 return ConstantRange(BitWidth, /* isFullSet = */ true); 5302 5303 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5304 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5305 } 5306 5307 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5308 const SCEV *Step, 5309 const SCEV *MaxBECount, 5310 unsigned BitWidth) { 5311 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5312 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5313 "Precondition!"); 5314 5315 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5316 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5317 5318 // First, consider step signed. 5319 ConstantRange StartSRange = getSignedRange(Start); 5320 ConstantRange StepSRange = getSignedRange(Step); 5321 5322 // If Step can be both positive and negative, we need to find ranges for the 5323 // maximum absolute step values in both directions and union them. 5324 ConstantRange SR = 5325 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5326 MaxBECountValue, BitWidth, /* Signed = */ true); 5327 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5328 StartSRange, MaxBECountValue, 5329 BitWidth, /* Signed = */ true)); 5330 5331 // Next, consider step unsigned. 5332 ConstantRange UR = getRangeForAffineARHelper( 5333 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5334 MaxBECountValue, BitWidth, /* Signed = */ false); 5335 5336 // Finally, intersect signed and unsigned ranges. 5337 return SR.intersectWith(UR); 5338 } 5339 5340 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5341 const SCEV *Step, 5342 const SCEV *MaxBECount, 5343 unsigned BitWidth) { 5344 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5345 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5346 5347 struct SelectPattern { 5348 Value *Condition = nullptr; 5349 APInt TrueValue; 5350 APInt FalseValue; 5351 5352 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5353 const SCEV *S) { 5354 Optional<unsigned> CastOp; 5355 APInt Offset(BitWidth, 0); 5356 5357 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5358 "Should be!"); 5359 5360 // Peel off a constant offset: 5361 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5362 // In the future we could consider being smarter here and handle 5363 // {Start+Step,+,Step} too. 5364 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5365 return; 5366 5367 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5368 S = SA->getOperand(1); 5369 } 5370 5371 // Peel off a cast operation 5372 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5373 CastOp = SCast->getSCEVType(); 5374 S = SCast->getOperand(); 5375 } 5376 5377 using namespace llvm::PatternMatch; 5378 5379 auto *SU = dyn_cast<SCEVUnknown>(S); 5380 const APInt *TrueVal, *FalseVal; 5381 if (!SU || 5382 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5383 m_APInt(FalseVal)))) { 5384 Condition = nullptr; 5385 return; 5386 } 5387 5388 TrueValue = *TrueVal; 5389 FalseValue = *FalseVal; 5390 5391 // Re-apply the cast we peeled off earlier 5392 if (CastOp.hasValue()) 5393 switch (*CastOp) { 5394 default: 5395 llvm_unreachable("Unknown SCEV cast type!"); 5396 5397 case scTruncate: 5398 TrueValue = TrueValue.trunc(BitWidth); 5399 FalseValue = FalseValue.trunc(BitWidth); 5400 break; 5401 case scZeroExtend: 5402 TrueValue = TrueValue.zext(BitWidth); 5403 FalseValue = FalseValue.zext(BitWidth); 5404 break; 5405 case scSignExtend: 5406 TrueValue = TrueValue.sext(BitWidth); 5407 FalseValue = FalseValue.sext(BitWidth); 5408 break; 5409 } 5410 5411 // Re-apply the constant offset we peeled off earlier 5412 TrueValue += Offset; 5413 FalseValue += Offset; 5414 } 5415 5416 bool isRecognized() { return Condition != nullptr; } 5417 }; 5418 5419 SelectPattern StartPattern(*this, BitWidth, Start); 5420 if (!StartPattern.isRecognized()) 5421 return ConstantRange(BitWidth, /* isFullSet = */ true); 5422 5423 SelectPattern StepPattern(*this, BitWidth, Step); 5424 if (!StepPattern.isRecognized()) 5425 return ConstantRange(BitWidth, /* isFullSet = */ true); 5426 5427 if (StartPattern.Condition != StepPattern.Condition) { 5428 // We don't handle this case today; but we could, by considering four 5429 // possibilities below instead of two. I'm not sure if there are cases where 5430 // that will help over what getRange already does, though. 5431 return ConstantRange(BitWidth, /* isFullSet = */ true); 5432 } 5433 5434 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5435 // construct arbitrary general SCEV expressions here. This function is called 5436 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5437 // say) can end up caching a suboptimal value. 5438 5439 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5440 // C2352 and C2512 (otherwise it isn't needed). 5441 5442 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5443 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5444 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5445 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5446 5447 ConstantRange TrueRange = 5448 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5449 ConstantRange FalseRange = 5450 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5451 5452 return TrueRange.unionWith(FalseRange); 5453 } 5454 5455 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5456 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5457 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5458 5459 // Return early if there are no flags to propagate to the SCEV. 5460 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5461 if (BinOp->hasNoUnsignedWrap()) 5462 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5463 if (BinOp->hasNoSignedWrap()) 5464 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5465 if (Flags == SCEV::FlagAnyWrap) 5466 return SCEV::FlagAnyWrap; 5467 5468 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5469 } 5470 5471 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5472 // Here we check that I is in the header of the innermost loop containing I, 5473 // since we only deal with instructions in the loop header. The actual loop we 5474 // need to check later will come from an add recurrence, but getting that 5475 // requires computing the SCEV of the operands, which can be expensive. This 5476 // check we can do cheaply to rule out some cases early. 5477 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5478 if (InnermostContainingLoop == nullptr || 5479 InnermostContainingLoop->getHeader() != I->getParent()) 5480 return false; 5481 5482 // Only proceed if we can prove that I does not yield poison. 5483 if (!programUndefinedIfFullPoison(I)) 5484 return false; 5485 5486 // At this point we know that if I is executed, then it does not wrap 5487 // according to at least one of NSW or NUW. If I is not executed, then we do 5488 // not know if the calculation that I represents would wrap. Multiple 5489 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5490 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5491 // derived from other instructions that map to the same SCEV. We cannot make 5492 // that guarantee for cases where I is not executed. So we need to find the 5493 // loop that I is considered in relation to and prove that I is executed for 5494 // every iteration of that loop. That implies that the value that I 5495 // calculates does not wrap anywhere in the loop, so then we can apply the 5496 // flags to the SCEV. 5497 // 5498 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5499 // from different loops, so that we know which loop to prove that I is 5500 // executed in. 5501 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5502 // I could be an extractvalue from a call to an overflow intrinsic. 5503 // TODO: We can do better here in some cases. 5504 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5505 return false; 5506 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5507 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5508 bool AllOtherOpsLoopInvariant = true; 5509 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5510 ++OtherOpIndex) { 5511 if (OtherOpIndex != OpIndex) { 5512 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5513 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5514 AllOtherOpsLoopInvariant = false; 5515 break; 5516 } 5517 } 5518 } 5519 if (AllOtherOpsLoopInvariant && 5520 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5521 return true; 5522 } 5523 } 5524 return false; 5525 } 5526 5527 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5528 // If we know that \c I can never be poison period, then that's enough. 5529 if (isSCEVExprNeverPoison(I)) 5530 return true; 5531 5532 // For an add recurrence specifically, we assume that infinite loops without 5533 // side effects are undefined behavior, and then reason as follows: 5534 // 5535 // If the add recurrence is poison in any iteration, it is poison on all 5536 // future iterations (since incrementing poison yields poison). If the result 5537 // of the add recurrence is fed into the loop latch condition and the loop 5538 // does not contain any throws or exiting blocks other than the latch, we now 5539 // have the ability to "choose" whether the backedge is taken or not (by 5540 // choosing a sufficiently evil value for the poison feeding into the branch) 5541 // for every iteration including and after the one in which \p I first became 5542 // poison. There are two possibilities (let's call the iteration in which \p 5543 // I first became poison as K): 5544 // 5545 // 1. In the set of iterations including and after K, the loop body executes 5546 // no side effects. In this case executing the backege an infinte number 5547 // of times will yield undefined behavior. 5548 // 5549 // 2. In the set of iterations including and after K, the loop body executes 5550 // at least one side effect. In this case, that specific instance of side 5551 // effect is control dependent on poison, which also yields undefined 5552 // behavior. 5553 5554 auto *ExitingBB = L->getExitingBlock(); 5555 auto *LatchBB = L->getLoopLatch(); 5556 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5557 return false; 5558 5559 SmallPtrSet<const Instruction *, 16> Pushed; 5560 SmallVector<const Instruction *, 8> PoisonStack; 5561 5562 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5563 // things that are known to be fully poison under that assumption go on the 5564 // PoisonStack. 5565 Pushed.insert(I); 5566 PoisonStack.push_back(I); 5567 5568 bool LatchControlDependentOnPoison = false; 5569 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5570 const Instruction *Poison = PoisonStack.pop_back_val(); 5571 5572 for (auto *PoisonUser : Poison->users()) { 5573 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5574 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5575 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5576 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5577 assert(BI->isConditional() && "Only possibility!"); 5578 if (BI->getParent() == LatchBB) { 5579 LatchControlDependentOnPoison = true; 5580 break; 5581 } 5582 } 5583 } 5584 } 5585 5586 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5587 } 5588 5589 ScalarEvolution::LoopProperties 5590 ScalarEvolution::getLoopProperties(const Loop *L) { 5591 typedef ScalarEvolution::LoopProperties LoopProperties; 5592 5593 auto Itr = LoopPropertiesCache.find(L); 5594 if (Itr == LoopPropertiesCache.end()) { 5595 auto HasSideEffects = [](Instruction *I) { 5596 if (auto *SI = dyn_cast<StoreInst>(I)) 5597 return !SI->isSimple(); 5598 5599 return I->mayHaveSideEffects(); 5600 }; 5601 5602 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5603 /*HasNoSideEffects*/ true}; 5604 5605 for (auto *BB : L->getBlocks()) 5606 for (auto &I : *BB) { 5607 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5608 LP.HasNoAbnormalExits = false; 5609 if (HasSideEffects(&I)) 5610 LP.HasNoSideEffects = false; 5611 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5612 break; // We're already as pessimistic as we can get. 5613 } 5614 5615 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5616 assert(InsertPair.second && "We just checked!"); 5617 Itr = InsertPair.first; 5618 } 5619 5620 return Itr->second; 5621 } 5622 5623 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5624 if (!isSCEVable(V->getType())) 5625 return getUnknown(V); 5626 5627 if (Instruction *I = dyn_cast<Instruction>(V)) { 5628 // Don't attempt to analyze instructions in blocks that aren't 5629 // reachable. Such instructions don't matter, and they aren't required 5630 // to obey basic rules for definitions dominating uses which this 5631 // analysis depends on. 5632 if (!DT.isReachableFromEntry(I->getParent())) 5633 return getUnknown(V); 5634 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5635 return getConstant(CI); 5636 else if (isa<ConstantPointerNull>(V)) 5637 return getZero(V->getType()); 5638 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5639 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5640 else if (!isa<ConstantExpr>(V)) 5641 return getUnknown(V); 5642 5643 Operator *U = cast<Operator>(V); 5644 if (auto BO = MatchBinaryOp(U, DT)) { 5645 switch (BO->Opcode) { 5646 case Instruction::Add: { 5647 // The simple thing to do would be to just call getSCEV on both operands 5648 // and call getAddExpr with the result. However if we're looking at a 5649 // bunch of things all added together, this can be quite inefficient, 5650 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5651 // Instead, gather up all the operands and make a single getAddExpr call. 5652 // LLVM IR canonical form means we need only traverse the left operands. 5653 SmallVector<const SCEV *, 4> AddOps; 5654 do { 5655 if (BO->Op) { 5656 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5657 AddOps.push_back(OpSCEV); 5658 break; 5659 } 5660 5661 // If a NUW or NSW flag can be applied to the SCEV for this 5662 // addition, then compute the SCEV for this addition by itself 5663 // with a separate call to getAddExpr. We need to do that 5664 // instead of pushing the operands of the addition onto AddOps, 5665 // since the flags are only known to apply to this particular 5666 // addition - they may not apply to other additions that can be 5667 // formed with operands from AddOps. 5668 const SCEV *RHS = getSCEV(BO->RHS); 5669 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5670 if (Flags != SCEV::FlagAnyWrap) { 5671 const SCEV *LHS = getSCEV(BO->LHS); 5672 if (BO->Opcode == Instruction::Sub) 5673 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5674 else 5675 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5676 break; 5677 } 5678 } 5679 5680 if (BO->Opcode == Instruction::Sub) 5681 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5682 else 5683 AddOps.push_back(getSCEV(BO->RHS)); 5684 5685 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5686 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5687 NewBO->Opcode != Instruction::Sub)) { 5688 AddOps.push_back(getSCEV(BO->LHS)); 5689 break; 5690 } 5691 BO = NewBO; 5692 } while (true); 5693 5694 return getAddExpr(AddOps); 5695 } 5696 5697 case Instruction::Mul: { 5698 SmallVector<const SCEV *, 4> MulOps; 5699 do { 5700 if (BO->Op) { 5701 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5702 MulOps.push_back(OpSCEV); 5703 break; 5704 } 5705 5706 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5707 if (Flags != SCEV::FlagAnyWrap) { 5708 MulOps.push_back( 5709 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5710 break; 5711 } 5712 } 5713 5714 MulOps.push_back(getSCEV(BO->RHS)); 5715 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5716 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5717 MulOps.push_back(getSCEV(BO->LHS)); 5718 break; 5719 } 5720 BO = NewBO; 5721 } while (true); 5722 5723 return getMulExpr(MulOps); 5724 } 5725 case Instruction::UDiv: 5726 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5727 case Instruction::Sub: { 5728 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5729 if (BO->Op) 5730 Flags = getNoWrapFlagsFromUB(BO->Op); 5731 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5732 } 5733 case Instruction::And: 5734 // For an expression like x&255 that merely masks off the high bits, 5735 // use zext(trunc(x)) as the SCEV expression. 5736 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5737 if (CI->isZero()) 5738 return getSCEV(BO->RHS); 5739 if (CI->isMinusOne()) 5740 return getSCEV(BO->LHS); 5741 const APInt &A = CI->getValue(); 5742 5743 // Instcombine's ShrinkDemandedConstant may strip bits out of 5744 // constants, obscuring what would otherwise be a low-bits mask. 5745 // Use computeKnownBits to compute what ShrinkDemandedConstant 5746 // knew about to reconstruct a low-bits mask value. 5747 unsigned LZ = A.countLeadingZeros(); 5748 unsigned TZ = A.countTrailingZeros(); 5749 unsigned BitWidth = A.getBitWidth(); 5750 KnownBits Known(BitWidth); 5751 computeKnownBits(BO->LHS, Known, getDataLayout(), 5752 0, &AC, nullptr, &DT); 5753 5754 APInt EffectiveMask = 5755 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5756 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 5757 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5758 const SCEV *LHS = getSCEV(BO->LHS); 5759 const SCEV *ShiftedLHS = nullptr; 5760 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5761 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5762 // For an expression like (x * 8) & 8, simplify the multiply. 5763 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5764 unsigned GCD = std::min(MulZeros, TZ); 5765 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5766 SmallVector<const SCEV*, 4> MulOps; 5767 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5768 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5769 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5770 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5771 } 5772 } 5773 if (!ShiftedLHS) 5774 ShiftedLHS = getUDivExpr(LHS, MulCount); 5775 return getMulExpr( 5776 getZeroExtendExpr( 5777 getTruncateExpr(ShiftedLHS, 5778 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5779 BO->LHS->getType()), 5780 MulCount); 5781 } 5782 } 5783 break; 5784 5785 case Instruction::Or: 5786 // If the RHS of the Or is a constant, we may have something like: 5787 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5788 // optimizations will transparently handle this case. 5789 // 5790 // In order for this transformation to be safe, the LHS must be of the 5791 // form X*(2^n) and the Or constant must be less than 2^n. 5792 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5793 const SCEV *LHS = getSCEV(BO->LHS); 5794 const APInt &CIVal = CI->getValue(); 5795 if (GetMinTrailingZeros(LHS) >= 5796 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5797 // Build a plain add SCEV. 5798 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5799 // If the LHS of the add was an addrec and it has no-wrap flags, 5800 // transfer the no-wrap flags, since an or won't introduce a wrap. 5801 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5802 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5803 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5804 OldAR->getNoWrapFlags()); 5805 } 5806 return S; 5807 } 5808 } 5809 break; 5810 5811 case Instruction::Xor: 5812 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5813 // If the RHS of xor is -1, then this is a not operation. 5814 if (CI->isMinusOne()) 5815 return getNotSCEV(getSCEV(BO->LHS)); 5816 5817 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5818 // This is a variant of the check for xor with -1, and it handles 5819 // the case where instcombine has trimmed non-demanded bits out 5820 // of an xor with -1. 5821 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5822 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5823 if (LBO->getOpcode() == Instruction::And && 5824 LCI->getValue() == CI->getValue()) 5825 if (const SCEVZeroExtendExpr *Z = 5826 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5827 Type *UTy = BO->LHS->getType(); 5828 const SCEV *Z0 = Z->getOperand(); 5829 Type *Z0Ty = Z0->getType(); 5830 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5831 5832 // If C is a low-bits mask, the zero extend is serving to 5833 // mask off the high bits. Complement the operand and 5834 // re-apply the zext. 5835 if (CI->getValue().isMask(Z0TySize)) 5836 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5837 5838 // If C is a single bit, it may be in the sign-bit position 5839 // before the zero-extend. In this case, represent the xor 5840 // using an add, which is equivalent, and re-apply the zext. 5841 APInt Trunc = CI->getValue().trunc(Z0TySize); 5842 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5843 Trunc.isSignMask()) 5844 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5845 UTy); 5846 } 5847 } 5848 break; 5849 5850 case Instruction::Shl: 5851 // Turn shift left of a constant amount into a multiply. 5852 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5853 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5854 5855 // If the shift count is not less than the bitwidth, the result of 5856 // the shift is undefined. Don't try to analyze it, because the 5857 // resolution chosen here may differ from the resolution chosen in 5858 // other parts of the compiler. 5859 if (SA->getValue().uge(BitWidth)) 5860 break; 5861 5862 // It is currently not resolved how to interpret NSW for left 5863 // shift by BitWidth - 1, so we avoid applying flags in that 5864 // case. Remove this check (or this comment) once the situation 5865 // is resolved. See 5866 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5867 // and http://reviews.llvm.org/D8890 . 5868 auto Flags = SCEV::FlagAnyWrap; 5869 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5870 Flags = getNoWrapFlagsFromUB(BO->Op); 5871 5872 Constant *X = ConstantInt::get(getContext(), 5873 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5874 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5875 } 5876 break; 5877 5878 case Instruction::AShr: 5879 // AShr X, C, where C is a constant. 5880 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5881 if (!CI) 5882 break; 5883 5884 Type *OuterTy = BO->LHS->getType(); 5885 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5886 // If the shift count is not less than the bitwidth, the result of 5887 // the shift is undefined. Don't try to analyze it, because the 5888 // resolution chosen here may differ from the resolution chosen in 5889 // other parts of the compiler. 5890 if (CI->getValue().uge(BitWidth)) 5891 break; 5892 5893 if (CI->isZero()) 5894 return getSCEV(BO->LHS); // shift by zero --> noop 5895 5896 uint64_t AShrAmt = CI->getZExtValue(); 5897 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5898 5899 Operator *L = dyn_cast<Operator>(BO->LHS); 5900 if (L && L->getOpcode() == Instruction::Shl) { 5901 // X = Shl A, n 5902 // Y = AShr X, m 5903 // Both n and m are constant. 5904 5905 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5906 if (L->getOperand(1) == BO->RHS) 5907 // For a two-shift sext-inreg, i.e. n = m, 5908 // use sext(trunc(x)) as the SCEV expression. 5909 return getSignExtendExpr( 5910 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5911 5912 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5913 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5914 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5915 if (ShlAmt > AShrAmt) { 5916 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5917 // expression. We already checked that ShlAmt < BitWidth, so 5918 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5919 // ShlAmt - AShrAmt < Amt. 5920 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5921 ShlAmt - AShrAmt); 5922 return getSignExtendExpr( 5923 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5924 getConstant(Mul)), OuterTy); 5925 } 5926 } 5927 } 5928 break; 5929 } 5930 } 5931 5932 switch (U->getOpcode()) { 5933 case Instruction::Trunc: 5934 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5935 5936 case Instruction::ZExt: 5937 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5938 5939 case Instruction::SExt: 5940 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5941 5942 case Instruction::BitCast: 5943 // BitCasts are no-op casts so we just eliminate the cast. 5944 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5945 return getSCEV(U->getOperand(0)); 5946 break; 5947 5948 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5949 // lead to pointer expressions which cannot safely be expanded to GEPs, 5950 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5951 // simplifying integer expressions. 5952 5953 case Instruction::GetElementPtr: 5954 return createNodeForGEP(cast<GEPOperator>(U)); 5955 5956 case Instruction::PHI: 5957 return createNodeForPHI(cast<PHINode>(U)); 5958 5959 case Instruction::Select: 5960 // U can also be a select constant expr, which let fall through. Since 5961 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5962 // constant expressions cannot have instructions as operands, we'd have 5963 // returned getUnknown for a select constant expressions anyway. 5964 if (isa<Instruction>(U)) 5965 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5966 U->getOperand(1), U->getOperand(2)); 5967 break; 5968 5969 case Instruction::Call: 5970 case Instruction::Invoke: 5971 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5972 return getSCEV(RV); 5973 break; 5974 } 5975 5976 return getUnknown(V); 5977 } 5978 5979 5980 5981 //===----------------------------------------------------------------------===// 5982 // Iteration Count Computation Code 5983 // 5984 5985 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5986 if (!ExitCount) 5987 return 0; 5988 5989 ConstantInt *ExitConst = ExitCount->getValue(); 5990 5991 // Guard against huge trip counts. 5992 if (ExitConst->getValue().getActiveBits() > 32) 5993 return 0; 5994 5995 // In case of integer overflow, this returns 0, which is correct. 5996 return ((unsigned)ExitConst->getZExtValue()) + 1; 5997 } 5998 5999 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6000 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6001 return getSmallConstantTripCount(L, ExitingBB); 6002 6003 // No trip count information for multiple exits. 6004 return 0; 6005 } 6006 6007 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6008 BasicBlock *ExitingBlock) { 6009 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6010 assert(L->isLoopExiting(ExitingBlock) && 6011 "Exiting block must actually branch out of the loop!"); 6012 const SCEVConstant *ExitCount = 6013 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6014 return getConstantTripCount(ExitCount); 6015 } 6016 6017 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6018 const auto *MaxExitCount = 6019 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6020 return getConstantTripCount(MaxExitCount); 6021 } 6022 6023 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6024 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6025 return getSmallConstantTripMultiple(L, ExitingBB); 6026 6027 // No trip multiple information for multiple exits. 6028 return 0; 6029 } 6030 6031 /// Returns the largest constant divisor of the trip count of this loop as a 6032 /// normal unsigned value, if possible. This means that the actual trip count is 6033 /// always a multiple of the returned value (don't forget the trip count could 6034 /// very well be zero as well!). 6035 /// 6036 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6037 /// multiple of a constant (which is also the case if the trip count is simply 6038 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6039 /// if the trip count is very large (>= 2^32). 6040 /// 6041 /// As explained in the comments for getSmallConstantTripCount, this assumes 6042 /// that control exits the loop via ExitingBlock. 6043 unsigned 6044 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6045 BasicBlock *ExitingBlock) { 6046 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6047 assert(L->isLoopExiting(ExitingBlock) && 6048 "Exiting block must actually branch out of the loop!"); 6049 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6050 if (ExitCount == getCouldNotCompute()) 6051 return 1; 6052 6053 // Get the trip count from the BE count by adding 1. 6054 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6055 6056 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6057 if (!TC) 6058 // Attempt to factor more general cases. Returns the greatest power of 6059 // two divisor. If overflow happens, the trip count expression is still 6060 // divisible by the greatest power of 2 divisor returned. 6061 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6062 6063 ConstantInt *Result = TC->getValue(); 6064 6065 // Guard against huge trip counts (this requires checking 6066 // for zero to handle the case where the trip count == -1 and the 6067 // addition wraps). 6068 if (!Result || Result->getValue().getActiveBits() > 32 || 6069 Result->getValue().getActiveBits() == 0) 6070 return 1; 6071 6072 return (unsigned)Result->getZExtValue(); 6073 } 6074 6075 /// Get the expression for the number of loop iterations for which this loop is 6076 /// guaranteed not to exit via ExitingBlock. Otherwise return 6077 /// SCEVCouldNotCompute. 6078 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6079 BasicBlock *ExitingBlock) { 6080 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6081 } 6082 6083 const SCEV * 6084 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6085 SCEVUnionPredicate &Preds) { 6086 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6087 } 6088 6089 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6090 return getBackedgeTakenInfo(L).getExact(this); 6091 } 6092 6093 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6094 /// known never to be less than the actual backedge taken count. 6095 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6096 return getBackedgeTakenInfo(L).getMax(this); 6097 } 6098 6099 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6100 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6101 } 6102 6103 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6104 static void 6105 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6106 BasicBlock *Header = L->getHeader(); 6107 6108 // Push all Loop-header PHIs onto the Worklist stack. 6109 for (BasicBlock::iterator I = Header->begin(); 6110 PHINode *PN = dyn_cast<PHINode>(I); ++I) 6111 Worklist.push_back(PN); 6112 } 6113 6114 const ScalarEvolution::BackedgeTakenInfo & 6115 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6116 auto &BTI = getBackedgeTakenInfo(L); 6117 if (BTI.hasFullInfo()) 6118 return BTI; 6119 6120 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6121 6122 if (!Pair.second) 6123 return Pair.first->second; 6124 6125 BackedgeTakenInfo Result = 6126 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6127 6128 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6129 } 6130 6131 const ScalarEvolution::BackedgeTakenInfo & 6132 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6133 // Initially insert an invalid entry for this loop. If the insertion 6134 // succeeds, proceed to actually compute a backedge-taken count and 6135 // update the value. The temporary CouldNotCompute value tells SCEV 6136 // code elsewhere that it shouldn't attempt to request a new 6137 // backedge-taken count, which could result in infinite recursion. 6138 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6139 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6140 if (!Pair.second) 6141 return Pair.first->second; 6142 6143 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6144 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6145 // must be cleared in this scope. 6146 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6147 6148 if (Result.getExact(this) != getCouldNotCompute()) { 6149 assert(isLoopInvariant(Result.getExact(this), L) && 6150 isLoopInvariant(Result.getMax(this), L) && 6151 "Computed backedge-taken count isn't loop invariant for loop!"); 6152 ++NumTripCountsComputed; 6153 } 6154 else if (Result.getMax(this) == getCouldNotCompute() && 6155 isa<PHINode>(L->getHeader()->begin())) { 6156 // Only count loops that have phi nodes as not being computable. 6157 ++NumTripCountsNotComputed; 6158 } 6159 6160 // Now that we know more about the trip count for this loop, forget any 6161 // existing SCEV values for PHI nodes in this loop since they are only 6162 // conservative estimates made without the benefit of trip count 6163 // information. This is similar to the code in forgetLoop, except that 6164 // it handles SCEVUnknown PHI nodes specially. 6165 if (Result.hasAnyInfo()) { 6166 SmallVector<Instruction *, 16> Worklist; 6167 PushLoopPHIs(L, Worklist); 6168 6169 SmallPtrSet<Instruction *, 8> Visited; 6170 while (!Worklist.empty()) { 6171 Instruction *I = Worklist.pop_back_val(); 6172 if (!Visited.insert(I).second) 6173 continue; 6174 6175 ValueExprMapType::iterator It = 6176 ValueExprMap.find_as(static_cast<Value *>(I)); 6177 if (It != ValueExprMap.end()) { 6178 const SCEV *Old = It->second; 6179 6180 // SCEVUnknown for a PHI either means that it has an unrecognized 6181 // structure, or it's a PHI that's in the progress of being computed 6182 // by createNodeForPHI. In the former case, additional loop trip 6183 // count information isn't going to change anything. In the later 6184 // case, createNodeForPHI will perform the necessary updates on its 6185 // own when it gets to that point. 6186 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6187 eraseValueFromMap(It->first); 6188 forgetMemoizedResults(Old); 6189 } 6190 if (PHINode *PN = dyn_cast<PHINode>(I)) 6191 ConstantEvolutionLoopExitValue.erase(PN); 6192 } 6193 6194 PushDefUseChildren(I, Worklist); 6195 } 6196 } 6197 6198 // Re-lookup the insert position, since the call to 6199 // computeBackedgeTakenCount above could result in a 6200 // recusive call to getBackedgeTakenInfo (on a different 6201 // loop), which would invalidate the iterator computed 6202 // earlier. 6203 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6204 } 6205 6206 void ScalarEvolution::forgetLoop(const Loop *L) { 6207 // Drop any stored trip count value. 6208 auto RemoveLoopFromBackedgeMap = 6209 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 6210 auto BTCPos = Map.find(L); 6211 if (BTCPos != Map.end()) { 6212 BTCPos->second.clear(); 6213 Map.erase(BTCPos); 6214 } 6215 }; 6216 6217 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 6218 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 6219 6220 // Drop information about predicated SCEV rewrites for this loop. 6221 for (auto I = PredicatedSCEVRewrites.begin(); 6222 I != PredicatedSCEVRewrites.end();) { 6223 std::pair<const SCEV *, const Loop *> Entry = I->first; 6224 if (Entry.second == L) 6225 PredicatedSCEVRewrites.erase(I++); 6226 else 6227 ++I; 6228 } 6229 6230 // Drop information about expressions based on loop-header PHIs. 6231 SmallVector<Instruction *, 16> Worklist; 6232 PushLoopPHIs(L, Worklist); 6233 6234 SmallPtrSet<Instruction *, 8> Visited; 6235 while (!Worklist.empty()) { 6236 Instruction *I = Worklist.pop_back_val(); 6237 if (!Visited.insert(I).second) 6238 continue; 6239 6240 ValueExprMapType::iterator It = 6241 ValueExprMap.find_as(static_cast<Value *>(I)); 6242 if (It != ValueExprMap.end()) { 6243 eraseValueFromMap(It->first); 6244 forgetMemoizedResults(It->second); 6245 if (PHINode *PN = dyn_cast<PHINode>(I)) 6246 ConstantEvolutionLoopExitValue.erase(PN); 6247 } 6248 6249 PushDefUseChildren(I, Worklist); 6250 } 6251 6252 // Forget all contained loops too, to avoid dangling entries in the 6253 // ValuesAtScopes map. 6254 for (Loop *I : *L) 6255 forgetLoop(I); 6256 6257 LoopPropertiesCache.erase(L); 6258 } 6259 6260 void ScalarEvolution::forgetValue(Value *V) { 6261 Instruction *I = dyn_cast<Instruction>(V); 6262 if (!I) return; 6263 6264 // Drop information about expressions based on loop-header PHIs. 6265 SmallVector<Instruction *, 16> Worklist; 6266 Worklist.push_back(I); 6267 6268 SmallPtrSet<Instruction *, 8> Visited; 6269 while (!Worklist.empty()) { 6270 I = Worklist.pop_back_val(); 6271 if (!Visited.insert(I).second) 6272 continue; 6273 6274 ValueExprMapType::iterator It = 6275 ValueExprMap.find_as(static_cast<Value *>(I)); 6276 if (It != ValueExprMap.end()) { 6277 eraseValueFromMap(It->first); 6278 forgetMemoizedResults(It->second); 6279 if (PHINode *PN = dyn_cast<PHINode>(I)) 6280 ConstantEvolutionLoopExitValue.erase(PN); 6281 } 6282 6283 PushDefUseChildren(I, Worklist); 6284 } 6285 } 6286 6287 /// Get the exact loop backedge taken count considering all loop exits. A 6288 /// computable result can only be returned for loops with a single exit. 6289 /// Returning the minimum taken count among all exits is incorrect because one 6290 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6291 /// the limit of each loop test is never skipped. This is a valid assumption as 6292 /// long as the loop exits via that test. For precise results, it is the 6293 /// caller's responsibility to specify the relevant loop exit using 6294 /// getExact(ExitingBlock, SE). 6295 const SCEV * 6296 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6297 SCEVUnionPredicate *Preds) const { 6298 // If any exits were not computable, the loop is not computable. 6299 if (!isComplete() || ExitNotTaken.empty()) 6300 return SE->getCouldNotCompute(); 6301 6302 const SCEV *BECount = nullptr; 6303 for (auto &ENT : ExitNotTaken) { 6304 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6305 6306 if (!BECount) 6307 BECount = ENT.ExactNotTaken; 6308 else if (BECount != ENT.ExactNotTaken) 6309 return SE->getCouldNotCompute(); 6310 if (Preds && !ENT.hasAlwaysTruePredicate()) 6311 Preds->add(ENT.Predicate.get()); 6312 6313 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6314 "Predicate should be always true!"); 6315 } 6316 6317 assert(BECount && "Invalid not taken count for loop exit"); 6318 return BECount; 6319 } 6320 6321 /// Get the exact not taken count for this loop exit. 6322 const SCEV * 6323 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6324 ScalarEvolution *SE) const { 6325 for (auto &ENT : ExitNotTaken) 6326 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6327 return ENT.ExactNotTaken; 6328 6329 return SE->getCouldNotCompute(); 6330 } 6331 6332 /// getMax - Get the max backedge taken count for the loop. 6333 const SCEV * 6334 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6335 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6336 return !ENT.hasAlwaysTruePredicate(); 6337 }; 6338 6339 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6340 return SE->getCouldNotCompute(); 6341 6342 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6343 "No point in having a non-constant max backedge taken count!"); 6344 return getMax(); 6345 } 6346 6347 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6348 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6349 return !ENT.hasAlwaysTruePredicate(); 6350 }; 6351 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6352 } 6353 6354 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6355 ScalarEvolution *SE) const { 6356 if (getMax() && getMax() != SE->getCouldNotCompute() && 6357 SE->hasOperand(getMax(), S)) 6358 return true; 6359 6360 for (auto &ENT : ExitNotTaken) 6361 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6362 SE->hasOperand(ENT.ExactNotTaken, S)) 6363 return true; 6364 6365 return false; 6366 } 6367 6368 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6369 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) { 6370 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6371 isa<SCEVConstant>(MaxNotTaken)) && 6372 "No point in having a non-constant max backedge taken count!"); 6373 } 6374 6375 ScalarEvolution::ExitLimit::ExitLimit( 6376 const SCEV *E, const SCEV *M, bool MaxOrZero, 6377 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6378 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6379 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6380 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6381 "Exact is not allowed to be less precise than Max"); 6382 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6383 isa<SCEVConstant>(MaxNotTaken)) && 6384 "No point in having a non-constant max backedge taken count!"); 6385 for (auto *PredSet : PredSetList) 6386 for (auto *P : *PredSet) 6387 addPredicate(P); 6388 } 6389 6390 ScalarEvolution::ExitLimit::ExitLimit( 6391 const SCEV *E, const SCEV *M, bool MaxOrZero, 6392 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6393 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6394 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6395 isa<SCEVConstant>(MaxNotTaken)) && 6396 "No point in having a non-constant max backedge taken count!"); 6397 } 6398 6399 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6400 bool MaxOrZero) 6401 : ExitLimit(E, M, MaxOrZero, None) { 6402 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6403 isa<SCEVConstant>(MaxNotTaken)) && 6404 "No point in having a non-constant max backedge taken count!"); 6405 } 6406 6407 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6408 /// computable exit into a persistent ExitNotTakenInfo array. 6409 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6410 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6411 &&ExitCounts, 6412 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6413 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6414 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 6415 ExitNotTaken.reserve(ExitCounts.size()); 6416 std::transform( 6417 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6418 [&](const EdgeExitInfo &EEI) { 6419 BasicBlock *ExitBB = EEI.first; 6420 const ExitLimit &EL = EEI.second; 6421 if (EL.Predicates.empty()) 6422 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6423 6424 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6425 for (auto *Pred : EL.Predicates) 6426 Predicate->add(Pred); 6427 6428 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6429 }); 6430 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6431 "No point in having a non-constant max backedge taken count!"); 6432 } 6433 6434 /// Invalidate this result and free the ExitNotTakenInfo array. 6435 void ScalarEvolution::BackedgeTakenInfo::clear() { 6436 ExitNotTaken.clear(); 6437 } 6438 6439 /// Compute the number of times the backedge of the specified loop will execute. 6440 ScalarEvolution::BackedgeTakenInfo 6441 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6442 bool AllowPredicates) { 6443 SmallVector<BasicBlock *, 8> ExitingBlocks; 6444 L->getExitingBlocks(ExitingBlocks); 6445 6446 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 6447 6448 SmallVector<EdgeExitInfo, 4> ExitCounts; 6449 bool CouldComputeBECount = true; 6450 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6451 const SCEV *MustExitMaxBECount = nullptr; 6452 const SCEV *MayExitMaxBECount = nullptr; 6453 bool MustExitMaxOrZero = false; 6454 6455 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6456 // and compute maxBECount. 6457 // Do a union of all the predicates here. 6458 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6459 BasicBlock *ExitBB = ExitingBlocks[i]; 6460 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6461 6462 assert((AllowPredicates || EL.Predicates.empty()) && 6463 "Predicated exit limit when predicates are not allowed!"); 6464 6465 // 1. For each exit that can be computed, add an entry to ExitCounts. 6466 // CouldComputeBECount is true only if all exits can be computed. 6467 if (EL.ExactNotTaken == getCouldNotCompute()) 6468 // We couldn't compute an exact value for this exit, so 6469 // we won't be able to compute an exact value for the loop. 6470 CouldComputeBECount = false; 6471 else 6472 ExitCounts.emplace_back(ExitBB, EL); 6473 6474 // 2. Derive the loop's MaxBECount from each exit's max number of 6475 // non-exiting iterations. Partition the loop exits into two kinds: 6476 // LoopMustExits and LoopMayExits. 6477 // 6478 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6479 // is a LoopMayExit. If any computable LoopMustExit is found, then 6480 // MaxBECount is the minimum EL.MaxNotTaken of computable 6481 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6482 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6483 // computable EL.MaxNotTaken. 6484 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6485 DT.dominates(ExitBB, Latch)) { 6486 if (!MustExitMaxBECount) { 6487 MustExitMaxBECount = EL.MaxNotTaken; 6488 MustExitMaxOrZero = EL.MaxOrZero; 6489 } else { 6490 MustExitMaxBECount = 6491 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6492 } 6493 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6494 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6495 MayExitMaxBECount = EL.MaxNotTaken; 6496 else { 6497 MayExitMaxBECount = 6498 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6499 } 6500 } 6501 } 6502 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6503 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6504 // The loop backedge will be taken the maximum or zero times if there's 6505 // a single exit that must be taken the maximum or zero times. 6506 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6507 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6508 MaxBECount, MaxOrZero); 6509 } 6510 6511 ScalarEvolution::ExitLimit 6512 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6513 bool AllowPredicates) { 6514 6515 // Okay, we've chosen an exiting block. See what condition causes us to exit 6516 // at this block and remember the exit block and whether all other targets 6517 // lead to the loop header. 6518 bool MustExecuteLoopHeader = true; 6519 BasicBlock *Exit = nullptr; 6520 for (auto *SBB : successors(ExitingBlock)) 6521 if (!L->contains(SBB)) { 6522 if (Exit) // Multiple exit successors. 6523 return getCouldNotCompute(); 6524 Exit = SBB; 6525 } else if (SBB != L->getHeader()) { 6526 MustExecuteLoopHeader = false; 6527 } 6528 6529 // At this point, we know we have a conditional branch that determines whether 6530 // the loop is exited. However, we don't know if the branch is executed each 6531 // time through the loop. If not, then the execution count of the branch will 6532 // not be equal to the trip count of the loop. 6533 // 6534 // Currently we check for this by checking to see if the Exit branch goes to 6535 // the loop header. If so, we know it will always execute the same number of 6536 // times as the loop. We also handle the case where the exit block *is* the 6537 // loop header. This is common for un-rotated loops. 6538 // 6539 // If both of those tests fail, walk up the unique predecessor chain to the 6540 // header, stopping if there is an edge that doesn't exit the loop. If the 6541 // header is reached, the execution count of the branch will be equal to the 6542 // trip count of the loop. 6543 // 6544 // More extensive analysis could be done to handle more cases here. 6545 // 6546 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6547 // The simple checks failed, try climbing the unique predecessor chain 6548 // up to the header. 6549 bool Ok = false; 6550 for (BasicBlock *BB = ExitingBlock; BB; ) { 6551 BasicBlock *Pred = BB->getUniquePredecessor(); 6552 if (!Pred) 6553 return getCouldNotCompute(); 6554 TerminatorInst *PredTerm = Pred->getTerminator(); 6555 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6556 if (PredSucc == BB) 6557 continue; 6558 // If the predecessor has a successor that isn't BB and isn't 6559 // outside the loop, assume the worst. 6560 if (L->contains(PredSucc)) 6561 return getCouldNotCompute(); 6562 } 6563 if (Pred == L->getHeader()) { 6564 Ok = true; 6565 break; 6566 } 6567 BB = Pred; 6568 } 6569 if (!Ok) 6570 return getCouldNotCompute(); 6571 } 6572 6573 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6574 TerminatorInst *Term = ExitingBlock->getTerminator(); 6575 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6576 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6577 // Proceed to the next level to examine the exit condition expression. 6578 return computeExitLimitFromCond( 6579 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6580 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6581 } 6582 6583 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6584 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6585 /*ControlsExit=*/IsOnlyExit); 6586 6587 return getCouldNotCompute(); 6588 } 6589 6590 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6591 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6592 bool ControlsExit, bool AllowPredicates) { 6593 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6594 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6595 ControlsExit, AllowPredicates); 6596 } 6597 6598 Optional<ScalarEvolution::ExitLimit> 6599 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6600 BasicBlock *TBB, BasicBlock *FBB, 6601 bool ControlsExit, bool AllowPredicates) { 6602 (void)this->L; 6603 (void)this->TBB; 6604 (void)this->FBB; 6605 (void)this->AllowPredicates; 6606 6607 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6608 this->AllowPredicates == AllowPredicates && 6609 "Variance in assumed invariant key components!"); 6610 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6611 if (Itr == TripCountMap.end()) 6612 return None; 6613 return Itr->second; 6614 } 6615 6616 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6617 BasicBlock *TBB, BasicBlock *FBB, 6618 bool ControlsExit, 6619 bool AllowPredicates, 6620 const ExitLimit &EL) { 6621 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6622 this->AllowPredicates == AllowPredicates && 6623 "Variance in assumed invariant key components!"); 6624 6625 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6626 assert(InsertResult.second && "Expected successful insertion!"); 6627 (void)InsertResult; 6628 } 6629 6630 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6631 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6632 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6633 6634 if (auto MaybeEL = 6635 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6636 return *MaybeEL; 6637 6638 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6639 ControlsExit, AllowPredicates); 6640 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6641 return EL; 6642 } 6643 6644 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6645 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6646 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6647 // Check if the controlling expression for this loop is an And or Or. 6648 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6649 if (BO->getOpcode() == Instruction::And) { 6650 // Recurse on the operands of the and. 6651 bool EitherMayExit = L->contains(TBB); 6652 ExitLimit EL0 = computeExitLimitFromCondCached( 6653 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6654 AllowPredicates); 6655 ExitLimit EL1 = computeExitLimitFromCondCached( 6656 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6657 AllowPredicates); 6658 const SCEV *BECount = getCouldNotCompute(); 6659 const SCEV *MaxBECount = getCouldNotCompute(); 6660 if (EitherMayExit) { 6661 // Both conditions must be true for the loop to continue executing. 6662 // Choose the less conservative count. 6663 if (EL0.ExactNotTaken == getCouldNotCompute() || 6664 EL1.ExactNotTaken == getCouldNotCompute()) 6665 BECount = getCouldNotCompute(); 6666 else 6667 BECount = 6668 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6669 if (EL0.MaxNotTaken == getCouldNotCompute()) 6670 MaxBECount = EL1.MaxNotTaken; 6671 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6672 MaxBECount = EL0.MaxNotTaken; 6673 else 6674 MaxBECount = 6675 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6676 } else { 6677 // Both conditions must be true at the same time for the loop to exit. 6678 // For now, be conservative. 6679 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6680 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6681 MaxBECount = EL0.MaxNotTaken; 6682 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6683 BECount = EL0.ExactNotTaken; 6684 } 6685 6686 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6687 // to be more aggressive when computing BECount than when computing 6688 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6689 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6690 // to not. 6691 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6692 !isa<SCEVCouldNotCompute>(BECount)) 6693 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 6694 6695 return ExitLimit(BECount, MaxBECount, false, 6696 {&EL0.Predicates, &EL1.Predicates}); 6697 } 6698 if (BO->getOpcode() == Instruction::Or) { 6699 // Recurse on the operands of the or. 6700 bool EitherMayExit = L->contains(FBB); 6701 ExitLimit EL0 = computeExitLimitFromCondCached( 6702 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6703 AllowPredicates); 6704 ExitLimit EL1 = computeExitLimitFromCondCached( 6705 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6706 AllowPredicates); 6707 const SCEV *BECount = getCouldNotCompute(); 6708 const SCEV *MaxBECount = getCouldNotCompute(); 6709 if (EitherMayExit) { 6710 // Both conditions must be false for the loop to continue executing. 6711 // Choose the less conservative count. 6712 if (EL0.ExactNotTaken == getCouldNotCompute() || 6713 EL1.ExactNotTaken == getCouldNotCompute()) 6714 BECount = getCouldNotCompute(); 6715 else 6716 BECount = 6717 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6718 if (EL0.MaxNotTaken == getCouldNotCompute()) 6719 MaxBECount = EL1.MaxNotTaken; 6720 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6721 MaxBECount = EL0.MaxNotTaken; 6722 else 6723 MaxBECount = 6724 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6725 } else { 6726 // Both conditions must be false at the same time for the loop to exit. 6727 // For now, be conservative. 6728 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6729 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6730 MaxBECount = EL0.MaxNotTaken; 6731 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6732 BECount = EL0.ExactNotTaken; 6733 } 6734 6735 return ExitLimit(BECount, MaxBECount, false, 6736 {&EL0.Predicates, &EL1.Predicates}); 6737 } 6738 } 6739 6740 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6741 // Proceed to the next level to examine the icmp. 6742 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6743 ExitLimit EL = 6744 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6745 if (EL.hasFullInfo() || !AllowPredicates) 6746 return EL; 6747 6748 // Try again, but use SCEV predicates this time. 6749 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6750 /*AllowPredicates=*/true); 6751 } 6752 6753 // Check for a constant condition. These are normally stripped out by 6754 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6755 // preserve the CFG and is temporarily leaving constant conditions 6756 // in place. 6757 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6758 if (L->contains(FBB) == !CI->getZExtValue()) 6759 // The backedge is always taken. 6760 return getCouldNotCompute(); 6761 else 6762 // The backedge is never taken. 6763 return getZero(CI->getType()); 6764 } 6765 6766 // If it's not an integer or pointer comparison then compute it the hard way. 6767 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6768 } 6769 6770 ScalarEvolution::ExitLimit 6771 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6772 ICmpInst *ExitCond, 6773 BasicBlock *TBB, 6774 BasicBlock *FBB, 6775 bool ControlsExit, 6776 bool AllowPredicates) { 6777 6778 // If the condition was exit on true, convert the condition to exit on false 6779 ICmpInst::Predicate Cond; 6780 if (!L->contains(FBB)) 6781 Cond = ExitCond->getPredicate(); 6782 else 6783 Cond = ExitCond->getInversePredicate(); 6784 6785 // Handle common loops like: for (X = "string"; *X; ++X) 6786 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6787 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6788 ExitLimit ItCnt = 6789 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6790 if (ItCnt.hasAnyInfo()) 6791 return ItCnt; 6792 } 6793 6794 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6795 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6796 6797 // Try to evaluate any dependencies out of the loop. 6798 LHS = getSCEVAtScope(LHS, L); 6799 RHS = getSCEVAtScope(RHS, L); 6800 6801 // At this point, we would like to compute how many iterations of the 6802 // loop the predicate will return true for these inputs. 6803 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6804 // If there is a loop-invariant, force it into the RHS. 6805 std::swap(LHS, RHS); 6806 Cond = ICmpInst::getSwappedPredicate(Cond); 6807 } 6808 6809 // Simplify the operands before analyzing them. 6810 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6811 6812 // If we have a comparison of a chrec against a constant, try to use value 6813 // ranges to answer this query. 6814 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6815 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6816 if (AddRec->getLoop() == L) { 6817 // Form the constant range. 6818 ConstantRange CompRange = 6819 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6820 6821 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6822 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6823 } 6824 6825 switch (Cond) { 6826 case ICmpInst::ICMP_NE: { // while (X != Y) 6827 // Convert to: while (X-Y != 0) 6828 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6829 AllowPredicates); 6830 if (EL.hasAnyInfo()) return EL; 6831 break; 6832 } 6833 case ICmpInst::ICMP_EQ: { // while (X == Y) 6834 // Convert to: while (X-Y == 0) 6835 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6836 if (EL.hasAnyInfo()) return EL; 6837 break; 6838 } 6839 case ICmpInst::ICMP_SLT: 6840 case ICmpInst::ICMP_ULT: { // while (X < Y) 6841 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6842 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6843 AllowPredicates); 6844 if (EL.hasAnyInfo()) return EL; 6845 break; 6846 } 6847 case ICmpInst::ICMP_SGT: 6848 case ICmpInst::ICMP_UGT: { // while (X > Y) 6849 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6850 ExitLimit EL = 6851 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6852 AllowPredicates); 6853 if (EL.hasAnyInfo()) return EL; 6854 break; 6855 } 6856 default: 6857 break; 6858 } 6859 6860 auto *ExhaustiveCount = 6861 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6862 6863 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6864 return ExhaustiveCount; 6865 6866 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6867 ExitCond->getOperand(1), L, Cond); 6868 } 6869 6870 ScalarEvolution::ExitLimit 6871 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6872 SwitchInst *Switch, 6873 BasicBlock *ExitingBlock, 6874 bool ControlsExit) { 6875 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6876 6877 // Give up if the exit is the default dest of a switch. 6878 if (Switch->getDefaultDest() == ExitingBlock) 6879 return getCouldNotCompute(); 6880 6881 assert(L->contains(Switch->getDefaultDest()) && 6882 "Default case must not exit the loop!"); 6883 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6884 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6885 6886 // while (X != Y) --> while (X-Y != 0) 6887 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6888 if (EL.hasAnyInfo()) 6889 return EL; 6890 6891 return getCouldNotCompute(); 6892 } 6893 6894 static ConstantInt * 6895 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6896 ScalarEvolution &SE) { 6897 const SCEV *InVal = SE.getConstant(C); 6898 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6899 assert(isa<SCEVConstant>(Val) && 6900 "Evaluation of SCEV at constant didn't fold correctly?"); 6901 return cast<SCEVConstant>(Val)->getValue(); 6902 } 6903 6904 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6905 /// compute the backedge execution count. 6906 ScalarEvolution::ExitLimit 6907 ScalarEvolution::computeLoadConstantCompareExitLimit( 6908 LoadInst *LI, 6909 Constant *RHS, 6910 const Loop *L, 6911 ICmpInst::Predicate predicate) { 6912 6913 if (LI->isVolatile()) return getCouldNotCompute(); 6914 6915 // Check to see if the loaded pointer is a getelementptr of a global. 6916 // TODO: Use SCEV instead of manually grubbing with GEPs. 6917 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6918 if (!GEP) return getCouldNotCompute(); 6919 6920 // Make sure that it is really a constant global we are gepping, with an 6921 // initializer, and make sure the first IDX is really 0. 6922 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6923 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6924 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6925 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6926 return getCouldNotCompute(); 6927 6928 // Okay, we allow one non-constant index into the GEP instruction. 6929 Value *VarIdx = nullptr; 6930 std::vector<Constant*> Indexes; 6931 unsigned VarIdxNum = 0; 6932 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6933 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6934 Indexes.push_back(CI); 6935 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6936 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6937 VarIdx = GEP->getOperand(i); 6938 VarIdxNum = i-2; 6939 Indexes.push_back(nullptr); 6940 } 6941 6942 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6943 if (!VarIdx) 6944 return getCouldNotCompute(); 6945 6946 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6947 // Check to see if X is a loop variant variable value now. 6948 const SCEV *Idx = getSCEV(VarIdx); 6949 Idx = getSCEVAtScope(Idx, L); 6950 6951 // We can only recognize very limited forms of loop index expressions, in 6952 // particular, only affine AddRec's like {C1,+,C2}. 6953 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6954 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6955 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6956 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6957 return getCouldNotCompute(); 6958 6959 unsigned MaxSteps = MaxBruteForceIterations; 6960 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6961 ConstantInt *ItCst = ConstantInt::get( 6962 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6963 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6964 6965 // Form the GEP offset. 6966 Indexes[VarIdxNum] = Val; 6967 6968 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6969 Indexes); 6970 if (!Result) break; // Cannot compute! 6971 6972 // Evaluate the condition for this iteration. 6973 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6974 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6975 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6976 ++NumArrayLenItCounts; 6977 return getConstant(ItCst); // Found terminating iteration! 6978 } 6979 } 6980 return getCouldNotCompute(); 6981 } 6982 6983 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6984 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6985 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6986 if (!RHS) 6987 return getCouldNotCompute(); 6988 6989 const BasicBlock *Latch = L->getLoopLatch(); 6990 if (!Latch) 6991 return getCouldNotCompute(); 6992 6993 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6994 if (!Predecessor) 6995 return getCouldNotCompute(); 6996 6997 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6998 // Return LHS in OutLHS and shift_opt in OutOpCode. 6999 auto MatchPositiveShift = 7000 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7001 7002 using namespace PatternMatch; 7003 7004 ConstantInt *ShiftAmt; 7005 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7006 OutOpCode = Instruction::LShr; 7007 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7008 OutOpCode = Instruction::AShr; 7009 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7010 OutOpCode = Instruction::Shl; 7011 else 7012 return false; 7013 7014 return ShiftAmt->getValue().isStrictlyPositive(); 7015 }; 7016 7017 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7018 // 7019 // loop: 7020 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7021 // %iv.shifted = lshr i32 %iv, <positive constant> 7022 // 7023 // Return true on a successful match. Return the corresponding PHI node (%iv 7024 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7025 auto MatchShiftRecurrence = 7026 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7027 Optional<Instruction::BinaryOps> PostShiftOpCode; 7028 7029 { 7030 Instruction::BinaryOps OpC; 7031 Value *V; 7032 7033 // If we encounter a shift instruction, "peel off" the shift operation, 7034 // and remember that we did so. Later when we inspect %iv's backedge 7035 // value, we will make sure that the backedge value uses the same 7036 // operation. 7037 // 7038 // Note: the peeled shift operation does not have to be the same 7039 // instruction as the one feeding into the PHI's backedge value. We only 7040 // really care about it being the same *kind* of shift instruction -- 7041 // that's all that is required for our later inferences to hold. 7042 if (MatchPositiveShift(LHS, V, OpC)) { 7043 PostShiftOpCode = OpC; 7044 LHS = V; 7045 } 7046 } 7047 7048 PNOut = dyn_cast<PHINode>(LHS); 7049 if (!PNOut || PNOut->getParent() != L->getHeader()) 7050 return false; 7051 7052 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7053 Value *OpLHS; 7054 7055 return 7056 // The backedge value for the PHI node must be a shift by a positive 7057 // amount 7058 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7059 7060 // of the PHI node itself 7061 OpLHS == PNOut && 7062 7063 // and the kind of shift should be match the kind of shift we peeled 7064 // off, if any. 7065 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7066 }; 7067 7068 PHINode *PN; 7069 Instruction::BinaryOps OpCode; 7070 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7071 return getCouldNotCompute(); 7072 7073 const DataLayout &DL = getDataLayout(); 7074 7075 // The key rationale for this optimization is that for some kinds of shift 7076 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7077 // within a finite number of iterations. If the condition guarding the 7078 // backedge (in the sense that the backedge is taken if the condition is true) 7079 // is false for the value the shift recurrence stabilizes to, then we know 7080 // that the backedge is taken only a finite number of times. 7081 7082 ConstantInt *StableValue = nullptr; 7083 switch (OpCode) { 7084 default: 7085 llvm_unreachable("Impossible case!"); 7086 7087 case Instruction::AShr: { 7088 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7089 // bitwidth(K) iterations. 7090 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7091 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7092 Predecessor->getTerminator(), &DT); 7093 auto *Ty = cast<IntegerType>(RHS->getType()); 7094 if (Known.isNonNegative()) 7095 StableValue = ConstantInt::get(Ty, 0); 7096 else if (Known.isNegative()) 7097 StableValue = ConstantInt::get(Ty, -1, true); 7098 else 7099 return getCouldNotCompute(); 7100 7101 break; 7102 } 7103 case Instruction::LShr: 7104 case Instruction::Shl: 7105 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7106 // stabilize to 0 in at most bitwidth(K) iterations. 7107 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7108 break; 7109 } 7110 7111 auto *Result = 7112 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7113 assert(Result->getType()->isIntegerTy(1) && 7114 "Otherwise cannot be an operand to a branch instruction"); 7115 7116 if (Result->isZeroValue()) { 7117 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7118 const SCEV *UpperBound = 7119 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7120 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7121 } 7122 7123 return getCouldNotCompute(); 7124 } 7125 7126 /// Return true if we can constant fold an instruction of the specified type, 7127 /// assuming that all operands were constants. 7128 static bool CanConstantFold(const Instruction *I) { 7129 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7130 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7131 isa<LoadInst>(I)) 7132 return true; 7133 7134 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7135 if (const Function *F = CI->getCalledFunction()) 7136 return canConstantFoldCallTo(CI, F); 7137 return false; 7138 } 7139 7140 /// Determine whether this instruction can constant evolve within this loop 7141 /// assuming its operands can all constant evolve. 7142 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7143 // An instruction outside of the loop can't be derived from a loop PHI. 7144 if (!L->contains(I)) return false; 7145 7146 if (isa<PHINode>(I)) { 7147 // We don't currently keep track of the control flow needed to evaluate 7148 // PHIs, so we cannot handle PHIs inside of loops. 7149 return L->getHeader() == I->getParent(); 7150 } 7151 7152 // If we won't be able to constant fold this expression even if the operands 7153 // are constants, bail early. 7154 return CanConstantFold(I); 7155 } 7156 7157 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7158 /// recursing through each instruction operand until reaching a loop header phi. 7159 static PHINode * 7160 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7161 DenseMap<Instruction *, PHINode *> &PHIMap, 7162 unsigned Depth) { 7163 if (Depth > MaxConstantEvolvingDepth) 7164 return nullptr; 7165 7166 // Otherwise, we can evaluate this instruction if all of its operands are 7167 // constant or derived from a PHI node themselves. 7168 PHINode *PHI = nullptr; 7169 for (Value *Op : UseInst->operands()) { 7170 if (isa<Constant>(Op)) continue; 7171 7172 Instruction *OpInst = dyn_cast<Instruction>(Op); 7173 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7174 7175 PHINode *P = dyn_cast<PHINode>(OpInst); 7176 if (!P) 7177 // If this operand is already visited, reuse the prior result. 7178 // We may have P != PHI if this is the deepest point at which the 7179 // inconsistent paths meet. 7180 P = PHIMap.lookup(OpInst); 7181 if (!P) { 7182 // Recurse and memoize the results, whether a phi is found or not. 7183 // This recursive call invalidates pointers into PHIMap. 7184 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7185 PHIMap[OpInst] = P; 7186 } 7187 if (!P) 7188 return nullptr; // Not evolving from PHI 7189 if (PHI && PHI != P) 7190 return nullptr; // Evolving from multiple different PHIs. 7191 PHI = P; 7192 } 7193 // This is a expression evolving from a constant PHI! 7194 return PHI; 7195 } 7196 7197 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7198 /// in the loop that V is derived from. We allow arbitrary operations along the 7199 /// way, but the operands of an operation must either be constants or a value 7200 /// derived from a constant PHI. If this expression does not fit with these 7201 /// constraints, return null. 7202 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7203 Instruction *I = dyn_cast<Instruction>(V); 7204 if (!I || !canConstantEvolve(I, L)) return nullptr; 7205 7206 if (PHINode *PN = dyn_cast<PHINode>(I)) 7207 return PN; 7208 7209 // Record non-constant instructions contained by the loop. 7210 DenseMap<Instruction *, PHINode *> PHIMap; 7211 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7212 } 7213 7214 /// EvaluateExpression - Given an expression that passes the 7215 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7216 /// in the loop has the value PHIVal. If we can't fold this expression for some 7217 /// reason, return null. 7218 static Constant *EvaluateExpression(Value *V, const Loop *L, 7219 DenseMap<Instruction *, Constant *> &Vals, 7220 const DataLayout &DL, 7221 const TargetLibraryInfo *TLI) { 7222 // Convenient constant check, but redundant for recursive calls. 7223 if (Constant *C = dyn_cast<Constant>(V)) return C; 7224 Instruction *I = dyn_cast<Instruction>(V); 7225 if (!I) return nullptr; 7226 7227 if (Constant *C = Vals.lookup(I)) return C; 7228 7229 // An instruction inside the loop depends on a value outside the loop that we 7230 // weren't given a mapping for, or a value such as a call inside the loop. 7231 if (!canConstantEvolve(I, L)) return nullptr; 7232 7233 // An unmapped PHI can be due to a branch or another loop inside this loop, 7234 // or due to this not being the initial iteration through a loop where we 7235 // couldn't compute the evolution of this particular PHI last time. 7236 if (isa<PHINode>(I)) return nullptr; 7237 7238 std::vector<Constant*> Operands(I->getNumOperands()); 7239 7240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7241 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7242 if (!Operand) { 7243 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7244 if (!Operands[i]) return nullptr; 7245 continue; 7246 } 7247 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7248 Vals[Operand] = C; 7249 if (!C) return nullptr; 7250 Operands[i] = C; 7251 } 7252 7253 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7254 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7255 Operands[1], DL, TLI); 7256 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7257 if (!LI->isVolatile()) 7258 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7259 } 7260 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7261 } 7262 7263 7264 // If every incoming value to PN except the one for BB is a specific Constant, 7265 // return that, else return nullptr. 7266 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7267 Constant *IncomingVal = nullptr; 7268 7269 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7270 if (PN->getIncomingBlock(i) == BB) 7271 continue; 7272 7273 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7274 if (!CurrentVal) 7275 return nullptr; 7276 7277 if (IncomingVal != CurrentVal) { 7278 if (IncomingVal) 7279 return nullptr; 7280 IncomingVal = CurrentVal; 7281 } 7282 } 7283 7284 return IncomingVal; 7285 } 7286 7287 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7288 /// in the header of its containing loop, we know the loop executes a 7289 /// constant number of times, and the PHI node is just a recurrence 7290 /// involving constants, fold it. 7291 Constant * 7292 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7293 const APInt &BEs, 7294 const Loop *L) { 7295 auto I = ConstantEvolutionLoopExitValue.find(PN); 7296 if (I != ConstantEvolutionLoopExitValue.end()) 7297 return I->second; 7298 7299 if (BEs.ugt(MaxBruteForceIterations)) 7300 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7301 7302 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7303 7304 DenseMap<Instruction *, Constant *> CurrentIterVals; 7305 BasicBlock *Header = L->getHeader(); 7306 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7307 7308 BasicBlock *Latch = L->getLoopLatch(); 7309 if (!Latch) 7310 return nullptr; 7311 7312 for (auto &I : *Header) { 7313 PHINode *PHI = dyn_cast<PHINode>(&I); 7314 if (!PHI) break; 7315 auto *StartCST = getOtherIncomingValue(PHI, Latch); 7316 if (!StartCST) continue; 7317 CurrentIterVals[PHI] = StartCST; 7318 } 7319 if (!CurrentIterVals.count(PN)) 7320 return RetVal = nullptr; 7321 7322 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7323 7324 // Execute the loop symbolically to determine the exit value. 7325 if (BEs.getActiveBits() >= 32) 7326 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 7327 7328 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7329 unsigned IterationNum = 0; 7330 const DataLayout &DL = getDataLayout(); 7331 for (; ; ++IterationNum) { 7332 if (IterationNum == NumIterations) 7333 return RetVal = CurrentIterVals[PN]; // Got exit value! 7334 7335 // Compute the value of the PHIs for the next iteration. 7336 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7337 DenseMap<Instruction *, Constant *> NextIterVals; 7338 Constant *NextPHI = 7339 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7340 if (!NextPHI) 7341 return nullptr; // Couldn't evaluate! 7342 NextIterVals[PN] = NextPHI; 7343 7344 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7345 7346 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7347 // cease to be able to evaluate one of them or if they stop evolving, 7348 // because that doesn't necessarily prevent us from computing PN. 7349 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7350 for (const auto &I : CurrentIterVals) { 7351 PHINode *PHI = dyn_cast<PHINode>(I.first); 7352 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7353 PHIsToCompute.emplace_back(PHI, I.second); 7354 } 7355 // We use two distinct loops because EvaluateExpression may invalidate any 7356 // iterators into CurrentIterVals. 7357 for (const auto &I : PHIsToCompute) { 7358 PHINode *PHI = I.first; 7359 Constant *&NextPHI = NextIterVals[PHI]; 7360 if (!NextPHI) { // Not already computed. 7361 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7362 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7363 } 7364 if (NextPHI != I.second) 7365 StoppedEvolving = false; 7366 } 7367 7368 // If all entries in CurrentIterVals == NextIterVals then we can stop 7369 // iterating, the loop can't continue to change. 7370 if (StoppedEvolving) 7371 return RetVal = CurrentIterVals[PN]; 7372 7373 CurrentIterVals.swap(NextIterVals); 7374 } 7375 } 7376 7377 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7378 Value *Cond, 7379 bool ExitWhen) { 7380 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7381 if (!PN) return getCouldNotCompute(); 7382 7383 // If the loop is canonicalized, the PHI will have exactly two entries. 7384 // That's the only form we support here. 7385 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7386 7387 DenseMap<Instruction *, Constant *> CurrentIterVals; 7388 BasicBlock *Header = L->getHeader(); 7389 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7390 7391 BasicBlock *Latch = L->getLoopLatch(); 7392 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7393 7394 for (auto &I : *Header) { 7395 PHINode *PHI = dyn_cast<PHINode>(&I); 7396 if (!PHI) 7397 break; 7398 auto *StartCST = getOtherIncomingValue(PHI, Latch); 7399 if (!StartCST) continue; 7400 CurrentIterVals[PHI] = StartCST; 7401 } 7402 if (!CurrentIterVals.count(PN)) 7403 return getCouldNotCompute(); 7404 7405 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7406 // the loop symbolically to determine when the condition gets a value of 7407 // "ExitWhen". 7408 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7409 const DataLayout &DL = getDataLayout(); 7410 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7411 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7412 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7413 7414 // Couldn't symbolically evaluate. 7415 if (!CondVal) return getCouldNotCompute(); 7416 7417 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7418 ++NumBruteForceTripCountsComputed; 7419 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7420 } 7421 7422 // Update all the PHI nodes for the next iteration. 7423 DenseMap<Instruction *, Constant *> NextIterVals; 7424 7425 // Create a list of which PHIs we need to compute. We want to do this before 7426 // calling EvaluateExpression on them because that may invalidate iterators 7427 // into CurrentIterVals. 7428 SmallVector<PHINode *, 8> PHIsToCompute; 7429 for (const auto &I : CurrentIterVals) { 7430 PHINode *PHI = dyn_cast<PHINode>(I.first); 7431 if (!PHI || PHI->getParent() != Header) continue; 7432 PHIsToCompute.push_back(PHI); 7433 } 7434 for (PHINode *PHI : PHIsToCompute) { 7435 Constant *&NextPHI = NextIterVals[PHI]; 7436 if (NextPHI) continue; // Already computed! 7437 7438 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7439 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7440 } 7441 CurrentIterVals.swap(NextIterVals); 7442 } 7443 7444 // Too many iterations were needed to evaluate. 7445 return getCouldNotCompute(); 7446 } 7447 7448 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7449 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7450 ValuesAtScopes[V]; 7451 // Check to see if we've folded this expression at this loop before. 7452 for (auto &LS : Values) 7453 if (LS.first == L) 7454 return LS.second ? LS.second : V; 7455 7456 Values.emplace_back(L, nullptr); 7457 7458 // Otherwise compute it. 7459 const SCEV *C = computeSCEVAtScope(V, L); 7460 for (auto &LS : reverse(ValuesAtScopes[V])) 7461 if (LS.first == L) { 7462 LS.second = C; 7463 break; 7464 } 7465 return C; 7466 } 7467 7468 /// This builds up a Constant using the ConstantExpr interface. That way, we 7469 /// will return Constants for objects which aren't represented by a 7470 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7471 /// Returns NULL if the SCEV isn't representable as a Constant. 7472 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7473 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7474 case scCouldNotCompute: 7475 case scAddRecExpr: 7476 break; 7477 case scConstant: 7478 return cast<SCEVConstant>(V)->getValue(); 7479 case scUnknown: 7480 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7481 case scSignExtend: { 7482 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7483 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7484 return ConstantExpr::getSExt(CastOp, SS->getType()); 7485 break; 7486 } 7487 case scZeroExtend: { 7488 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7489 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7490 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7491 break; 7492 } 7493 case scTruncate: { 7494 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7495 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7496 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7497 break; 7498 } 7499 case scAddExpr: { 7500 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7501 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7502 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7503 unsigned AS = PTy->getAddressSpace(); 7504 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7505 C = ConstantExpr::getBitCast(C, DestPtrTy); 7506 } 7507 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7508 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7509 if (!C2) return nullptr; 7510 7511 // First pointer! 7512 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7513 unsigned AS = C2->getType()->getPointerAddressSpace(); 7514 std::swap(C, C2); 7515 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7516 // The offsets have been converted to bytes. We can add bytes to an 7517 // i8* by GEP with the byte count in the first index. 7518 C = ConstantExpr::getBitCast(C, DestPtrTy); 7519 } 7520 7521 // Don't bother trying to sum two pointers. We probably can't 7522 // statically compute a load that results from it anyway. 7523 if (C2->getType()->isPointerTy()) 7524 return nullptr; 7525 7526 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7527 if (PTy->getElementType()->isStructTy()) 7528 C2 = ConstantExpr::getIntegerCast( 7529 C2, Type::getInt32Ty(C->getContext()), true); 7530 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7531 } else 7532 C = ConstantExpr::getAdd(C, C2); 7533 } 7534 return C; 7535 } 7536 break; 7537 } 7538 case scMulExpr: { 7539 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7540 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7541 // Don't bother with pointers at all. 7542 if (C->getType()->isPointerTy()) return nullptr; 7543 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7544 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7545 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7546 C = ConstantExpr::getMul(C, C2); 7547 } 7548 return C; 7549 } 7550 break; 7551 } 7552 case scUDivExpr: { 7553 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7554 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7555 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7556 if (LHS->getType() == RHS->getType()) 7557 return ConstantExpr::getUDiv(LHS, RHS); 7558 break; 7559 } 7560 case scSMaxExpr: 7561 case scUMaxExpr: 7562 break; // TODO: smax, umax. 7563 } 7564 return nullptr; 7565 } 7566 7567 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7568 if (isa<SCEVConstant>(V)) return V; 7569 7570 // If this instruction is evolved from a constant-evolving PHI, compute the 7571 // exit value from the loop without using SCEVs. 7572 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7573 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7574 const Loop *LI = this->LI[I->getParent()]; 7575 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7576 if (PHINode *PN = dyn_cast<PHINode>(I)) 7577 if (PN->getParent() == LI->getHeader()) { 7578 // Okay, there is no closed form solution for the PHI node. Check 7579 // to see if the loop that contains it has a known backedge-taken 7580 // count. If so, we may be able to force computation of the exit 7581 // value. 7582 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7583 if (const SCEVConstant *BTCC = 7584 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7585 // Okay, we know how many times the containing loop executes. If 7586 // this is a constant evolving PHI node, get the final value at 7587 // the specified iteration number. 7588 Constant *RV = 7589 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7590 if (RV) return getSCEV(RV); 7591 } 7592 } 7593 7594 // Okay, this is an expression that we cannot symbolically evaluate 7595 // into a SCEV. Check to see if it's possible to symbolically evaluate 7596 // the arguments into constants, and if so, try to constant propagate the 7597 // result. This is particularly useful for computing loop exit values. 7598 if (CanConstantFold(I)) { 7599 SmallVector<Constant *, 4> Operands; 7600 bool MadeImprovement = false; 7601 for (Value *Op : I->operands()) { 7602 if (Constant *C = dyn_cast<Constant>(Op)) { 7603 Operands.push_back(C); 7604 continue; 7605 } 7606 7607 // If any of the operands is non-constant and if they are 7608 // non-integer and non-pointer, don't even try to analyze them 7609 // with scev techniques. 7610 if (!isSCEVable(Op->getType())) 7611 return V; 7612 7613 const SCEV *OrigV = getSCEV(Op); 7614 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7615 MadeImprovement |= OrigV != OpV; 7616 7617 Constant *C = BuildConstantFromSCEV(OpV); 7618 if (!C) return V; 7619 if (C->getType() != Op->getType()) 7620 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7621 Op->getType(), 7622 false), 7623 C, Op->getType()); 7624 Operands.push_back(C); 7625 } 7626 7627 // Check to see if getSCEVAtScope actually made an improvement. 7628 if (MadeImprovement) { 7629 Constant *C = nullptr; 7630 const DataLayout &DL = getDataLayout(); 7631 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7632 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7633 Operands[1], DL, &TLI); 7634 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7635 if (!LI->isVolatile()) 7636 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7637 } else 7638 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7639 if (!C) return V; 7640 return getSCEV(C); 7641 } 7642 } 7643 } 7644 7645 // This is some other type of SCEVUnknown, just return it. 7646 return V; 7647 } 7648 7649 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7650 // Avoid performing the look-up in the common case where the specified 7651 // expression has no loop-variant portions. 7652 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7653 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7654 if (OpAtScope != Comm->getOperand(i)) { 7655 // Okay, at least one of these operands is loop variant but might be 7656 // foldable. Build a new instance of the folded commutative expression. 7657 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7658 Comm->op_begin()+i); 7659 NewOps.push_back(OpAtScope); 7660 7661 for (++i; i != e; ++i) { 7662 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7663 NewOps.push_back(OpAtScope); 7664 } 7665 if (isa<SCEVAddExpr>(Comm)) 7666 return getAddExpr(NewOps); 7667 if (isa<SCEVMulExpr>(Comm)) 7668 return getMulExpr(NewOps); 7669 if (isa<SCEVSMaxExpr>(Comm)) 7670 return getSMaxExpr(NewOps); 7671 if (isa<SCEVUMaxExpr>(Comm)) 7672 return getUMaxExpr(NewOps); 7673 llvm_unreachable("Unknown commutative SCEV type!"); 7674 } 7675 } 7676 // If we got here, all operands are loop invariant. 7677 return Comm; 7678 } 7679 7680 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7681 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7682 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7683 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7684 return Div; // must be loop invariant 7685 return getUDivExpr(LHS, RHS); 7686 } 7687 7688 // If this is a loop recurrence for a loop that does not contain L, then we 7689 // are dealing with the final value computed by the loop. 7690 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7691 // First, attempt to evaluate each operand. 7692 // Avoid performing the look-up in the common case where the specified 7693 // expression has no loop-variant portions. 7694 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7695 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7696 if (OpAtScope == AddRec->getOperand(i)) 7697 continue; 7698 7699 // Okay, at least one of these operands is loop variant but might be 7700 // foldable. Build a new instance of the folded commutative expression. 7701 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7702 AddRec->op_begin()+i); 7703 NewOps.push_back(OpAtScope); 7704 for (++i; i != e; ++i) 7705 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7706 7707 const SCEV *FoldedRec = 7708 getAddRecExpr(NewOps, AddRec->getLoop(), 7709 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7710 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7711 // The addrec may be folded to a nonrecurrence, for example, if the 7712 // induction variable is multiplied by zero after constant folding. Go 7713 // ahead and return the folded value. 7714 if (!AddRec) 7715 return FoldedRec; 7716 break; 7717 } 7718 7719 // If the scope is outside the addrec's loop, evaluate it by using the 7720 // loop exit value of the addrec. 7721 if (!AddRec->getLoop()->contains(L)) { 7722 // To evaluate this recurrence, we need to know how many times the AddRec 7723 // loop iterates. Compute this now. 7724 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7725 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7726 7727 // Then, evaluate the AddRec. 7728 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7729 } 7730 7731 return AddRec; 7732 } 7733 7734 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7735 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7736 if (Op == Cast->getOperand()) 7737 return Cast; // must be loop invariant 7738 return getZeroExtendExpr(Op, Cast->getType()); 7739 } 7740 7741 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7742 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7743 if (Op == Cast->getOperand()) 7744 return Cast; // must be loop invariant 7745 return getSignExtendExpr(Op, Cast->getType()); 7746 } 7747 7748 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7749 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7750 if (Op == Cast->getOperand()) 7751 return Cast; // must be loop invariant 7752 return getTruncateExpr(Op, Cast->getType()); 7753 } 7754 7755 llvm_unreachable("Unknown SCEV type!"); 7756 } 7757 7758 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7759 return getSCEVAtScope(getSCEV(V), L); 7760 } 7761 7762 /// Finds the minimum unsigned root of the following equation: 7763 /// 7764 /// A * X = B (mod N) 7765 /// 7766 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7767 /// A and B isn't important. 7768 /// 7769 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7770 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7771 ScalarEvolution &SE) { 7772 uint32_t BW = A.getBitWidth(); 7773 assert(BW == SE.getTypeSizeInBits(B->getType())); 7774 assert(A != 0 && "A must be non-zero."); 7775 7776 // 1. D = gcd(A, N) 7777 // 7778 // The gcd of A and N may have only one prime factor: 2. The number of 7779 // trailing zeros in A is its multiplicity 7780 uint32_t Mult2 = A.countTrailingZeros(); 7781 // D = 2^Mult2 7782 7783 // 2. Check if B is divisible by D. 7784 // 7785 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7786 // is not less than multiplicity of this prime factor for D. 7787 if (SE.GetMinTrailingZeros(B) < Mult2) 7788 return SE.getCouldNotCompute(); 7789 7790 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7791 // modulo (N / D). 7792 // 7793 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7794 // (N / D) in general. The inverse itself always fits into BW bits, though, 7795 // so we immediately truncate it. 7796 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7797 APInt Mod(BW + 1, 0); 7798 Mod.setBit(BW - Mult2); // Mod = N / D 7799 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7800 7801 // 4. Compute the minimum unsigned root of the equation: 7802 // I * (B / D) mod (N / D) 7803 // To simplify the computation, we factor out the divide by D: 7804 // (I * B mod N) / D 7805 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7806 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7807 } 7808 7809 /// Find the roots of the quadratic equation for the given quadratic chrec 7810 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7811 /// two SCEVCouldNotCompute objects. 7812 /// 7813 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7814 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7815 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7816 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7817 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7818 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7819 7820 // We currently can only solve this if the coefficients are constants. 7821 if (!LC || !MC || !NC) 7822 return None; 7823 7824 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7825 const APInt &L = LC->getAPInt(); 7826 const APInt &M = MC->getAPInt(); 7827 const APInt &N = NC->getAPInt(); 7828 APInt Two(BitWidth, 2); 7829 7830 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7831 7832 // The A coefficient is N/2 7833 APInt A = N.sdiv(Two); 7834 7835 // The B coefficient is M-N/2 7836 APInt B = M; 7837 B -= A; // A is the same as N/2. 7838 7839 // The C coefficient is L. 7840 const APInt& C = L; 7841 7842 // Compute the B^2-4ac term. 7843 APInt SqrtTerm = B; 7844 SqrtTerm *= B; 7845 SqrtTerm -= 4 * (A * C); 7846 7847 if (SqrtTerm.isNegative()) { 7848 // The loop is provably infinite. 7849 return None; 7850 } 7851 7852 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7853 // integer value or else APInt::sqrt() will assert. 7854 APInt SqrtVal = SqrtTerm.sqrt(); 7855 7856 // Compute the two solutions for the quadratic formula. 7857 // The divisions must be performed as signed divisions. 7858 APInt NegB = -std::move(B); 7859 APInt TwoA = std::move(A); 7860 TwoA <<= 1; 7861 if (TwoA.isNullValue()) 7862 return None; 7863 7864 LLVMContext &Context = SE.getContext(); 7865 7866 ConstantInt *Solution1 = 7867 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7868 ConstantInt *Solution2 = 7869 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7870 7871 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7872 cast<SCEVConstant>(SE.getConstant(Solution2))); 7873 } 7874 7875 ScalarEvolution::ExitLimit 7876 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7877 bool AllowPredicates) { 7878 7879 // This is only used for loops with a "x != y" exit test. The exit condition 7880 // is now expressed as a single expression, V = x-y. So the exit test is 7881 // effectively V != 0. We know and take advantage of the fact that this 7882 // expression only being used in a comparison by zero context. 7883 7884 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7885 // If the value is a constant 7886 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7887 // If the value is already zero, the branch will execute zero times. 7888 if (C->getValue()->isZero()) return C; 7889 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7890 } 7891 7892 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7893 if (!AddRec && AllowPredicates) 7894 // Try to make this an AddRec using runtime tests, in the first X 7895 // iterations of this loop, where X is the SCEV expression found by the 7896 // algorithm below. 7897 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7898 7899 if (!AddRec || AddRec->getLoop() != L) 7900 return getCouldNotCompute(); 7901 7902 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7903 // the quadratic equation to solve it. 7904 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7905 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7906 const SCEVConstant *R1 = Roots->first; 7907 const SCEVConstant *R2 = Roots->second; 7908 // Pick the smallest positive root value. 7909 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7910 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7911 if (!CB->getZExtValue()) 7912 std::swap(R1, R2); // R1 is the minimum root now. 7913 7914 // We can only use this value if the chrec ends up with an exact zero 7915 // value at this index. When solving for "X*X != 5", for example, we 7916 // should not accept a root of 2. 7917 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7918 if (Val->isZero()) 7919 // We found a quadratic root! 7920 return ExitLimit(R1, R1, false, Predicates); 7921 } 7922 } 7923 return getCouldNotCompute(); 7924 } 7925 7926 // Otherwise we can only handle this if it is affine. 7927 if (!AddRec->isAffine()) 7928 return getCouldNotCompute(); 7929 7930 // If this is an affine expression, the execution count of this branch is 7931 // the minimum unsigned root of the following equation: 7932 // 7933 // Start + Step*N = 0 (mod 2^BW) 7934 // 7935 // equivalent to: 7936 // 7937 // Step*N = -Start (mod 2^BW) 7938 // 7939 // where BW is the common bit width of Start and Step. 7940 7941 // Get the initial value for the loop. 7942 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7943 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7944 7945 // For now we handle only constant steps. 7946 // 7947 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7948 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7949 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7950 // We have not yet seen any such cases. 7951 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7952 if (!StepC || StepC->getValue()->isZero()) 7953 return getCouldNotCompute(); 7954 7955 // For positive steps (counting up until unsigned overflow): 7956 // N = -Start/Step (as unsigned) 7957 // For negative steps (counting down to zero): 7958 // N = Start/-Step 7959 // First compute the unsigned distance from zero in the direction of Step. 7960 bool CountDown = StepC->getAPInt().isNegative(); 7961 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7962 7963 // Handle unitary steps, which cannot wraparound. 7964 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7965 // N = Distance (as unsigned) 7966 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 7967 APInt MaxBECount = getUnsignedRangeMax(Distance); 7968 7969 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7970 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7971 // case, and see if we can improve the bound. 7972 // 7973 // Explicitly handling this here is necessary because getUnsignedRange 7974 // isn't context-sensitive; it doesn't know that we only care about the 7975 // range inside the loop. 7976 const SCEV *Zero = getZero(Distance->getType()); 7977 const SCEV *One = getOne(Distance->getType()); 7978 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7979 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7980 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7981 // as "unsigned_max(Distance + 1) - 1". 7982 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7983 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7984 } 7985 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7986 } 7987 7988 // If the condition controls loop exit (the loop exits only if the expression 7989 // is true) and the addition is no-wrap we can use unsigned divide to 7990 // compute the backedge count. In this case, the step may not divide the 7991 // distance, but we don't care because if the condition is "missed" the loop 7992 // will have undefined behavior due to wrapping. 7993 if (ControlsExit && AddRec->hasNoSelfWrap() && 7994 loopHasNoAbnormalExits(AddRec->getLoop())) { 7995 const SCEV *Exact = 7996 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7997 const SCEV *Max = 7998 Exact == getCouldNotCompute() 7999 ? Exact 8000 : getConstant(getUnsignedRangeMax(Exact)); 8001 return ExitLimit(Exact, Max, false, Predicates); 8002 } 8003 8004 // Solve the general equation. 8005 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8006 getNegativeSCEV(Start), *this); 8007 const SCEV *M = E == getCouldNotCompute() 8008 ? E 8009 : getConstant(getUnsignedRangeMax(E)); 8010 return ExitLimit(E, M, false, Predicates); 8011 } 8012 8013 ScalarEvolution::ExitLimit 8014 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8015 // Loops that look like: while (X == 0) are very strange indeed. We don't 8016 // handle them yet except for the trivial case. This could be expanded in the 8017 // future as needed. 8018 8019 // If the value is a constant, check to see if it is known to be non-zero 8020 // already. If so, the backedge will execute zero times. 8021 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8022 if (!C->getValue()->isZero()) 8023 return getZero(C->getType()); 8024 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8025 } 8026 8027 // We could implement others, but I really doubt anyone writes loops like 8028 // this, and if they did, they would already be constant folded. 8029 return getCouldNotCompute(); 8030 } 8031 8032 std::pair<BasicBlock *, BasicBlock *> 8033 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8034 // If the block has a unique predecessor, then there is no path from the 8035 // predecessor to the block that does not go through the direct edge 8036 // from the predecessor to the block. 8037 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8038 return {Pred, BB}; 8039 8040 // A loop's header is defined to be a block that dominates the loop. 8041 // If the header has a unique predecessor outside the loop, it must be 8042 // a block that has exactly one successor that can reach the loop. 8043 if (Loop *L = LI.getLoopFor(BB)) 8044 return {L->getLoopPredecessor(), L->getHeader()}; 8045 8046 return {nullptr, nullptr}; 8047 } 8048 8049 /// SCEV structural equivalence is usually sufficient for testing whether two 8050 /// expressions are equal, however for the purposes of looking for a condition 8051 /// guarding a loop, it can be useful to be a little more general, since a 8052 /// front-end may have replicated the controlling expression. 8053 /// 8054 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8055 // Quick check to see if they are the same SCEV. 8056 if (A == B) return true; 8057 8058 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8059 // Not all instructions that are "identical" compute the same value. For 8060 // instance, two distinct alloca instructions allocating the same type are 8061 // identical and do not read memory; but compute distinct values. 8062 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8063 }; 8064 8065 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8066 // two different instructions with the same value. Check for this case. 8067 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8068 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8069 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8070 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8071 if (ComputesEqualValues(AI, BI)) 8072 return true; 8073 8074 // Otherwise assume they may have a different value. 8075 return false; 8076 } 8077 8078 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8079 const SCEV *&LHS, const SCEV *&RHS, 8080 unsigned Depth) { 8081 bool Changed = false; 8082 8083 // If we hit the max recursion limit bail out. 8084 if (Depth >= 3) 8085 return false; 8086 8087 // Canonicalize a constant to the right side. 8088 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8089 // Check for both operands constant. 8090 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8091 if (ConstantExpr::getICmp(Pred, 8092 LHSC->getValue(), 8093 RHSC->getValue())->isNullValue()) 8094 goto trivially_false; 8095 else 8096 goto trivially_true; 8097 } 8098 // Otherwise swap the operands to put the constant on the right. 8099 std::swap(LHS, RHS); 8100 Pred = ICmpInst::getSwappedPredicate(Pred); 8101 Changed = true; 8102 } 8103 8104 // If we're comparing an addrec with a value which is loop-invariant in the 8105 // addrec's loop, put the addrec on the left. Also make a dominance check, 8106 // as both operands could be addrecs loop-invariant in each other's loop. 8107 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8108 const Loop *L = AR->getLoop(); 8109 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8110 std::swap(LHS, RHS); 8111 Pred = ICmpInst::getSwappedPredicate(Pred); 8112 Changed = true; 8113 } 8114 } 8115 8116 // If there's a constant operand, canonicalize comparisons with boundary 8117 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8118 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8119 const APInt &RA = RC->getAPInt(); 8120 8121 bool SimplifiedByConstantRange = false; 8122 8123 if (!ICmpInst::isEquality(Pred)) { 8124 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8125 if (ExactCR.isFullSet()) 8126 goto trivially_true; 8127 else if (ExactCR.isEmptySet()) 8128 goto trivially_false; 8129 8130 APInt NewRHS; 8131 CmpInst::Predicate NewPred; 8132 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8133 ICmpInst::isEquality(NewPred)) { 8134 // We were able to convert an inequality to an equality. 8135 Pred = NewPred; 8136 RHS = getConstant(NewRHS); 8137 Changed = SimplifiedByConstantRange = true; 8138 } 8139 } 8140 8141 if (!SimplifiedByConstantRange) { 8142 switch (Pred) { 8143 default: 8144 break; 8145 case ICmpInst::ICMP_EQ: 8146 case ICmpInst::ICMP_NE: 8147 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8148 if (!RA) 8149 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8150 if (const SCEVMulExpr *ME = 8151 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8152 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8153 ME->getOperand(0)->isAllOnesValue()) { 8154 RHS = AE->getOperand(1); 8155 LHS = ME->getOperand(1); 8156 Changed = true; 8157 } 8158 break; 8159 8160 8161 // The "Should have been caught earlier!" messages refer to the fact 8162 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8163 // should have fired on the corresponding cases, and canonicalized the 8164 // check to trivially_true or trivially_false. 8165 8166 case ICmpInst::ICMP_UGE: 8167 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8168 Pred = ICmpInst::ICMP_UGT; 8169 RHS = getConstant(RA - 1); 8170 Changed = true; 8171 break; 8172 case ICmpInst::ICMP_ULE: 8173 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8174 Pred = ICmpInst::ICMP_ULT; 8175 RHS = getConstant(RA + 1); 8176 Changed = true; 8177 break; 8178 case ICmpInst::ICMP_SGE: 8179 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8180 Pred = ICmpInst::ICMP_SGT; 8181 RHS = getConstant(RA - 1); 8182 Changed = true; 8183 break; 8184 case ICmpInst::ICMP_SLE: 8185 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8186 Pred = ICmpInst::ICMP_SLT; 8187 RHS = getConstant(RA + 1); 8188 Changed = true; 8189 break; 8190 } 8191 } 8192 } 8193 8194 // Check for obvious equality. 8195 if (HasSameValue(LHS, RHS)) { 8196 if (ICmpInst::isTrueWhenEqual(Pred)) 8197 goto trivially_true; 8198 if (ICmpInst::isFalseWhenEqual(Pred)) 8199 goto trivially_false; 8200 } 8201 8202 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8203 // adding or subtracting 1 from one of the operands. 8204 switch (Pred) { 8205 case ICmpInst::ICMP_SLE: 8206 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8207 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8208 SCEV::FlagNSW); 8209 Pred = ICmpInst::ICMP_SLT; 8210 Changed = true; 8211 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8212 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8213 SCEV::FlagNSW); 8214 Pred = ICmpInst::ICMP_SLT; 8215 Changed = true; 8216 } 8217 break; 8218 case ICmpInst::ICMP_SGE: 8219 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8220 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8221 SCEV::FlagNSW); 8222 Pred = ICmpInst::ICMP_SGT; 8223 Changed = true; 8224 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8225 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8226 SCEV::FlagNSW); 8227 Pred = ICmpInst::ICMP_SGT; 8228 Changed = true; 8229 } 8230 break; 8231 case ICmpInst::ICMP_ULE: 8232 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8233 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8234 SCEV::FlagNUW); 8235 Pred = ICmpInst::ICMP_ULT; 8236 Changed = true; 8237 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8238 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8239 Pred = ICmpInst::ICMP_ULT; 8240 Changed = true; 8241 } 8242 break; 8243 case ICmpInst::ICMP_UGE: 8244 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8245 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8246 Pred = ICmpInst::ICMP_UGT; 8247 Changed = true; 8248 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8249 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8250 SCEV::FlagNUW); 8251 Pred = ICmpInst::ICMP_UGT; 8252 Changed = true; 8253 } 8254 break; 8255 default: 8256 break; 8257 } 8258 8259 // TODO: More simplifications are possible here. 8260 8261 // Recursively simplify until we either hit a recursion limit or nothing 8262 // changes. 8263 if (Changed) 8264 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8265 8266 return Changed; 8267 8268 trivially_true: 8269 // Return 0 == 0. 8270 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8271 Pred = ICmpInst::ICMP_EQ; 8272 return true; 8273 8274 trivially_false: 8275 // Return 0 != 0. 8276 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8277 Pred = ICmpInst::ICMP_NE; 8278 return true; 8279 } 8280 8281 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8282 return getSignedRangeMax(S).isNegative(); 8283 } 8284 8285 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8286 return getSignedRangeMin(S).isStrictlyPositive(); 8287 } 8288 8289 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8290 return !getSignedRangeMin(S).isNegative(); 8291 } 8292 8293 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8294 return !getSignedRangeMax(S).isStrictlyPositive(); 8295 } 8296 8297 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8298 return isKnownNegative(S) || isKnownPositive(S); 8299 } 8300 8301 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8302 const SCEV *LHS, const SCEV *RHS) { 8303 // Canonicalize the inputs first. 8304 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8305 8306 // If LHS or RHS is an addrec, check to see if the condition is true in 8307 // every iteration of the loop. 8308 // If LHS and RHS are both addrec, both conditions must be true in 8309 // every iteration of the loop. 8310 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8311 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8312 bool LeftGuarded = false; 8313 bool RightGuarded = false; 8314 if (LAR) { 8315 const Loop *L = LAR->getLoop(); 8316 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 8317 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 8318 if (!RAR) return true; 8319 LeftGuarded = true; 8320 } 8321 } 8322 if (RAR) { 8323 const Loop *L = RAR->getLoop(); 8324 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 8325 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 8326 if (!LAR) return true; 8327 RightGuarded = true; 8328 } 8329 } 8330 if (LeftGuarded && RightGuarded) 8331 return true; 8332 8333 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8334 return true; 8335 8336 // Otherwise see what can be done with known constant ranges. 8337 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 8338 } 8339 8340 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8341 ICmpInst::Predicate Pred, 8342 bool &Increasing) { 8343 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8344 8345 #ifndef NDEBUG 8346 // Verify an invariant: inverting the predicate should turn a monotonically 8347 // increasing change to a monotonically decreasing one, and vice versa. 8348 bool IncreasingSwapped; 8349 bool ResultSwapped = isMonotonicPredicateImpl( 8350 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8351 8352 assert(Result == ResultSwapped && "should be able to analyze both!"); 8353 if (ResultSwapped) 8354 assert(Increasing == !IncreasingSwapped && 8355 "monotonicity should flip as we flip the predicate"); 8356 #endif 8357 8358 return Result; 8359 } 8360 8361 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8362 ICmpInst::Predicate Pred, 8363 bool &Increasing) { 8364 8365 // A zero step value for LHS means the induction variable is essentially a 8366 // loop invariant value. We don't really depend on the predicate actually 8367 // flipping from false to true (for increasing predicates, and the other way 8368 // around for decreasing predicates), all we care about is that *if* the 8369 // predicate changes then it only changes from false to true. 8370 // 8371 // A zero step value in itself is not very useful, but there may be places 8372 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8373 // as general as possible. 8374 8375 switch (Pred) { 8376 default: 8377 return false; // Conservative answer 8378 8379 case ICmpInst::ICMP_UGT: 8380 case ICmpInst::ICMP_UGE: 8381 case ICmpInst::ICMP_ULT: 8382 case ICmpInst::ICMP_ULE: 8383 if (!LHS->hasNoUnsignedWrap()) 8384 return false; 8385 8386 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8387 return true; 8388 8389 case ICmpInst::ICMP_SGT: 8390 case ICmpInst::ICMP_SGE: 8391 case ICmpInst::ICMP_SLT: 8392 case ICmpInst::ICMP_SLE: { 8393 if (!LHS->hasNoSignedWrap()) 8394 return false; 8395 8396 const SCEV *Step = LHS->getStepRecurrence(*this); 8397 8398 if (isKnownNonNegative(Step)) { 8399 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8400 return true; 8401 } 8402 8403 if (isKnownNonPositive(Step)) { 8404 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8405 return true; 8406 } 8407 8408 return false; 8409 } 8410 8411 } 8412 8413 llvm_unreachable("switch has default clause!"); 8414 } 8415 8416 bool ScalarEvolution::isLoopInvariantPredicate( 8417 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8418 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8419 const SCEV *&InvariantRHS) { 8420 8421 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8422 if (!isLoopInvariant(RHS, L)) { 8423 if (!isLoopInvariant(LHS, L)) 8424 return false; 8425 8426 std::swap(LHS, RHS); 8427 Pred = ICmpInst::getSwappedPredicate(Pred); 8428 } 8429 8430 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8431 if (!ArLHS || ArLHS->getLoop() != L) 8432 return false; 8433 8434 bool Increasing; 8435 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8436 return false; 8437 8438 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8439 // true as the loop iterates, and the backedge is control dependent on 8440 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8441 // 8442 // * if the predicate was false in the first iteration then the predicate 8443 // is never evaluated again, since the loop exits without taking the 8444 // backedge. 8445 // * if the predicate was true in the first iteration then it will 8446 // continue to be true for all future iterations since it is 8447 // monotonically increasing. 8448 // 8449 // For both the above possibilities, we can replace the loop varying 8450 // predicate with its value on the first iteration of the loop (which is 8451 // loop invariant). 8452 // 8453 // A similar reasoning applies for a monotonically decreasing predicate, by 8454 // replacing true with false and false with true in the above two bullets. 8455 8456 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8457 8458 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8459 return false; 8460 8461 InvariantPred = Pred; 8462 InvariantLHS = ArLHS->getStart(); 8463 InvariantRHS = RHS; 8464 return true; 8465 } 8466 8467 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8468 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8469 if (HasSameValue(LHS, RHS)) 8470 return ICmpInst::isTrueWhenEqual(Pred); 8471 8472 // This code is split out from isKnownPredicate because it is called from 8473 // within isLoopEntryGuardedByCond. 8474 8475 auto CheckRanges = 8476 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8477 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8478 .contains(RangeLHS); 8479 }; 8480 8481 // The check at the top of the function catches the case where the values are 8482 // known to be equal. 8483 if (Pred == CmpInst::ICMP_EQ) 8484 return false; 8485 8486 if (Pred == CmpInst::ICMP_NE) 8487 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8488 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8489 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8490 8491 if (CmpInst::isSigned(Pred)) 8492 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8493 8494 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8495 } 8496 8497 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8498 const SCEV *LHS, 8499 const SCEV *RHS) { 8500 8501 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8502 // Return Y via OutY. 8503 auto MatchBinaryAddToConst = 8504 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8505 SCEV::NoWrapFlags ExpectedFlags) { 8506 const SCEV *NonConstOp, *ConstOp; 8507 SCEV::NoWrapFlags FlagsPresent; 8508 8509 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8510 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8511 return false; 8512 8513 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8514 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8515 }; 8516 8517 APInt C; 8518 8519 switch (Pred) { 8520 default: 8521 break; 8522 8523 case ICmpInst::ICMP_SGE: 8524 std::swap(LHS, RHS); 8525 LLVM_FALLTHROUGH; 8526 case ICmpInst::ICMP_SLE: 8527 // X s<= (X + C)<nsw> if C >= 0 8528 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8529 return true; 8530 8531 // (X + C)<nsw> s<= X if C <= 0 8532 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8533 !C.isStrictlyPositive()) 8534 return true; 8535 break; 8536 8537 case ICmpInst::ICMP_SGT: 8538 std::swap(LHS, RHS); 8539 LLVM_FALLTHROUGH; 8540 case ICmpInst::ICMP_SLT: 8541 // X s< (X + C)<nsw> if C > 0 8542 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8543 C.isStrictlyPositive()) 8544 return true; 8545 8546 // (X + C)<nsw> s< X if C < 0 8547 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8548 return true; 8549 break; 8550 } 8551 8552 return false; 8553 } 8554 8555 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8556 const SCEV *LHS, 8557 const SCEV *RHS) { 8558 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8559 return false; 8560 8561 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8562 // the stack can result in exponential time complexity. 8563 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8564 8565 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8566 // 8567 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8568 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8569 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8570 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8571 // use isKnownPredicate later if needed. 8572 return isKnownNonNegative(RHS) && 8573 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8574 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8575 } 8576 8577 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8578 ICmpInst::Predicate Pred, 8579 const SCEV *LHS, const SCEV *RHS) { 8580 // No need to even try if we know the module has no guards. 8581 if (!HasGuards) 8582 return false; 8583 8584 return any_of(*BB, [&](Instruction &I) { 8585 using namespace llvm::PatternMatch; 8586 8587 Value *Condition; 8588 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8589 m_Value(Condition))) && 8590 isImpliedCond(Pred, LHS, RHS, Condition, false); 8591 }); 8592 } 8593 8594 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8595 /// protected by a conditional between LHS and RHS. This is used to 8596 /// to eliminate casts. 8597 bool 8598 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8599 ICmpInst::Predicate Pred, 8600 const SCEV *LHS, const SCEV *RHS) { 8601 // Interpret a null as meaning no loop, where there is obviously no guard 8602 // (interprocedural conditions notwithstanding). 8603 if (!L) return true; 8604 8605 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8606 return true; 8607 8608 BasicBlock *Latch = L->getLoopLatch(); 8609 if (!Latch) 8610 return false; 8611 8612 BranchInst *LoopContinuePredicate = 8613 dyn_cast<BranchInst>(Latch->getTerminator()); 8614 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8615 isImpliedCond(Pred, LHS, RHS, 8616 LoopContinuePredicate->getCondition(), 8617 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8618 return true; 8619 8620 // We don't want more than one activation of the following loops on the stack 8621 // -- that can lead to O(n!) time complexity. 8622 if (WalkingBEDominatingConds) 8623 return false; 8624 8625 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8626 8627 // See if we can exploit a trip count to prove the predicate. 8628 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8629 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8630 if (LatchBECount != getCouldNotCompute()) { 8631 // We know that Latch branches back to the loop header exactly 8632 // LatchBECount times. This means the backdege condition at Latch is 8633 // equivalent to "{0,+,1} u< LatchBECount". 8634 Type *Ty = LatchBECount->getType(); 8635 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8636 const SCEV *LoopCounter = 8637 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8638 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8639 LatchBECount)) 8640 return true; 8641 } 8642 8643 // Check conditions due to any @llvm.assume intrinsics. 8644 for (auto &AssumeVH : AC.assumptions()) { 8645 if (!AssumeVH) 8646 continue; 8647 auto *CI = cast<CallInst>(AssumeVH); 8648 if (!DT.dominates(CI, Latch->getTerminator())) 8649 continue; 8650 8651 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8652 return true; 8653 } 8654 8655 // If the loop is not reachable from the entry block, we risk running into an 8656 // infinite loop as we walk up into the dom tree. These loops do not matter 8657 // anyway, so we just return a conservative answer when we see them. 8658 if (!DT.isReachableFromEntry(L->getHeader())) 8659 return false; 8660 8661 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8662 return true; 8663 8664 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8665 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8666 8667 assert(DTN && "should reach the loop header before reaching the root!"); 8668 8669 BasicBlock *BB = DTN->getBlock(); 8670 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8671 return true; 8672 8673 BasicBlock *PBB = BB->getSinglePredecessor(); 8674 if (!PBB) 8675 continue; 8676 8677 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8678 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8679 continue; 8680 8681 Value *Condition = ContinuePredicate->getCondition(); 8682 8683 // If we have an edge `E` within the loop body that dominates the only 8684 // latch, the condition guarding `E` also guards the backedge. This 8685 // reasoning works only for loops with a single latch. 8686 8687 BasicBlockEdge DominatingEdge(PBB, BB); 8688 if (DominatingEdge.isSingleEdge()) { 8689 // We're constructively (and conservatively) enumerating edges within the 8690 // loop body that dominate the latch. The dominator tree better agree 8691 // with us on this: 8692 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8693 8694 if (isImpliedCond(Pred, LHS, RHS, Condition, 8695 BB != ContinuePredicate->getSuccessor(0))) 8696 return true; 8697 } 8698 } 8699 8700 return false; 8701 } 8702 8703 bool 8704 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8705 ICmpInst::Predicate Pred, 8706 const SCEV *LHS, const SCEV *RHS) { 8707 // Interpret a null as meaning no loop, where there is obviously no guard 8708 // (interprocedural conditions notwithstanding). 8709 if (!L) return false; 8710 8711 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8712 return true; 8713 8714 // Starting at the loop predecessor, climb up the predecessor chain, as long 8715 // as there are predecessors that can be found that have unique successors 8716 // leading to the original header. 8717 for (std::pair<BasicBlock *, BasicBlock *> 8718 Pair(L->getLoopPredecessor(), L->getHeader()); 8719 Pair.first; 8720 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8721 8722 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8723 return true; 8724 8725 BranchInst *LoopEntryPredicate = 8726 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8727 if (!LoopEntryPredicate || 8728 LoopEntryPredicate->isUnconditional()) 8729 continue; 8730 8731 if (isImpliedCond(Pred, LHS, RHS, 8732 LoopEntryPredicate->getCondition(), 8733 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8734 return true; 8735 } 8736 8737 // Check conditions due to any @llvm.assume intrinsics. 8738 for (auto &AssumeVH : AC.assumptions()) { 8739 if (!AssumeVH) 8740 continue; 8741 auto *CI = cast<CallInst>(AssumeVH); 8742 if (!DT.dominates(CI, L->getHeader())) 8743 continue; 8744 8745 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8746 return true; 8747 } 8748 8749 return false; 8750 } 8751 8752 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8753 const SCEV *LHS, const SCEV *RHS, 8754 Value *FoundCondValue, 8755 bool Inverse) { 8756 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8757 return false; 8758 8759 auto ClearOnExit = 8760 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8761 8762 // Recursively handle And and Or conditions. 8763 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8764 if (BO->getOpcode() == Instruction::And) { 8765 if (!Inverse) 8766 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8767 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8768 } else if (BO->getOpcode() == Instruction::Or) { 8769 if (Inverse) 8770 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8771 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8772 } 8773 } 8774 8775 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8776 if (!ICI) return false; 8777 8778 // Now that we found a conditional branch that dominates the loop or controls 8779 // the loop latch. Check to see if it is the comparison we are looking for. 8780 ICmpInst::Predicate FoundPred; 8781 if (Inverse) 8782 FoundPred = ICI->getInversePredicate(); 8783 else 8784 FoundPred = ICI->getPredicate(); 8785 8786 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8787 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8788 8789 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8790 } 8791 8792 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8793 const SCEV *RHS, 8794 ICmpInst::Predicate FoundPred, 8795 const SCEV *FoundLHS, 8796 const SCEV *FoundRHS) { 8797 // Balance the types. 8798 if (getTypeSizeInBits(LHS->getType()) < 8799 getTypeSizeInBits(FoundLHS->getType())) { 8800 if (CmpInst::isSigned(Pred)) { 8801 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8802 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8803 } else { 8804 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8805 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8806 } 8807 } else if (getTypeSizeInBits(LHS->getType()) > 8808 getTypeSizeInBits(FoundLHS->getType())) { 8809 if (CmpInst::isSigned(FoundPred)) { 8810 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8811 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8812 } else { 8813 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8814 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8815 } 8816 } 8817 8818 // Canonicalize the query to match the way instcombine will have 8819 // canonicalized the comparison. 8820 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8821 if (LHS == RHS) 8822 return CmpInst::isTrueWhenEqual(Pred); 8823 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8824 if (FoundLHS == FoundRHS) 8825 return CmpInst::isFalseWhenEqual(FoundPred); 8826 8827 // Check to see if we can make the LHS or RHS match. 8828 if (LHS == FoundRHS || RHS == FoundLHS) { 8829 if (isa<SCEVConstant>(RHS)) { 8830 std::swap(FoundLHS, FoundRHS); 8831 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8832 } else { 8833 std::swap(LHS, RHS); 8834 Pred = ICmpInst::getSwappedPredicate(Pred); 8835 } 8836 } 8837 8838 // Check whether the found predicate is the same as the desired predicate. 8839 if (FoundPred == Pred) 8840 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8841 8842 // Check whether swapping the found predicate makes it the same as the 8843 // desired predicate. 8844 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8845 if (isa<SCEVConstant>(RHS)) 8846 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8847 else 8848 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8849 RHS, LHS, FoundLHS, FoundRHS); 8850 } 8851 8852 // Unsigned comparison is the same as signed comparison when both the operands 8853 // are non-negative. 8854 if (CmpInst::isUnsigned(FoundPred) && 8855 CmpInst::getSignedPredicate(FoundPred) == Pred && 8856 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8857 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8858 8859 // Check if we can make progress by sharpening ranges. 8860 if (FoundPred == ICmpInst::ICMP_NE && 8861 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8862 8863 const SCEVConstant *C = nullptr; 8864 const SCEV *V = nullptr; 8865 8866 if (isa<SCEVConstant>(FoundLHS)) { 8867 C = cast<SCEVConstant>(FoundLHS); 8868 V = FoundRHS; 8869 } else { 8870 C = cast<SCEVConstant>(FoundRHS); 8871 V = FoundLHS; 8872 } 8873 8874 // The guarding predicate tells us that C != V. If the known range 8875 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8876 // range we consider has to correspond to same signedness as the 8877 // predicate we're interested in folding. 8878 8879 APInt Min = ICmpInst::isSigned(Pred) ? 8880 getSignedRangeMin(V) : getUnsignedRangeMin(V); 8881 8882 if (Min == C->getAPInt()) { 8883 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8884 // This is true even if (Min + 1) wraps around -- in case of 8885 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8886 8887 APInt SharperMin = Min + 1; 8888 8889 switch (Pred) { 8890 case ICmpInst::ICMP_SGE: 8891 case ICmpInst::ICMP_UGE: 8892 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8893 // RHS, we're done. 8894 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8895 getConstant(SharperMin))) 8896 return true; 8897 LLVM_FALLTHROUGH; 8898 8899 case ICmpInst::ICMP_SGT: 8900 case ICmpInst::ICMP_UGT: 8901 // We know from the range information that (V `Pred` Min || 8902 // V == Min). We know from the guarding condition that !(V 8903 // == Min). This gives us 8904 // 8905 // V `Pred` Min || V == Min && !(V == Min) 8906 // => V `Pred` Min 8907 // 8908 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8909 8910 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8911 return true; 8912 LLVM_FALLTHROUGH; 8913 8914 default: 8915 // No change 8916 break; 8917 } 8918 } 8919 } 8920 8921 // Check whether the actual condition is beyond sufficient. 8922 if (FoundPred == ICmpInst::ICMP_EQ) 8923 if (ICmpInst::isTrueWhenEqual(Pred)) 8924 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8925 return true; 8926 if (Pred == ICmpInst::ICMP_NE) 8927 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8928 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8929 return true; 8930 8931 // Otherwise assume the worst. 8932 return false; 8933 } 8934 8935 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8936 const SCEV *&L, const SCEV *&R, 8937 SCEV::NoWrapFlags &Flags) { 8938 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8939 if (!AE || AE->getNumOperands() != 2) 8940 return false; 8941 8942 L = AE->getOperand(0); 8943 R = AE->getOperand(1); 8944 Flags = AE->getNoWrapFlags(); 8945 return true; 8946 } 8947 8948 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8949 const SCEV *Less) { 8950 // We avoid subtracting expressions here because this function is usually 8951 // fairly deep in the call stack (i.e. is called many times). 8952 8953 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8954 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8955 const auto *MAR = cast<SCEVAddRecExpr>(More); 8956 8957 if (LAR->getLoop() != MAR->getLoop()) 8958 return None; 8959 8960 // We look at affine expressions only; not for correctness but to keep 8961 // getStepRecurrence cheap. 8962 if (!LAR->isAffine() || !MAR->isAffine()) 8963 return None; 8964 8965 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8966 return None; 8967 8968 Less = LAR->getStart(); 8969 More = MAR->getStart(); 8970 8971 // fall through 8972 } 8973 8974 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8975 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8976 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8977 return M - L; 8978 } 8979 8980 const SCEV *L, *R; 8981 SCEV::NoWrapFlags Flags; 8982 if (splitBinaryAdd(Less, L, R, Flags)) 8983 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8984 if (R == More) 8985 return -(LC->getAPInt()); 8986 8987 if (splitBinaryAdd(More, L, R, Flags)) 8988 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8989 if (R == Less) 8990 return LC->getAPInt(); 8991 8992 return None; 8993 } 8994 8995 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8996 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8997 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8998 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8999 return false; 9000 9001 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9002 if (!AddRecLHS) 9003 return false; 9004 9005 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9006 if (!AddRecFoundLHS) 9007 return false; 9008 9009 // We'd like to let SCEV reason about control dependencies, so we constrain 9010 // both the inequalities to be about add recurrences on the same loop. This 9011 // way we can use isLoopEntryGuardedByCond later. 9012 9013 const Loop *L = AddRecFoundLHS->getLoop(); 9014 if (L != AddRecLHS->getLoop()) 9015 return false; 9016 9017 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9018 // 9019 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9020 // ... (2) 9021 // 9022 // Informal proof for (2), assuming (1) [*]: 9023 // 9024 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9025 // 9026 // Then 9027 // 9028 // FoundLHS s< FoundRHS s< INT_MIN - C 9029 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9030 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9031 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9032 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9033 // <=> FoundLHS + C s< FoundRHS + C 9034 // 9035 // [*]: (1) can be proved by ruling out overflow. 9036 // 9037 // [**]: This can be proved by analyzing all the four possibilities: 9038 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9039 // (A s>= 0, B s>= 0). 9040 // 9041 // Note: 9042 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9043 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9044 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9045 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9046 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9047 // C)". 9048 9049 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9050 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9051 if (!LDiff || !RDiff || *LDiff != *RDiff) 9052 return false; 9053 9054 if (LDiff->isMinValue()) 9055 return true; 9056 9057 APInt FoundRHSLimit; 9058 9059 if (Pred == CmpInst::ICMP_ULT) { 9060 FoundRHSLimit = -(*RDiff); 9061 } else { 9062 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9063 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9064 } 9065 9066 // Try to prove (1) or (2), as needed. 9067 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9068 getConstant(FoundRHSLimit)); 9069 } 9070 9071 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9072 const SCEV *LHS, const SCEV *RHS, 9073 const SCEV *FoundLHS, 9074 const SCEV *FoundRHS) { 9075 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9076 return true; 9077 9078 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9079 return true; 9080 9081 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9082 FoundLHS, FoundRHS) || 9083 // ~x < ~y --> x > y 9084 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9085 getNotSCEV(FoundRHS), 9086 getNotSCEV(FoundLHS)); 9087 } 9088 9089 9090 /// If Expr computes ~A, return A else return nullptr 9091 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9092 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9093 if (!Add || Add->getNumOperands() != 2 || 9094 !Add->getOperand(0)->isAllOnesValue()) 9095 return nullptr; 9096 9097 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9098 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9099 !AddRHS->getOperand(0)->isAllOnesValue()) 9100 return nullptr; 9101 9102 return AddRHS->getOperand(1); 9103 } 9104 9105 9106 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9107 template<typename MaxExprType> 9108 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9109 const SCEV *Candidate) { 9110 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9111 if (!MaxExpr) return false; 9112 9113 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9114 } 9115 9116 9117 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9118 template<typename MaxExprType> 9119 static bool IsMinConsistingOf(ScalarEvolution &SE, 9120 const SCEV *MaybeMinExpr, 9121 const SCEV *Candidate) { 9122 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9123 if (!MaybeMaxExpr) 9124 return false; 9125 9126 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9127 } 9128 9129 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9130 ICmpInst::Predicate Pred, 9131 const SCEV *LHS, const SCEV *RHS) { 9132 9133 // If both sides are affine addrecs for the same loop, with equal 9134 // steps, and we know the recurrences don't wrap, then we only 9135 // need to check the predicate on the starting values. 9136 9137 if (!ICmpInst::isRelational(Pred)) 9138 return false; 9139 9140 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9141 if (!LAR) 9142 return false; 9143 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9144 if (!RAR) 9145 return false; 9146 if (LAR->getLoop() != RAR->getLoop()) 9147 return false; 9148 if (!LAR->isAffine() || !RAR->isAffine()) 9149 return false; 9150 9151 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9152 return false; 9153 9154 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9155 SCEV::FlagNSW : SCEV::FlagNUW; 9156 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9157 return false; 9158 9159 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9160 } 9161 9162 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9163 /// expression? 9164 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9165 ICmpInst::Predicate Pred, 9166 const SCEV *LHS, const SCEV *RHS) { 9167 switch (Pred) { 9168 default: 9169 return false; 9170 9171 case ICmpInst::ICMP_SGE: 9172 std::swap(LHS, RHS); 9173 LLVM_FALLTHROUGH; 9174 case ICmpInst::ICMP_SLE: 9175 return 9176 // min(A, ...) <= A 9177 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9178 // A <= max(A, ...) 9179 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9180 9181 case ICmpInst::ICMP_UGE: 9182 std::swap(LHS, RHS); 9183 LLVM_FALLTHROUGH; 9184 case ICmpInst::ICMP_ULE: 9185 return 9186 // min(A, ...) <= A 9187 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9188 // A <= max(A, ...) 9189 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9190 } 9191 9192 llvm_unreachable("covered switch fell through?!"); 9193 } 9194 9195 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9196 const SCEV *LHS, const SCEV *RHS, 9197 const SCEV *FoundLHS, 9198 const SCEV *FoundRHS, 9199 unsigned Depth) { 9200 assert(getTypeSizeInBits(LHS->getType()) == 9201 getTypeSizeInBits(RHS->getType()) && 9202 "LHS and RHS have different sizes?"); 9203 assert(getTypeSizeInBits(FoundLHS->getType()) == 9204 getTypeSizeInBits(FoundRHS->getType()) && 9205 "FoundLHS and FoundRHS have different sizes?"); 9206 // We want to avoid hurting the compile time with analysis of too big trees. 9207 if (Depth > MaxSCEVOperationsImplicationDepth) 9208 return false; 9209 // We only want to work with ICMP_SGT comparison so far. 9210 // TODO: Extend to ICMP_UGT? 9211 if (Pred == ICmpInst::ICMP_SLT) { 9212 Pred = ICmpInst::ICMP_SGT; 9213 std::swap(LHS, RHS); 9214 std::swap(FoundLHS, FoundRHS); 9215 } 9216 if (Pred != ICmpInst::ICMP_SGT) 9217 return false; 9218 9219 auto GetOpFromSExt = [&](const SCEV *S) { 9220 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9221 return Ext->getOperand(); 9222 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9223 // the constant in some cases. 9224 return S; 9225 }; 9226 9227 // Acquire values from extensions. 9228 auto *OrigFoundLHS = FoundLHS; 9229 LHS = GetOpFromSExt(LHS); 9230 FoundLHS = GetOpFromSExt(FoundLHS); 9231 9232 // Is the SGT predicate can be proved trivially or using the found context. 9233 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9234 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9235 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9236 FoundRHS, Depth + 1); 9237 }; 9238 9239 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9240 // We want to avoid creation of any new non-constant SCEV. Since we are 9241 // going to compare the operands to RHS, we should be certain that we don't 9242 // need any size extensions for this. So let's decline all cases when the 9243 // sizes of types of LHS and RHS do not match. 9244 // TODO: Maybe try to get RHS from sext to catch more cases? 9245 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9246 return false; 9247 9248 // Should not overflow. 9249 if (!LHSAddExpr->hasNoSignedWrap()) 9250 return false; 9251 9252 auto *LL = LHSAddExpr->getOperand(0); 9253 auto *LR = LHSAddExpr->getOperand(1); 9254 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9255 9256 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9257 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9258 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9259 }; 9260 // Try to prove the following rule: 9261 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9262 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9263 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9264 return true; 9265 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9266 Value *LL, *LR; 9267 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9268 using namespace llvm::PatternMatch; 9269 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9270 // Rules for division. 9271 // We are going to perform some comparisons with Denominator and its 9272 // derivative expressions. In general case, creating a SCEV for it may 9273 // lead to a complex analysis of the entire graph, and in particular it 9274 // can request trip count recalculation for the same loop. This would 9275 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9276 // this, we only want to create SCEVs that are constants in this section. 9277 // So we bail if Denominator is not a constant. 9278 if (!isa<ConstantInt>(LR)) 9279 return false; 9280 9281 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9282 9283 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9284 // then a SCEV for the numerator already exists and matches with FoundLHS. 9285 auto *Numerator = getExistingSCEV(LL); 9286 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9287 return false; 9288 9289 // Make sure that the numerator matches with FoundLHS and the denominator 9290 // is positive. 9291 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9292 return false; 9293 9294 auto *DTy = Denominator->getType(); 9295 auto *FRHSTy = FoundRHS->getType(); 9296 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9297 // One of types is a pointer and another one is not. We cannot extend 9298 // them properly to a wider type, so let us just reject this case. 9299 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9300 // to avoid this check. 9301 return false; 9302 9303 // Given that: 9304 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9305 auto *WTy = getWiderType(DTy, FRHSTy); 9306 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9307 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9308 9309 // Try to prove the following rule: 9310 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9311 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9312 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9313 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9314 if (isKnownNonPositive(RHS) && 9315 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9316 return true; 9317 9318 // Try to prove the following rule: 9319 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9320 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9321 // If we divide it by Denominator > 2, then: 9322 // 1. If FoundLHS is negative, then the result is 0. 9323 // 2. If FoundLHS is non-negative, then the result is non-negative. 9324 // Anyways, the result is non-negative. 9325 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9326 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9327 if (isKnownNegative(RHS) && 9328 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9329 return true; 9330 } 9331 } 9332 9333 return false; 9334 } 9335 9336 bool 9337 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 9338 const SCEV *LHS, const SCEV *RHS) { 9339 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9340 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9341 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9342 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9343 } 9344 9345 bool 9346 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9347 const SCEV *LHS, const SCEV *RHS, 9348 const SCEV *FoundLHS, 9349 const SCEV *FoundRHS) { 9350 switch (Pred) { 9351 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9352 case ICmpInst::ICMP_EQ: 9353 case ICmpInst::ICMP_NE: 9354 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9355 return true; 9356 break; 9357 case ICmpInst::ICMP_SLT: 9358 case ICmpInst::ICMP_SLE: 9359 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9360 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9361 return true; 9362 break; 9363 case ICmpInst::ICMP_SGT: 9364 case ICmpInst::ICMP_SGE: 9365 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9366 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9367 return true; 9368 break; 9369 case ICmpInst::ICMP_ULT: 9370 case ICmpInst::ICMP_ULE: 9371 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9372 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9373 return true; 9374 break; 9375 case ICmpInst::ICMP_UGT: 9376 case ICmpInst::ICMP_UGE: 9377 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9378 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9379 return true; 9380 break; 9381 } 9382 9383 // Maybe it can be proved via operations? 9384 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9385 return true; 9386 9387 return false; 9388 } 9389 9390 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9391 const SCEV *LHS, 9392 const SCEV *RHS, 9393 const SCEV *FoundLHS, 9394 const SCEV *FoundRHS) { 9395 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9396 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9397 // reduce the compile time impact of this optimization. 9398 return false; 9399 9400 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9401 if (!Addend) 9402 return false; 9403 9404 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9405 9406 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9407 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9408 ConstantRange FoundLHSRange = 9409 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9410 9411 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9412 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9413 9414 // We can also compute the range of values for `LHS` that satisfy the 9415 // consequent, "`LHS` `Pred` `RHS`": 9416 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9417 ConstantRange SatisfyingLHSRange = 9418 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9419 9420 // The antecedent implies the consequent if every value of `LHS` that 9421 // satisfies the antecedent also satisfies the consequent. 9422 return SatisfyingLHSRange.contains(LHSRange); 9423 } 9424 9425 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9426 bool IsSigned, bool NoWrap) { 9427 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9428 9429 if (NoWrap) return false; 9430 9431 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9432 const SCEV *One = getOne(Stride->getType()); 9433 9434 if (IsSigned) { 9435 APInt MaxRHS = getSignedRangeMax(RHS); 9436 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9437 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9438 9439 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9440 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9441 } 9442 9443 APInt MaxRHS = getUnsignedRangeMax(RHS); 9444 APInt MaxValue = APInt::getMaxValue(BitWidth); 9445 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9446 9447 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9448 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9449 } 9450 9451 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9452 bool IsSigned, bool NoWrap) { 9453 if (NoWrap) return false; 9454 9455 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9456 const SCEV *One = getOne(Stride->getType()); 9457 9458 if (IsSigned) { 9459 APInt MinRHS = getSignedRangeMin(RHS); 9460 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9461 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9462 9463 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9464 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9465 } 9466 9467 APInt MinRHS = getUnsignedRangeMin(RHS); 9468 APInt MinValue = APInt::getMinValue(BitWidth); 9469 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9470 9471 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9472 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9473 } 9474 9475 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9476 bool Equality) { 9477 const SCEV *One = getOne(Step->getType()); 9478 Delta = Equality ? getAddExpr(Delta, Step) 9479 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9480 return getUDivExpr(Delta, Step); 9481 } 9482 9483 ScalarEvolution::ExitLimit 9484 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9485 const Loop *L, bool IsSigned, 9486 bool ControlsExit, bool AllowPredicates) { 9487 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9488 // We handle only IV < Invariant 9489 if (!isLoopInvariant(RHS, L)) 9490 return getCouldNotCompute(); 9491 9492 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9493 bool PredicatedIV = false; 9494 9495 if (!IV && AllowPredicates) { 9496 // Try to make this an AddRec using runtime tests, in the first X 9497 // iterations of this loop, where X is the SCEV expression found by the 9498 // algorithm below. 9499 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9500 PredicatedIV = true; 9501 } 9502 9503 // Avoid weird loops 9504 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9505 return getCouldNotCompute(); 9506 9507 bool NoWrap = ControlsExit && 9508 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9509 9510 const SCEV *Stride = IV->getStepRecurrence(*this); 9511 9512 bool PositiveStride = isKnownPositive(Stride); 9513 9514 // Avoid negative or zero stride values. 9515 if (!PositiveStride) { 9516 // We can compute the correct backedge taken count for loops with unknown 9517 // strides if we can prove that the loop is not an infinite loop with side 9518 // effects. Here's the loop structure we are trying to handle - 9519 // 9520 // i = start 9521 // do { 9522 // A[i] = i; 9523 // i += s; 9524 // } while (i < end); 9525 // 9526 // The backedge taken count for such loops is evaluated as - 9527 // (max(end, start + stride) - start - 1) /u stride 9528 // 9529 // The additional preconditions that we need to check to prove correctness 9530 // of the above formula is as follows - 9531 // 9532 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9533 // NoWrap flag). 9534 // b) loop is single exit with no side effects. 9535 // 9536 // 9537 // Precondition a) implies that if the stride is negative, this is a single 9538 // trip loop. The backedge taken count formula reduces to zero in this case. 9539 // 9540 // Precondition b) implies that the unknown stride cannot be zero otherwise 9541 // we have UB. 9542 // 9543 // The positive stride case is the same as isKnownPositive(Stride) returning 9544 // true (original behavior of the function). 9545 // 9546 // We want to make sure that the stride is truly unknown as there are edge 9547 // cases where ScalarEvolution propagates no wrap flags to the 9548 // post-increment/decrement IV even though the increment/decrement operation 9549 // itself is wrapping. The computed backedge taken count may be wrong in 9550 // such cases. This is prevented by checking that the stride is not known to 9551 // be either positive or non-positive. For example, no wrap flags are 9552 // propagated to the post-increment IV of this loop with a trip count of 2 - 9553 // 9554 // unsigned char i; 9555 // for(i=127; i<128; i+=129) 9556 // A[i] = i; 9557 // 9558 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9559 !loopHasNoSideEffects(L)) 9560 return getCouldNotCompute(); 9561 9562 } else if (!Stride->isOne() && 9563 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9564 // Avoid proven overflow cases: this will ensure that the backedge taken 9565 // count will not generate any unsigned overflow. Relaxed no-overflow 9566 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9567 // undefined behaviors like the case of C language. 9568 return getCouldNotCompute(); 9569 9570 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9571 : ICmpInst::ICMP_ULT; 9572 const SCEV *Start = IV->getStart(); 9573 const SCEV *End = RHS; 9574 // If the backedge is taken at least once, then it will be taken 9575 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9576 // is the LHS value of the less-than comparison the first time it is evaluated 9577 // and End is the RHS. 9578 const SCEV *BECountIfBackedgeTaken = 9579 computeBECount(getMinusSCEV(End, Start), Stride, false); 9580 // If the loop entry is guarded by the result of the backedge test of the 9581 // first loop iteration, then we know the backedge will be taken at least 9582 // once and so the backedge taken count is as above. If not then we use the 9583 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9584 // as if the backedge is taken at least once max(End,Start) is End and so the 9585 // result is as above, and if not max(End,Start) is Start so we get a backedge 9586 // count of zero. 9587 const SCEV *BECount; 9588 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9589 BECount = BECountIfBackedgeTaken; 9590 else { 9591 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9592 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9593 } 9594 9595 const SCEV *MaxBECount; 9596 bool MaxOrZero = false; 9597 if (isa<SCEVConstant>(BECount)) 9598 MaxBECount = BECount; 9599 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9600 // If we know exactly how many times the backedge will be taken if it's 9601 // taken at least once, then the backedge count will either be that or 9602 // zero. 9603 MaxBECount = BECountIfBackedgeTaken; 9604 MaxOrZero = true; 9605 } else { 9606 // Calculate the maximum backedge count based on the range of values 9607 // permitted by Start, End, and Stride. 9608 APInt MinStart = IsSigned ? getSignedRangeMin(Start) 9609 : getUnsignedRangeMin(Start); 9610 9611 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9612 9613 APInt StrideForMaxBECount; 9614 9615 if (PositiveStride) 9616 StrideForMaxBECount = 9617 IsSigned ? getSignedRangeMin(Stride) 9618 : getUnsignedRangeMin(Stride); 9619 else 9620 // Using a stride of 1 is safe when computing max backedge taken count for 9621 // a loop with unknown stride. 9622 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9623 9624 APInt Limit = 9625 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9626 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9627 9628 // Although End can be a MAX expression we estimate MaxEnd considering only 9629 // the case End = RHS. This is safe because in the other case (End - Start) 9630 // is zero, leading to a zero maximum backedge taken count. 9631 APInt MaxEnd = 9632 IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit) 9633 : APIntOps::umin(getUnsignedRangeMax(RHS), Limit); 9634 9635 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9636 getConstant(StrideForMaxBECount), false); 9637 } 9638 9639 if (isa<SCEVCouldNotCompute>(MaxBECount) && 9640 !isa<SCEVCouldNotCompute>(BECount)) 9641 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 9642 9643 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9644 } 9645 9646 ScalarEvolution::ExitLimit 9647 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9648 const Loop *L, bool IsSigned, 9649 bool ControlsExit, bool AllowPredicates) { 9650 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9651 // We handle only IV > Invariant 9652 if (!isLoopInvariant(RHS, L)) 9653 return getCouldNotCompute(); 9654 9655 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9656 if (!IV && AllowPredicates) 9657 // Try to make this an AddRec using runtime tests, in the first X 9658 // iterations of this loop, where X is the SCEV expression found by the 9659 // algorithm below. 9660 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9661 9662 // Avoid weird loops 9663 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9664 return getCouldNotCompute(); 9665 9666 bool NoWrap = ControlsExit && 9667 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9668 9669 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9670 9671 // Avoid negative or zero stride values 9672 if (!isKnownPositive(Stride)) 9673 return getCouldNotCompute(); 9674 9675 // Avoid proven overflow cases: this will ensure that the backedge taken count 9676 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9677 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9678 // behaviors like the case of C language. 9679 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9680 return getCouldNotCompute(); 9681 9682 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9683 : ICmpInst::ICMP_UGT; 9684 9685 const SCEV *Start = IV->getStart(); 9686 const SCEV *End = RHS; 9687 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9688 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9689 9690 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9691 9692 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 9693 : getUnsignedRangeMax(Start); 9694 9695 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 9696 : getUnsignedRangeMin(Stride); 9697 9698 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9699 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9700 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9701 9702 // Although End can be a MIN expression we estimate MinEnd considering only 9703 // the case End = RHS. This is safe because in the other case (Start - End) 9704 // is zero, leading to a zero maximum backedge taken count. 9705 APInt MinEnd = 9706 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 9707 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 9708 9709 9710 const SCEV *MaxBECount = getCouldNotCompute(); 9711 if (isa<SCEVConstant>(BECount)) 9712 MaxBECount = BECount; 9713 else 9714 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9715 getConstant(MinStride), false); 9716 9717 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9718 MaxBECount = BECount; 9719 9720 return ExitLimit(BECount, MaxBECount, false, Predicates); 9721 } 9722 9723 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9724 ScalarEvolution &SE) const { 9725 if (Range.isFullSet()) // Infinite loop. 9726 return SE.getCouldNotCompute(); 9727 9728 // If the start is a non-zero constant, shift the range to simplify things. 9729 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9730 if (!SC->getValue()->isZero()) { 9731 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9732 Operands[0] = SE.getZero(SC->getType()); 9733 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9734 getNoWrapFlags(FlagNW)); 9735 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9736 return ShiftedAddRec->getNumIterationsInRange( 9737 Range.subtract(SC->getAPInt()), SE); 9738 // This is strange and shouldn't happen. 9739 return SE.getCouldNotCompute(); 9740 } 9741 9742 // The only time we can solve this is when we have all constant indices. 9743 // Otherwise, we cannot determine the overflow conditions. 9744 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9745 return SE.getCouldNotCompute(); 9746 9747 // Okay at this point we know that all elements of the chrec are constants and 9748 // that the start element is zero. 9749 9750 // First check to see if the range contains zero. If not, the first 9751 // iteration exits. 9752 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9753 if (!Range.contains(APInt(BitWidth, 0))) 9754 return SE.getZero(getType()); 9755 9756 if (isAffine()) { 9757 // If this is an affine expression then we have this situation: 9758 // Solve {0,+,A} in Range === Ax in Range 9759 9760 // We know that zero is in the range. If A is positive then we know that 9761 // the upper value of the range must be the first possible exit value. 9762 // If A is negative then the lower of the range is the last possible loop 9763 // value. Also note that we already checked for a full range. 9764 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9765 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 9766 9767 // The exit value should be (End+A)/A. 9768 APInt ExitVal = (End + A).udiv(A); 9769 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9770 9771 // Evaluate at the exit value. If we really did fall out of the valid 9772 // range, then we computed our trip count, otherwise wrap around or other 9773 // things must have happened. 9774 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9775 if (Range.contains(Val->getValue())) 9776 return SE.getCouldNotCompute(); // Something strange happened 9777 9778 // Ensure that the previous value is in the range. This is a sanity check. 9779 assert(Range.contains( 9780 EvaluateConstantChrecAtConstant(this, 9781 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 9782 "Linear scev computation is off in a bad way!"); 9783 return SE.getConstant(ExitValue); 9784 } else if (isQuadratic()) { 9785 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9786 // quadratic equation to solve it. To do this, we must frame our problem in 9787 // terms of figuring out when zero is crossed, instead of when 9788 // Range.getUpper() is crossed. 9789 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9790 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9791 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9792 9793 // Next, solve the constructed addrec 9794 if (auto Roots = 9795 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9796 const SCEVConstant *R1 = Roots->first; 9797 const SCEVConstant *R2 = Roots->second; 9798 // Pick the smallest positive root value. 9799 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9800 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9801 if (!CB->getZExtValue()) 9802 std::swap(R1, R2); // R1 is the minimum root now. 9803 9804 // Make sure the root is not off by one. The returned iteration should 9805 // not be in the range, but the previous one should be. When solving 9806 // for "X*X < 5", for example, we should not return a root of 2. 9807 ConstantInt *R1Val = 9808 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9809 if (Range.contains(R1Val->getValue())) { 9810 // The next iteration must be out of the range... 9811 ConstantInt *NextVal = 9812 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9813 9814 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9815 if (!Range.contains(R1Val->getValue())) 9816 return SE.getConstant(NextVal); 9817 return SE.getCouldNotCompute(); // Something strange happened 9818 } 9819 9820 // If R1 was not in the range, then it is a good return value. Make 9821 // sure that R1-1 WAS in the range though, just in case. 9822 ConstantInt *NextVal = 9823 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9824 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9825 if (Range.contains(R1Val->getValue())) 9826 return R1; 9827 return SE.getCouldNotCompute(); // Something strange happened 9828 } 9829 } 9830 } 9831 9832 return SE.getCouldNotCompute(); 9833 } 9834 9835 // Return true when S contains at least an undef value. 9836 static inline bool containsUndefs(const SCEV *S) { 9837 return SCEVExprContains(S, [](const SCEV *S) { 9838 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9839 return isa<UndefValue>(SU->getValue()); 9840 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9841 return isa<UndefValue>(SC->getValue()); 9842 return false; 9843 }); 9844 } 9845 9846 namespace { 9847 // Collect all steps of SCEV expressions. 9848 struct SCEVCollectStrides { 9849 ScalarEvolution &SE; 9850 SmallVectorImpl<const SCEV *> &Strides; 9851 9852 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9853 : SE(SE), Strides(S) {} 9854 9855 bool follow(const SCEV *S) { 9856 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9857 Strides.push_back(AR->getStepRecurrence(SE)); 9858 return true; 9859 } 9860 bool isDone() const { return false; } 9861 }; 9862 9863 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9864 struct SCEVCollectTerms { 9865 SmallVectorImpl<const SCEV *> &Terms; 9866 9867 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9868 : Terms(T) {} 9869 9870 bool follow(const SCEV *S) { 9871 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9872 isa<SCEVSignExtendExpr>(S)) { 9873 if (!containsUndefs(S)) 9874 Terms.push_back(S); 9875 9876 // Stop recursion: once we collected a term, do not walk its operands. 9877 return false; 9878 } 9879 9880 // Keep looking. 9881 return true; 9882 } 9883 bool isDone() const { return false; } 9884 }; 9885 9886 // Check if a SCEV contains an AddRecExpr. 9887 struct SCEVHasAddRec { 9888 bool &ContainsAddRec; 9889 9890 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9891 ContainsAddRec = false; 9892 } 9893 9894 bool follow(const SCEV *S) { 9895 if (isa<SCEVAddRecExpr>(S)) { 9896 ContainsAddRec = true; 9897 9898 // Stop recursion: once we collected a term, do not walk its operands. 9899 return false; 9900 } 9901 9902 // Keep looking. 9903 return true; 9904 } 9905 bool isDone() const { return false; } 9906 }; 9907 9908 // Find factors that are multiplied with an expression that (possibly as a 9909 // subexpression) contains an AddRecExpr. In the expression: 9910 // 9911 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9912 // 9913 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9914 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9915 // parameters as they form a product with an induction variable. 9916 // 9917 // This collector expects all array size parameters to be in the same MulExpr. 9918 // It might be necessary to later add support for collecting parameters that are 9919 // spread over different nested MulExpr. 9920 struct SCEVCollectAddRecMultiplies { 9921 SmallVectorImpl<const SCEV *> &Terms; 9922 ScalarEvolution &SE; 9923 9924 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9925 : Terms(T), SE(SE) {} 9926 9927 bool follow(const SCEV *S) { 9928 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9929 bool HasAddRec = false; 9930 SmallVector<const SCEV *, 0> Operands; 9931 for (auto Op : Mul->operands()) { 9932 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 9933 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 9934 Operands.push_back(Op); 9935 } else if (Unknown) { 9936 HasAddRec = true; 9937 } else { 9938 bool ContainsAddRec; 9939 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9940 visitAll(Op, ContiansAddRec); 9941 HasAddRec |= ContainsAddRec; 9942 } 9943 } 9944 if (Operands.size() == 0) 9945 return true; 9946 9947 if (!HasAddRec) 9948 return false; 9949 9950 Terms.push_back(SE.getMulExpr(Operands)); 9951 // Stop recursion: once we collected a term, do not walk its operands. 9952 return false; 9953 } 9954 9955 // Keep looking. 9956 return true; 9957 } 9958 bool isDone() const { return false; } 9959 }; 9960 } 9961 9962 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9963 /// two places: 9964 /// 1) The strides of AddRec expressions. 9965 /// 2) Unknowns that are multiplied with AddRec expressions. 9966 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9967 SmallVectorImpl<const SCEV *> &Terms) { 9968 SmallVector<const SCEV *, 4> Strides; 9969 SCEVCollectStrides StrideCollector(*this, Strides); 9970 visitAll(Expr, StrideCollector); 9971 9972 DEBUG({ 9973 dbgs() << "Strides:\n"; 9974 for (const SCEV *S : Strides) 9975 dbgs() << *S << "\n"; 9976 }); 9977 9978 for (const SCEV *S : Strides) { 9979 SCEVCollectTerms TermCollector(Terms); 9980 visitAll(S, TermCollector); 9981 } 9982 9983 DEBUG({ 9984 dbgs() << "Terms:\n"; 9985 for (const SCEV *T : Terms) 9986 dbgs() << *T << "\n"; 9987 }); 9988 9989 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9990 visitAll(Expr, MulCollector); 9991 } 9992 9993 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9994 SmallVectorImpl<const SCEV *> &Terms, 9995 SmallVectorImpl<const SCEV *> &Sizes) { 9996 int Last = Terms.size() - 1; 9997 const SCEV *Step = Terms[Last]; 9998 9999 // End of recursion. 10000 if (Last == 0) { 10001 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10002 SmallVector<const SCEV *, 2> Qs; 10003 for (const SCEV *Op : M->operands()) 10004 if (!isa<SCEVConstant>(Op)) 10005 Qs.push_back(Op); 10006 10007 Step = SE.getMulExpr(Qs); 10008 } 10009 10010 Sizes.push_back(Step); 10011 return true; 10012 } 10013 10014 for (const SCEV *&Term : Terms) { 10015 // Normalize the terms before the next call to findArrayDimensionsRec. 10016 const SCEV *Q, *R; 10017 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10018 10019 // Bail out when GCD does not evenly divide one of the terms. 10020 if (!R->isZero()) 10021 return false; 10022 10023 Term = Q; 10024 } 10025 10026 // Remove all SCEVConstants. 10027 Terms.erase( 10028 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10029 Terms.end()); 10030 10031 if (Terms.size() > 0) 10032 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10033 return false; 10034 10035 Sizes.push_back(Step); 10036 return true; 10037 } 10038 10039 10040 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10041 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10042 for (const SCEV *T : Terms) 10043 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10044 return true; 10045 return false; 10046 } 10047 10048 // Return the number of product terms in S. 10049 static inline int numberOfTerms(const SCEV *S) { 10050 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10051 return Expr->getNumOperands(); 10052 return 1; 10053 } 10054 10055 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10056 if (isa<SCEVConstant>(T)) 10057 return nullptr; 10058 10059 if (isa<SCEVUnknown>(T)) 10060 return T; 10061 10062 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10063 SmallVector<const SCEV *, 2> Factors; 10064 for (const SCEV *Op : M->operands()) 10065 if (!isa<SCEVConstant>(Op)) 10066 Factors.push_back(Op); 10067 10068 return SE.getMulExpr(Factors); 10069 } 10070 10071 return T; 10072 } 10073 10074 /// Return the size of an element read or written by Inst. 10075 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10076 Type *Ty; 10077 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10078 Ty = Store->getValueOperand()->getType(); 10079 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10080 Ty = Load->getType(); 10081 else 10082 return nullptr; 10083 10084 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10085 return getSizeOfExpr(ETy, Ty); 10086 } 10087 10088 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10089 SmallVectorImpl<const SCEV *> &Sizes, 10090 const SCEV *ElementSize) { 10091 if (Terms.size() < 1 || !ElementSize) 10092 return; 10093 10094 // Early return when Terms do not contain parameters: we do not delinearize 10095 // non parametric SCEVs. 10096 if (!containsParameters(Terms)) 10097 return; 10098 10099 DEBUG({ 10100 dbgs() << "Terms:\n"; 10101 for (const SCEV *T : Terms) 10102 dbgs() << *T << "\n"; 10103 }); 10104 10105 // Remove duplicates. 10106 array_pod_sort(Terms.begin(), Terms.end()); 10107 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10108 10109 // Put larger terms first. 10110 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10111 return numberOfTerms(LHS) > numberOfTerms(RHS); 10112 }); 10113 10114 // Try to divide all terms by the element size. If term is not divisible by 10115 // element size, proceed with the original term. 10116 for (const SCEV *&Term : Terms) { 10117 const SCEV *Q, *R; 10118 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10119 if (!Q->isZero()) 10120 Term = Q; 10121 } 10122 10123 SmallVector<const SCEV *, 4> NewTerms; 10124 10125 // Remove constant factors. 10126 for (const SCEV *T : Terms) 10127 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10128 NewTerms.push_back(NewT); 10129 10130 DEBUG({ 10131 dbgs() << "Terms after sorting:\n"; 10132 for (const SCEV *T : NewTerms) 10133 dbgs() << *T << "\n"; 10134 }); 10135 10136 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10137 Sizes.clear(); 10138 return; 10139 } 10140 10141 // The last element to be pushed into Sizes is the size of an element. 10142 Sizes.push_back(ElementSize); 10143 10144 DEBUG({ 10145 dbgs() << "Sizes:\n"; 10146 for (const SCEV *S : Sizes) 10147 dbgs() << *S << "\n"; 10148 }); 10149 } 10150 10151 void ScalarEvolution::computeAccessFunctions( 10152 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10153 SmallVectorImpl<const SCEV *> &Sizes) { 10154 10155 // Early exit in case this SCEV is not an affine multivariate function. 10156 if (Sizes.empty()) 10157 return; 10158 10159 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10160 if (!AR->isAffine()) 10161 return; 10162 10163 const SCEV *Res = Expr; 10164 int Last = Sizes.size() - 1; 10165 for (int i = Last; i >= 0; i--) { 10166 const SCEV *Q, *R; 10167 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10168 10169 DEBUG({ 10170 dbgs() << "Res: " << *Res << "\n"; 10171 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10172 dbgs() << "Res divided by Sizes[i]:\n"; 10173 dbgs() << "Quotient: " << *Q << "\n"; 10174 dbgs() << "Remainder: " << *R << "\n"; 10175 }); 10176 10177 Res = Q; 10178 10179 // Do not record the last subscript corresponding to the size of elements in 10180 // the array. 10181 if (i == Last) { 10182 10183 // Bail out if the remainder is too complex. 10184 if (isa<SCEVAddRecExpr>(R)) { 10185 Subscripts.clear(); 10186 Sizes.clear(); 10187 return; 10188 } 10189 10190 continue; 10191 } 10192 10193 // Record the access function for the current subscript. 10194 Subscripts.push_back(R); 10195 } 10196 10197 // Also push in last position the remainder of the last division: it will be 10198 // the access function of the innermost dimension. 10199 Subscripts.push_back(Res); 10200 10201 std::reverse(Subscripts.begin(), Subscripts.end()); 10202 10203 DEBUG({ 10204 dbgs() << "Subscripts:\n"; 10205 for (const SCEV *S : Subscripts) 10206 dbgs() << *S << "\n"; 10207 }); 10208 } 10209 10210 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10211 /// sizes of an array access. Returns the remainder of the delinearization that 10212 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10213 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10214 /// expressions in the stride and base of a SCEV corresponding to the 10215 /// computation of a GCD (greatest common divisor) of base and stride. When 10216 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10217 /// 10218 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10219 /// 10220 /// void foo(long n, long m, long o, double A[n][m][o]) { 10221 /// 10222 /// for (long i = 0; i < n; i++) 10223 /// for (long j = 0; j < m; j++) 10224 /// for (long k = 0; k < o; k++) 10225 /// A[i][j][k] = 1.0; 10226 /// } 10227 /// 10228 /// the delinearization input is the following AddRec SCEV: 10229 /// 10230 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10231 /// 10232 /// From this SCEV, we are able to say that the base offset of the access is %A 10233 /// because it appears as an offset that does not divide any of the strides in 10234 /// the loops: 10235 /// 10236 /// CHECK: Base offset: %A 10237 /// 10238 /// and then SCEV->delinearize determines the size of some of the dimensions of 10239 /// the array as these are the multiples by which the strides are happening: 10240 /// 10241 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10242 /// 10243 /// Note that the outermost dimension remains of UnknownSize because there are 10244 /// no strides that would help identifying the size of the last dimension: when 10245 /// the array has been statically allocated, one could compute the size of that 10246 /// dimension by dividing the overall size of the array by the size of the known 10247 /// dimensions: %m * %o * 8. 10248 /// 10249 /// Finally delinearize provides the access functions for the array reference 10250 /// that does correspond to A[i][j][k] of the above C testcase: 10251 /// 10252 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10253 /// 10254 /// The testcases are checking the output of a function pass: 10255 /// DelinearizationPass that walks through all loads and stores of a function 10256 /// asking for the SCEV of the memory access with respect to all enclosing 10257 /// loops, calling SCEV->delinearize on that and printing the results. 10258 10259 void ScalarEvolution::delinearize(const SCEV *Expr, 10260 SmallVectorImpl<const SCEV *> &Subscripts, 10261 SmallVectorImpl<const SCEV *> &Sizes, 10262 const SCEV *ElementSize) { 10263 // First step: collect parametric terms. 10264 SmallVector<const SCEV *, 4> Terms; 10265 collectParametricTerms(Expr, Terms); 10266 10267 if (Terms.empty()) 10268 return; 10269 10270 // Second step: find subscript sizes. 10271 findArrayDimensions(Terms, Sizes, ElementSize); 10272 10273 if (Sizes.empty()) 10274 return; 10275 10276 // Third step: compute the access functions for each subscript. 10277 computeAccessFunctions(Expr, Subscripts, Sizes); 10278 10279 if (Subscripts.empty()) 10280 return; 10281 10282 DEBUG({ 10283 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10284 dbgs() << "ArrayDecl[UnknownSize]"; 10285 for (const SCEV *S : Sizes) 10286 dbgs() << "[" << *S << "]"; 10287 10288 dbgs() << "\nArrayRef"; 10289 for (const SCEV *S : Subscripts) 10290 dbgs() << "[" << *S << "]"; 10291 dbgs() << "\n"; 10292 }); 10293 } 10294 10295 //===----------------------------------------------------------------------===// 10296 // SCEVCallbackVH Class Implementation 10297 //===----------------------------------------------------------------------===// 10298 10299 void ScalarEvolution::SCEVCallbackVH::deleted() { 10300 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10301 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10302 SE->ConstantEvolutionLoopExitValue.erase(PN); 10303 SE->eraseValueFromMap(getValPtr()); 10304 // this now dangles! 10305 } 10306 10307 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10308 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10309 10310 // Forget all the expressions associated with users of the old value, 10311 // so that future queries will recompute the expressions using the new 10312 // value. 10313 Value *Old = getValPtr(); 10314 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10315 SmallPtrSet<User *, 8> Visited; 10316 while (!Worklist.empty()) { 10317 User *U = Worklist.pop_back_val(); 10318 // Deleting the Old value will cause this to dangle. Postpone 10319 // that until everything else is done. 10320 if (U == Old) 10321 continue; 10322 if (!Visited.insert(U).second) 10323 continue; 10324 if (PHINode *PN = dyn_cast<PHINode>(U)) 10325 SE->ConstantEvolutionLoopExitValue.erase(PN); 10326 SE->eraseValueFromMap(U); 10327 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10328 } 10329 // Delete the Old value. 10330 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10331 SE->ConstantEvolutionLoopExitValue.erase(PN); 10332 SE->eraseValueFromMap(Old); 10333 // this now dangles! 10334 } 10335 10336 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10337 : CallbackVH(V), SE(se) {} 10338 10339 //===----------------------------------------------------------------------===// 10340 // ScalarEvolution Class Implementation 10341 //===----------------------------------------------------------------------===// 10342 10343 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10344 AssumptionCache &AC, DominatorTree &DT, 10345 LoopInfo &LI) 10346 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10347 CouldNotCompute(new SCEVCouldNotCompute()), 10348 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 10349 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 10350 FirstUnknown(nullptr) { 10351 10352 // To use guards for proving predicates, we need to scan every instruction in 10353 // relevant basic blocks, and not just terminators. Doing this is a waste of 10354 // time if the IR does not actually contain any calls to 10355 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10356 // 10357 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10358 // to _add_ guards to the module when there weren't any before, and wants 10359 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10360 // efficient in lieu of being smart in that rather obscure case. 10361 10362 auto *GuardDecl = F.getParent()->getFunction( 10363 Intrinsic::getName(Intrinsic::experimental_guard)); 10364 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10365 } 10366 10367 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10368 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10369 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10370 ValueExprMap(std::move(Arg.ValueExprMap)), 10371 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10372 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 10373 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10374 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10375 PredicatedBackedgeTakenCounts( 10376 std::move(Arg.PredicatedBackedgeTakenCounts)), 10377 ConstantEvolutionLoopExitValue( 10378 std::move(Arg.ConstantEvolutionLoopExitValue)), 10379 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10380 LoopDispositions(std::move(Arg.LoopDispositions)), 10381 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10382 BlockDispositions(std::move(Arg.BlockDispositions)), 10383 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10384 SignedRanges(std::move(Arg.SignedRanges)), 10385 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10386 UniquePreds(std::move(Arg.UniquePreds)), 10387 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10388 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10389 FirstUnknown(Arg.FirstUnknown) { 10390 Arg.FirstUnknown = nullptr; 10391 } 10392 10393 ScalarEvolution::~ScalarEvolution() { 10394 // Iterate through all the SCEVUnknown instances and call their 10395 // destructors, so that they release their references to their values. 10396 for (SCEVUnknown *U = FirstUnknown; U;) { 10397 SCEVUnknown *Tmp = U; 10398 U = U->Next; 10399 Tmp->~SCEVUnknown(); 10400 } 10401 FirstUnknown = nullptr; 10402 10403 ExprValueMap.clear(); 10404 ValueExprMap.clear(); 10405 HasRecMap.clear(); 10406 10407 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10408 // that a loop had multiple computable exits. 10409 for (auto &BTCI : BackedgeTakenCounts) 10410 BTCI.second.clear(); 10411 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10412 BTCI.second.clear(); 10413 10414 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10415 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10416 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10417 } 10418 10419 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10420 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10421 } 10422 10423 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10424 const Loop *L) { 10425 // Print all inner loops first 10426 for (Loop *I : *L) 10427 PrintLoopInfo(OS, SE, I); 10428 10429 OS << "Loop "; 10430 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10431 OS << ": "; 10432 10433 SmallVector<BasicBlock *, 8> ExitBlocks; 10434 L->getExitBlocks(ExitBlocks); 10435 if (ExitBlocks.size() != 1) 10436 OS << "<multiple exits> "; 10437 10438 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10439 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10440 } else { 10441 OS << "Unpredictable backedge-taken count. "; 10442 } 10443 10444 OS << "\n" 10445 "Loop "; 10446 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10447 OS << ": "; 10448 10449 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10450 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10451 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10452 OS << ", actual taken count either this or zero."; 10453 } else { 10454 OS << "Unpredictable max backedge-taken count. "; 10455 } 10456 10457 OS << "\n" 10458 "Loop "; 10459 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10460 OS << ": "; 10461 10462 SCEVUnionPredicate Pred; 10463 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10464 if (!isa<SCEVCouldNotCompute>(PBT)) { 10465 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10466 OS << " Predicates:\n"; 10467 Pred.print(OS, 4); 10468 } else { 10469 OS << "Unpredictable predicated backedge-taken count. "; 10470 } 10471 OS << "\n"; 10472 10473 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10474 OS << "Loop "; 10475 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10476 OS << ": "; 10477 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10478 } 10479 } 10480 10481 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 10482 switch (LD) { 10483 case ScalarEvolution::LoopVariant: 10484 return "Variant"; 10485 case ScalarEvolution::LoopInvariant: 10486 return "Invariant"; 10487 case ScalarEvolution::LoopComputable: 10488 return "Computable"; 10489 } 10490 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 10491 } 10492 10493 void ScalarEvolution::print(raw_ostream &OS) const { 10494 // ScalarEvolution's implementation of the print method is to print 10495 // out SCEV values of all instructions that are interesting. Doing 10496 // this potentially causes it to create new SCEV objects though, 10497 // which technically conflicts with the const qualifier. This isn't 10498 // observable from outside the class though, so casting away the 10499 // const isn't dangerous. 10500 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10501 10502 OS << "Classifying expressions for: "; 10503 F.printAsOperand(OS, /*PrintType=*/false); 10504 OS << "\n"; 10505 for (Instruction &I : instructions(F)) 10506 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 10507 OS << I << '\n'; 10508 OS << " --> "; 10509 const SCEV *SV = SE.getSCEV(&I); 10510 SV->print(OS); 10511 if (!isa<SCEVCouldNotCompute>(SV)) { 10512 OS << " U: "; 10513 SE.getUnsignedRange(SV).print(OS); 10514 OS << " S: "; 10515 SE.getSignedRange(SV).print(OS); 10516 } 10517 10518 const Loop *L = LI.getLoopFor(I.getParent()); 10519 10520 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10521 if (AtUse != SV) { 10522 OS << " --> "; 10523 AtUse->print(OS); 10524 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10525 OS << " U: "; 10526 SE.getUnsignedRange(AtUse).print(OS); 10527 OS << " S: "; 10528 SE.getSignedRange(AtUse).print(OS); 10529 } 10530 } 10531 10532 if (L) { 10533 OS << "\t\t" "Exits: "; 10534 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10535 if (!SE.isLoopInvariant(ExitValue, L)) { 10536 OS << "<<Unknown>>"; 10537 } else { 10538 OS << *ExitValue; 10539 } 10540 10541 bool First = true; 10542 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10543 if (First) { 10544 OS << "\t\t" "LoopDispositions: { "; 10545 First = false; 10546 } else { 10547 OS << ", "; 10548 } 10549 10550 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10551 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10552 } 10553 10554 for (auto *InnerL : depth_first(L)) { 10555 if (InnerL == L) 10556 continue; 10557 if (First) { 10558 OS << "\t\t" "LoopDispositions: { "; 10559 First = false; 10560 } else { 10561 OS << ", "; 10562 } 10563 10564 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10565 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10566 } 10567 10568 OS << " }"; 10569 } 10570 10571 OS << "\n"; 10572 } 10573 10574 OS << "Determining loop execution counts for: "; 10575 F.printAsOperand(OS, /*PrintType=*/false); 10576 OS << "\n"; 10577 for (Loop *I : LI) 10578 PrintLoopInfo(OS, &SE, I); 10579 } 10580 10581 ScalarEvolution::LoopDisposition 10582 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10583 auto &Values = LoopDispositions[S]; 10584 for (auto &V : Values) { 10585 if (V.getPointer() == L) 10586 return V.getInt(); 10587 } 10588 Values.emplace_back(L, LoopVariant); 10589 LoopDisposition D = computeLoopDisposition(S, L); 10590 auto &Values2 = LoopDispositions[S]; 10591 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10592 if (V.getPointer() == L) { 10593 V.setInt(D); 10594 break; 10595 } 10596 } 10597 return D; 10598 } 10599 10600 ScalarEvolution::LoopDisposition 10601 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10602 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10603 case scConstant: 10604 return LoopInvariant; 10605 case scTruncate: 10606 case scZeroExtend: 10607 case scSignExtend: 10608 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10609 case scAddRecExpr: { 10610 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10611 10612 // If L is the addrec's loop, it's computable. 10613 if (AR->getLoop() == L) 10614 return LoopComputable; 10615 10616 // Add recurrences are never invariant in the function-body (null loop). 10617 if (!L) 10618 return LoopVariant; 10619 10620 // This recurrence is variant w.r.t. L if L contains AR's loop. 10621 if (L->contains(AR->getLoop())) 10622 return LoopVariant; 10623 10624 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10625 if (AR->getLoop()->contains(L)) 10626 return LoopInvariant; 10627 10628 // This recurrence is variant w.r.t. L if any of its operands 10629 // are variant. 10630 for (auto *Op : AR->operands()) 10631 if (!isLoopInvariant(Op, L)) 10632 return LoopVariant; 10633 10634 // Otherwise it's loop-invariant. 10635 return LoopInvariant; 10636 } 10637 case scAddExpr: 10638 case scMulExpr: 10639 case scUMaxExpr: 10640 case scSMaxExpr: { 10641 bool HasVarying = false; 10642 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10643 LoopDisposition D = getLoopDisposition(Op, L); 10644 if (D == LoopVariant) 10645 return LoopVariant; 10646 if (D == LoopComputable) 10647 HasVarying = true; 10648 } 10649 return HasVarying ? LoopComputable : LoopInvariant; 10650 } 10651 case scUDivExpr: { 10652 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10653 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10654 if (LD == LoopVariant) 10655 return LoopVariant; 10656 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10657 if (RD == LoopVariant) 10658 return LoopVariant; 10659 return (LD == LoopInvariant && RD == LoopInvariant) ? 10660 LoopInvariant : LoopComputable; 10661 } 10662 case scUnknown: 10663 // All non-instruction values are loop invariant. All instructions are loop 10664 // invariant if they are not contained in the specified loop. 10665 // Instructions are never considered invariant in the function body 10666 // (null loop) because they are defined within the "loop". 10667 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10668 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10669 return LoopInvariant; 10670 case scCouldNotCompute: 10671 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10672 } 10673 llvm_unreachable("Unknown SCEV kind!"); 10674 } 10675 10676 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10677 return getLoopDisposition(S, L) == LoopInvariant; 10678 } 10679 10680 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10681 return getLoopDisposition(S, L) == LoopComputable; 10682 } 10683 10684 ScalarEvolution::BlockDisposition 10685 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10686 auto &Values = BlockDispositions[S]; 10687 for (auto &V : Values) { 10688 if (V.getPointer() == BB) 10689 return V.getInt(); 10690 } 10691 Values.emplace_back(BB, DoesNotDominateBlock); 10692 BlockDisposition D = computeBlockDisposition(S, BB); 10693 auto &Values2 = BlockDispositions[S]; 10694 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10695 if (V.getPointer() == BB) { 10696 V.setInt(D); 10697 break; 10698 } 10699 } 10700 return D; 10701 } 10702 10703 ScalarEvolution::BlockDisposition 10704 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10705 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10706 case scConstant: 10707 return ProperlyDominatesBlock; 10708 case scTruncate: 10709 case scZeroExtend: 10710 case scSignExtend: 10711 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10712 case scAddRecExpr: { 10713 // This uses a "dominates" query instead of "properly dominates" query 10714 // to test for proper dominance too, because the instruction which 10715 // produces the addrec's value is a PHI, and a PHI effectively properly 10716 // dominates its entire containing block. 10717 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10718 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10719 return DoesNotDominateBlock; 10720 10721 // Fall through into SCEVNAryExpr handling. 10722 LLVM_FALLTHROUGH; 10723 } 10724 case scAddExpr: 10725 case scMulExpr: 10726 case scUMaxExpr: 10727 case scSMaxExpr: { 10728 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10729 bool Proper = true; 10730 for (const SCEV *NAryOp : NAry->operands()) { 10731 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10732 if (D == DoesNotDominateBlock) 10733 return DoesNotDominateBlock; 10734 if (D == DominatesBlock) 10735 Proper = false; 10736 } 10737 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10738 } 10739 case scUDivExpr: { 10740 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10741 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10742 BlockDisposition LD = getBlockDisposition(LHS, BB); 10743 if (LD == DoesNotDominateBlock) 10744 return DoesNotDominateBlock; 10745 BlockDisposition RD = getBlockDisposition(RHS, BB); 10746 if (RD == DoesNotDominateBlock) 10747 return DoesNotDominateBlock; 10748 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10749 ProperlyDominatesBlock : DominatesBlock; 10750 } 10751 case scUnknown: 10752 if (Instruction *I = 10753 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10754 if (I->getParent() == BB) 10755 return DominatesBlock; 10756 if (DT.properlyDominates(I->getParent(), BB)) 10757 return ProperlyDominatesBlock; 10758 return DoesNotDominateBlock; 10759 } 10760 return ProperlyDominatesBlock; 10761 case scCouldNotCompute: 10762 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10763 } 10764 llvm_unreachable("Unknown SCEV kind!"); 10765 } 10766 10767 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10768 return getBlockDisposition(S, BB) >= DominatesBlock; 10769 } 10770 10771 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10772 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10773 } 10774 10775 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10776 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10777 } 10778 10779 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10780 ValuesAtScopes.erase(S); 10781 LoopDispositions.erase(S); 10782 BlockDispositions.erase(S); 10783 UnsignedRanges.erase(S); 10784 SignedRanges.erase(S); 10785 ExprValueMap.erase(S); 10786 HasRecMap.erase(S); 10787 MinTrailingZerosCache.erase(S); 10788 10789 for (auto I = PredicatedSCEVRewrites.begin(); 10790 I != PredicatedSCEVRewrites.end();) { 10791 std::pair<const SCEV *, const Loop *> Entry = I->first; 10792 if (Entry.first == S) 10793 PredicatedSCEVRewrites.erase(I++); 10794 else 10795 ++I; 10796 } 10797 10798 auto RemoveSCEVFromBackedgeMap = 10799 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10800 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10801 BackedgeTakenInfo &BEInfo = I->second; 10802 if (BEInfo.hasOperand(S, this)) { 10803 BEInfo.clear(); 10804 Map.erase(I++); 10805 } else 10806 ++I; 10807 } 10808 }; 10809 10810 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10811 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10812 } 10813 10814 void ScalarEvolution::verify() const { 10815 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10816 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10817 10818 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 10819 10820 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 10821 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 10822 const SCEV *visitConstant(const SCEVConstant *Constant) { 10823 return SE.getConstant(Constant->getAPInt()); 10824 } 10825 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10826 return SE.getUnknown(Expr->getValue()); 10827 } 10828 10829 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 10830 return SE.getCouldNotCompute(); 10831 } 10832 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 10833 }; 10834 10835 SCEVMapper SCM(SE2); 10836 10837 while (!LoopStack.empty()) { 10838 auto *L = LoopStack.pop_back_val(); 10839 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 10840 10841 auto *CurBECount = SCM.visit( 10842 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 10843 auto *NewBECount = SE2.getBackedgeTakenCount(L); 10844 10845 if (CurBECount == SE2.getCouldNotCompute() || 10846 NewBECount == SE2.getCouldNotCompute()) { 10847 // NB! This situation is legal, but is very suspicious -- whatever pass 10848 // change the loop to make a trip count go from could not compute to 10849 // computable or vice-versa *should have* invalidated SCEV. However, we 10850 // choose not to assert here (for now) since we don't want false 10851 // positives. 10852 continue; 10853 } 10854 10855 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 10856 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 10857 // not propagate undef aggressively). This means we can (and do) fail 10858 // verification in cases where a transform makes the trip count of a loop 10859 // go from "undef" to "undef+1" (say). The transform is fine, since in 10860 // both cases the loop iterates "undef" times, but SCEV thinks we 10861 // increased the trip count of the loop by 1 incorrectly. 10862 continue; 10863 } 10864 10865 if (SE.getTypeSizeInBits(CurBECount->getType()) > 10866 SE.getTypeSizeInBits(NewBECount->getType())) 10867 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 10868 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 10869 SE.getTypeSizeInBits(NewBECount->getType())) 10870 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 10871 10872 auto *ConstantDelta = 10873 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 10874 10875 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 10876 dbgs() << "Trip Count Changed!\n"; 10877 dbgs() << "Old: " << *CurBECount << "\n"; 10878 dbgs() << "New: " << *NewBECount << "\n"; 10879 dbgs() << "Delta: " << *ConstantDelta << "\n"; 10880 std::abort(); 10881 } 10882 } 10883 } 10884 10885 bool ScalarEvolution::invalidate( 10886 Function &F, const PreservedAnalyses &PA, 10887 FunctionAnalysisManager::Invalidator &Inv) { 10888 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10889 // of its dependencies is invalidated. 10890 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10891 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10892 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10893 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10894 Inv.invalidate<LoopAnalysis>(F, PA); 10895 } 10896 10897 AnalysisKey ScalarEvolutionAnalysis::Key; 10898 10899 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10900 FunctionAnalysisManager &AM) { 10901 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10902 AM.getResult<AssumptionAnalysis>(F), 10903 AM.getResult<DominatorTreeAnalysis>(F), 10904 AM.getResult<LoopAnalysis>(F)); 10905 } 10906 10907 PreservedAnalyses 10908 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10909 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10910 return PreservedAnalyses::all(); 10911 } 10912 10913 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10914 "Scalar Evolution Analysis", false, true) 10915 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10916 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10917 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10918 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10919 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10920 "Scalar Evolution Analysis", false, true) 10921 char ScalarEvolutionWrapperPass::ID = 0; 10922 10923 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10924 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10925 } 10926 10927 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10928 SE.reset(new ScalarEvolution( 10929 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10930 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10931 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10932 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10933 return false; 10934 } 10935 10936 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10937 10938 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10939 SE->print(OS); 10940 } 10941 10942 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10943 if (!VerifySCEV) 10944 return; 10945 10946 SE->verify(); 10947 } 10948 10949 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10950 AU.setPreservesAll(); 10951 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10952 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10953 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10954 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10955 } 10956 10957 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 10958 const SCEV *RHS) { 10959 FoldingSetNodeID ID; 10960 assert(LHS->getType() == RHS->getType() && 10961 "Type mismatch between LHS and RHS"); 10962 // Unique this node based on the arguments 10963 ID.AddInteger(SCEVPredicate::P_Equal); 10964 ID.AddPointer(LHS); 10965 ID.AddPointer(RHS); 10966 void *IP = nullptr; 10967 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10968 return S; 10969 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10970 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10971 UniquePreds.InsertNode(Eq, IP); 10972 return Eq; 10973 } 10974 10975 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10976 const SCEVAddRecExpr *AR, 10977 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10978 FoldingSetNodeID ID; 10979 // Unique this node based on the arguments 10980 ID.AddInteger(SCEVPredicate::P_Wrap); 10981 ID.AddPointer(AR); 10982 ID.AddInteger(AddedFlags); 10983 void *IP = nullptr; 10984 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10985 return S; 10986 auto *OF = new (SCEVAllocator) 10987 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10988 UniquePreds.InsertNode(OF, IP); 10989 return OF; 10990 } 10991 10992 namespace { 10993 10994 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10995 public: 10996 /// Rewrites \p S in the context of a loop L and the SCEV predication 10997 /// infrastructure. 10998 /// 10999 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11000 /// equivalences present in \p Pred. 11001 /// 11002 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11003 /// \p NewPreds such that the result will be an AddRecExpr. 11004 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11005 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11006 SCEVUnionPredicate *Pred) { 11007 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11008 return Rewriter.visit(S); 11009 } 11010 11011 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11012 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11013 SCEVUnionPredicate *Pred) 11014 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11015 11016 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11017 if (Pred) { 11018 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11019 for (auto *Pred : ExprPreds) 11020 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11021 if (IPred->getLHS() == Expr) 11022 return IPred->getRHS(); 11023 } 11024 return convertToAddRecWithPreds(Expr); 11025 } 11026 11027 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11028 const SCEV *Operand = visit(Expr->getOperand()); 11029 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11030 if (AR && AR->getLoop() == L && AR->isAffine()) { 11031 // This couldn't be folded because the operand didn't have the nuw 11032 // flag. Add the nusw flag as an assumption that we could make. 11033 const SCEV *Step = AR->getStepRecurrence(SE); 11034 Type *Ty = Expr->getType(); 11035 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11036 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11037 SE.getSignExtendExpr(Step, Ty), L, 11038 AR->getNoWrapFlags()); 11039 } 11040 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11041 } 11042 11043 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11044 const SCEV *Operand = visit(Expr->getOperand()); 11045 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11046 if (AR && AR->getLoop() == L && AR->isAffine()) { 11047 // This couldn't be folded because the operand didn't have the nsw 11048 // flag. Add the nssw flag as an assumption that we could make. 11049 const SCEV *Step = AR->getStepRecurrence(SE); 11050 Type *Ty = Expr->getType(); 11051 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11052 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11053 SE.getSignExtendExpr(Step, Ty), L, 11054 AR->getNoWrapFlags()); 11055 } 11056 return SE.getSignExtendExpr(Operand, Expr->getType()); 11057 } 11058 11059 private: 11060 bool addOverflowAssumption(const SCEVPredicate *P) { 11061 if (!NewPreds) { 11062 // Check if we've already made this assumption. 11063 return Pred && Pred->implies(P); 11064 } 11065 NewPreds->insert(P); 11066 return true; 11067 } 11068 11069 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11070 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11071 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11072 return addOverflowAssumption(A); 11073 } 11074 11075 // If \p Expr represents a PHINode, we try to see if it can be represented 11076 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11077 // to add this predicate as a runtime overflow check, we return the AddRec. 11078 // If \p Expr does not meet these conditions (is not a PHI node, or we 11079 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11080 // return \p Expr. 11081 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11082 if (!isa<PHINode>(Expr->getValue())) 11083 return Expr; 11084 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11085 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11086 if (!PredicatedRewrite) 11087 return Expr; 11088 for (auto *P : PredicatedRewrite->second){ 11089 if (!addOverflowAssumption(P)) 11090 return Expr; 11091 } 11092 return PredicatedRewrite->first; 11093 } 11094 11095 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11096 SCEVUnionPredicate *Pred; 11097 const Loop *L; 11098 }; 11099 } // end anonymous namespace 11100 11101 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11102 SCEVUnionPredicate &Preds) { 11103 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11104 } 11105 11106 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11107 const SCEV *S, const Loop *L, 11108 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11109 11110 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11111 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11112 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11113 11114 if (!AddRec) 11115 return nullptr; 11116 11117 // Since the transformation was successful, we can now transfer the SCEV 11118 // predicates. 11119 for (auto *P : TransformPreds) 11120 Preds.insert(P); 11121 11122 return AddRec; 11123 } 11124 11125 /// SCEV predicates 11126 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11127 SCEVPredicateKind Kind) 11128 : FastID(ID), Kind(Kind) {} 11129 11130 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11131 const SCEV *LHS, const SCEV *RHS) 11132 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11133 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11134 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11135 } 11136 11137 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11138 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11139 11140 if (!Op) 11141 return false; 11142 11143 return Op->LHS == LHS && Op->RHS == RHS; 11144 } 11145 11146 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11147 11148 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11149 11150 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11151 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11152 } 11153 11154 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11155 const SCEVAddRecExpr *AR, 11156 IncrementWrapFlags Flags) 11157 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11158 11159 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11160 11161 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11162 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11163 11164 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11165 } 11166 11167 bool SCEVWrapPredicate::isAlwaysTrue() const { 11168 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11169 IncrementWrapFlags IFlags = Flags; 11170 11171 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11172 IFlags = clearFlags(IFlags, IncrementNSSW); 11173 11174 return IFlags == IncrementAnyWrap; 11175 } 11176 11177 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11178 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11179 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11180 OS << "<nusw>"; 11181 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11182 OS << "<nssw>"; 11183 OS << "\n"; 11184 } 11185 11186 SCEVWrapPredicate::IncrementWrapFlags 11187 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11188 ScalarEvolution &SE) { 11189 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11190 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11191 11192 // We can safely transfer the NSW flag as NSSW. 11193 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11194 ImpliedFlags = IncrementNSSW; 11195 11196 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11197 // If the increment is positive, the SCEV NUW flag will also imply the 11198 // WrapPredicate NUSW flag. 11199 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11200 if (Step->getValue()->getValue().isNonNegative()) 11201 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11202 } 11203 11204 return ImpliedFlags; 11205 } 11206 11207 /// Union predicates don't get cached so create a dummy set ID for it. 11208 SCEVUnionPredicate::SCEVUnionPredicate() 11209 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11210 11211 bool SCEVUnionPredicate::isAlwaysTrue() const { 11212 return all_of(Preds, 11213 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11214 } 11215 11216 ArrayRef<const SCEVPredicate *> 11217 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11218 auto I = SCEVToPreds.find(Expr); 11219 if (I == SCEVToPreds.end()) 11220 return ArrayRef<const SCEVPredicate *>(); 11221 return I->second; 11222 } 11223 11224 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11225 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11226 return all_of(Set->Preds, 11227 [this](const SCEVPredicate *I) { return this->implies(I); }); 11228 11229 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11230 if (ScevPredsIt == SCEVToPreds.end()) 11231 return false; 11232 auto &SCEVPreds = ScevPredsIt->second; 11233 11234 return any_of(SCEVPreds, 11235 [N](const SCEVPredicate *I) { return I->implies(N); }); 11236 } 11237 11238 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11239 11240 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11241 for (auto Pred : Preds) 11242 Pred->print(OS, Depth); 11243 } 11244 11245 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11246 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11247 for (auto Pred : Set->Preds) 11248 add(Pred); 11249 return; 11250 } 11251 11252 if (implies(N)) 11253 return; 11254 11255 const SCEV *Key = N->getExpr(); 11256 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11257 " associated expression!"); 11258 11259 SCEVToPreds[Key].push_back(N); 11260 Preds.push_back(N); 11261 } 11262 11263 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11264 Loop &L) 11265 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 11266 11267 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11268 const SCEV *Expr = SE.getSCEV(V); 11269 RewriteEntry &Entry = RewriteMap[Expr]; 11270 11271 // If we already have an entry and the version matches, return it. 11272 if (Entry.second && Generation == Entry.first) 11273 return Entry.second; 11274 11275 // We found an entry but it's stale. Rewrite the stale entry 11276 // according to the current predicate. 11277 if (Entry.second) 11278 Expr = Entry.second; 11279 11280 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11281 Entry = {Generation, NewSCEV}; 11282 11283 return NewSCEV; 11284 } 11285 11286 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11287 if (!BackedgeCount) { 11288 SCEVUnionPredicate BackedgePred; 11289 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11290 addPredicate(BackedgePred); 11291 } 11292 return BackedgeCount; 11293 } 11294 11295 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11296 if (Preds.implies(&Pred)) 11297 return; 11298 Preds.add(&Pred); 11299 updateGeneration(); 11300 } 11301 11302 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11303 return Preds; 11304 } 11305 11306 void PredicatedScalarEvolution::updateGeneration() { 11307 // If the generation number wrapped recompute everything. 11308 if (++Generation == 0) { 11309 for (auto &II : RewriteMap) { 11310 const SCEV *Rewritten = II.second.second; 11311 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11312 } 11313 } 11314 } 11315 11316 void PredicatedScalarEvolution::setNoOverflow( 11317 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11318 const SCEV *Expr = getSCEV(V); 11319 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11320 11321 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11322 11323 // Clear the statically implied flags. 11324 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11325 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11326 11327 auto II = FlagsMap.insert({V, Flags}); 11328 if (!II.second) 11329 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11330 } 11331 11332 bool PredicatedScalarEvolution::hasNoOverflow( 11333 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11334 const SCEV *Expr = getSCEV(V); 11335 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11336 11337 Flags = SCEVWrapPredicate::clearFlags( 11338 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11339 11340 auto II = FlagsMap.find(V); 11341 11342 if (II != FlagsMap.end()) 11343 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11344 11345 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11346 } 11347 11348 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11349 const SCEV *Expr = this->getSCEV(V); 11350 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11351 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11352 11353 if (!New) 11354 return nullptr; 11355 11356 for (auto *P : NewPreds) 11357 Preds.add(P); 11358 11359 updateGeneration(); 11360 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11361 return New; 11362 } 11363 11364 PredicatedScalarEvolution::PredicatedScalarEvolution( 11365 const PredicatedScalarEvolution &Init) 11366 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11367 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11368 for (const auto &I : Init.FlagsMap) 11369 FlagsMap.insert(I); 11370 } 11371 11372 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11373 // For each block. 11374 for (auto *BB : L.getBlocks()) 11375 for (auto &I : *BB) { 11376 if (!SE.isSCEVable(I.getType())) 11377 continue; 11378 11379 auto *Expr = SE.getSCEV(&I); 11380 auto II = RewriteMap.find(Expr); 11381 11382 if (II == RewriteMap.end()) 11383 continue; 11384 11385 // Don't print things that are not interesting. 11386 if (II->second.second == Expr) 11387 continue; 11388 11389 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11390 OS.indent(Depth + 2) << *Expr << "\n"; 11391 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11392 } 11393 } 11394