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/APInt.h" 63 #include "llvm/ADT/ArrayRef.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/DepthFirstIterator.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/IR/Argument.h" 86 #include "llvm/IR/BasicBlock.h" 87 #include "llvm/IR/CFG.h" 88 #include "llvm/IR/CallSite.h" 89 #include "llvm/IR/Constant.h" 90 #include "llvm/IR/ConstantRange.h" 91 #include "llvm/IR/Constants.h" 92 #include "llvm/IR/DataLayout.h" 93 #include "llvm/IR/DerivedTypes.h" 94 #include "llvm/IR/Dominators.h" 95 #include "llvm/IR/Function.h" 96 #include "llvm/IR/GlobalAlias.h" 97 #include "llvm/IR/GlobalValue.h" 98 #include "llvm/IR/GlobalVariable.h" 99 #include "llvm/IR/InstIterator.h" 100 #include "llvm/IR/InstrTypes.h" 101 #include "llvm/IR/Instruction.h" 102 #include "llvm/IR/Instructions.h" 103 #include "llvm/IR/IntrinsicInst.h" 104 #include "llvm/IR/Intrinsics.h" 105 #include "llvm/IR/LLVMContext.h" 106 #include "llvm/IR/Metadata.h" 107 #include "llvm/IR/Operator.h" 108 #include "llvm/IR/PatternMatch.h" 109 #include "llvm/IR/Type.h" 110 #include "llvm/IR/Use.h" 111 #include "llvm/IR/User.h" 112 #include "llvm/IR/Value.h" 113 #include "llvm/Pass.h" 114 #include "llvm/Support/Casting.h" 115 #include "llvm/Support/CommandLine.h" 116 #include "llvm/Support/Compiler.h" 117 #include "llvm/Support/Debug.h" 118 #include "llvm/Support/ErrorHandling.h" 119 #include "llvm/Support/KnownBits.h" 120 #include "llvm/Support/SaveAndRestore.h" 121 #include "llvm/Support/raw_ostream.h" 122 #include <algorithm> 123 #include <cassert> 124 #include <climits> 125 #include <cstddef> 126 #include <cstdint> 127 #include <cstdlib> 128 #include <map> 129 #include <memory> 130 #include <tuple> 131 #include <utility> 132 #include <vector> 133 134 using namespace llvm; 135 136 #define DEBUG_TYPE "scalar-evolution" 137 138 STATISTIC(NumArrayLenItCounts, 139 "Number of trip counts computed with array length"); 140 STATISTIC(NumTripCountsComputed, 141 "Number of loops with predictable loop counts"); 142 STATISTIC(NumTripCountsNotComputed, 143 "Number of loops without predictable loop counts"); 144 STATISTIC(NumBruteForceTripCountsComputed, 145 "Number of loops with trip counts computed by force"); 146 147 static cl::opt<unsigned> 148 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 149 cl::desc("Maximum number of iterations SCEV will " 150 "symbolically execute a constant " 151 "derived loop"), 152 cl::init(100)); 153 154 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 155 static cl::opt<bool> 156 VerifySCEV("verify-scev", 157 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 158 static cl::opt<bool> 159 VerifySCEVMap("verify-scev-maps", 160 cl::desc("Verify no dangling value in ScalarEvolution's " 161 "ExprValueMap (slow)")); 162 163 static cl::opt<unsigned> MulOpsInlineThreshold( 164 "scev-mulops-inline-threshold", cl::Hidden, 165 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 166 cl::init(32)); 167 168 static cl::opt<unsigned> AddOpsInlineThreshold( 169 "scev-addops-inline-threshold", cl::Hidden, 170 cl::desc("Threshold for inlining addition operands into a SCEV"), 171 cl::init(500)); 172 173 static cl::opt<unsigned> MaxSCEVCompareDepth( 174 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 175 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 176 cl::init(32)); 177 178 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 179 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 180 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 181 cl::init(2)); 182 183 static cl::opt<unsigned> MaxValueCompareDepth( 184 "scalar-evolution-max-value-compare-depth", cl::Hidden, 185 cl::desc("Maximum depth of recursive value complexity comparisons"), 186 cl::init(2)); 187 188 static cl::opt<unsigned> 189 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 190 cl::desc("Maximum depth of recursive arithmetics"), 191 cl::init(32)); 192 193 static cl::opt<unsigned> MaxConstantEvolvingDepth( 194 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 195 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 196 197 static cl::opt<unsigned> 198 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 199 cl::desc("Maximum depth of recursive SExt/ZExt"), 200 cl::init(8)); 201 202 static cl::opt<unsigned> 203 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 204 cl::desc("Max coefficients in AddRec during evolving"), 205 cl::init(16)); 206 207 //===----------------------------------------------------------------------===// 208 // SCEV class definitions 209 //===----------------------------------------------------------------------===// 210 211 //===----------------------------------------------------------------------===// 212 // Implementation of the SCEV class. 213 // 214 215 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 216 LLVM_DUMP_METHOD void SCEV::dump() const { 217 print(dbgs()); 218 dbgs() << '\n'; 219 } 220 #endif 221 222 void SCEV::print(raw_ostream &OS) const { 223 switch (static_cast<SCEVTypes>(getSCEVType())) { 224 case scConstant: 225 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 226 return; 227 case scTruncate: { 228 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 229 const SCEV *Op = Trunc->getOperand(); 230 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 231 << *Trunc->getType() << ")"; 232 return; 233 } 234 case scZeroExtend: { 235 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 236 const SCEV *Op = ZExt->getOperand(); 237 OS << "(zext " << *Op->getType() << " " << *Op << " to " 238 << *ZExt->getType() << ")"; 239 return; 240 } 241 case scSignExtend: { 242 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 243 const SCEV *Op = SExt->getOperand(); 244 OS << "(sext " << *Op->getType() << " " << *Op << " to " 245 << *SExt->getType() << ")"; 246 return; 247 } 248 case scAddRecExpr: { 249 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 250 OS << "{" << *AR->getOperand(0); 251 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 252 OS << ",+," << *AR->getOperand(i); 253 OS << "}<"; 254 if (AR->hasNoUnsignedWrap()) 255 OS << "nuw><"; 256 if (AR->hasNoSignedWrap()) 257 OS << "nsw><"; 258 if (AR->hasNoSelfWrap() && 259 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 260 OS << "nw><"; 261 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 262 OS << ">"; 263 return; 264 } 265 case scAddExpr: 266 case scMulExpr: 267 case scUMaxExpr: 268 case scSMaxExpr: { 269 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 270 const char *OpStr = nullptr; 271 switch (NAry->getSCEVType()) { 272 case scAddExpr: OpStr = " + "; break; 273 case scMulExpr: OpStr = " * "; break; 274 case scUMaxExpr: OpStr = " umax "; break; 275 case scSMaxExpr: OpStr = " smax "; break; 276 } 277 OS << "("; 278 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 279 I != E; ++I) { 280 OS << **I; 281 if (std::next(I) != E) 282 OS << OpStr; 283 } 284 OS << ")"; 285 switch (NAry->getSCEVType()) { 286 case scAddExpr: 287 case scMulExpr: 288 if (NAry->hasNoUnsignedWrap()) 289 OS << "<nuw>"; 290 if (NAry->hasNoSignedWrap()) 291 OS << "<nsw>"; 292 } 293 return; 294 } 295 case scUDivExpr: { 296 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 297 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 298 return; 299 } 300 case scUnknown: { 301 const SCEVUnknown *U = cast<SCEVUnknown>(this); 302 Type *AllocTy; 303 if (U->isSizeOf(AllocTy)) { 304 OS << "sizeof(" << *AllocTy << ")"; 305 return; 306 } 307 if (U->isAlignOf(AllocTy)) { 308 OS << "alignof(" << *AllocTy << ")"; 309 return; 310 } 311 312 Type *CTy; 313 Constant *FieldNo; 314 if (U->isOffsetOf(CTy, FieldNo)) { 315 OS << "offsetof(" << *CTy << ", "; 316 FieldNo->printAsOperand(OS, false); 317 OS << ")"; 318 return; 319 } 320 321 // Otherwise just print it normally. 322 U->getValue()->printAsOperand(OS, false); 323 return; 324 } 325 case scCouldNotCompute: 326 OS << "***COULDNOTCOMPUTE***"; 327 return; 328 } 329 llvm_unreachable("Unknown SCEV kind!"); 330 } 331 332 Type *SCEV::getType() const { 333 switch (static_cast<SCEVTypes>(getSCEVType())) { 334 case scConstant: 335 return cast<SCEVConstant>(this)->getType(); 336 case scTruncate: 337 case scZeroExtend: 338 case scSignExtend: 339 return cast<SCEVCastExpr>(this)->getType(); 340 case scAddRecExpr: 341 case scMulExpr: 342 case scUMaxExpr: 343 case scSMaxExpr: 344 return cast<SCEVNAryExpr>(this)->getType(); 345 case scAddExpr: 346 return cast<SCEVAddExpr>(this)->getType(); 347 case scUDivExpr: 348 return cast<SCEVUDivExpr>(this)->getType(); 349 case scUnknown: 350 return cast<SCEVUnknown>(this)->getType(); 351 case scCouldNotCompute: 352 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 353 } 354 llvm_unreachable("Unknown SCEV kind!"); 355 } 356 357 bool SCEV::isZero() const { 358 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 359 return SC->getValue()->isZero(); 360 return false; 361 } 362 363 bool SCEV::isOne() const { 364 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 365 return SC->getValue()->isOne(); 366 return false; 367 } 368 369 bool SCEV::isAllOnesValue() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isMinusOne(); 372 return false; 373 } 374 375 bool SCEV::isNonConstantNegative() const { 376 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 377 if (!Mul) return false; 378 379 // If there is a constant factor, it will be first. 380 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 381 if (!SC) return false; 382 383 // Return true if the value is negative, this matches things like (-42 * V). 384 return SC->getAPInt().isNegative(); 385 } 386 387 SCEVCouldNotCompute::SCEVCouldNotCompute() : 388 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 389 390 bool SCEVCouldNotCompute::classof(const SCEV *S) { 391 return S->getSCEVType() == scCouldNotCompute; 392 } 393 394 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 395 FoldingSetNodeID ID; 396 ID.AddInteger(scConstant); 397 ID.AddPointer(V); 398 void *IP = nullptr; 399 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 400 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 401 UniqueSCEVs.InsertNode(S, IP); 402 return S; 403 } 404 405 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 406 return getConstant(ConstantInt::get(getContext(), Val)); 407 } 408 409 const SCEV * 410 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 411 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 412 return getConstant(ConstantInt::get(ITy, V, isSigned)); 413 } 414 415 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 416 unsigned SCEVTy, const SCEV *op, Type *ty) 417 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 418 419 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 420 const SCEV *op, Type *ty) 421 : SCEVCastExpr(ID, scTruncate, op, ty) { 422 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 423 (Ty->isIntegerTy() || Ty->isPointerTy()) && 424 "Cannot truncate non-integer value!"); 425 } 426 427 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 428 const SCEV *op, Type *ty) 429 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 430 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 431 (Ty->isIntegerTy() || Ty->isPointerTy()) && 432 "Cannot zero extend non-integer value!"); 433 } 434 435 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 436 const SCEV *op, Type *ty) 437 : SCEVCastExpr(ID, scSignExtend, op, ty) { 438 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 439 (Ty->isIntegerTy() || Ty->isPointerTy()) && 440 "Cannot sign extend non-integer value!"); 441 } 442 443 void SCEVUnknown::deleted() { 444 // Clear this SCEVUnknown from various maps. 445 SE->forgetMemoizedResults(this); 446 447 // Remove this SCEVUnknown from the uniquing map. 448 SE->UniqueSCEVs.RemoveNode(this); 449 450 // Release the value. 451 setValPtr(nullptr); 452 } 453 454 void SCEVUnknown::allUsesReplacedWith(Value *New) { 455 // Remove this SCEVUnknown from the uniquing map. 456 SE->UniqueSCEVs.RemoveNode(this); 457 458 // Update this SCEVUnknown to point to the new value. This is needed 459 // because there may still be outstanding SCEVs which still point to 460 // this SCEVUnknown. 461 setValPtr(New); 462 } 463 464 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 465 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 466 if (VCE->getOpcode() == Instruction::PtrToInt) 467 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 468 if (CE->getOpcode() == Instruction::GetElementPtr && 469 CE->getOperand(0)->isNullValue() && 470 CE->getNumOperands() == 2) 471 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 472 if (CI->isOne()) { 473 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 474 ->getElementType(); 475 return true; 476 } 477 478 return false; 479 } 480 481 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 482 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 483 if (VCE->getOpcode() == Instruction::PtrToInt) 484 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 485 if (CE->getOpcode() == Instruction::GetElementPtr && 486 CE->getOperand(0)->isNullValue()) { 487 Type *Ty = 488 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 489 if (StructType *STy = dyn_cast<StructType>(Ty)) 490 if (!STy->isPacked() && 491 CE->getNumOperands() == 3 && 492 CE->getOperand(1)->isNullValue()) { 493 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 494 if (CI->isOne() && 495 STy->getNumElements() == 2 && 496 STy->getElementType(0)->isIntegerTy(1)) { 497 AllocTy = STy->getElementType(1); 498 return true; 499 } 500 } 501 } 502 503 return false; 504 } 505 506 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 507 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 508 if (VCE->getOpcode() == Instruction::PtrToInt) 509 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 510 if (CE->getOpcode() == Instruction::GetElementPtr && 511 CE->getNumOperands() == 3 && 512 CE->getOperand(0)->isNullValue() && 513 CE->getOperand(1)->isNullValue()) { 514 Type *Ty = 515 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 516 // Ignore vector types here so that ScalarEvolutionExpander doesn't 517 // emit getelementptrs that index into vectors. 518 if (Ty->isStructTy() || Ty->isArrayTy()) { 519 CTy = Ty; 520 FieldNo = CE->getOperand(2); 521 return true; 522 } 523 } 524 525 return false; 526 } 527 528 //===----------------------------------------------------------------------===// 529 // SCEV Utilities 530 //===----------------------------------------------------------------------===// 531 532 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 533 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 534 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 535 /// have been previously deemed to be "equally complex" by this routine. It is 536 /// intended to avoid exponential time complexity in cases like: 537 /// 538 /// %a = f(%x, %y) 539 /// %b = f(%a, %a) 540 /// %c = f(%b, %b) 541 /// 542 /// %d = f(%x, %y) 543 /// %e = f(%d, %d) 544 /// %f = f(%e, %e) 545 /// 546 /// CompareValueComplexity(%f, %c) 547 /// 548 /// Since we do not continue running this routine on expression trees once we 549 /// have seen unequal values, there is no need to track them in the cache. 550 static int 551 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 552 const LoopInfo *const LI, Value *LV, Value *RV, 553 unsigned Depth) { 554 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV})) 555 return 0; 556 557 // Order pointer values after integer values. This helps SCEVExpander form 558 // GEPs. 559 bool LIsPointer = LV->getType()->isPointerTy(), 560 RIsPointer = RV->getType()->isPointerTy(); 561 if (LIsPointer != RIsPointer) 562 return (int)LIsPointer - (int)RIsPointer; 563 564 // Compare getValueID values. 565 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 566 if (LID != RID) 567 return (int)LID - (int)RID; 568 569 // Sort arguments by their position. 570 if (const auto *LA = dyn_cast<Argument>(LV)) { 571 const auto *RA = cast<Argument>(RV); 572 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 573 return (int)LArgNo - (int)RArgNo; 574 } 575 576 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 577 const auto *RGV = cast<GlobalValue>(RV); 578 579 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 580 auto LT = GV->getLinkage(); 581 return !(GlobalValue::isPrivateLinkage(LT) || 582 GlobalValue::isInternalLinkage(LT)); 583 }; 584 585 // Use the names to distinguish the two values, but only if the 586 // names are semantically important. 587 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 588 return LGV->getName().compare(RGV->getName()); 589 } 590 591 // For instructions, compare their loop depth, and their operand count. This 592 // is pretty loose. 593 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 594 const auto *RInst = cast<Instruction>(RV); 595 596 // Compare loop depths. 597 const BasicBlock *LParent = LInst->getParent(), 598 *RParent = RInst->getParent(); 599 if (LParent != RParent) { 600 unsigned LDepth = LI->getLoopDepth(LParent), 601 RDepth = LI->getLoopDepth(RParent); 602 if (LDepth != RDepth) 603 return (int)LDepth - (int)RDepth; 604 } 605 606 // Compare the number of operands. 607 unsigned LNumOps = LInst->getNumOperands(), 608 RNumOps = RInst->getNumOperands(); 609 if (LNumOps != RNumOps) 610 return (int)LNumOps - (int)RNumOps; 611 612 for (unsigned Idx : seq(0u, LNumOps)) { 613 int Result = 614 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 615 RInst->getOperand(Idx), Depth + 1); 616 if (Result != 0) 617 return Result; 618 } 619 } 620 621 EqCache.insert({LV, RV}); 622 return 0; 623 } 624 625 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 626 // than RHS, respectively. A three-way result allows recursive comparisons to be 627 // more efficient. 628 static int CompareSCEVComplexity( 629 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 630 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 631 DominatorTree &DT, unsigned Depth = 0) { 632 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 633 if (LHS == RHS) 634 return 0; 635 636 // Primarily, sort the SCEVs by their getSCEVType(). 637 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 638 if (LType != RType) 639 return (int)LType - (int)RType; 640 641 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS})) 642 return 0; 643 // Aside from the getSCEVType() ordering, the particular ordering 644 // isn't very important except that it's beneficial to be consistent, 645 // so that (a + b) and (b + a) don't end up as different expressions. 646 switch (static_cast<SCEVTypes>(LType)) { 647 case scUnknown: { 648 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 649 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 650 651 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 652 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 653 Depth + 1); 654 if (X == 0) 655 EqCacheSCEV.insert({LHS, RHS}); 656 return X; 657 } 658 659 case scConstant: { 660 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 661 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 662 663 // Compare constant values. 664 const APInt &LA = LC->getAPInt(); 665 const APInt &RA = RC->getAPInt(); 666 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 667 if (LBitWidth != RBitWidth) 668 return (int)LBitWidth - (int)RBitWidth; 669 return LA.ult(RA) ? -1 : 1; 670 } 671 672 case scAddRecExpr: { 673 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 674 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 675 676 // There is always a dominance between two recs that are used by one SCEV, 677 // so we can safely sort recs by loop header dominance. We require such 678 // order in getAddExpr. 679 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 680 if (LLoop != RLoop) { 681 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 682 assert(LHead != RHead && "Two loops share the same header?"); 683 if (DT.dominates(LHead, RHead)) 684 return 1; 685 else 686 assert(DT.dominates(RHead, LHead) && 687 "No dominance between recurrences used by one SCEV?"); 688 return -1; 689 } 690 691 // Addrec complexity grows with operand count. 692 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 693 if (LNumOps != RNumOps) 694 return (int)LNumOps - (int)RNumOps; 695 696 // Lexicographically compare. 697 for (unsigned i = 0; i != LNumOps; ++i) { 698 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 699 RA->getOperand(i), DT, Depth + 1); 700 if (X != 0) 701 return X; 702 } 703 EqCacheSCEV.insert({LHS, RHS}); 704 return 0; 705 } 706 707 case scAddExpr: 708 case scMulExpr: 709 case scSMaxExpr: 710 case scUMaxExpr: { 711 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 712 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 713 714 // Lexicographically compare n-ary expressions. 715 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 716 if (LNumOps != RNumOps) 717 return (int)LNumOps - (int)RNumOps; 718 719 for (unsigned i = 0; i != LNumOps; ++i) { 720 if (i >= RNumOps) 721 return 1; 722 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 723 RC->getOperand(i), DT, Depth + 1); 724 if (X != 0) 725 return X; 726 } 727 EqCacheSCEV.insert({LHS, RHS}); 728 return 0; 729 } 730 731 case scUDivExpr: { 732 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 733 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 734 735 // Lexicographically compare udiv expressions. 736 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 737 DT, Depth + 1); 738 if (X != 0) 739 return X; 740 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT, 741 Depth + 1); 742 if (X == 0) 743 EqCacheSCEV.insert({LHS, RHS}); 744 return X; 745 } 746 747 case scTruncate: 748 case scZeroExtend: 749 case scSignExtend: { 750 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 751 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 752 753 // Compare cast expressions by operand. 754 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 755 RC->getOperand(), DT, Depth + 1); 756 if (X == 0) 757 EqCacheSCEV.insert({LHS, RHS}); 758 return X; 759 } 760 761 case scCouldNotCompute: 762 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 763 } 764 llvm_unreachable("Unknown SCEV kind!"); 765 } 766 767 /// Given a list of SCEV objects, order them by their complexity, and group 768 /// objects of the same complexity together by value. When this routine is 769 /// finished, we know that any duplicates in the vector are consecutive and that 770 /// complexity is monotonically increasing. 771 /// 772 /// Note that we go take special precautions to ensure that we get deterministic 773 /// results from this routine. In other words, we don't want the results of 774 /// this to depend on where the addresses of various SCEV objects happened to 775 /// land in memory. 776 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 777 LoopInfo *LI, DominatorTree &DT) { 778 if (Ops.size() < 2) return; // Noop 779 780 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 781 if (Ops.size() == 2) { 782 // This is the common case, which also happens to be trivially simple. 783 // Special case it. 784 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 785 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0) 786 std::swap(LHS, RHS); 787 return; 788 } 789 790 // Do the rough sort by complexity. 791 std::stable_sort(Ops.begin(), Ops.end(), 792 [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) { 793 return 794 CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0; 795 }); 796 797 // Now that we are sorted by complexity, group elements of the same 798 // complexity. Note that this is, at worst, N^2, but the vector is likely to 799 // be extremely short in practice. Note that we take this approach because we 800 // do not want to depend on the addresses of the objects we are grouping. 801 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 802 const SCEV *S = Ops[i]; 803 unsigned Complexity = S->getSCEVType(); 804 805 // If there are any objects of the same complexity and same value as this 806 // one, group them. 807 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 808 if (Ops[j] == S) { // Found a duplicate. 809 // Move it to immediately after i'th element. 810 std::swap(Ops[i+1], Ops[j]); 811 ++i; // no need to rescan it. 812 if (i == e-2) return; // Done! 813 } 814 } 815 } 816 } 817 818 // Returns the size of the SCEV S. 819 static inline int sizeOfSCEV(const SCEV *S) { 820 struct FindSCEVSize { 821 int Size = 0; 822 823 FindSCEVSize() = default; 824 825 bool follow(const SCEV *S) { 826 ++Size; 827 // Keep looking at all operands of S. 828 return true; 829 } 830 831 bool isDone() const { 832 return false; 833 } 834 }; 835 836 FindSCEVSize F; 837 SCEVTraversal<FindSCEVSize> ST(F); 838 ST.visitAll(S); 839 return F.Size; 840 } 841 842 namespace { 843 844 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 845 public: 846 // Computes the Quotient and Remainder of the division of Numerator by 847 // Denominator. 848 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 849 const SCEV *Denominator, const SCEV **Quotient, 850 const SCEV **Remainder) { 851 assert(Numerator && Denominator && "Uninitialized SCEV"); 852 853 SCEVDivision D(SE, Numerator, Denominator); 854 855 // Check for the trivial case here to avoid having to check for it in the 856 // rest of the code. 857 if (Numerator == Denominator) { 858 *Quotient = D.One; 859 *Remainder = D.Zero; 860 return; 861 } 862 863 if (Numerator->isZero()) { 864 *Quotient = D.Zero; 865 *Remainder = D.Zero; 866 return; 867 } 868 869 // A simple case when N/1. The quotient is N. 870 if (Denominator->isOne()) { 871 *Quotient = Numerator; 872 *Remainder = D.Zero; 873 return; 874 } 875 876 // Split the Denominator when it is a product. 877 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 878 const SCEV *Q, *R; 879 *Quotient = Numerator; 880 for (const SCEV *Op : T->operands()) { 881 divide(SE, *Quotient, Op, &Q, &R); 882 *Quotient = Q; 883 884 // Bail out when the Numerator is not divisible by one of the terms of 885 // the Denominator. 886 if (!R->isZero()) { 887 *Quotient = D.Zero; 888 *Remainder = Numerator; 889 return; 890 } 891 } 892 *Remainder = D.Zero; 893 return; 894 } 895 896 D.visit(Numerator); 897 *Quotient = D.Quotient; 898 *Remainder = D.Remainder; 899 } 900 901 // Except in the trivial case described above, we do not know how to divide 902 // Expr by Denominator for the following functions with empty implementation. 903 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 904 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 905 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 906 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 907 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 908 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 909 void visitUnknown(const SCEVUnknown *Numerator) {} 910 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 911 912 void visitConstant(const SCEVConstant *Numerator) { 913 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 914 APInt NumeratorVal = Numerator->getAPInt(); 915 APInt DenominatorVal = D->getAPInt(); 916 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 917 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 918 919 if (NumeratorBW > DenominatorBW) 920 DenominatorVal = DenominatorVal.sext(NumeratorBW); 921 else if (NumeratorBW < DenominatorBW) 922 NumeratorVal = NumeratorVal.sext(DenominatorBW); 923 924 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 925 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 926 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 927 Quotient = SE.getConstant(QuotientVal); 928 Remainder = SE.getConstant(RemainderVal); 929 return; 930 } 931 } 932 933 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 934 const SCEV *StartQ, *StartR, *StepQ, *StepR; 935 if (!Numerator->isAffine()) 936 return cannotDivide(Numerator); 937 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 938 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 939 // Bail out if the types do not match. 940 Type *Ty = Denominator->getType(); 941 if (Ty != StartQ->getType() || Ty != StartR->getType() || 942 Ty != StepQ->getType() || Ty != StepR->getType()) 943 return cannotDivide(Numerator); 944 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 945 Numerator->getNoWrapFlags()); 946 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 947 Numerator->getNoWrapFlags()); 948 } 949 950 void visitAddExpr(const SCEVAddExpr *Numerator) { 951 SmallVector<const SCEV *, 2> Qs, Rs; 952 Type *Ty = Denominator->getType(); 953 954 for (const SCEV *Op : Numerator->operands()) { 955 const SCEV *Q, *R; 956 divide(SE, Op, Denominator, &Q, &R); 957 958 // Bail out if types do not match. 959 if (Ty != Q->getType() || Ty != R->getType()) 960 return cannotDivide(Numerator); 961 962 Qs.push_back(Q); 963 Rs.push_back(R); 964 } 965 966 if (Qs.size() == 1) { 967 Quotient = Qs[0]; 968 Remainder = Rs[0]; 969 return; 970 } 971 972 Quotient = SE.getAddExpr(Qs); 973 Remainder = SE.getAddExpr(Rs); 974 } 975 976 void visitMulExpr(const SCEVMulExpr *Numerator) { 977 SmallVector<const SCEV *, 2> Qs; 978 Type *Ty = Denominator->getType(); 979 980 bool FoundDenominatorTerm = false; 981 for (const SCEV *Op : Numerator->operands()) { 982 // Bail out if types do not match. 983 if (Ty != Op->getType()) 984 return cannotDivide(Numerator); 985 986 if (FoundDenominatorTerm) { 987 Qs.push_back(Op); 988 continue; 989 } 990 991 // Check whether Denominator divides one of the product operands. 992 const SCEV *Q, *R; 993 divide(SE, Op, Denominator, &Q, &R); 994 if (!R->isZero()) { 995 Qs.push_back(Op); 996 continue; 997 } 998 999 // Bail out if types do not match. 1000 if (Ty != Q->getType()) 1001 return cannotDivide(Numerator); 1002 1003 FoundDenominatorTerm = true; 1004 Qs.push_back(Q); 1005 } 1006 1007 if (FoundDenominatorTerm) { 1008 Remainder = Zero; 1009 if (Qs.size() == 1) 1010 Quotient = Qs[0]; 1011 else 1012 Quotient = SE.getMulExpr(Qs); 1013 return; 1014 } 1015 1016 if (!isa<SCEVUnknown>(Denominator)) 1017 return cannotDivide(Numerator); 1018 1019 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1020 ValueToValueMap RewriteMap; 1021 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1022 cast<SCEVConstant>(Zero)->getValue(); 1023 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1024 1025 if (Remainder->isZero()) { 1026 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1027 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1028 cast<SCEVConstant>(One)->getValue(); 1029 Quotient = 1030 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1031 return; 1032 } 1033 1034 // Quotient is (Numerator - Remainder) divided by Denominator. 1035 const SCEV *Q, *R; 1036 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1037 // This SCEV does not seem to simplify: fail the division here. 1038 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1039 return cannotDivide(Numerator); 1040 divide(SE, Diff, Denominator, &Q, &R); 1041 if (R != Zero) 1042 return cannotDivide(Numerator); 1043 Quotient = Q; 1044 } 1045 1046 private: 1047 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1048 const SCEV *Denominator) 1049 : SE(S), Denominator(Denominator) { 1050 Zero = SE.getZero(Denominator->getType()); 1051 One = SE.getOne(Denominator->getType()); 1052 1053 // We generally do not know how to divide Expr by Denominator. We 1054 // initialize the division to a "cannot divide" state to simplify the rest 1055 // of the code. 1056 cannotDivide(Numerator); 1057 } 1058 1059 // Convenience function for giving up on the division. We set the quotient to 1060 // be equal to zero and the remainder to be equal to the numerator. 1061 void cannotDivide(const SCEV *Numerator) { 1062 Quotient = Zero; 1063 Remainder = Numerator; 1064 } 1065 1066 ScalarEvolution &SE; 1067 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1068 }; 1069 1070 } // end anonymous namespace 1071 1072 //===----------------------------------------------------------------------===// 1073 // Simple SCEV method implementations 1074 //===----------------------------------------------------------------------===// 1075 1076 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1077 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1078 ScalarEvolution &SE, 1079 Type *ResultTy) { 1080 // Handle the simplest case efficiently. 1081 if (K == 1) 1082 return SE.getTruncateOrZeroExtend(It, ResultTy); 1083 1084 // We are using the following formula for BC(It, K): 1085 // 1086 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1087 // 1088 // Suppose, W is the bitwidth of the return value. We must be prepared for 1089 // overflow. Hence, we must assure that the result of our computation is 1090 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1091 // safe in modular arithmetic. 1092 // 1093 // However, this code doesn't use exactly that formula; the formula it uses 1094 // is something like the following, where T is the number of factors of 2 in 1095 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1096 // exponentiation: 1097 // 1098 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1099 // 1100 // This formula is trivially equivalent to the previous formula. However, 1101 // this formula can be implemented much more efficiently. The trick is that 1102 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1103 // arithmetic. To do exact division in modular arithmetic, all we have 1104 // to do is multiply by the inverse. Therefore, this step can be done at 1105 // width W. 1106 // 1107 // The next issue is how to safely do the division by 2^T. The way this 1108 // is done is by doing the multiplication step at a width of at least W + T 1109 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1110 // when we perform the division by 2^T (which is equivalent to a right shift 1111 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1112 // truncated out after the division by 2^T. 1113 // 1114 // In comparison to just directly using the first formula, this technique 1115 // is much more efficient; using the first formula requires W * K bits, 1116 // but this formula less than W + K bits. Also, the first formula requires 1117 // a division step, whereas this formula only requires multiplies and shifts. 1118 // 1119 // It doesn't matter whether the subtraction step is done in the calculation 1120 // width or the input iteration count's width; if the subtraction overflows, 1121 // the result must be zero anyway. We prefer here to do it in the width of 1122 // the induction variable because it helps a lot for certain cases; CodeGen 1123 // isn't smart enough to ignore the overflow, which leads to much less 1124 // efficient code if the width of the subtraction is wider than the native 1125 // register width. 1126 // 1127 // (It's possible to not widen at all by pulling out factors of 2 before 1128 // the multiplication; for example, K=2 can be calculated as 1129 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1130 // extra arithmetic, so it's not an obvious win, and it gets 1131 // much more complicated for K > 3.) 1132 1133 // Protection from insane SCEVs; this bound is conservative, 1134 // but it probably doesn't matter. 1135 if (K > 1000) 1136 return SE.getCouldNotCompute(); 1137 1138 unsigned W = SE.getTypeSizeInBits(ResultTy); 1139 1140 // Calculate K! / 2^T and T; we divide out the factors of two before 1141 // multiplying for calculating K! / 2^T to avoid overflow. 1142 // Other overflow doesn't matter because we only care about the bottom 1143 // W bits of the result. 1144 APInt OddFactorial(W, 1); 1145 unsigned T = 1; 1146 for (unsigned i = 3; i <= K; ++i) { 1147 APInt Mult(W, i); 1148 unsigned TwoFactors = Mult.countTrailingZeros(); 1149 T += TwoFactors; 1150 Mult.lshrInPlace(TwoFactors); 1151 OddFactorial *= Mult; 1152 } 1153 1154 // We need at least W + T bits for the multiplication step 1155 unsigned CalculationBits = W + T; 1156 1157 // Calculate 2^T, at width T+W. 1158 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1159 1160 // Calculate the multiplicative inverse of K! / 2^T; 1161 // this multiplication factor will perform the exact division by 1162 // K! / 2^T. 1163 APInt Mod = APInt::getSignedMinValue(W+1); 1164 APInt MultiplyFactor = OddFactorial.zext(W+1); 1165 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1166 MultiplyFactor = MultiplyFactor.trunc(W); 1167 1168 // Calculate the product, at width T+W 1169 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1170 CalculationBits); 1171 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1172 for (unsigned i = 1; i != K; ++i) { 1173 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1174 Dividend = SE.getMulExpr(Dividend, 1175 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1176 } 1177 1178 // Divide by 2^T 1179 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1180 1181 // Truncate the result, and divide by K! / 2^T. 1182 1183 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1184 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1185 } 1186 1187 /// Return the value of this chain of recurrences at the specified iteration 1188 /// number. We can evaluate this recurrence by multiplying each element in the 1189 /// chain by the binomial coefficient corresponding to it. In other words, we 1190 /// can evaluate {A,+,B,+,C,+,D} as: 1191 /// 1192 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1193 /// 1194 /// where BC(It, k) stands for binomial coefficient. 1195 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1196 ScalarEvolution &SE) const { 1197 const SCEV *Result = getStart(); 1198 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1199 // The computation is correct in the face of overflow provided that the 1200 // multiplication is performed _after_ the evaluation of the binomial 1201 // coefficient. 1202 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1203 if (isa<SCEVCouldNotCompute>(Coeff)) 1204 return Coeff; 1205 1206 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1207 } 1208 return Result; 1209 } 1210 1211 //===----------------------------------------------------------------------===// 1212 // SCEV Expression folder implementations 1213 //===----------------------------------------------------------------------===// 1214 1215 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1216 Type *Ty) { 1217 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1218 "This is not a truncating conversion!"); 1219 assert(isSCEVable(Ty) && 1220 "This is not a conversion to a SCEVable type!"); 1221 Ty = getEffectiveSCEVType(Ty); 1222 1223 FoldingSetNodeID ID; 1224 ID.AddInteger(scTruncate); 1225 ID.AddPointer(Op); 1226 ID.AddPointer(Ty); 1227 void *IP = nullptr; 1228 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1229 1230 // Fold if the operand is constant. 1231 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1232 return getConstant( 1233 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1234 1235 // trunc(trunc(x)) --> trunc(x) 1236 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1237 return getTruncateExpr(ST->getOperand(), Ty); 1238 1239 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1240 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1241 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1242 1243 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1244 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1245 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1246 1247 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1248 // eliminate all the truncates, or we replace other casts with truncates. 1249 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1250 SmallVector<const SCEV *, 4> Operands; 1251 bool hasTrunc = false; 1252 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1253 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1254 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1255 hasTrunc = isa<SCEVTruncateExpr>(S); 1256 Operands.push_back(S); 1257 } 1258 if (!hasTrunc) 1259 return getAddExpr(Operands); 1260 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1261 } 1262 1263 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1264 // eliminate all the truncates, or we replace other casts with truncates. 1265 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1266 SmallVector<const SCEV *, 4> Operands; 1267 bool hasTrunc = false; 1268 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1269 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1270 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1271 hasTrunc = isa<SCEVTruncateExpr>(S); 1272 Operands.push_back(S); 1273 } 1274 if (!hasTrunc) 1275 return getMulExpr(Operands); 1276 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1277 } 1278 1279 // If the input value is a chrec scev, truncate the chrec's operands. 1280 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1281 SmallVector<const SCEV *, 4> Operands; 1282 for (const SCEV *Op : AddRec->operands()) 1283 Operands.push_back(getTruncateExpr(Op, Ty)); 1284 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1285 } 1286 1287 // The cast wasn't folded; create an explicit cast node. We can reuse 1288 // the existing insert position since if we get here, we won't have 1289 // made any changes which would invalidate it. 1290 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1291 Op, Ty); 1292 UniqueSCEVs.InsertNode(S, IP); 1293 return S; 1294 } 1295 1296 // Get the limit of a recurrence such that incrementing by Step cannot cause 1297 // signed overflow as long as the value of the recurrence within the 1298 // loop does not exceed this limit before incrementing. 1299 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1300 ICmpInst::Predicate *Pred, 1301 ScalarEvolution *SE) { 1302 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1303 if (SE->isKnownPositive(Step)) { 1304 *Pred = ICmpInst::ICMP_SLT; 1305 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1306 SE->getSignedRangeMax(Step)); 1307 } 1308 if (SE->isKnownNegative(Step)) { 1309 *Pred = ICmpInst::ICMP_SGT; 1310 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1311 SE->getSignedRangeMin(Step)); 1312 } 1313 return nullptr; 1314 } 1315 1316 // Get the limit of a recurrence such that incrementing by Step cannot cause 1317 // unsigned overflow as long as the value of the recurrence within the loop does 1318 // not exceed this limit before incrementing. 1319 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1320 ICmpInst::Predicate *Pred, 1321 ScalarEvolution *SE) { 1322 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1323 *Pred = ICmpInst::ICMP_ULT; 1324 1325 return SE->getConstant(APInt::getMinValue(BitWidth) - 1326 SE->getUnsignedRangeMax(Step)); 1327 } 1328 1329 namespace { 1330 1331 struct ExtendOpTraitsBase { 1332 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1333 unsigned); 1334 }; 1335 1336 // Used to make code generic over signed and unsigned overflow. 1337 template <typename ExtendOp> struct ExtendOpTraits { 1338 // Members present: 1339 // 1340 // static const SCEV::NoWrapFlags WrapType; 1341 // 1342 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1343 // 1344 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1345 // ICmpInst::Predicate *Pred, 1346 // ScalarEvolution *SE); 1347 }; 1348 1349 template <> 1350 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1351 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1352 1353 static const GetExtendExprTy GetExtendExpr; 1354 1355 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1356 ICmpInst::Predicate *Pred, 1357 ScalarEvolution *SE) { 1358 return getSignedOverflowLimitForStep(Step, Pred, SE); 1359 } 1360 }; 1361 1362 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1363 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1364 1365 template <> 1366 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1367 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1368 1369 static const GetExtendExprTy GetExtendExpr; 1370 1371 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1372 ICmpInst::Predicate *Pred, 1373 ScalarEvolution *SE) { 1374 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1375 } 1376 }; 1377 1378 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1379 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1380 1381 } // end anonymous namespace 1382 1383 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1384 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1385 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1386 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1387 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1388 // expression "Step + sext/zext(PreIncAR)" is congruent with 1389 // "sext/zext(PostIncAR)" 1390 template <typename ExtendOpTy> 1391 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1392 ScalarEvolution *SE, unsigned Depth) { 1393 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1394 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1395 1396 const Loop *L = AR->getLoop(); 1397 const SCEV *Start = AR->getStart(); 1398 const SCEV *Step = AR->getStepRecurrence(*SE); 1399 1400 // Check for a simple looking step prior to loop entry. 1401 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1402 if (!SA) 1403 return nullptr; 1404 1405 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1406 // subtraction is expensive. For this purpose, perform a quick and dirty 1407 // difference, by checking for Step in the operand list. 1408 SmallVector<const SCEV *, 4> DiffOps; 1409 for (const SCEV *Op : SA->operands()) 1410 if (Op != Step) 1411 DiffOps.push_back(Op); 1412 1413 if (DiffOps.size() == SA->getNumOperands()) 1414 return nullptr; 1415 1416 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1417 // `Step`: 1418 1419 // 1. NSW/NUW flags on the step increment. 1420 auto PreStartFlags = 1421 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1422 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1423 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1424 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1425 1426 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1427 // "S+X does not sign/unsign-overflow". 1428 // 1429 1430 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1431 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1432 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1433 return PreStart; 1434 1435 // 2. Direct overflow check on the step operation's expression. 1436 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1437 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1438 const SCEV *OperandExtendedStart = 1439 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1440 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1441 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1442 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1443 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1444 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1445 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1446 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1447 } 1448 return PreStart; 1449 } 1450 1451 // 3. Loop precondition. 1452 ICmpInst::Predicate Pred; 1453 const SCEV *OverflowLimit = 1454 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1455 1456 if (OverflowLimit && 1457 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1458 return PreStart; 1459 1460 return nullptr; 1461 } 1462 1463 // Get the normalized zero or sign extended expression for this AddRec's Start. 1464 template <typename ExtendOpTy> 1465 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1466 ScalarEvolution *SE, 1467 unsigned Depth) { 1468 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1469 1470 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1471 if (!PreStart) 1472 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1473 1474 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1475 Depth), 1476 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1477 } 1478 1479 // Try to prove away overflow by looking at "nearby" add recurrences. A 1480 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1481 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1482 // 1483 // Formally: 1484 // 1485 // {S,+,X} == {S-T,+,X} + T 1486 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1487 // 1488 // If ({S-T,+,X} + T) does not overflow ... (1) 1489 // 1490 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1491 // 1492 // If {S-T,+,X} does not overflow ... (2) 1493 // 1494 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1495 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1496 // 1497 // If (S-T)+T does not overflow ... (3) 1498 // 1499 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1500 // == {Ext(S),+,Ext(X)} == LHS 1501 // 1502 // Thus, if (1), (2) and (3) are true for some T, then 1503 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1504 // 1505 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1506 // does not overflow" restricted to the 0th iteration. Therefore we only need 1507 // to check for (1) and (2). 1508 // 1509 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1510 // is `Delta` (defined below). 1511 template <typename ExtendOpTy> 1512 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1513 const SCEV *Step, 1514 const Loop *L) { 1515 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1516 1517 // We restrict `Start` to a constant to prevent SCEV from spending too much 1518 // time here. It is correct (but more expensive) to continue with a 1519 // non-constant `Start` and do a general SCEV subtraction to compute 1520 // `PreStart` below. 1521 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1522 if (!StartC) 1523 return false; 1524 1525 APInt StartAI = StartC->getAPInt(); 1526 1527 for (unsigned Delta : {-2, -1, 1, 2}) { 1528 const SCEV *PreStart = getConstant(StartAI - Delta); 1529 1530 FoldingSetNodeID ID; 1531 ID.AddInteger(scAddRecExpr); 1532 ID.AddPointer(PreStart); 1533 ID.AddPointer(Step); 1534 ID.AddPointer(L); 1535 void *IP = nullptr; 1536 const auto *PreAR = 1537 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1538 1539 // Give up if we don't already have the add recurrence we need because 1540 // actually constructing an add recurrence is relatively expensive. 1541 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1542 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1543 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1544 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1545 DeltaS, &Pred, this); 1546 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1547 return true; 1548 } 1549 } 1550 1551 return false; 1552 } 1553 1554 const SCEV * 1555 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1556 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1557 "This is not an extending conversion!"); 1558 assert(isSCEVable(Ty) && 1559 "This is not a conversion to a SCEVable type!"); 1560 Ty = getEffectiveSCEVType(Ty); 1561 1562 // Fold if the operand is constant. 1563 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1564 return getConstant( 1565 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1566 1567 // zext(zext(x)) --> zext(x) 1568 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1569 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1570 1571 // Before doing any expensive analysis, check to see if we've already 1572 // computed a SCEV for this Op and Ty. 1573 FoldingSetNodeID ID; 1574 ID.AddInteger(scZeroExtend); 1575 ID.AddPointer(Op); 1576 ID.AddPointer(Ty); 1577 void *IP = nullptr; 1578 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1579 if (Depth > MaxExtDepth) { 1580 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1581 Op, Ty); 1582 UniqueSCEVs.InsertNode(S, IP); 1583 return S; 1584 } 1585 1586 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1587 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1588 // It's possible the bits taken off by the truncate were all zero bits. If 1589 // so, we should be able to simplify this further. 1590 const SCEV *X = ST->getOperand(); 1591 ConstantRange CR = getUnsignedRange(X); 1592 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1593 unsigned NewBits = getTypeSizeInBits(Ty); 1594 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1595 CR.zextOrTrunc(NewBits))) 1596 return getTruncateOrZeroExtend(X, Ty); 1597 } 1598 1599 // If the input value is a chrec scev, and we can prove that the value 1600 // did not overflow the old, smaller, value, we can zero extend all of the 1601 // operands (often constants). This allows analysis of something like 1602 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1603 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1604 if (AR->isAffine()) { 1605 const SCEV *Start = AR->getStart(); 1606 const SCEV *Step = AR->getStepRecurrence(*this); 1607 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1608 const Loop *L = AR->getLoop(); 1609 1610 if (!AR->hasNoUnsignedWrap()) { 1611 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1612 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1613 } 1614 1615 // If we have special knowledge that this addrec won't overflow, 1616 // we don't need to do any further analysis. 1617 if (AR->hasNoUnsignedWrap()) 1618 return getAddRecExpr( 1619 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1620 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1621 1622 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1623 // Note that this serves two purposes: It filters out loops that are 1624 // simply not analyzable, and it covers the case where this code is 1625 // being called from within backedge-taken count analysis, such that 1626 // attempting to ask for the backedge-taken count would likely result 1627 // in infinite recursion. In the later case, the analysis code will 1628 // cope with a conservative value, and it will take care to purge 1629 // that value once it has finished. 1630 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1631 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1632 // Manually compute the final value for AR, checking for 1633 // overflow. 1634 1635 // Check whether the backedge-taken count can be losslessly casted to 1636 // the addrec's type. The count is always unsigned. 1637 const SCEV *CastedMaxBECount = 1638 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1639 const SCEV *RecastedMaxBECount = 1640 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1641 if (MaxBECount == RecastedMaxBECount) { 1642 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1643 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1644 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1645 SCEV::FlagAnyWrap, Depth + 1); 1646 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1647 SCEV::FlagAnyWrap, 1648 Depth + 1), 1649 WideTy, Depth + 1); 1650 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1651 const SCEV *WideMaxBECount = 1652 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1653 const SCEV *OperandExtendedAdd = 1654 getAddExpr(WideStart, 1655 getMulExpr(WideMaxBECount, 1656 getZeroExtendExpr(Step, WideTy, Depth + 1), 1657 SCEV::FlagAnyWrap, Depth + 1), 1658 SCEV::FlagAnyWrap, Depth + 1); 1659 if (ZAdd == OperandExtendedAdd) { 1660 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1661 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1662 // Return the expression with the addrec on the outside. 1663 return getAddRecExpr( 1664 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1665 Depth + 1), 1666 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1667 AR->getNoWrapFlags()); 1668 } 1669 // Similar to above, only this time treat the step value as signed. 1670 // This covers loops that count down. 1671 OperandExtendedAdd = 1672 getAddExpr(WideStart, 1673 getMulExpr(WideMaxBECount, 1674 getSignExtendExpr(Step, WideTy, Depth + 1), 1675 SCEV::FlagAnyWrap, Depth + 1), 1676 SCEV::FlagAnyWrap, Depth + 1); 1677 if (ZAdd == OperandExtendedAdd) { 1678 // Cache knowledge of AR NW, which is propagated to this AddRec. 1679 // Negative step causes unsigned wrap, but it still can't self-wrap. 1680 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1681 // Return the expression with the addrec on the outside. 1682 return getAddRecExpr( 1683 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1684 Depth + 1), 1685 getSignExtendExpr(Step, Ty, Depth + 1), L, 1686 AR->getNoWrapFlags()); 1687 } 1688 } 1689 } 1690 1691 // Normally, in the cases we can prove no-overflow via a 1692 // backedge guarding condition, we can also compute a backedge 1693 // taken count for the loop. The exceptions are assumptions and 1694 // guards present in the loop -- SCEV is not great at exploiting 1695 // these to compute max backedge taken counts, but can still use 1696 // these to prove lack of overflow. Use this fact to avoid 1697 // doing extra work that may not pay off. 1698 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1699 !AC.assumptions().empty()) { 1700 // If the backedge is guarded by a comparison with the pre-inc 1701 // value the addrec is safe. Also, if the entry is guarded by 1702 // a comparison with the start value and the backedge is 1703 // guarded by a comparison with the post-inc value, the addrec 1704 // is safe. 1705 if (isKnownPositive(Step)) { 1706 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1707 getUnsignedRangeMax(Step)); 1708 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1709 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1710 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1711 AR->getPostIncExpr(*this), N))) { 1712 // Cache knowledge of AR NUW, which is propagated to this 1713 // AddRec. 1714 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1715 // Return the expression with the addrec on the outside. 1716 return getAddRecExpr( 1717 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1718 Depth + 1), 1719 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1720 AR->getNoWrapFlags()); 1721 } 1722 } else if (isKnownNegative(Step)) { 1723 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1724 getSignedRangeMin(Step)); 1725 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1726 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1727 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1728 AR->getPostIncExpr(*this), N))) { 1729 // Cache knowledge of AR NW, which is propagated to this 1730 // AddRec. Negative step causes unsigned wrap, but it 1731 // still can't self-wrap. 1732 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1733 // Return the expression with the addrec on the outside. 1734 return getAddRecExpr( 1735 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1736 Depth + 1), 1737 getSignExtendExpr(Step, Ty, Depth + 1), L, 1738 AR->getNoWrapFlags()); 1739 } 1740 } 1741 } 1742 1743 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1744 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1745 return getAddRecExpr( 1746 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1747 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1748 } 1749 } 1750 1751 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1752 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1753 if (SA->hasNoUnsignedWrap()) { 1754 // If the addition does not unsign overflow then we can, by definition, 1755 // commute the zero extension with the addition operation. 1756 SmallVector<const SCEV *, 4> Ops; 1757 for (const auto *Op : SA->operands()) 1758 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1759 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1760 } 1761 } 1762 1763 // The cast wasn't folded; create an explicit cast node. 1764 // Recompute the insert position, as it may have been invalidated. 1765 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1766 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1767 Op, Ty); 1768 UniqueSCEVs.InsertNode(S, IP); 1769 return S; 1770 } 1771 1772 const SCEV * 1773 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1774 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1775 "This is not an extending conversion!"); 1776 assert(isSCEVable(Ty) && 1777 "This is not a conversion to a SCEVable type!"); 1778 Ty = getEffectiveSCEVType(Ty); 1779 1780 // Fold if the operand is constant. 1781 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1782 return getConstant( 1783 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1784 1785 // sext(sext(x)) --> sext(x) 1786 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1787 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1788 1789 // sext(zext(x)) --> zext(x) 1790 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1791 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1792 1793 // Before doing any expensive analysis, check to see if we've already 1794 // computed a SCEV for this Op and Ty. 1795 FoldingSetNodeID ID; 1796 ID.AddInteger(scSignExtend); 1797 ID.AddPointer(Op); 1798 ID.AddPointer(Ty); 1799 void *IP = nullptr; 1800 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1801 // Limit recursion depth. 1802 if (Depth > MaxExtDepth) { 1803 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1804 Op, Ty); 1805 UniqueSCEVs.InsertNode(S, IP); 1806 return S; 1807 } 1808 1809 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1810 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1811 // It's possible the bits taken off by the truncate were all sign bits. If 1812 // so, we should be able to simplify this further. 1813 const SCEV *X = ST->getOperand(); 1814 ConstantRange CR = getSignedRange(X); 1815 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1816 unsigned NewBits = getTypeSizeInBits(Ty); 1817 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1818 CR.sextOrTrunc(NewBits))) 1819 return getTruncateOrSignExtend(X, Ty); 1820 } 1821 1822 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1823 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1824 if (SA->getNumOperands() == 2) { 1825 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1826 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1827 if (SMul && SC1) { 1828 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1829 const APInt &C1 = SC1->getAPInt(); 1830 const APInt &C2 = SC2->getAPInt(); 1831 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1832 C2.ugt(C1) && C2.isPowerOf2()) 1833 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1834 getSignExtendExpr(SMul, Ty, Depth + 1), 1835 SCEV::FlagAnyWrap, Depth + 1); 1836 } 1837 } 1838 } 1839 1840 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1841 if (SA->hasNoSignedWrap()) { 1842 // If the addition does not sign overflow then we can, by definition, 1843 // commute the sign extension with the addition operation. 1844 SmallVector<const SCEV *, 4> Ops; 1845 for (const auto *Op : SA->operands()) 1846 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1847 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1848 } 1849 } 1850 // If the input value is a chrec scev, and we can prove that the value 1851 // did not overflow the old, smaller, value, we can sign extend all of the 1852 // operands (often constants). This allows analysis of something like 1853 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1854 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1855 if (AR->isAffine()) { 1856 const SCEV *Start = AR->getStart(); 1857 const SCEV *Step = AR->getStepRecurrence(*this); 1858 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1859 const Loop *L = AR->getLoop(); 1860 1861 if (!AR->hasNoSignedWrap()) { 1862 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1863 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1864 } 1865 1866 // If we have special knowledge that this addrec won't overflow, 1867 // we don't need to do any further analysis. 1868 if (AR->hasNoSignedWrap()) 1869 return getAddRecExpr( 1870 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1871 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1872 1873 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1874 // Note that this serves two purposes: It filters out loops that are 1875 // simply not analyzable, and it covers the case where this code is 1876 // being called from within backedge-taken count analysis, such that 1877 // attempting to ask for the backedge-taken count would likely result 1878 // in infinite recursion. In the later case, the analysis code will 1879 // cope with a conservative value, and it will take care to purge 1880 // that value once it has finished. 1881 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1882 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1883 // Manually compute the final value for AR, checking for 1884 // overflow. 1885 1886 // Check whether the backedge-taken count can be losslessly casted to 1887 // the addrec's type. The count is always unsigned. 1888 const SCEV *CastedMaxBECount = 1889 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1890 const SCEV *RecastedMaxBECount = 1891 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1892 if (MaxBECount == RecastedMaxBECount) { 1893 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1894 // Check whether Start+Step*MaxBECount has no signed overflow. 1895 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1896 SCEV::FlagAnyWrap, Depth + 1); 1897 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1898 SCEV::FlagAnyWrap, 1899 Depth + 1), 1900 WideTy, Depth + 1); 1901 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1902 const SCEV *WideMaxBECount = 1903 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1904 const SCEV *OperandExtendedAdd = 1905 getAddExpr(WideStart, 1906 getMulExpr(WideMaxBECount, 1907 getSignExtendExpr(Step, WideTy, Depth + 1), 1908 SCEV::FlagAnyWrap, Depth + 1), 1909 SCEV::FlagAnyWrap, Depth + 1); 1910 if (SAdd == OperandExtendedAdd) { 1911 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1912 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1913 // Return the expression with the addrec on the outside. 1914 return getAddRecExpr( 1915 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1916 Depth + 1), 1917 getSignExtendExpr(Step, Ty, Depth + 1), L, 1918 AR->getNoWrapFlags()); 1919 } 1920 // Similar to above, only this time treat the step value as unsigned. 1921 // This covers loops that count up with an unsigned step. 1922 OperandExtendedAdd = 1923 getAddExpr(WideStart, 1924 getMulExpr(WideMaxBECount, 1925 getZeroExtendExpr(Step, WideTy, Depth + 1), 1926 SCEV::FlagAnyWrap, Depth + 1), 1927 SCEV::FlagAnyWrap, Depth + 1); 1928 if (SAdd == OperandExtendedAdd) { 1929 // If AR wraps around then 1930 // 1931 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1932 // => SAdd != OperandExtendedAdd 1933 // 1934 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1935 // (SAdd == OperandExtendedAdd => AR is NW) 1936 1937 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1938 1939 // Return the expression with the addrec on the outside. 1940 return getAddRecExpr( 1941 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1942 Depth + 1), 1943 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1944 AR->getNoWrapFlags()); 1945 } 1946 } 1947 } 1948 1949 // Normally, in the cases we can prove no-overflow via a 1950 // backedge guarding condition, we can also compute a backedge 1951 // taken count for the loop. The exceptions are assumptions and 1952 // guards present in the loop -- SCEV is not great at exploiting 1953 // these to compute max backedge taken counts, but can still use 1954 // these to prove lack of overflow. Use this fact to avoid 1955 // doing extra work that may not pay off. 1956 1957 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1958 !AC.assumptions().empty()) { 1959 // If the backedge is guarded by a comparison with the pre-inc 1960 // value the addrec is safe. Also, if the entry is guarded by 1961 // a comparison with the start value and the backedge is 1962 // guarded by a comparison with the post-inc value, the addrec 1963 // is safe. 1964 ICmpInst::Predicate Pred; 1965 const SCEV *OverflowLimit = 1966 getSignedOverflowLimitForStep(Step, &Pred, this); 1967 if (OverflowLimit && 1968 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1969 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1970 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1971 OverflowLimit)))) { 1972 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1973 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1974 return getAddRecExpr( 1975 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1976 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1977 } 1978 } 1979 1980 // If Start and Step are constants, check if we can apply this 1981 // transformation: 1982 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1983 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1984 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1985 if (SC1 && SC2) { 1986 const APInt &C1 = SC1->getAPInt(); 1987 const APInt &C2 = SC2->getAPInt(); 1988 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1989 C2.isPowerOf2()) { 1990 Start = getSignExtendExpr(Start, Ty, Depth + 1); 1991 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1992 AR->getNoWrapFlags()); 1993 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 1994 SCEV::FlagAnyWrap, Depth + 1); 1995 } 1996 } 1997 1998 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1999 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2000 return getAddRecExpr( 2001 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2002 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2003 } 2004 } 2005 2006 // If the input value is provably positive and we could not simplify 2007 // away the sext build a zext instead. 2008 if (isKnownNonNegative(Op)) 2009 return getZeroExtendExpr(Op, Ty, Depth + 1); 2010 2011 // The cast wasn't folded; create an explicit cast node. 2012 // Recompute the insert position, as it may have been invalidated. 2013 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2014 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2015 Op, Ty); 2016 UniqueSCEVs.InsertNode(S, IP); 2017 return S; 2018 } 2019 2020 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2021 /// unspecified bits out to the given type. 2022 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2023 Type *Ty) { 2024 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2025 "This is not an extending conversion!"); 2026 assert(isSCEVable(Ty) && 2027 "This is not a conversion to a SCEVable type!"); 2028 Ty = getEffectiveSCEVType(Ty); 2029 2030 // Sign-extend negative constants. 2031 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2032 if (SC->getAPInt().isNegative()) 2033 return getSignExtendExpr(Op, Ty); 2034 2035 // Peel off a truncate cast. 2036 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2037 const SCEV *NewOp = T->getOperand(); 2038 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2039 return getAnyExtendExpr(NewOp, Ty); 2040 return getTruncateOrNoop(NewOp, Ty); 2041 } 2042 2043 // Next try a zext cast. If the cast is folded, use it. 2044 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2045 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2046 return ZExt; 2047 2048 // Next try a sext cast. If the cast is folded, use it. 2049 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2050 if (!isa<SCEVSignExtendExpr>(SExt)) 2051 return SExt; 2052 2053 // Force the cast to be folded into the operands of an addrec. 2054 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2055 SmallVector<const SCEV *, 4> Ops; 2056 for (const SCEV *Op : AR->operands()) 2057 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2058 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2059 } 2060 2061 // If the expression is obviously signed, use the sext cast value. 2062 if (isa<SCEVSMaxExpr>(Op)) 2063 return SExt; 2064 2065 // Absent any other information, use the zext cast value. 2066 return ZExt; 2067 } 2068 2069 /// Process the given Ops list, which is a list of operands to be added under 2070 /// the given scale, update the given map. This is a helper function for 2071 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2072 /// that would form an add expression like this: 2073 /// 2074 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2075 /// 2076 /// where A and B are constants, update the map with these values: 2077 /// 2078 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2079 /// 2080 /// and add 13 + A*B*29 to AccumulatedConstant. 2081 /// This will allow getAddRecExpr to produce this: 2082 /// 2083 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2084 /// 2085 /// This form often exposes folding opportunities that are hidden in 2086 /// the original operand list. 2087 /// 2088 /// Return true iff it appears that any interesting folding opportunities 2089 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2090 /// the common case where no interesting opportunities are present, and 2091 /// is also used as a check to avoid infinite recursion. 2092 static bool 2093 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2094 SmallVectorImpl<const SCEV *> &NewOps, 2095 APInt &AccumulatedConstant, 2096 const SCEV *const *Ops, size_t NumOperands, 2097 const APInt &Scale, 2098 ScalarEvolution &SE) { 2099 bool Interesting = false; 2100 2101 // Iterate over the add operands. They are sorted, with constants first. 2102 unsigned i = 0; 2103 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2104 ++i; 2105 // Pull a buried constant out to the outside. 2106 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2107 Interesting = true; 2108 AccumulatedConstant += Scale * C->getAPInt(); 2109 } 2110 2111 // Next comes everything else. We're especially interested in multiplies 2112 // here, but they're in the middle, so just visit the rest with one loop. 2113 for (; i != NumOperands; ++i) { 2114 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2115 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2116 APInt NewScale = 2117 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2118 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2119 // A multiplication of a constant with another add; recurse. 2120 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2121 Interesting |= 2122 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2123 Add->op_begin(), Add->getNumOperands(), 2124 NewScale, SE); 2125 } else { 2126 // A multiplication of a constant with some other value. Update 2127 // the map. 2128 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2129 const SCEV *Key = SE.getMulExpr(MulOps); 2130 auto Pair = M.insert({Key, NewScale}); 2131 if (Pair.second) { 2132 NewOps.push_back(Pair.first->first); 2133 } else { 2134 Pair.first->second += NewScale; 2135 // The map already had an entry for this value, which may indicate 2136 // a folding opportunity. 2137 Interesting = true; 2138 } 2139 } 2140 } else { 2141 // An ordinary operand. Update the map. 2142 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2143 M.insert({Ops[i], Scale}); 2144 if (Pair.second) { 2145 NewOps.push_back(Pair.first->first); 2146 } else { 2147 Pair.first->second += Scale; 2148 // The map already had an entry for this value, which may indicate 2149 // a folding opportunity. 2150 Interesting = true; 2151 } 2152 } 2153 } 2154 2155 return Interesting; 2156 } 2157 2158 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2159 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2160 // can't-overflow flags for the operation if possible. 2161 static SCEV::NoWrapFlags 2162 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2163 const SmallVectorImpl<const SCEV *> &Ops, 2164 SCEV::NoWrapFlags Flags) { 2165 using namespace std::placeholders; 2166 2167 using OBO = OverflowingBinaryOperator; 2168 2169 bool CanAnalyze = 2170 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2171 (void)CanAnalyze; 2172 assert(CanAnalyze && "don't call from other places!"); 2173 2174 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2175 SCEV::NoWrapFlags SignOrUnsignWrap = 2176 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2177 2178 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2179 auto IsKnownNonNegative = [&](const SCEV *S) { 2180 return SE->isKnownNonNegative(S); 2181 }; 2182 2183 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2184 Flags = 2185 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2186 2187 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2188 2189 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2190 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2191 2192 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2193 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2194 2195 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2196 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2197 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2198 Instruction::Add, C, OBO::NoSignedWrap); 2199 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2200 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2201 } 2202 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2203 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2204 Instruction::Add, C, OBO::NoUnsignedWrap); 2205 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2206 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2207 } 2208 } 2209 2210 return Flags; 2211 } 2212 2213 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2214 if (!isLoopInvariant(S, L)) 2215 return false; 2216 // If a value depends on a SCEVUnknown which is defined after the loop, we 2217 // conservatively assume that we cannot calculate it at the loop's entry. 2218 struct FindDominatedSCEVUnknown { 2219 bool Found = false; 2220 const Loop *L; 2221 DominatorTree &DT; 2222 LoopInfo &LI; 2223 2224 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI) 2225 : L(L), DT(DT), LI(LI) {} 2226 2227 bool checkSCEVUnknown(const SCEVUnknown *SU) { 2228 if (auto *I = dyn_cast<Instruction>(SU->getValue())) { 2229 if (DT.dominates(L->getHeader(), I->getParent())) 2230 Found = true; 2231 else 2232 assert(DT.dominates(I->getParent(), L->getHeader()) && 2233 "No dominance relationship between SCEV and loop?"); 2234 } 2235 return false; 2236 } 2237 2238 bool follow(const SCEV *S) { 2239 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 2240 case scConstant: 2241 return false; 2242 case scAddRecExpr: 2243 case scTruncate: 2244 case scZeroExtend: 2245 case scSignExtend: 2246 case scAddExpr: 2247 case scMulExpr: 2248 case scUMaxExpr: 2249 case scSMaxExpr: 2250 case scUDivExpr: 2251 return true; 2252 case scUnknown: 2253 return checkSCEVUnknown(cast<SCEVUnknown>(S)); 2254 case scCouldNotCompute: 2255 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 2256 } 2257 return false; 2258 } 2259 2260 bool isDone() { return Found; } 2261 }; 2262 2263 FindDominatedSCEVUnknown FSU(L, DT, LI); 2264 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU); 2265 ST.visitAll(S); 2266 return !FSU.Found; 2267 } 2268 2269 /// Get a canonical add expression, or something simpler if possible. 2270 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2271 SCEV::NoWrapFlags Flags, 2272 unsigned Depth) { 2273 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2274 "only nuw or nsw allowed"); 2275 assert(!Ops.empty() && "Cannot get empty add!"); 2276 if (Ops.size() == 1) return Ops[0]; 2277 #ifndef NDEBUG 2278 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2279 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2280 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2281 "SCEVAddExpr operand types don't match!"); 2282 #endif 2283 2284 // Sort by complexity, this groups all similar expression types together. 2285 GroupByComplexity(Ops, &LI, DT); 2286 2287 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2288 2289 // If there are any constants, fold them together. 2290 unsigned Idx = 0; 2291 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2292 ++Idx; 2293 assert(Idx < Ops.size()); 2294 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2295 // We found two constants, fold them together! 2296 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2297 if (Ops.size() == 2) return Ops[0]; 2298 Ops.erase(Ops.begin()+1); // Erase the folded element 2299 LHSC = cast<SCEVConstant>(Ops[0]); 2300 } 2301 2302 // If we are left with a constant zero being added, strip it off. 2303 if (LHSC->getValue()->isZero()) { 2304 Ops.erase(Ops.begin()); 2305 --Idx; 2306 } 2307 2308 if (Ops.size() == 1) return Ops[0]; 2309 } 2310 2311 // Limit recursion calls depth. 2312 if (Depth > MaxArithDepth) 2313 return getOrCreateAddExpr(Ops, Flags); 2314 2315 // Okay, check to see if the same value occurs in the operand list more than 2316 // once. If so, merge them together into an multiply expression. Since we 2317 // sorted the list, these values are required to be adjacent. 2318 Type *Ty = Ops[0]->getType(); 2319 bool FoundMatch = false; 2320 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2321 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2322 // Scan ahead to count how many equal operands there are. 2323 unsigned Count = 2; 2324 while (i+Count != e && Ops[i+Count] == Ops[i]) 2325 ++Count; 2326 // Merge the values into a multiply. 2327 const SCEV *Scale = getConstant(Ty, Count); 2328 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2329 if (Ops.size() == Count) 2330 return Mul; 2331 Ops[i] = Mul; 2332 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2333 --i; e -= Count - 1; 2334 FoundMatch = true; 2335 } 2336 if (FoundMatch) 2337 return getAddExpr(Ops, Flags); 2338 2339 // Check for truncates. If all the operands are truncated from the same 2340 // type, see if factoring out the truncate would permit the result to be 2341 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2342 // if the contents of the resulting outer trunc fold to something simple. 2343 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2344 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2345 Type *DstType = Trunc->getType(); 2346 Type *SrcType = Trunc->getOperand()->getType(); 2347 SmallVector<const SCEV *, 8> LargeOps; 2348 bool Ok = true; 2349 // Check all the operands to see if they can be represented in the 2350 // source type of the truncate. 2351 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2352 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2353 if (T->getOperand()->getType() != SrcType) { 2354 Ok = false; 2355 break; 2356 } 2357 LargeOps.push_back(T->getOperand()); 2358 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2359 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2361 SmallVector<const SCEV *, 8> LargeMulOps; 2362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2363 if (const SCEVTruncateExpr *T = 2364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2365 if (T->getOperand()->getType() != SrcType) { 2366 Ok = false; 2367 break; 2368 } 2369 LargeMulOps.push_back(T->getOperand()); 2370 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2371 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2372 } else { 2373 Ok = false; 2374 break; 2375 } 2376 } 2377 if (Ok) 2378 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2379 } else { 2380 Ok = false; 2381 break; 2382 } 2383 } 2384 if (Ok) { 2385 // Evaluate the expression in the larger type. 2386 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2387 // If it folds to something simple, use it. Otherwise, don't. 2388 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2389 return getTruncateExpr(Fold, DstType); 2390 } 2391 } 2392 2393 // Skip past any other cast SCEVs. 2394 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2395 ++Idx; 2396 2397 // If there are add operands they would be next. 2398 if (Idx < Ops.size()) { 2399 bool DeletedAdd = false; 2400 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2401 if (Ops.size() > AddOpsInlineThreshold || 2402 Add->getNumOperands() > AddOpsInlineThreshold) 2403 break; 2404 // If we have an add, expand the add operands onto the end of the operands 2405 // list. 2406 Ops.erase(Ops.begin()+Idx); 2407 Ops.append(Add->op_begin(), Add->op_end()); 2408 DeletedAdd = true; 2409 } 2410 2411 // If we deleted at least one add, we added operands to the end of the list, 2412 // and they are not necessarily sorted. Recurse to resort and resimplify 2413 // any operands we just acquired. 2414 if (DeletedAdd) 2415 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2416 } 2417 2418 // Skip over the add expression until we get to a multiply. 2419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2420 ++Idx; 2421 2422 // Check to see if there are any folding opportunities present with 2423 // operands multiplied by constant values. 2424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2425 uint64_t BitWidth = getTypeSizeInBits(Ty); 2426 DenseMap<const SCEV *, APInt> M; 2427 SmallVector<const SCEV *, 8> NewOps; 2428 APInt AccumulatedConstant(BitWidth, 0); 2429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2430 Ops.data(), Ops.size(), 2431 APInt(BitWidth, 1), *this)) { 2432 struct APIntCompare { 2433 bool operator()(const APInt &LHS, const APInt &RHS) const { 2434 return LHS.ult(RHS); 2435 } 2436 }; 2437 2438 // Some interesting folding opportunity is present, so its worthwhile to 2439 // re-generate the operands list. Group the operands by constant scale, 2440 // to avoid multiplying by the same constant scale multiple times. 2441 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2442 for (const SCEV *NewOp : NewOps) 2443 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2444 // Re-generate the operands list. 2445 Ops.clear(); 2446 if (AccumulatedConstant != 0) 2447 Ops.push_back(getConstant(AccumulatedConstant)); 2448 for (auto &MulOp : MulOpLists) 2449 if (MulOp.first != 0) 2450 Ops.push_back(getMulExpr( 2451 getConstant(MulOp.first), 2452 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2453 SCEV::FlagAnyWrap, Depth + 1)); 2454 if (Ops.empty()) 2455 return getZero(Ty); 2456 if (Ops.size() == 1) 2457 return Ops[0]; 2458 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2459 } 2460 } 2461 2462 // If we are adding something to a multiply expression, make sure the 2463 // something is not already an operand of the multiply. If so, merge it into 2464 // the multiply. 2465 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2466 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2467 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2468 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2469 if (isa<SCEVConstant>(MulOpSCEV)) 2470 continue; 2471 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2472 if (MulOpSCEV == Ops[AddOp]) { 2473 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2474 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2475 if (Mul->getNumOperands() != 2) { 2476 // If the multiply has more than two operands, we must get the 2477 // Y*Z term. 2478 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2479 Mul->op_begin()+MulOp); 2480 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2481 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2482 } 2483 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2484 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2485 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2486 SCEV::FlagAnyWrap, Depth + 1); 2487 if (Ops.size() == 2) return OuterMul; 2488 if (AddOp < Idx) { 2489 Ops.erase(Ops.begin()+AddOp); 2490 Ops.erase(Ops.begin()+Idx-1); 2491 } else { 2492 Ops.erase(Ops.begin()+Idx); 2493 Ops.erase(Ops.begin()+AddOp-1); 2494 } 2495 Ops.push_back(OuterMul); 2496 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2497 } 2498 2499 // Check this multiply against other multiplies being added together. 2500 for (unsigned OtherMulIdx = Idx+1; 2501 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2502 ++OtherMulIdx) { 2503 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2504 // If MulOp occurs in OtherMul, we can fold the two multiplies 2505 // together. 2506 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2507 OMulOp != e; ++OMulOp) 2508 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2509 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2510 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2511 if (Mul->getNumOperands() != 2) { 2512 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2513 Mul->op_begin()+MulOp); 2514 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2515 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2516 } 2517 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2518 if (OtherMul->getNumOperands() != 2) { 2519 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2520 OtherMul->op_begin()+OMulOp); 2521 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2522 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2523 } 2524 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2525 const SCEV *InnerMulSum = 2526 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2527 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2528 SCEV::FlagAnyWrap, Depth + 1); 2529 if (Ops.size() == 2) return OuterMul; 2530 Ops.erase(Ops.begin()+Idx); 2531 Ops.erase(Ops.begin()+OtherMulIdx-1); 2532 Ops.push_back(OuterMul); 2533 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2534 } 2535 } 2536 } 2537 } 2538 2539 // If there are any add recurrences in the operands list, see if any other 2540 // added values are loop invariant. If so, we can fold them into the 2541 // recurrence. 2542 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2543 ++Idx; 2544 2545 // Scan over all recurrences, trying to fold loop invariants into them. 2546 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2547 // Scan all of the other operands to this add and add them to the vector if 2548 // they are loop invariant w.r.t. the recurrence. 2549 SmallVector<const SCEV *, 8> LIOps; 2550 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2551 const Loop *AddRecLoop = AddRec->getLoop(); 2552 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2553 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2554 LIOps.push_back(Ops[i]); 2555 Ops.erase(Ops.begin()+i); 2556 --i; --e; 2557 } 2558 2559 // If we found some loop invariants, fold them into the recurrence. 2560 if (!LIOps.empty()) { 2561 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2562 LIOps.push_back(AddRec->getStart()); 2563 2564 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2565 AddRec->op_end()); 2566 // This follows from the fact that the no-wrap flags on the outer add 2567 // expression are applicable on the 0th iteration, when the add recurrence 2568 // will be equal to its start value. 2569 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2570 2571 // Build the new addrec. Propagate the NUW and NSW flags if both the 2572 // outer add and the inner addrec are guaranteed to have no overflow. 2573 // Always propagate NW. 2574 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2575 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2576 2577 // If all of the other operands were loop invariant, we are done. 2578 if (Ops.size() == 1) return NewRec; 2579 2580 // Otherwise, add the folded AddRec by the non-invariant parts. 2581 for (unsigned i = 0;; ++i) 2582 if (Ops[i] == AddRec) { 2583 Ops[i] = NewRec; 2584 break; 2585 } 2586 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2587 } 2588 2589 // Okay, if there weren't any loop invariants to be folded, check to see if 2590 // there are multiple AddRec's with the same loop induction variable being 2591 // added together. If so, we can fold them. 2592 for (unsigned OtherIdx = Idx+1; 2593 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2594 ++OtherIdx) { 2595 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2596 // so that the 1st found AddRecExpr is dominated by all others. 2597 assert(DT.dominates( 2598 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2599 AddRec->getLoop()->getHeader()) && 2600 "AddRecExprs are not sorted in reverse dominance order?"); 2601 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2602 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2603 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2604 AddRec->op_end()); 2605 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2606 ++OtherIdx) { 2607 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2608 if (OtherAddRec->getLoop() == AddRecLoop) { 2609 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2610 i != e; ++i) { 2611 if (i >= AddRecOps.size()) { 2612 AddRecOps.append(OtherAddRec->op_begin()+i, 2613 OtherAddRec->op_end()); 2614 break; 2615 } 2616 SmallVector<const SCEV *, 2> TwoOps = { 2617 AddRecOps[i], OtherAddRec->getOperand(i)}; 2618 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2619 } 2620 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2621 } 2622 } 2623 // Step size has changed, so we cannot guarantee no self-wraparound. 2624 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2625 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2626 } 2627 } 2628 2629 // Otherwise couldn't fold anything into this recurrence. Move onto the 2630 // next one. 2631 } 2632 2633 // Okay, it looks like we really DO need an add expr. Check to see if we 2634 // already have one, otherwise create a new one. 2635 return getOrCreateAddExpr(Ops, Flags); 2636 } 2637 2638 const SCEV * 2639 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2640 SCEV::NoWrapFlags Flags) { 2641 FoldingSetNodeID ID; 2642 ID.AddInteger(scAddExpr); 2643 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2644 ID.AddPointer(Ops[i]); 2645 void *IP = nullptr; 2646 SCEVAddExpr *S = 2647 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2648 if (!S) { 2649 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2650 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2651 S = new (SCEVAllocator) 2652 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2653 UniqueSCEVs.InsertNode(S, IP); 2654 } 2655 S->setNoWrapFlags(Flags); 2656 return S; 2657 } 2658 2659 const SCEV * 2660 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2661 SCEV::NoWrapFlags Flags) { 2662 FoldingSetNodeID ID; 2663 ID.AddInteger(scMulExpr); 2664 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2665 ID.AddPointer(Ops[i]); 2666 void *IP = nullptr; 2667 SCEVMulExpr *S = 2668 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2669 if (!S) { 2670 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2671 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2672 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2673 O, Ops.size()); 2674 UniqueSCEVs.InsertNode(S, IP); 2675 } 2676 S->setNoWrapFlags(Flags); 2677 return S; 2678 } 2679 2680 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2681 uint64_t k = i*j; 2682 if (j > 1 && k / j != i) Overflow = true; 2683 return k; 2684 } 2685 2686 /// Compute the result of "n choose k", the binomial coefficient. If an 2687 /// intermediate computation overflows, Overflow will be set and the return will 2688 /// be garbage. Overflow is not cleared on absence of overflow. 2689 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2690 // We use the multiplicative formula: 2691 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2692 // At each iteration, we take the n-th term of the numeral and divide by the 2693 // (k-n)th term of the denominator. This division will always produce an 2694 // integral result, and helps reduce the chance of overflow in the 2695 // intermediate computations. However, we can still overflow even when the 2696 // final result would fit. 2697 2698 if (n == 0 || n == k) return 1; 2699 if (k > n) return 0; 2700 2701 if (k > n/2) 2702 k = n-k; 2703 2704 uint64_t r = 1; 2705 for (uint64_t i = 1; i <= k; ++i) { 2706 r = umul_ov(r, n-(i-1), Overflow); 2707 r /= i; 2708 } 2709 return r; 2710 } 2711 2712 /// Determine if any of the operands in this SCEV are a constant or if 2713 /// any of the add or multiply expressions in this SCEV contain a constant. 2714 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2715 struct FindConstantInAddMulChain { 2716 bool FoundConstant = false; 2717 2718 bool follow(const SCEV *S) { 2719 FoundConstant |= isa<SCEVConstant>(S); 2720 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2721 } 2722 2723 bool isDone() const { 2724 return FoundConstant; 2725 } 2726 }; 2727 2728 FindConstantInAddMulChain F; 2729 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2730 ST.visitAll(StartExpr); 2731 return F.FoundConstant; 2732 } 2733 2734 /// Get a canonical multiply expression, or something simpler if possible. 2735 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2736 SCEV::NoWrapFlags Flags, 2737 unsigned Depth) { 2738 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2739 "only nuw or nsw allowed"); 2740 assert(!Ops.empty() && "Cannot get empty mul!"); 2741 if (Ops.size() == 1) return Ops[0]; 2742 #ifndef NDEBUG 2743 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2744 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2745 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2746 "SCEVMulExpr operand types don't match!"); 2747 #endif 2748 2749 // Sort by complexity, this groups all similar expression types together. 2750 GroupByComplexity(Ops, &LI, DT); 2751 2752 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2753 2754 // Limit recursion calls depth. 2755 if (Depth > MaxArithDepth) 2756 return getOrCreateMulExpr(Ops, Flags); 2757 2758 // If there are any constants, fold them together. 2759 unsigned Idx = 0; 2760 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2761 2762 // C1*(C2+V) -> C1*C2 + C1*V 2763 if (Ops.size() == 2) 2764 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2765 // If any of Add's ops are Adds or Muls with a constant, 2766 // apply this transformation as well. 2767 if (Add->getNumOperands() == 2) 2768 // TODO: There are some cases where this transformation is not 2769 // profitable, for example: 2770 // Add = (C0 + X) * Y + Z. 2771 // Maybe the scope of this transformation should be narrowed down. 2772 if (containsConstantInAddMulChain(Add)) 2773 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2774 SCEV::FlagAnyWrap, Depth + 1), 2775 getMulExpr(LHSC, Add->getOperand(1), 2776 SCEV::FlagAnyWrap, Depth + 1), 2777 SCEV::FlagAnyWrap, Depth + 1); 2778 2779 ++Idx; 2780 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2781 // We found two constants, fold them together! 2782 ConstantInt *Fold = 2783 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2784 Ops[0] = getConstant(Fold); 2785 Ops.erase(Ops.begin()+1); // Erase the folded element 2786 if (Ops.size() == 1) return Ops[0]; 2787 LHSC = cast<SCEVConstant>(Ops[0]); 2788 } 2789 2790 // If we are left with a constant one being multiplied, strip it off. 2791 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2792 Ops.erase(Ops.begin()); 2793 --Idx; 2794 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2795 // If we have a multiply of zero, it will always be zero. 2796 return Ops[0]; 2797 } else if (Ops[0]->isAllOnesValue()) { 2798 // If we have a mul by -1 of an add, try distributing the -1 among the 2799 // add operands. 2800 if (Ops.size() == 2) { 2801 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2802 SmallVector<const SCEV *, 4> NewOps; 2803 bool AnyFolded = false; 2804 for (const SCEV *AddOp : Add->operands()) { 2805 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2806 Depth + 1); 2807 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2808 NewOps.push_back(Mul); 2809 } 2810 if (AnyFolded) 2811 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2812 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2813 // Negation preserves a recurrence's no self-wrap property. 2814 SmallVector<const SCEV *, 4> Operands; 2815 for (const SCEV *AddRecOp : AddRec->operands()) 2816 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2817 Depth + 1)); 2818 2819 return getAddRecExpr(Operands, AddRec->getLoop(), 2820 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2821 } 2822 } 2823 } 2824 2825 if (Ops.size() == 1) 2826 return Ops[0]; 2827 } 2828 2829 // Skip over the add expression until we get to a multiply. 2830 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2831 ++Idx; 2832 2833 // If there are mul operands inline them all into this expression. 2834 if (Idx < Ops.size()) { 2835 bool DeletedMul = false; 2836 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2837 if (Ops.size() > MulOpsInlineThreshold) 2838 break; 2839 // If we have an mul, expand the mul operands onto the end of the 2840 // operands list. 2841 Ops.erase(Ops.begin()+Idx); 2842 Ops.append(Mul->op_begin(), Mul->op_end()); 2843 DeletedMul = true; 2844 } 2845 2846 // If we deleted at least one mul, we added operands to the end of the 2847 // list, and they are not necessarily sorted. Recurse to resort and 2848 // resimplify any operands we just acquired. 2849 if (DeletedMul) 2850 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2851 } 2852 2853 // If there are any add recurrences in the operands list, see if any other 2854 // added values are loop invariant. If so, we can fold them into the 2855 // recurrence. 2856 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2857 ++Idx; 2858 2859 // Scan over all recurrences, trying to fold loop invariants into them. 2860 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2861 // Scan all of the other operands to this mul and add them to the vector 2862 // if they are loop invariant w.r.t. the recurrence. 2863 SmallVector<const SCEV *, 8> LIOps; 2864 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2865 const Loop *AddRecLoop = AddRec->getLoop(); 2866 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2867 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2868 LIOps.push_back(Ops[i]); 2869 Ops.erase(Ops.begin()+i); 2870 --i; --e; 2871 } 2872 2873 // If we found some loop invariants, fold them into the recurrence. 2874 if (!LIOps.empty()) { 2875 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2876 SmallVector<const SCEV *, 4> NewOps; 2877 NewOps.reserve(AddRec->getNumOperands()); 2878 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2879 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2880 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2881 SCEV::FlagAnyWrap, Depth + 1)); 2882 2883 // Build the new addrec. Propagate the NUW and NSW flags if both the 2884 // outer mul and the inner addrec are guaranteed to have no overflow. 2885 // 2886 // No self-wrap cannot be guaranteed after changing the step size, but 2887 // will be inferred if either NUW or NSW is true. 2888 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2889 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2890 2891 // If all of the other operands were loop invariant, we are done. 2892 if (Ops.size() == 1) return NewRec; 2893 2894 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2895 for (unsigned i = 0;; ++i) 2896 if (Ops[i] == AddRec) { 2897 Ops[i] = NewRec; 2898 break; 2899 } 2900 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2901 } 2902 2903 // Okay, if there weren't any loop invariants to be folded, check to see 2904 // if there are multiple AddRec's with the same loop induction variable 2905 // being multiplied together. If so, we can fold them. 2906 2907 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2908 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2909 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2910 // ]]],+,...up to x=2n}. 2911 // Note that the arguments to choose() are always integers with values 2912 // known at compile time, never SCEV objects. 2913 // 2914 // The implementation avoids pointless extra computations when the two 2915 // addrec's are of different length (mathematically, it's equivalent to 2916 // an infinite stream of zeros on the right). 2917 bool OpsModified = false; 2918 for (unsigned OtherIdx = Idx+1; 2919 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2920 ++OtherIdx) { 2921 const SCEVAddRecExpr *OtherAddRec = 2922 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2923 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2924 continue; 2925 2926 // Limit max number of arguments to avoid creation of unreasonably big 2927 // SCEVAddRecs with very complex operands. 2928 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2929 MaxAddRecSize) 2930 continue; 2931 2932 bool Overflow = false; 2933 Type *Ty = AddRec->getType(); 2934 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2935 SmallVector<const SCEV*, 7> AddRecOps; 2936 for (int x = 0, xe = AddRec->getNumOperands() + 2937 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2938 const SCEV *Term = getZero(Ty); 2939 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2940 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2941 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2942 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2943 z < ze && !Overflow; ++z) { 2944 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2945 uint64_t Coeff; 2946 if (LargerThan64Bits) 2947 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2948 else 2949 Coeff = Coeff1*Coeff2; 2950 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2951 const SCEV *Term1 = AddRec->getOperand(y-z); 2952 const SCEV *Term2 = OtherAddRec->getOperand(z); 2953 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2954 SCEV::FlagAnyWrap, Depth + 1), 2955 SCEV::FlagAnyWrap, Depth + 1); 2956 } 2957 } 2958 AddRecOps.push_back(Term); 2959 } 2960 if (!Overflow) { 2961 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2962 SCEV::FlagAnyWrap); 2963 if (Ops.size() == 2) return NewAddRec; 2964 Ops[Idx] = NewAddRec; 2965 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2966 OpsModified = true; 2967 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2968 if (!AddRec) 2969 break; 2970 } 2971 } 2972 if (OpsModified) 2973 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2974 2975 // Otherwise couldn't fold anything into this recurrence. Move onto the 2976 // next one. 2977 } 2978 2979 // Okay, it looks like we really DO need an mul expr. Check to see if we 2980 // already have one, otherwise create a new one. 2981 return getOrCreateMulExpr(Ops, Flags); 2982 } 2983 2984 /// Get a canonical unsigned division expression, or something simpler if 2985 /// possible. 2986 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2987 const SCEV *RHS) { 2988 assert(getEffectiveSCEVType(LHS->getType()) == 2989 getEffectiveSCEVType(RHS->getType()) && 2990 "SCEVUDivExpr operand types don't match!"); 2991 2992 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2993 if (RHSC->getValue()->isOne()) 2994 return LHS; // X udiv 1 --> x 2995 // If the denominator is zero, the result of the udiv is undefined. Don't 2996 // try to analyze it, because the resolution chosen here may differ from 2997 // the resolution chosen in other parts of the compiler. 2998 if (!RHSC->getValue()->isZero()) { 2999 // Determine if the division can be folded into the operands of 3000 // its operands. 3001 // TODO: Generalize this to non-constants by using known-bits information. 3002 Type *Ty = LHS->getType(); 3003 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3004 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3005 // For non-power-of-two values, effectively round the value up to the 3006 // nearest power of two. 3007 if (!RHSC->getAPInt().isPowerOf2()) 3008 ++MaxShiftAmt; 3009 IntegerType *ExtTy = 3010 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3011 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3012 if (const SCEVConstant *Step = 3013 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3014 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3015 const APInt &StepInt = Step->getAPInt(); 3016 const APInt &DivInt = RHSC->getAPInt(); 3017 if (!StepInt.urem(DivInt) && 3018 getZeroExtendExpr(AR, ExtTy) == 3019 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3020 getZeroExtendExpr(Step, ExtTy), 3021 AR->getLoop(), SCEV::FlagAnyWrap)) { 3022 SmallVector<const SCEV *, 4> Operands; 3023 for (const SCEV *Op : AR->operands()) 3024 Operands.push_back(getUDivExpr(Op, RHS)); 3025 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3026 } 3027 /// Get a canonical UDivExpr for a recurrence. 3028 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3029 // We can currently only fold X%N if X is constant. 3030 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3031 if (StartC && !DivInt.urem(StepInt) && 3032 getZeroExtendExpr(AR, ExtTy) == 3033 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3034 getZeroExtendExpr(Step, ExtTy), 3035 AR->getLoop(), SCEV::FlagAnyWrap)) { 3036 const APInt &StartInt = StartC->getAPInt(); 3037 const APInt &StartRem = StartInt.urem(StepInt); 3038 if (StartRem != 0) 3039 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3040 AR->getLoop(), SCEV::FlagNW); 3041 } 3042 } 3043 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3044 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3045 SmallVector<const SCEV *, 4> Operands; 3046 for (const SCEV *Op : M->operands()) 3047 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3048 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3049 // Find an operand that's safely divisible. 3050 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3051 const SCEV *Op = M->getOperand(i); 3052 const SCEV *Div = getUDivExpr(Op, RHSC); 3053 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3054 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3055 M->op_end()); 3056 Operands[i] = Div; 3057 return getMulExpr(Operands); 3058 } 3059 } 3060 } 3061 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3062 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3063 SmallVector<const SCEV *, 4> Operands; 3064 for (const SCEV *Op : A->operands()) 3065 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3066 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3067 Operands.clear(); 3068 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3069 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3070 if (isa<SCEVUDivExpr>(Op) || 3071 getMulExpr(Op, RHS) != A->getOperand(i)) 3072 break; 3073 Operands.push_back(Op); 3074 } 3075 if (Operands.size() == A->getNumOperands()) 3076 return getAddExpr(Operands); 3077 } 3078 } 3079 3080 // Fold if both operands are constant. 3081 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3082 Constant *LHSCV = LHSC->getValue(); 3083 Constant *RHSCV = RHSC->getValue(); 3084 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3085 RHSCV))); 3086 } 3087 } 3088 } 3089 3090 FoldingSetNodeID ID; 3091 ID.AddInteger(scUDivExpr); 3092 ID.AddPointer(LHS); 3093 ID.AddPointer(RHS); 3094 void *IP = nullptr; 3095 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3096 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3097 LHS, RHS); 3098 UniqueSCEVs.InsertNode(S, IP); 3099 return S; 3100 } 3101 3102 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3103 APInt A = C1->getAPInt().abs(); 3104 APInt B = C2->getAPInt().abs(); 3105 uint32_t ABW = A.getBitWidth(); 3106 uint32_t BBW = B.getBitWidth(); 3107 3108 if (ABW > BBW) 3109 B = B.zext(ABW); 3110 else if (ABW < BBW) 3111 A = A.zext(BBW); 3112 3113 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3114 } 3115 3116 /// Get a canonical unsigned division expression, or something simpler if 3117 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3118 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3119 /// it's not exact because the udiv may be clearing bits. 3120 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3121 const SCEV *RHS) { 3122 // TODO: we could try to find factors in all sorts of things, but for now we 3123 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3124 // end of this file for inspiration. 3125 3126 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3127 if (!Mul || !Mul->hasNoUnsignedWrap()) 3128 return getUDivExpr(LHS, RHS); 3129 3130 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3131 // If the mulexpr multiplies by a constant, then that constant must be the 3132 // first element of the mulexpr. 3133 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3134 if (LHSCst == RHSCst) { 3135 SmallVector<const SCEV *, 2> Operands; 3136 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3137 return getMulExpr(Operands); 3138 } 3139 3140 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3141 // that there's a factor provided by one of the other terms. We need to 3142 // check. 3143 APInt Factor = gcd(LHSCst, RHSCst); 3144 if (!Factor.isIntN(1)) { 3145 LHSCst = 3146 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3147 RHSCst = 3148 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3149 SmallVector<const SCEV *, 2> Operands; 3150 Operands.push_back(LHSCst); 3151 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3152 LHS = getMulExpr(Operands); 3153 RHS = RHSCst; 3154 Mul = dyn_cast<SCEVMulExpr>(LHS); 3155 if (!Mul) 3156 return getUDivExactExpr(LHS, RHS); 3157 } 3158 } 3159 } 3160 3161 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3162 if (Mul->getOperand(i) == RHS) { 3163 SmallVector<const SCEV *, 2> Operands; 3164 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3165 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3166 return getMulExpr(Operands); 3167 } 3168 } 3169 3170 return getUDivExpr(LHS, RHS); 3171 } 3172 3173 /// Get an add recurrence expression for the specified loop. Simplify the 3174 /// expression as much as possible. 3175 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3176 const Loop *L, 3177 SCEV::NoWrapFlags Flags) { 3178 SmallVector<const SCEV *, 4> Operands; 3179 Operands.push_back(Start); 3180 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3181 if (StepChrec->getLoop() == L) { 3182 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3183 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3184 } 3185 3186 Operands.push_back(Step); 3187 return getAddRecExpr(Operands, L, Flags); 3188 } 3189 3190 /// Get an add recurrence expression for the specified loop. Simplify the 3191 /// expression as much as possible. 3192 const SCEV * 3193 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3194 const Loop *L, SCEV::NoWrapFlags Flags) { 3195 if (Operands.size() == 1) return Operands[0]; 3196 #ifndef NDEBUG 3197 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3198 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3199 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3200 "SCEVAddRecExpr operand types don't match!"); 3201 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3202 assert(isLoopInvariant(Operands[i], L) && 3203 "SCEVAddRecExpr operand is not loop-invariant!"); 3204 #endif 3205 3206 if (Operands.back()->isZero()) { 3207 Operands.pop_back(); 3208 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3209 } 3210 3211 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3212 // use that information to infer NUW and NSW flags. However, computing a 3213 // BE count requires calling getAddRecExpr, so we may not yet have a 3214 // meaningful BE count at this point (and if we don't, we'd be stuck 3215 // with a SCEVCouldNotCompute as the cached BE count). 3216 3217 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3218 3219 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3220 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3221 const Loop *NestedLoop = NestedAR->getLoop(); 3222 if (L->contains(NestedLoop) 3223 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3224 : (!NestedLoop->contains(L) && 3225 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3226 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3227 NestedAR->op_end()); 3228 Operands[0] = NestedAR->getStart(); 3229 // AddRecs require their operands be loop-invariant with respect to their 3230 // loops. Don't perform this transformation if it would break this 3231 // requirement. 3232 bool AllInvariant = all_of( 3233 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3234 3235 if (AllInvariant) { 3236 // Create a recurrence for the outer loop with the same step size. 3237 // 3238 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3239 // inner recurrence has the same property. 3240 SCEV::NoWrapFlags OuterFlags = 3241 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3242 3243 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3244 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3245 return isLoopInvariant(Op, NestedLoop); 3246 }); 3247 3248 if (AllInvariant) { 3249 // Ok, both add recurrences are valid after the transformation. 3250 // 3251 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3252 // the outer recurrence has the same property. 3253 SCEV::NoWrapFlags InnerFlags = 3254 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3255 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3256 } 3257 } 3258 // Reset Operands to its original state. 3259 Operands[0] = NestedAR; 3260 } 3261 } 3262 3263 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3264 // already have one, otherwise create a new one. 3265 FoldingSetNodeID ID; 3266 ID.AddInteger(scAddRecExpr); 3267 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3268 ID.AddPointer(Operands[i]); 3269 ID.AddPointer(L); 3270 void *IP = nullptr; 3271 SCEVAddRecExpr *S = 3272 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3273 if (!S) { 3274 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3275 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3276 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3277 O, Operands.size(), L); 3278 UniqueSCEVs.InsertNode(S, IP); 3279 } 3280 S->setNoWrapFlags(Flags); 3281 return S; 3282 } 3283 3284 const SCEV * 3285 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3286 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3287 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3288 // getSCEV(Base)->getType() has the same address space as Base->getType() 3289 // because SCEV::getType() preserves the address space. 3290 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3291 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3292 // instruction to its SCEV, because the Instruction may be guarded by control 3293 // flow and the no-overflow bits may not be valid for the expression in any 3294 // context. This can be fixed similarly to how these flags are handled for 3295 // adds. 3296 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3297 : SCEV::FlagAnyWrap; 3298 3299 const SCEV *TotalOffset = getZero(IntPtrTy); 3300 // The array size is unimportant. The first thing we do on CurTy is getting 3301 // its element type. 3302 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3303 for (const SCEV *IndexExpr : IndexExprs) { 3304 // Compute the (potentially symbolic) offset in bytes for this index. 3305 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3306 // For a struct, add the member offset. 3307 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3308 unsigned FieldNo = Index->getZExtValue(); 3309 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3310 3311 // Add the field offset to the running total offset. 3312 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3313 3314 // Update CurTy to the type of the field at Index. 3315 CurTy = STy->getTypeAtIndex(Index); 3316 } else { 3317 // Update CurTy to its element type. 3318 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3319 // For an array, add the element offset, explicitly scaled. 3320 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3321 // Getelementptr indices are signed. 3322 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3323 3324 // Multiply the index by the element size to compute the element offset. 3325 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3326 3327 // Add the element offset to the running total offset. 3328 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3329 } 3330 } 3331 3332 // Add the total offset from all the GEP indices to the base. 3333 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3334 } 3335 3336 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3337 const SCEV *RHS) { 3338 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3339 return getSMaxExpr(Ops); 3340 } 3341 3342 const SCEV * 3343 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3344 assert(!Ops.empty() && "Cannot get empty smax!"); 3345 if (Ops.size() == 1) return Ops[0]; 3346 #ifndef NDEBUG 3347 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3348 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3349 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3350 "SCEVSMaxExpr operand types don't match!"); 3351 #endif 3352 3353 // Sort by complexity, this groups all similar expression types together. 3354 GroupByComplexity(Ops, &LI, DT); 3355 3356 // If there are any constants, fold them together. 3357 unsigned Idx = 0; 3358 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3359 ++Idx; 3360 assert(Idx < Ops.size()); 3361 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3362 // We found two constants, fold them together! 3363 ConstantInt *Fold = ConstantInt::get( 3364 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3365 Ops[0] = getConstant(Fold); 3366 Ops.erase(Ops.begin()+1); // Erase the folded element 3367 if (Ops.size() == 1) return Ops[0]; 3368 LHSC = cast<SCEVConstant>(Ops[0]); 3369 } 3370 3371 // If we are left with a constant minimum-int, strip it off. 3372 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3373 Ops.erase(Ops.begin()); 3374 --Idx; 3375 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3376 // If we have an smax with a constant maximum-int, it will always be 3377 // maximum-int. 3378 return Ops[0]; 3379 } 3380 3381 if (Ops.size() == 1) return Ops[0]; 3382 } 3383 3384 // Find the first SMax 3385 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3386 ++Idx; 3387 3388 // Check to see if one of the operands is an SMax. If so, expand its operands 3389 // onto our operand list, and recurse to simplify. 3390 if (Idx < Ops.size()) { 3391 bool DeletedSMax = false; 3392 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3393 Ops.erase(Ops.begin()+Idx); 3394 Ops.append(SMax->op_begin(), SMax->op_end()); 3395 DeletedSMax = true; 3396 } 3397 3398 if (DeletedSMax) 3399 return getSMaxExpr(Ops); 3400 } 3401 3402 // Okay, check to see if the same value occurs in the operand list twice. If 3403 // so, delete one. Since we sorted the list, these values are required to 3404 // be adjacent. 3405 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3406 // X smax Y smax Y --> X smax Y 3407 // X smax Y --> X, if X is always greater than Y 3408 if (Ops[i] == Ops[i+1] || 3409 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3410 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3411 --i; --e; 3412 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3413 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3414 --i; --e; 3415 } 3416 3417 if (Ops.size() == 1) return Ops[0]; 3418 3419 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3420 3421 // Okay, it looks like we really DO need an smax expr. Check to see if we 3422 // already have one, otherwise create a new one. 3423 FoldingSetNodeID ID; 3424 ID.AddInteger(scSMaxExpr); 3425 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3426 ID.AddPointer(Ops[i]); 3427 void *IP = nullptr; 3428 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3429 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3430 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3431 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3432 O, Ops.size()); 3433 UniqueSCEVs.InsertNode(S, IP); 3434 return S; 3435 } 3436 3437 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3438 const SCEV *RHS) { 3439 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3440 return getUMaxExpr(Ops); 3441 } 3442 3443 const SCEV * 3444 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3445 assert(!Ops.empty() && "Cannot get empty umax!"); 3446 if (Ops.size() == 1) return Ops[0]; 3447 #ifndef NDEBUG 3448 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3449 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3450 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3451 "SCEVUMaxExpr operand types don't match!"); 3452 #endif 3453 3454 // Sort by complexity, this groups all similar expression types together. 3455 GroupByComplexity(Ops, &LI, DT); 3456 3457 // If there are any constants, fold them together. 3458 unsigned Idx = 0; 3459 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3460 ++Idx; 3461 assert(Idx < Ops.size()); 3462 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3463 // We found two constants, fold them together! 3464 ConstantInt *Fold = ConstantInt::get( 3465 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3466 Ops[0] = getConstant(Fold); 3467 Ops.erase(Ops.begin()+1); // Erase the folded element 3468 if (Ops.size() == 1) return Ops[0]; 3469 LHSC = cast<SCEVConstant>(Ops[0]); 3470 } 3471 3472 // If we are left with a constant minimum-int, strip it off. 3473 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3474 Ops.erase(Ops.begin()); 3475 --Idx; 3476 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3477 // If we have an umax with a constant maximum-int, it will always be 3478 // maximum-int. 3479 return Ops[0]; 3480 } 3481 3482 if (Ops.size() == 1) return Ops[0]; 3483 } 3484 3485 // Find the first UMax 3486 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3487 ++Idx; 3488 3489 // Check to see if one of the operands is a UMax. If so, expand its operands 3490 // onto our operand list, and recurse to simplify. 3491 if (Idx < Ops.size()) { 3492 bool DeletedUMax = false; 3493 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3494 Ops.erase(Ops.begin()+Idx); 3495 Ops.append(UMax->op_begin(), UMax->op_end()); 3496 DeletedUMax = true; 3497 } 3498 3499 if (DeletedUMax) 3500 return getUMaxExpr(Ops); 3501 } 3502 3503 // Okay, check to see if the same value occurs in the operand list twice. If 3504 // so, delete one. Since we sorted the list, these values are required to 3505 // be adjacent. 3506 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3507 // X umax Y umax Y --> X umax Y 3508 // X umax Y --> X, if X is always greater than Y 3509 if (Ops[i] == Ops[i+1] || 3510 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3511 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3512 --i; --e; 3513 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3514 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3515 --i; --e; 3516 } 3517 3518 if (Ops.size() == 1) return Ops[0]; 3519 3520 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3521 3522 // Okay, it looks like we really DO need a umax expr. Check to see if we 3523 // already have one, otherwise create a new one. 3524 FoldingSetNodeID ID; 3525 ID.AddInteger(scUMaxExpr); 3526 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3527 ID.AddPointer(Ops[i]); 3528 void *IP = nullptr; 3529 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3530 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3531 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3532 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3533 O, Ops.size()); 3534 UniqueSCEVs.InsertNode(S, IP); 3535 return S; 3536 } 3537 3538 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3539 const SCEV *RHS) { 3540 // ~smax(~x, ~y) == smin(x, y). 3541 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3542 } 3543 3544 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3545 const SCEV *RHS) { 3546 // ~umax(~x, ~y) == umin(x, y) 3547 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3548 } 3549 3550 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3551 // We can bypass creating a target-independent 3552 // constant expression and then folding it back into a ConstantInt. 3553 // This is just a compile-time optimization. 3554 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3555 } 3556 3557 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3558 StructType *STy, 3559 unsigned FieldNo) { 3560 // We can bypass creating a target-independent 3561 // constant expression and then folding it back into a ConstantInt. 3562 // This is just a compile-time optimization. 3563 return getConstant( 3564 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3565 } 3566 3567 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3568 // Don't attempt to do anything other than create a SCEVUnknown object 3569 // here. createSCEV only calls getUnknown after checking for all other 3570 // interesting possibilities, and any other code that calls getUnknown 3571 // is doing so in order to hide a value from SCEV canonicalization. 3572 3573 FoldingSetNodeID ID; 3574 ID.AddInteger(scUnknown); 3575 ID.AddPointer(V); 3576 void *IP = nullptr; 3577 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3578 assert(cast<SCEVUnknown>(S)->getValue() == V && 3579 "Stale SCEVUnknown in uniquing map!"); 3580 return S; 3581 } 3582 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3583 FirstUnknown); 3584 FirstUnknown = cast<SCEVUnknown>(S); 3585 UniqueSCEVs.InsertNode(S, IP); 3586 return S; 3587 } 3588 3589 //===----------------------------------------------------------------------===// 3590 // Basic SCEV Analysis and PHI Idiom Recognition Code 3591 // 3592 3593 /// Test if values of the given type are analyzable within the SCEV 3594 /// framework. This primarily includes integer types, and it can optionally 3595 /// include pointer types if the ScalarEvolution class has access to 3596 /// target-specific information. 3597 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3598 // Integers and pointers are always SCEVable. 3599 return Ty->isIntegerTy() || Ty->isPointerTy(); 3600 } 3601 3602 /// Return the size in bits of the specified type, for which isSCEVable must 3603 /// return true. 3604 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3605 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3606 return getDataLayout().getTypeSizeInBits(Ty); 3607 } 3608 3609 /// Return a type with the same bitwidth as the given type and which represents 3610 /// how SCEV will treat the given type, for which isSCEVable must return 3611 /// true. For pointer types, this is the pointer-sized integer type. 3612 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3613 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3614 3615 if (Ty->isIntegerTy()) 3616 return Ty; 3617 3618 // The only other support type is pointer. 3619 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3620 return getDataLayout().getIntPtrType(Ty); 3621 } 3622 3623 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3624 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3625 } 3626 3627 const SCEV *ScalarEvolution::getCouldNotCompute() { 3628 return CouldNotCompute.get(); 3629 } 3630 3631 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3632 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3633 auto *SU = dyn_cast<SCEVUnknown>(S); 3634 return SU && SU->getValue() == nullptr; 3635 }); 3636 3637 return !ContainsNulls; 3638 } 3639 3640 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3641 HasRecMapType::iterator I = HasRecMap.find(S); 3642 if (I != HasRecMap.end()) 3643 return I->second; 3644 3645 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3646 HasRecMap.insert({S, FoundAddRec}); 3647 return FoundAddRec; 3648 } 3649 3650 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3651 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3652 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3653 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3654 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3655 if (!Add) 3656 return {S, nullptr}; 3657 3658 if (Add->getNumOperands() != 2) 3659 return {S, nullptr}; 3660 3661 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3662 if (!ConstOp) 3663 return {S, nullptr}; 3664 3665 return {Add->getOperand(1), ConstOp->getValue()}; 3666 } 3667 3668 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3669 /// by the value and offset from any ValueOffsetPair in the set. 3670 SetVector<ScalarEvolution::ValueOffsetPair> * 3671 ScalarEvolution::getSCEVValues(const SCEV *S) { 3672 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3673 if (SI == ExprValueMap.end()) 3674 return nullptr; 3675 #ifndef NDEBUG 3676 if (VerifySCEVMap) { 3677 // Check there is no dangling Value in the set returned. 3678 for (const auto &VE : SI->second) 3679 assert(ValueExprMap.count(VE.first)); 3680 } 3681 #endif 3682 return &SI->second; 3683 } 3684 3685 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3686 /// cannot be used separately. eraseValueFromMap should be used to remove 3687 /// V from ValueExprMap and ExprValueMap at the same time. 3688 void ScalarEvolution::eraseValueFromMap(Value *V) { 3689 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3690 if (I != ValueExprMap.end()) { 3691 const SCEV *S = I->second; 3692 // Remove {V, 0} from the set of ExprValueMap[S] 3693 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3694 SV->remove({V, nullptr}); 3695 3696 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3697 const SCEV *Stripped; 3698 ConstantInt *Offset; 3699 std::tie(Stripped, Offset) = splitAddExpr(S); 3700 if (Offset != nullptr) { 3701 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3702 SV->remove({V, Offset}); 3703 } 3704 ValueExprMap.erase(V); 3705 } 3706 } 3707 3708 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3709 /// create a new one. 3710 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3711 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3712 3713 const SCEV *S = getExistingSCEV(V); 3714 if (S == nullptr) { 3715 S = createSCEV(V); 3716 // During PHI resolution, it is possible to create two SCEVs for the same 3717 // V, so it is needed to double check whether V->S is inserted into 3718 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3719 std::pair<ValueExprMapType::iterator, bool> Pair = 3720 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3721 if (Pair.second) { 3722 ExprValueMap[S].insert({V, nullptr}); 3723 3724 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3725 // ExprValueMap. 3726 const SCEV *Stripped = S; 3727 ConstantInt *Offset = nullptr; 3728 std::tie(Stripped, Offset) = splitAddExpr(S); 3729 // If stripped is SCEVUnknown, don't bother to save 3730 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3731 // increase the complexity of the expansion code. 3732 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3733 // because it may generate add/sub instead of GEP in SCEV expansion. 3734 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3735 !isa<GetElementPtrInst>(V)) 3736 ExprValueMap[Stripped].insert({V, Offset}); 3737 } 3738 } 3739 return S; 3740 } 3741 3742 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3743 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3744 3745 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3746 if (I != ValueExprMap.end()) { 3747 const SCEV *S = I->second; 3748 if (checkValidity(S)) 3749 return S; 3750 eraseValueFromMap(V); 3751 forgetMemoizedResults(S); 3752 } 3753 return nullptr; 3754 } 3755 3756 /// Return a SCEV corresponding to -V = -1*V 3757 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3758 SCEV::NoWrapFlags Flags) { 3759 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3760 return getConstant( 3761 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3762 3763 Type *Ty = V->getType(); 3764 Ty = getEffectiveSCEVType(Ty); 3765 return getMulExpr( 3766 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3767 } 3768 3769 /// Return a SCEV corresponding to ~V = -1-V 3770 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3771 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3772 return getConstant( 3773 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3774 3775 Type *Ty = V->getType(); 3776 Ty = getEffectiveSCEVType(Ty); 3777 const SCEV *AllOnes = 3778 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3779 return getMinusSCEV(AllOnes, V); 3780 } 3781 3782 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3783 SCEV::NoWrapFlags Flags, 3784 unsigned Depth) { 3785 // Fast path: X - X --> 0. 3786 if (LHS == RHS) 3787 return getZero(LHS->getType()); 3788 3789 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3790 // makes it so that we cannot make much use of NUW. 3791 auto AddFlags = SCEV::FlagAnyWrap; 3792 const bool RHSIsNotMinSigned = 3793 !getSignedRangeMin(RHS).isMinSignedValue(); 3794 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3795 // Let M be the minimum representable signed value. Then (-1)*RHS 3796 // signed-wraps if and only if RHS is M. That can happen even for 3797 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3798 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3799 // (-1)*RHS, we need to prove that RHS != M. 3800 // 3801 // If LHS is non-negative and we know that LHS - RHS does not 3802 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3803 // either by proving that RHS > M or that LHS >= 0. 3804 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3805 AddFlags = SCEV::FlagNSW; 3806 } 3807 } 3808 3809 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3810 // RHS is NSW and LHS >= 0. 3811 // 3812 // The difficulty here is that the NSW flag may have been proven 3813 // relative to a loop that is to be found in a recurrence in LHS and 3814 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3815 // larger scope than intended. 3816 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3817 3818 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3819 } 3820 3821 const SCEV * 3822 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3823 Type *SrcTy = V->getType(); 3824 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3825 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3826 "Cannot truncate or zero extend with non-integer arguments!"); 3827 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3828 return V; // No conversion 3829 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3830 return getTruncateExpr(V, Ty); 3831 return getZeroExtendExpr(V, Ty); 3832 } 3833 3834 const SCEV * 3835 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3836 Type *Ty) { 3837 Type *SrcTy = V->getType(); 3838 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3839 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3840 "Cannot truncate or zero extend with non-integer arguments!"); 3841 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3842 return V; // No conversion 3843 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3844 return getTruncateExpr(V, Ty); 3845 return getSignExtendExpr(V, Ty); 3846 } 3847 3848 const SCEV * 3849 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3850 Type *SrcTy = V->getType(); 3851 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3852 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3853 "Cannot noop or zero extend with non-integer arguments!"); 3854 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3855 "getNoopOrZeroExtend cannot truncate!"); 3856 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3857 return V; // No conversion 3858 return getZeroExtendExpr(V, Ty); 3859 } 3860 3861 const SCEV * 3862 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3863 Type *SrcTy = V->getType(); 3864 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3865 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3866 "Cannot noop or sign extend with non-integer arguments!"); 3867 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3868 "getNoopOrSignExtend cannot truncate!"); 3869 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3870 return V; // No conversion 3871 return getSignExtendExpr(V, Ty); 3872 } 3873 3874 const SCEV * 3875 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3876 Type *SrcTy = V->getType(); 3877 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3878 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3879 "Cannot noop or any extend with non-integer arguments!"); 3880 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3881 "getNoopOrAnyExtend cannot truncate!"); 3882 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3883 return V; // No conversion 3884 return getAnyExtendExpr(V, Ty); 3885 } 3886 3887 const SCEV * 3888 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3889 Type *SrcTy = V->getType(); 3890 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3891 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3892 "Cannot truncate or noop with non-integer arguments!"); 3893 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3894 "getTruncateOrNoop cannot extend!"); 3895 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3896 return V; // No conversion 3897 return getTruncateExpr(V, Ty); 3898 } 3899 3900 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3901 const SCEV *RHS) { 3902 const SCEV *PromotedLHS = LHS; 3903 const SCEV *PromotedRHS = RHS; 3904 3905 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3906 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3907 else 3908 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3909 3910 return getUMaxExpr(PromotedLHS, PromotedRHS); 3911 } 3912 3913 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3914 const SCEV *RHS) { 3915 const SCEV *PromotedLHS = LHS; 3916 const SCEV *PromotedRHS = RHS; 3917 3918 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3919 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3920 else 3921 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3922 3923 return getUMinExpr(PromotedLHS, PromotedRHS); 3924 } 3925 3926 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3927 // A pointer operand may evaluate to a nonpointer expression, such as null. 3928 if (!V->getType()->isPointerTy()) 3929 return V; 3930 3931 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3932 return getPointerBase(Cast->getOperand()); 3933 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3934 const SCEV *PtrOp = nullptr; 3935 for (const SCEV *NAryOp : NAry->operands()) { 3936 if (NAryOp->getType()->isPointerTy()) { 3937 // Cannot find the base of an expression with multiple pointer operands. 3938 if (PtrOp) 3939 return V; 3940 PtrOp = NAryOp; 3941 } 3942 } 3943 if (!PtrOp) 3944 return V; 3945 return getPointerBase(PtrOp); 3946 } 3947 return V; 3948 } 3949 3950 /// Push users of the given Instruction onto the given Worklist. 3951 static void 3952 PushDefUseChildren(Instruction *I, 3953 SmallVectorImpl<Instruction *> &Worklist) { 3954 // Push the def-use children onto the Worklist stack. 3955 for (User *U : I->users()) 3956 Worklist.push_back(cast<Instruction>(U)); 3957 } 3958 3959 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3960 SmallVector<Instruction *, 16> Worklist; 3961 PushDefUseChildren(PN, Worklist); 3962 3963 SmallPtrSet<Instruction *, 8> Visited; 3964 Visited.insert(PN); 3965 while (!Worklist.empty()) { 3966 Instruction *I = Worklist.pop_back_val(); 3967 if (!Visited.insert(I).second) 3968 continue; 3969 3970 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3971 if (It != ValueExprMap.end()) { 3972 const SCEV *Old = It->second; 3973 3974 // Short-circuit the def-use traversal if the symbolic name 3975 // ceases to appear in expressions. 3976 if (Old != SymName && !hasOperand(Old, SymName)) 3977 continue; 3978 3979 // SCEVUnknown for a PHI either means that it has an unrecognized 3980 // structure, it's a PHI that's in the progress of being computed 3981 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3982 // additional loop trip count information isn't going to change anything. 3983 // In the second case, createNodeForPHI will perform the necessary 3984 // updates on its own when it gets to that point. In the third, we do 3985 // want to forget the SCEVUnknown. 3986 if (!isa<PHINode>(I) || 3987 !isa<SCEVUnknown>(Old) || 3988 (I != PN && Old == SymName)) { 3989 eraseValueFromMap(It->first); 3990 forgetMemoizedResults(Old); 3991 } 3992 } 3993 3994 PushDefUseChildren(I, Worklist); 3995 } 3996 } 3997 3998 namespace { 3999 4000 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4001 public: 4002 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4003 : SCEVRewriteVisitor(SE), L(L) {} 4004 4005 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4006 ScalarEvolution &SE) { 4007 SCEVInitRewriter Rewriter(L, SE); 4008 const SCEV *Result = Rewriter.visit(S); 4009 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4010 } 4011 4012 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4013 if (!SE.isLoopInvariant(Expr, L)) 4014 Valid = false; 4015 return Expr; 4016 } 4017 4018 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4019 // Only allow AddRecExprs for this loop. 4020 if (Expr->getLoop() == L) 4021 return Expr->getStart(); 4022 Valid = false; 4023 return Expr; 4024 } 4025 4026 bool isValid() { return Valid; } 4027 4028 private: 4029 const Loop *L; 4030 bool Valid = true; 4031 }; 4032 4033 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4034 public: 4035 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4036 : SCEVRewriteVisitor(SE), L(L) {} 4037 4038 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4039 ScalarEvolution &SE) { 4040 SCEVShiftRewriter Rewriter(L, SE); 4041 const SCEV *Result = Rewriter.visit(S); 4042 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4043 } 4044 4045 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4046 // Only allow AddRecExprs for this loop. 4047 if (!SE.isLoopInvariant(Expr, L)) 4048 Valid = false; 4049 return Expr; 4050 } 4051 4052 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4053 if (Expr->getLoop() == L && Expr->isAffine()) 4054 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4055 Valid = false; 4056 return Expr; 4057 } 4058 4059 bool isValid() { return Valid; } 4060 4061 private: 4062 const Loop *L; 4063 bool Valid = true; 4064 }; 4065 4066 } // end anonymous namespace 4067 4068 SCEV::NoWrapFlags 4069 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4070 if (!AR->isAffine()) 4071 return SCEV::FlagAnyWrap; 4072 4073 using OBO = OverflowingBinaryOperator; 4074 4075 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4076 4077 if (!AR->hasNoSignedWrap()) { 4078 ConstantRange AddRecRange = getSignedRange(AR); 4079 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4080 4081 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4082 Instruction::Add, IncRange, OBO::NoSignedWrap); 4083 if (NSWRegion.contains(AddRecRange)) 4084 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4085 } 4086 4087 if (!AR->hasNoUnsignedWrap()) { 4088 ConstantRange AddRecRange = getUnsignedRange(AR); 4089 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4090 4091 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4092 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4093 if (NUWRegion.contains(AddRecRange)) 4094 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4095 } 4096 4097 return Result; 4098 } 4099 4100 namespace { 4101 4102 /// Represents an abstract binary operation. This may exist as a 4103 /// normal instruction or constant expression, or may have been 4104 /// derived from an expression tree. 4105 struct BinaryOp { 4106 unsigned Opcode; 4107 Value *LHS; 4108 Value *RHS; 4109 bool IsNSW = false; 4110 bool IsNUW = false; 4111 4112 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4113 /// constant expression. 4114 Operator *Op = nullptr; 4115 4116 explicit BinaryOp(Operator *Op) 4117 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4118 Op(Op) { 4119 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4120 IsNSW = OBO->hasNoSignedWrap(); 4121 IsNUW = OBO->hasNoUnsignedWrap(); 4122 } 4123 } 4124 4125 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4126 bool IsNUW = false) 4127 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4128 }; 4129 4130 } // end anonymous namespace 4131 4132 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4133 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4134 auto *Op = dyn_cast<Operator>(V); 4135 if (!Op) 4136 return None; 4137 4138 // Implementation detail: all the cleverness here should happen without 4139 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4140 // SCEV expressions when possible, and we should not break that. 4141 4142 switch (Op->getOpcode()) { 4143 case Instruction::Add: 4144 case Instruction::Sub: 4145 case Instruction::Mul: 4146 case Instruction::UDiv: 4147 case Instruction::And: 4148 case Instruction::Or: 4149 case Instruction::AShr: 4150 case Instruction::Shl: 4151 return BinaryOp(Op); 4152 4153 case Instruction::Xor: 4154 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4155 // If the RHS of the xor is a signmask, then this is just an add. 4156 // Instcombine turns add of signmask into xor as a strength reduction step. 4157 if (RHSC->getValue().isSignMask()) 4158 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4159 return BinaryOp(Op); 4160 4161 case Instruction::LShr: 4162 // Turn logical shift right of a constant into a unsigned divide. 4163 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4164 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4165 4166 // If the shift count is not less than the bitwidth, the result of 4167 // the shift is undefined. Don't try to analyze it, because the 4168 // resolution chosen here may differ from the resolution chosen in 4169 // other parts of the compiler. 4170 if (SA->getValue().ult(BitWidth)) { 4171 Constant *X = 4172 ConstantInt::get(SA->getContext(), 4173 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4174 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4175 } 4176 } 4177 return BinaryOp(Op); 4178 4179 case Instruction::ExtractValue: { 4180 auto *EVI = cast<ExtractValueInst>(Op); 4181 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4182 break; 4183 4184 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4185 if (!CI) 4186 break; 4187 4188 if (auto *F = CI->getCalledFunction()) 4189 switch (F->getIntrinsicID()) { 4190 case Intrinsic::sadd_with_overflow: 4191 case Intrinsic::uadd_with_overflow: 4192 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4193 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4194 CI->getArgOperand(1)); 4195 4196 // Now that we know that all uses of the arithmetic-result component of 4197 // CI are guarded by the overflow check, we can go ahead and pretend 4198 // that the arithmetic is non-overflowing. 4199 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4200 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4201 CI->getArgOperand(1), /* IsNSW = */ true, 4202 /* IsNUW = */ false); 4203 else 4204 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4205 CI->getArgOperand(1), /* IsNSW = */ false, 4206 /* IsNUW*/ true); 4207 case Intrinsic::ssub_with_overflow: 4208 case Intrinsic::usub_with_overflow: 4209 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4210 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4211 CI->getArgOperand(1)); 4212 4213 // The same reasoning as sadd/uadd above. 4214 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4215 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4216 CI->getArgOperand(1), /* IsNSW = */ true, 4217 /* IsNUW = */ false); 4218 else 4219 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4220 CI->getArgOperand(1), /* IsNSW = */ false, 4221 /* IsNUW = */ true); 4222 case Intrinsic::smul_with_overflow: 4223 case Intrinsic::umul_with_overflow: 4224 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4225 CI->getArgOperand(1)); 4226 default: 4227 break; 4228 } 4229 } 4230 4231 default: 4232 break; 4233 } 4234 4235 return None; 4236 } 4237 4238 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4239 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4240 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4241 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4242 /// follows one of the following patterns: 4243 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4244 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4245 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4246 /// we return the type of the truncation operation, and indicate whether the 4247 /// truncated type should be treated as signed/unsigned by setting 4248 /// \p Signed to true/false, respectively. 4249 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4250 bool &Signed, ScalarEvolution &SE) { 4251 // The case where Op == SymbolicPHI (that is, with no type conversions on 4252 // the way) is handled by the regular add recurrence creating logic and 4253 // would have already been triggered in createAddRecForPHI. Reaching it here 4254 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4255 // because one of the other operands of the SCEVAddExpr updating this PHI is 4256 // not invariant). 4257 // 4258 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4259 // this case predicates that allow us to prove that Op == SymbolicPHI will 4260 // be added. 4261 if (Op == SymbolicPHI) 4262 return nullptr; 4263 4264 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4265 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4266 if (SourceBits != NewBits) 4267 return nullptr; 4268 4269 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4270 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4271 if (!SExt && !ZExt) 4272 return nullptr; 4273 const SCEVTruncateExpr *Trunc = 4274 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4275 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4276 if (!Trunc) 4277 return nullptr; 4278 const SCEV *X = Trunc->getOperand(); 4279 if (X != SymbolicPHI) 4280 return nullptr; 4281 Signed = SExt != nullptr; 4282 return Trunc->getType(); 4283 } 4284 4285 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4286 if (!PN->getType()->isIntegerTy()) 4287 return nullptr; 4288 const Loop *L = LI.getLoopFor(PN->getParent()); 4289 if (!L || L->getHeader() != PN->getParent()) 4290 return nullptr; 4291 return L; 4292 } 4293 4294 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4295 // computation that updates the phi follows the following pattern: 4296 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4297 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4298 // If so, try to see if it can be rewritten as an AddRecExpr under some 4299 // Predicates. If successful, return them as a pair. Also cache the results 4300 // of the analysis. 4301 // 4302 // Example usage scenario: 4303 // Say the Rewriter is called for the following SCEV: 4304 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4305 // where: 4306 // %X = phi i64 (%Start, %BEValue) 4307 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4308 // and call this function with %SymbolicPHI = %X. 4309 // 4310 // The analysis will find that the value coming around the backedge has 4311 // the following SCEV: 4312 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4313 // Upon concluding that this matches the desired pattern, the function 4314 // will return the pair {NewAddRec, SmallPredsVec} where: 4315 // NewAddRec = {%Start,+,%Step} 4316 // SmallPredsVec = {P1, P2, P3} as follows: 4317 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4318 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4319 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4320 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4321 // under the predicates {P1,P2,P3}. 4322 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4323 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4324 // 4325 // TODO's: 4326 // 4327 // 1) Extend the Induction descriptor to also support inductions that involve 4328 // casts: When needed (namely, when we are called in the context of the 4329 // vectorizer induction analysis), a Set of cast instructions will be 4330 // populated by this method, and provided back to isInductionPHI. This is 4331 // needed to allow the vectorizer to properly record them to be ignored by 4332 // the cost model and to avoid vectorizing them (otherwise these casts, 4333 // which are redundant under the runtime overflow checks, will be 4334 // vectorized, which can be costly). 4335 // 4336 // 2) Support additional induction/PHISCEV patterns: We also want to support 4337 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4338 // after the induction update operation (the induction increment): 4339 // 4340 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4341 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4342 // 4343 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4344 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4345 // 4346 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4347 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4348 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4349 SmallVector<const SCEVPredicate *, 3> Predicates; 4350 4351 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4352 // return an AddRec expression under some predicate. 4353 4354 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4355 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4356 assert(L && "Expecting an integer loop header phi"); 4357 4358 // The loop may have multiple entrances or multiple exits; we can analyze 4359 // this phi as an addrec if it has a unique entry value and a unique 4360 // backedge value. 4361 Value *BEValueV = nullptr, *StartValueV = nullptr; 4362 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4363 Value *V = PN->getIncomingValue(i); 4364 if (L->contains(PN->getIncomingBlock(i))) { 4365 if (!BEValueV) { 4366 BEValueV = V; 4367 } else if (BEValueV != V) { 4368 BEValueV = nullptr; 4369 break; 4370 } 4371 } else if (!StartValueV) { 4372 StartValueV = V; 4373 } else if (StartValueV != V) { 4374 StartValueV = nullptr; 4375 break; 4376 } 4377 } 4378 if (!BEValueV || !StartValueV) 4379 return None; 4380 4381 const SCEV *BEValue = getSCEV(BEValueV); 4382 4383 // If the value coming around the backedge is an add with the symbolic 4384 // value we just inserted, possibly with casts that we can ignore under 4385 // an appropriate runtime guard, then we found a simple induction variable! 4386 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4387 if (!Add) 4388 return None; 4389 4390 // If there is a single occurrence of the symbolic value, possibly 4391 // casted, replace it with a recurrence. 4392 unsigned FoundIndex = Add->getNumOperands(); 4393 Type *TruncTy = nullptr; 4394 bool Signed; 4395 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4396 if ((TruncTy = 4397 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4398 if (FoundIndex == e) { 4399 FoundIndex = i; 4400 break; 4401 } 4402 4403 if (FoundIndex == Add->getNumOperands()) 4404 return None; 4405 4406 // Create an add with everything but the specified operand. 4407 SmallVector<const SCEV *, 8> Ops; 4408 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4409 if (i != FoundIndex) 4410 Ops.push_back(Add->getOperand(i)); 4411 const SCEV *Accum = getAddExpr(Ops); 4412 4413 // The runtime checks will not be valid if the step amount is 4414 // varying inside the loop. 4415 if (!isLoopInvariant(Accum, L)) 4416 return None; 4417 4418 // *** Part2: Create the predicates 4419 4420 // Analysis was successful: we have a phi-with-cast pattern for which we 4421 // can return an AddRec expression under the following predicates: 4422 // 4423 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4424 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4425 // P2: An Equal predicate that guarantees that 4426 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4427 // P3: An Equal predicate that guarantees that 4428 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4429 // 4430 // As we next prove, the above predicates guarantee that: 4431 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4432 // 4433 // 4434 // More formally, we want to prove that: 4435 // Expr(i+1) = Start + (i+1) * Accum 4436 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4437 // 4438 // Given that: 4439 // 1) Expr(0) = Start 4440 // 2) Expr(1) = Start + Accum 4441 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4442 // 3) Induction hypothesis (step i): 4443 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4444 // 4445 // Proof: 4446 // Expr(i+1) = 4447 // = Start + (i+1)*Accum 4448 // = (Start + i*Accum) + Accum 4449 // = Expr(i) + Accum 4450 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4451 // :: from step i 4452 // 4453 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4454 // 4455 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4456 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4457 // + Accum :: from P3 4458 // 4459 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4460 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4461 // 4462 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4463 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4464 // 4465 // By induction, the same applies to all iterations 1<=i<n: 4466 // 4467 4468 // Create a truncated addrec for which we will add a no overflow check (P1). 4469 const SCEV *StartVal = getSCEV(StartValueV); 4470 const SCEV *PHISCEV = 4471 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4472 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4473 const auto *AR = cast<SCEVAddRecExpr>(PHISCEV); 4474 4475 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4476 Signed ? SCEVWrapPredicate::IncrementNSSW 4477 : SCEVWrapPredicate::IncrementNUSW; 4478 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4479 Predicates.push_back(AddRecPred); 4480 4481 // Create the Equal Predicates P2,P3: 4482 auto AppendPredicate = [&](const SCEV *Expr) -> void { 4483 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4484 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4485 const SCEV *ExtendedExpr = 4486 Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4487 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4488 if (Expr != ExtendedExpr && 4489 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4490 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4491 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4492 Predicates.push_back(Pred); 4493 } 4494 }; 4495 4496 AppendPredicate(StartVal); 4497 AppendPredicate(Accum); 4498 4499 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4500 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4501 // into NewAR if it will also add the runtime overflow checks specified in 4502 // Predicates. 4503 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4504 4505 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4506 std::make_pair(NewAR, Predicates); 4507 // Remember the result of the analysis for this SCEV at this locayyytion. 4508 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4509 return PredRewrite; 4510 } 4511 4512 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4513 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4514 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4515 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4516 if (!L) 4517 return None; 4518 4519 // Check to see if we already analyzed this PHI. 4520 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4521 if (I != PredicatedSCEVRewrites.end()) { 4522 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4523 I->second; 4524 // Analysis was done before and failed to create an AddRec: 4525 if (Rewrite.first == SymbolicPHI) 4526 return None; 4527 // Analysis was done before and succeeded to create an AddRec under 4528 // a predicate: 4529 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4530 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4531 return Rewrite; 4532 } 4533 4534 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4535 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4536 4537 // Record in the cache that the analysis failed 4538 if (!Rewrite) { 4539 SmallVector<const SCEVPredicate *, 3> Predicates; 4540 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4541 return None; 4542 } 4543 4544 return Rewrite; 4545 } 4546 4547 /// A helper function for createAddRecFromPHI to handle simple cases. 4548 /// 4549 /// This function tries to find an AddRec expression for the simplest (yet most 4550 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4551 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4552 /// technique for finding the AddRec expression. 4553 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4554 Value *BEValueV, 4555 Value *StartValueV) { 4556 const Loop *L = LI.getLoopFor(PN->getParent()); 4557 assert(L && L->getHeader() == PN->getParent()); 4558 assert(BEValueV && StartValueV); 4559 4560 auto BO = MatchBinaryOp(BEValueV, DT); 4561 if (!BO) 4562 return nullptr; 4563 4564 if (BO->Opcode != Instruction::Add) 4565 return nullptr; 4566 4567 const SCEV *Accum = nullptr; 4568 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4569 Accum = getSCEV(BO->RHS); 4570 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4571 Accum = getSCEV(BO->LHS); 4572 4573 if (!Accum) 4574 return nullptr; 4575 4576 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4577 if (BO->IsNUW) 4578 Flags = setFlags(Flags, SCEV::FlagNUW); 4579 if (BO->IsNSW) 4580 Flags = setFlags(Flags, SCEV::FlagNSW); 4581 4582 const SCEV *StartVal = getSCEV(StartValueV); 4583 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4584 4585 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4586 4587 // We can add Flags to the post-inc expression only if we 4588 // know that it is *undefined behavior* for BEValueV to 4589 // overflow. 4590 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4591 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4592 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4593 4594 return PHISCEV; 4595 } 4596 4597 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4598 const Loop *L = LI.getLoopFor(PN->getParent()); 4599 if (!L || L->getHeader() != PN->getParent()) 4600 return nullptr; 4601 4602 // The loop may have multiple entrances or multiple exits; we can analyze 4603 // this phi as an addrec if it has a unique entry value and a unique 4604 // backedge value. 4605 Value *BEValueV = nullptr, *StartValueV = nullptr; 4606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4607 Value *V = PN->getIncomingValue(i); 4608 if (L->contains(PN->getIncomingBlock(i))) { 4609 if (!BEValueV) { 4610 BEValueV = V; 4611 } else if (BEValueV != V) { 4612 BEValueV = nullptr; 4613 break; 4614 } 4615 } else if (!StartValueV) { 4616 StartValueV = V; 4617 } else if (StartValueV != V) { 4618 StartValueV = nullptr; 4619 break; 4620 } 4621 } 4622 if (!BEValueV || !StartValueV) 4623 return nullptr; 4624 4625 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4626 "PHI node already processed?"); 4627 4628 // First, try to find AddRec expression without creating a fictituos symbolic 4629 // value for PN. 4630 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4631 return S; 4632 4633 // Handle PHI node value symbolically. 4634 const SCEV *SymbolicName = getUnknown(PN); 4635 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4636 4637 // Using this symbolic name for the PHI, analyze the value coming around 4638 // the back-edge. 4639 const SCEV *BEValue = getSCEV(BEValueV); 4640 4641 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4642 // has a special value for the first iteration of the loop. 4643 4644 // If the value coming around the backedge is an add with the symbolic 4645 // value we just inserted, then we found a simple induction variable! 4646 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4647 // If there is a single occurrence of the symbolic value, replace it 4648 // with a recurrence. 4649 unsigned FoundIndex = Add->getNumOperands(); 4650 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4651 if (Add->getOperand(i) == SymbolicName) 4652 if (FoundIndex == e) { 4653 FoundIndex = i; 4654 break; 4655 } 4656 4657 if (FoundIndex != Add->getNumOperands()) { 4658 // Create an add with everything but the specified operand. 4659 SmallVector<const SCEV *, 8> Ops; 4660 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4661 if (i != FoundIndex) 4662 Ops.push_back(Add->getOperand(i)); 4663 const SCEV *Accum = getAddExpr(Ops); 4664 4665 // This is not a valid addrec if the step amount is varying each 4666 // loop iteration, but is not itself an addrec in this loop. 4667 if (isLoopInvariant(Accum, L) || 4668 (isa<SCEVAddRecExpr>(Accum) && 4669 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4670 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4671 4672 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4673 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4674 if (BO->IsNUW) 4675 Flags = setFlags(Flags, SCEV::FlagNUW); 4676 if (BO->IsNSW) 4677 Flags = setFlags(Flags, SCEV::FlagNSW); 4678 } 4679 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4680 // If the increment is an inbounds GEP, then we know the address 4681 // space cannot be wrapped around. We cannot make any guarantee 4682 // about signed or unsigned overflow because pointers are 4683 // unsigned but we may have a negative index from the base 4684 // pointer. We can guarantee that no unsigned wrap occurs if the 4685 // indices form a positive value. 4686 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4687 Flags = setFlags(Flags, SCEV::FlagNW); 4688 4689 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4690 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4691 Flags = setFlags(Flags, SCEV::FlagNUW); 4692 } 4693 4694 // We cannot transfer nuw and nsw flags from subtraction 4695 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4696 // for instance. 4697 } 4698 4699 const SCEV *StartVal = getSCEV(StartValueV); 4700 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4701 4702 // Okay, for the entire analysis of this edge we assumed the PHI 4703 // to be symbolic. We now need to go back and purge all of the 4704 // entries for the scalars that use the symbolic expression. 4705 forgetSymbolicName(PN, SymbolicName); 4706 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4707 4708 // We can add Flags to the post-inc expression only if we 4709 // know that it is *undefined behavior* for BEValueV to 4710 // overflow. 4711 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4712 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4713 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4714 4715 return PHISCEV; 4716 } 4717 } 4718 } else { 4719 // Otherwise, this could be a loop like this: 4720 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4721 // In this case, j = {1,+,1} and BEValue is j. 4722 // Because the other in-value of i (0) fits the evolution of BEValue 4723 // i really is an addrec evolution. 4724 // 4725 // We can generalize this saying that i is the shifted value of BEValue 4726 // by one iteration: 4727 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4728 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4729 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4730 if (Shifted != getCouldNotCompute() && 4731 Start != getCouldNotCompute()) { 4732 const SCEV *StartVal = getSCEV(StartValueV); 4733 if (Start == StartVal) { 4734 // Okay, for the entire analysis of this edge we assumed the PHI 4735 // to be symbolic. We now need to go back and purge all of the 4736 // entries for the scalars that use the symbolic expression. 4737 forgetSymbolicName(PN, SymbolicName); 4738 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4739 return Shifted; 4740 } 4741 } 4742 } 4743 4744 // Remove the temporary PHI node SCEV that has been inserted while intending 4745 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4746 // as it will prevent later (possibly simpler) SCEV expressions to be added 4747 // to the ValueExprMap. 4748 eraseValueFromMap(PN); 4749 4750 return nullptr; 4751 } 4752 4753 // Checks if the SCEV S is available at BB. S is considered available at BB 4754 // if S can be materialized at BB without introducing a fault. 4755 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4756 BasicBlock *BB) { 4757 struct CheckAvailable { 4758 bool TraversalDone = false; 4759 bool Available = true; 4760 4761 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4762 BasicBlock *BB = nullptr; 4763 DominatorTree &DT; 4764 4765 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4766 : L(L), BB(BB), DT(DT) {} 4767 4768 bool setUnavailable() { 4769 TraversalDone = true; 4770 Available = false; 4771 return false; 4772 } 4773 4774 bool follow(const SCEV *S) { 4775 switch (S->getSCEVType()) { 4776 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4777 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4778 // These expressions are available if their operand(s) is/are. 4779 return true; 4780 4781 case scAddRecExpr: { 4782 // We allow add recurrences that are on the loop BB is in, or some 4783 // outer loop. This guarantees availability because the value of the 4784 // add recurrence at BB is simply the "current" value of the induction 4785 // variable. We can relax this in the future; for instance an add 4786 // recurrence on a sibling dominating loop is also available at BB. 4787 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4788 if (L && (ARLoop == L || ARLoop->contains(L))) 4789 return true; 4790 4791 return setUnavailable(); 4792 } 4793 4794 case scUnknown: { 4795 // For SCEVUnknown, we check for simple dominance. 4796 const auto *SU = cast<SCEVUnknown>(S); 4797 Value *V = SU->getValue(); 4798 4799 if (isa<Argument>(V)) 4800 return false; 4801 4802 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4803 return false; 4804 4805 return setUnavailable(); 4806 } 4807 4808 case scUDivExpr: 4809 case scCouldNotCompute: 4810 // We do not try to smart about these at all. 4811 return setUnavailable(); 4812 } 4813 llvm_unreachable("switch should be fully covered!"); 4814 } 4815 4816 bool isDone() { return TraversalDone; } 4817 }; 4818 4819 CheckAvailable CA(L, BB, DT); 4820 SCEVTraversal<CheckAvailable> ST(CA); 4821 4822 ST.visitAll(S); 4823 return CA.Available; 4824 } 4825 4826 // Try to match a control flow sequence that branches out at BI and merges back 4827 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4828 // match. 4829 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4830 Value *&C, Value *&LHS, Value *&RHS) { 4831 C = BI->getCondition(); 4832 4833 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4834 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4835 4836 if (!LeftEdge.isSingleEdge()) 4837 return false; 4838 4839 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4840 4841 Use &LeftUse = Merge->getOperandUse(0); 4842 Use &RightUse = Merge->getOperandUse(1); 4843 4844 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4845 LHS = LeftUse; 4846 RHS = RightUse; 4847 return true; 4848 } 4849 4850 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4851 LHS = RightUse; 4852 RHS = LeftUse; 4853 return true; 4854 } 4855 4856 return false; 4857 } 4858 4859 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4860 auto IsReachable = 4861 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4862 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4863 const Loop *L = LI.getLoopFor(PN->getParent()); 4864 4865 // We don't want to break LCSSA, even in a SCEV expression tree. 4866 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4867 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4868 return nullptr; 4869 4870 // Try to match 4871 // 4872 // br %cond, label %left, label %right 4873 // left: 4874 // br label %merge 4875 // right: 4876 // br label %merge 4877 // merge: 4878 // V = phi [ %x, %left ], [ %y, %right ] 4879 // 4880 // as "select %cond, %x, %y" 4881 4882 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4883 assert(IDom && "At least the entry block should dominate PN"); 4884 4885 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4886 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4887 4888 if (BI && BI->isConditional() && 4889 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4890 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4891 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4892 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4893 } 4894 4895 return nullptr; 4896 } 4897 4898 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4899 if (const SCEV *S = createAddRecFromPHI(PN)) 4900 return S; 4901 4902 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4903 return S; 4904 4905 // If the PHI has a single incoming value, follow that value, unless the 4906 // PHI's incoming blocks are in a different loop, in which case doing so 4907 // risks breaking LCSSA form. Instcombine would normally zap these, but 4908 // it doesn't have DominatorTree information, so it may miss cases. 4909 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 4910 if (LI.replacementPreservesLCSSAForm(PN, V)) 4911 return getSCEV(V); 4912 4913 // If it's not a loop phi, we can't handle it yet. 4914 return getUnknown(PN); 4915 } 4916 4917 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4918 Value *Cond, 4919 Value *TrueVal, 4920 Value *FalseVal) { 4921 // Handle "constant" branch or select. This can occur for instance when a 4922 // loop pass transforms an inner loop and moves on to process the outer loop. 4923 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4924 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4925 4926 // Try to match some simple smax or umax patterns. 4927 auto *ICI = dyn_cast<ICmpInst>(Cond); 4928 if (!ICI) 4929 return getUnknown(I); 4930 4931 Value *LHS = ICI->getOperand(0); 4932 Value *RHS = ICI->getOperand(1); 4933 4934 switch (ICI->getPredicate()) { 4935 case ICmpInst::ICMP_SLT: 4936 case ICmpInst::ICMP_SLE: 4937 std::swap(LHS, RHS); 4938 LLVM_FALLTHROUGH; 4939 case ICmpInst::ICMP_SGT: 4940 case ICmpInst::ICMP_SGE: 4941 // a >s b ? a+x : b+x -> smax(a, b)+x 4942 // a >s b ? b+x : a+x -> smin(a, b)+x 4943 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4944 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4945 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4946 const SCEV *LA = getSCEV(TrueVal); 4947 const SCEV *RA = getSCEV(FalseVal); 4948 const SCEV *LDiff = getMinusSCEV(LA, LS); 4949 const SCEV *RDiff = getMinusSCEV(RA, RS); 4950 if (LDiff == RDiff) 4951 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4952 LDiff = getMinusSCEV(LA, RS); 4953 RDiff = getMinusSCEV(RA, LS); 4954 if (LDiff == RDiff) 4955 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4956 } 4957 break; 4958 case ICmpInst::ICMP_ULT: 4959 case ICmpInst::ICMP_ULE: 4960 std::swap(LHS, RHS); 4961 LLVM_FALLTHROUGH; 4962 case ICmpInst::ICMP_UGT: 4963 case ICmpInst::ICMP_UGE: 4964 // a >u b ? a+x : b+x -> umax(a, b)+x 4965 // a >u b ? b+x : a+x -> umin(a, b)+x 4966 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4967 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4968 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4969 const SCEV *LA = getSCEV(TrueVal); 4970 const SCEV *RA = getSCEV(FalseVal); 4971 const SCEV *LDiff = getMinusSCEV(LA, LS); 4972 const SCEV *RDiff = getMinusSCEV(RA, RS); 4973 if (LDiff == RDiff) 4974 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4975 LDiff = getMinusSCEV(LA, RS); 4976 RDiff = getMinusSCEV(RA, LS); 4977 if (LDiff == RDiff) 4978 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4979 } 4980 break; 4981 case ICmpInst::ICMP_NE: 4982 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4983 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4984 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4985 const SCEV *One = getOne(I->getType()); 4986 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4987 const SCEV *LA = getSCEV(TrueVal); 4988 const SCEV *RA = getSCEV(FalseVal); 4989 const SCEV *LDiff = getMinusSCEV(LA, LS); 4990 const SCEV *RDiff = getMinusSCEV(RA, One); 4991 if (LDiff == RDiff) 4992 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4993 } 4994 break; 4995 case ICmpInst::ICMP_EQ: 4996 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4997 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4998 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4999 const SCEV *One = getOne(I->getType()); 5000 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5001 const SCEV *LA = getSCEV(TrueVal); 5002 const SCEV *RA = getSCEV(FalseVal); 5003 const SCEV *LDiff = getMinusSCEV(LA, One); 5004 const SCEV *RDiff = getMinusSCEV(RA, LS); 5005 if (LDiff == RDiff) 5006 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5007 } 5008 break; 5009 default: 5010 break; 5011 } 5012 5013 return getUnknown(I); 5014 } 5015 5016 /// Expand GEP instructions into add and multiply operations. This allows them 5017 /// to be analyzed by regular SCEV code. 5018 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5019 // Don't attempt to analyze GEPs over unsized objects. 5020 if (!GEP->getSourceElementType()->isSized()) 5021 return getUnknown(GEP); 5022 5023 SmallVector<const SCEV *, 4> IndexExprs; 5024 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5025 IndexExprs.push_back(getSCEV(*Index)); 5026 return getGEPExpr(GEP, IndexExprs); 5027 } 5028 5029 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5030 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5031 return C->getAPInt().countTrailingZeros(); 5032 5033 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5034 return std::min(GetMinTrailingZeros(T->getOperand()), 5035 (uint32_t)getTypeSizeInBits(T->getType())); 5036 5037 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5038 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5039 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5040 ? getTypeSizeInBits(E->getType()) 5041 : OpRes; 5042 } 5043 5044 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5045 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5046 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5047 ? getTypeSizeInBits(E->getType()) 5048 : OpRes; 5049 } 5050 5051 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5052 // The result is the min of all operands results. 5053 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5054 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5055 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5056 return MinOpRes; 5057 } 5058 5059 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5060 // The result is the sum of all operands results. 5061 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5062 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5063 for (unsigned i = 1, e = M->getNumOperands(); 5064 SumOpRes != BitWidth && i != e; ++i) 5065 SumOpRes = 5066 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5067 return SumOpRes; 5068 } 5069 5070 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5071 // The result is the min of all operands results. 5072 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5073 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5074 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5075 return MinOpRes; 5076 } 5077 5078 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5079 // The result is the min of all operands results. 5080 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5081 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5082 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5083 return MinOpRes; 5084 } 5085 5086 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5087 // The result is the min of all operands results. 5088 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5089 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5090 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5091 return MinOpRes; 5092 } 5093 5094 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5095 // For a SCEVUnknown, ask ValueTracking. 5096 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5097 return Known.countMinTrailingZeros(); 5098 } 5099 5100 // SCEVUDivExpr 5101 return 0; 5102 } 5103 5104 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5105 auto I = MinTrailingZerosCache.find(S); 5106 if (I != MinTrailingZerosCache.end()) 5107 return I->second; 5108 5109 uint32_t Result = GetMinTrailingZerosImpl(S); 5110 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5111 assert(InsertPair.second && "Should insert a new key"); 5112 return InsertPair.first->second; 5113 } 5114 5115 /// Helper method to assign a range to V from metadata present in the IR. 5116 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5117 if (Instruction *I = dyn_cast<Instruction>(V)) 5118 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5119 return getConstantRangeFromMetadata(*MD); 5120 5121 return None; 5122 } 5123 5124 /// Determine the range for a particular SCEV. If SignHint is 5125 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5126 /// with a "cleaner" unsigned (resp. signed) representation. 5127 const ConstantRange & 5128 ScalarEvolution::getRangeRef(const SCEV *S, 5129 ScalarEvolution::RangeSignHint SignHint) { 5130 DenseMap<const SCEV *, ConstantRange> &Cache = 5131 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5132 : SignedRanges; 5133 5134 // See if we've computed this range already. 5135 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5136 if (I != Cache.end()) 5137 return I->second; 5138 5139 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5140 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5141 5142 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5143 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5144 5145 // If the value has known zeros, the maximum value will have those known zeros 5146 // as well. 5147 uint32_t TZ = GetMinTrailingZeros(S); 5148 if (TZ != 0) { 5149 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5150 ConservativeResult = 5151 ConstantRange(APInt::getMinValue(BitWidth), 5152 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5153 else 5154 ConservativeResult = ConstantRange( 5155 APInt::getSignedMinValue(BitWidth), 5156 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5157 } 5158 5159 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5160 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5161 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5162 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5163 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5164 } 5165 5166 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5167 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5168 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5169 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5170 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5171 } 5172 5173 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5174 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5175 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5176 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5177 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5178 } 5179 5180 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5181 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5182 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5183 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5184 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5185 } 5186 5187 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5188 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5189 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5190 return setRange(UDiv, SignHint, 5191 ConservativeResult.intersectWith(X.udiv(Y))); 5192 } 5193 5194 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5195 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5196 return setRange(ZExt, SignHint, 5197 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5198 } 5199 5200 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5201 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5202 return setRange(SExt, SignHint, 5203 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5204 } 5205 5206 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5207 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5208 return setRange(Trunc, SignHint, 5209 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5210 } 5211 5212 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5213 // If there's no unsigned wrap, the value will never be less than its 5214 // initial value. 5215 if (AddRec->hasNoUnsignedWrap()) 5216 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5217 if (!C->getValue()->isZero()) 5218 ConservativeResult = ConservativeResult.intersectWith( 5219 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5220 5221 // If there's no signed wrap, and all the operands have the same sign or 5222 // zero, the value won't ever change sign. 5223 if (AddRec->hasNoSignedWrap()) { 5224 bool AllNonNeg = true; 5225 bool AllNonPos = true; 5226 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5227 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5228 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5229 } 5230 if (AllNonNeg) 5231 ConservativeResult = ConservativeResult.intersectWith( 5232 ConstantRange(APInt(BitWidth, 0), 5233 APInt::getSignedMinValue(BitWidth))); 5234 else if (AllNonPos) 5235 ConservativeResult = ConservativeResult.intersectWith( 5236 ConstantRange(APInt::getSignedMinValue(BitWidth), 5237 APInt(BitWidth, 1))); 5238 } 5239 5240 // TODO: non-affine addrec 5241 if (AddRec->isAffine()) { 5242 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5243 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5244 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5245 auto RangeFromAffine = getRangeForAffineAR( 5246 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5247 BitWidth); 5248 if (!RangeFromAffine.isFullSet()) 5249 ConservativeResult = 5250 ConservativeResult.intersectWith(RangeFromAffine); 5251 5252 auto RangeFromFactoring = getRangeViaFactoring( 5253 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5254 BitWidth); 5255 if (!RangeFromFactoring.isFullSet()) 5256 ConservativeResult = 5257 ConservativeResult.intersectWith(RangeFromFactoring); 5258 } 5259 } 5260 5261 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5262 } 5263 5264 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5265 // Check if the IR explicitly contains !range metadata. 5266 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5267 if (MDRange.hasValue()) 5268 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5269 5270 // Split here to avoid paying the compile-time cost of calling both 5271 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5272 // if needed. 5273 const DataLayout &DL = getDataLayout(); 5274 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5275 // For a SCEVUnknown, ask ValueTracking. 5276 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5277 if (Known.One != ~Known.Zero + 1) 5278 ConservativeResult = 5279 ConservativeResult.intersectWith(ConstantRange(Known.One, 5280 ~Known.Zero + 1)); 5281 } else { 5282 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5283 "generalize as needed!"); 5284 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5285 if (NS > 1) 5286 ConservativeResult = ConservativeResult.intersectWith( 5287 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5288 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5289 } 5290 5291 return setRange(U, SignHint, std::move(ConservativeResult)); 5292 } 5293 5294 return setRange(S, SignHint, std::move(ConservativeResult)); 5295 } 5296 5297 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5298 // values that the expression can take. Initially, the expression has a value 5299 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5300 // argument defines if we treat Step as signed or unsigned. 5301 static ConstantRange getRangeForAffineARHelper(APInt Step, 5302 const ConstantRange &StartRange, 5303 const APInt &MaxBECount, 5304 unsigned BitWidth, bool Signed) { 5305 // If either Step or MaxBECount is 0, then the expression won't change, and we 5306 // just need to return the initial range. 5307 if (Step == 0 || MaxBECount == 0) 5308 return StartRange; 5309 5310 // If we don't know anything about the initial value (i.e. StartRange is 5311 // FullRange), then we don't know anything about the final range either. 5312 // Return FullRange. 5313 if (StartRange.isFullSet()) 5314 return ConstantRange(BitWidth, /* isFullSet = */ true); 5315 5316 // If Step is signed and negative, then we use its absolute value, but we also 5317 // note that we're moving in the opposite direction. 5318 bool Descending = Signed && Step.isNegative(); 5319 5320 if (Signed) 5321 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5322 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5323 // This equations hold true due to the well-defined wrap-around behavior of 5324 // APInt. 5325 Step = Step.abs(); 5326 5327 // Check if Offset is more than full span of BitWidth. If it is, the 5328 // expression is guaranteed to overflow. 5329 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5330 return ConstantRange(BitWidth, /* isFullSet = */ true); 5331 5332 // Offset is by how much the expression can change. Checks above guarantee no 5333 // overflow here. 5334 APInt Offset = Step * MaxBECount; 5335 5336 // Minimum value of the final range will match the minimal value of StartRange 5337 // if the expression is increasing and will be decreased by Offset otherwise. 5338 // Maximum value of the final range will match the maximal value of StartRange 5339 // if the expression is decreasing and will be increased by Offset otherwise. 5340 APInt StartLower = StartRange.getLower(); 5341 APInt StartUpper = StartRange.getUpper() - 1; 5342 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5343 : (StartUpper + std::move(Offset)); 5344 5345 // It's possible that the new minimum/maximum value will fall into the initial 5346 // range (due to wrap around). This means that the expression can take any 5347 // value in this bitwidth, and we have to return full range. 5348 if (StartRange.contains(MovedBoundary)) 5349 return ConstantRange(BitWidth, /* isFullSet = */ true); 5350 5351 APInt NewLower = 5352 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5353 APInt NewUpper = 5354 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5355 NewUpper += 1; 5356 5357 // If we end up with full range, return a proper full range. 5358 if (NewLower == NewUpper) 5359 return ConstantRange(BitWidth, /* isFullSet = */ true); 5360 5361 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5362 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5363 } 5364 5365 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5366 const SCEV *Step, 5367 const SCEV *MaxBECount, 5368 unsigned BitWidth) { 5369 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5370 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5371 "Precondition!"); 5372 5373 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5374 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5375 5376 // First, consider step signed. 5377 ConstantRange StartSRange = getSignedRange(Start); 5378 ConstantRange StepSRange = getSignedRange(Step); 5379 5380 // If Step can be both positive and negative, we need to find ranges for the 5381 // maximum absolute step values in both directions and union them. 5382 ConstantRange SR = 5383 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5384 MaxBECountValue, BitWidth, /* Signed = */ true); 5385 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5386 StartSRange, MaxBECountValue, 5387 BitWidth, /* Signed = */ true)); 5388 5389 // Next, consider step unsigned. 5390 ConstantRange UR = getRangeForAffineARHelper( 5391 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5392 MaxBECountValue, BitWidth, /* Signed = */ false); 5393 5394 // Finally, intersect signed and unsigned ranges. 5395 return SR.intersectWith(UR); 5396 } 5397 5398 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5399 const SCEV *Step, 5400 const SCEV *MaxBECount, 5401 unsigned BitWidth) { 5402 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5403 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5404 5405 struct SelectPattern { 5406 Value *Condition = nullptr; 5407 APInt TrueValue; 5408 APInt FalseValue; 5409 5410 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5411 const SCEV *S) { 5412 Optional<unsigned> CastOp; 5413 APInt Offset(BitWidth, 0); 5414 5415 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5416 "Should be!"); 5417 5418 // Peel off a constant offset: 5419 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5420 // In the future we could consider being smarter here and handle 5421 // {Start+Step,+,Step} too. 5422 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5423 return; 5424 5425 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5426 S = SA->getOperand(1); 5427 } 5428 5429 // Peel off a cast operation 5430 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5431 CastOp = SCast->getSCEVType(); 5432 S = SCast->getOperand(); 5433 } 5434 5435 using namespace llvm::PatternMatch; 5436 5437 auto *SU = dyn_cast<SCEVUnknown>(S); 5438 const APInt *TrueVal, *FalseVal; 5439 if (!SU || 5440 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5441 m_APInt(FalseVal)))) { 5442 Condition = nullptr; 5443 return; 5444 } 5445 5446 TrueValue = *TrueVal; 5447 FalseValue = *FalseVal; 5448 5449 // Re-apply the cast we peeled off earlier 5450 if (CastOp.hasValue()) 5451 switch (*CastOp) { 5452 default: 5453 llvm_unreachable("Unknown SCEV cast type!"); 5454 5455 case scTruncate: 5456 TrueValue = TrueValue.trunc(BitWidth); 5457 FalseValue = FalseValue.trunc(BitWidth); 5458 break; 5459 case scZeroExtend: 5460 TrueValue = TrueValue.zext(BitWidth); 5461 FalseValue = FalseValue.zext(BitWidth); 5462 break; 5463 case scSignExtend: 5464 TrueValue = TrueValue.sext(BitWidth); 5465 FalseValue = FalseValue.sext(BitWidth); 5466 break; 5467 } 5468 5469 // Re-apply the constant offset we peeled off earlier 5470 TrueValue += Offset; 5471 FalseValue += Offset; 5472 } 5473 5474 bool isRecognized() { return Condition != nullptr; } 5475 }; 5476 5477 SelectPattern StartPattern(*this, BitWidth, Start); 5478 if (!StartPattern.isRecognized()) 5479 return ConstantRange(BitWidth, /* isFullSet = */ true); 5480 5481 SelectPattern StepPattern(*this, BitWidth, Step); 5482 if (!StepPattern.isRecognized()) 5483 return ConstantRange(BitWidth, /* isFullSet = */ true); 5484 5485 if (StartPattern.Condition != StepPattern.Condition) { 5486 // We don't handle this case today; but we could, by considering four 5487 // possibilities below instead of two. I'm not sure if there are cases where 5488 // that will help over what getRange already does, though. 5489 return ConstantRange(BitWidth, /* isFullSet = */ true); 5490 } 5491 5492 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5493 // construct arbitrary general SCEV expressions here. This function is called 5494 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5495 // say) can end up caching a suboptimal value. 5496 5497 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5498 // C2352 and C2512 (otherwise it isn't needed). 5499 5500 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5501 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5502 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5503 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5504 5505 ConstantRange TrueRange = 5506 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5507 ConstantRange FalseRange = 5508 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5509 5510 return TrueRange.unionWith(FalseRange); 5511 } 5512 5513 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5514 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5515 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5516 5517 // Return early if there are no flags to propagate to the SCEV. 5518 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5519 if (BinOp->hasNoUnsignedWrap()) 5520 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5521 if (BinOp->hasNoSignedWrap()) 5522 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5523 if (Flags == SCEV::FlagAnyWrap) 5524 return SCEV::FlagAnyWrap; 5525 5526 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5527 } 5528 5529 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5530 // Here we check that I is in the header of the innermost loop containing I, 5531 // since we only deal with instructions in the loop header. The actual loop we 5532 // need to check later will come from an add recurrence, but getting that 5533 // requires computing the SCEV of the operands, which can be expensive. This 5534 // check we can do cheaply to rule out some cases early. 5535 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5536 if (InnermostContainingLoop == nullptr || 5537 InnermostContainingLoop->getHeader() != I->getParent()) 5538 return false; 5539 5540 // Only proceed if we can prove that I does not yield poison. 5541 if (!programUndefinedIfFullPoison(I)) 5542 return false; 5543 5544 // At this point we know that if I is executed, then it does not wrap 5545 // according to at least one of NSW or NUW. If I is not executed, then we do 5546 // not know if the calculation that I represents would wrap. Multiple 5547 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5548 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5549 // derived from other instructions that map to the same SCEV. We cannot make 5550 // that guarantee for cases where I is not executed. So we need to find the 5551 // loop that I is considered in relation to and prove that I is executed for 5552 // every iteration of that loop. That implies that the value that I 5553 // calculates does not wrap anywhere in the loop, so then we can apply the 5554 // flags to the SCEV. 5555 // 5556 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5557 // from different loops, so that we know which loop to prove that I is 5558 // executed in. 5559 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5560 // I could be an extractvalue from a call to an overflow intrinsic. 5561 // TODO: We can do better here in some cases. 5562 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5563 return false; 5564 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5565 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5566 bool AllOtherOpsLoopInvariant = true; 5567 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5568 ++OtherOpIndex) { 5569 if (OtherOpIndex != OpIndex) { 5570 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5571 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5572 AllOtherOpsLoopInvariant = false; 5573 break; 5574 } 5575 } 5576 } 5577 if (AllOtherOpsLoopInvariant && 5578 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5579 return true; 5580 } 5581 } 5582 return false; 5583 } 5584 5585 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5586 // If we know that \c I can never be poison period, then that's enough. 5587 if (isSCEVExprNeverPoison(I)) 5588 return true; 5589 5590 // For an add recurrence specifically, we assume that infinite loops without 5591 // side effects are undefined behavior, and then reason as follows: 5592 // 5593 // If the add recurrence is poison in any iteration, it is poison on all 5594 // future iterations (since incrementing poison yields poison). If the result 5595 // of the add recurrence is fed into the loop latch condition and the loop 5596 // does not contain any throws or exiting blocks other than the latch, we now 5597 // have the ability to "choose" whether the backedge is taken or not (by 5598 // choosing a sufficiently evil value for the poison feeding into the branch) 5599 // for every iteration including and after the one in which \p I first became 5600 // poison. There are two possibilities (let's call the iteration in which \p 5601 // I first became poison as K): 5602 // 5603 // 1. In the set of iterations including and after K, the loop body executes 5604 // no side effects. In this case executing the backege an infinte number 5605 // of times will yield undefined behavior. 5606 // 5607 // 2. In the set of iterations including and after K, the loop body executes 5608 // at least one side effect. In this case, that specific instance of side 5609 // effect is control dependent on poison, which also yields undefined 5610 // behavior. 5611 5612 auto *ExitingBB = L->getExitingBlock(); 5613 auto *LatchBB = L->getLoopLatch(); 5614 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5615 return false; 5616 5617 SmallPtrSet<const Instruction *, 16> Pushed; 5618 SmallVector<const Instruction *, 8> PoisonStack; 5619 5620 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5621 // things that are known to be fully poison under that assumption go on the 5622 // PoisonStack. 5623 Pushed.insert(I); 5624 PoisonStack.push_back(I); 5625 5626 bool LatchControlDependentOnPoison = false; 5627 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5628 const Instruction *Poison = PoisonStack.pop_back_val(); 5629 5630 for (auto *PoisonUser : Poison->users()) { 5631 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5632 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5633 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5634 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5635 assert(BI->isConditional() && "Only possibility!"); 5636 if (BI->getParent() == LatchBB) { 5637 LatchControlDependentOnPoison = true; 5638 break; 5639 } 5640 } 5641 } 5642 } 5643 5644 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5645 } 5646 5647 ScalarEvolution::LoopProperties 5648 ScalarEvolution::getLoopProperties(const Loop *L) { 5649 using LoopProperties = ScalarEvolution::LoopProperties; 5650 5651 auto Itr = LoopPropertiesCache.find(L); 5652 if (Itr == LoopPropertiesCache.end()) { 5653 auto HasSideEffects = [](Instruction *I) { 5654 if (auto *SI = dyn_cast<StoreInst>(I)) 5655 return !SI->isSimple(); 5656 5657 return I->mayHaveSideEffects(); 5658 }; 5659 5660 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5661 /*HasNoSideEffects*/ true}; 5662 5663 for (auto *BB : L->getBlocks()) 5664 for (auto &I : *BB) { 5665 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5666 LP.HasNoAbnormalExits = false; 5667 if (HasSideEffects(&I)) 5668 LP.HasNoSideEffects = false; 5669 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5670 break; // We're already as pessimistic as we can get. 5671 } 5672 5673 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5674 assert(InsertPair.second && "We just checked!"); 5675 Itr = InsertPair.first; 5676 } 5677 5678 return Itr->second; 5679 } 5680 5681 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5682 if (!isSCEVable(V->getType())) 5683 return getUnknown(V); 5684 5685 if (Instruction *I = dyn_cast<Instruction>(V)) { 5686 // Don't attempt to analyze instructions in blocks that aren't 5687 // reachable. Such instructions don't matter, and they aren't required 5688 // to obey basic rules for definitions dominating uses which this 5689 // analysis depends on. 5690 if (!DT.isReachableFromEntry(I->getParent())) 5691 return getUnknown(V); 5692 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5693 return getConstant(CI); 5694 else if (isa<ConstantPointerNull>(V)) 5695 return getZero(V->getType()); 5696 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5697 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5698 else if (!isa<ConstantExpr>(V)) 5699 return getUnknown(V); 5700 5701 Operator *U = cast<Operator>(V); 5702 if (auto BO = MatchBinaryOp(U, DT)) { 5703 switch (BO->Opcode) { 5704 case Instruction::Add: { 5705 // The simple thing to do would be to just call getSCEV on both operands 5706 // and call getAddExpr with the result. However if we're looking at a 5707 // bunch of things all added together, this can be quite inefficient, 5708 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5709 // Instead, gather up all the operands and make a single getAddExpr call. 5710 // LLVM IR canonical form means we need only traverse the left operands. 5711 SmallVector<const SCEV *, 4> AddOps; 5712 do { 5713 if (BO->Op) { 5714 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5715 AddOps.push_back(OpSCEV); 5716 break; 5717 } 5718 5719 // If a NUW or NSW flag can be applied to the SCEV for this 5720 // addition, then compute the SCEV for this addition by itself 5721 // with a separate call to getAddExpr. We need to do that 5722 // instead of pushing the operands of the addition onto AddOps, 5723 // since the flags are only known to apply to this particular 5724 // addition - they may not apply to other additions that can be 5725 // formed with operands from AddOps. 5726 const SCEV *RHS = getSCEV(BO->RHS); 5727 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5728 if (Flags != SCEV::FlagAnyWrap) { 5729 const SCEV *LHS = getSCEV(BO->LHS); 5730 if (BO->Opcode == Instruction::Sub) 5731 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5732 else 5733 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5734 break; 5735 } 5736 } 5737 5738 if (BO->Opcode == Instruction::Sub) 5739 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5740 else 5741 AddOps.push_back(getSCEV(BO->RHS)); 5742 5743 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5744 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5745 NewBO->Opcode != Instruction::Sub)) { 5746 AddOps.push_back(getSCEV(BO->LHS)); 5747 break; 5748 } 5749 BO = NewBO; 5750 } while (true); 5751 5752 return getAddExpr(AddOps); 5753 } 5754 5755 case Instruction::Mul: { 5756 SmallVector<const SCEV *, 4> MulOps; 5757 do { 5758 if (BO->Op) { 5759 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5760 MulOps.push_back(OpSCEV); 5761 break; 5762 } 5763 5764 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5765 if (Flags != SCEV::FlagAnyWrap) { 5766 MulOps.push_back( 5767 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5768 break; 5769 } 5770 } 5771 5772 MulOps.push_back(getSCEV(BO->RHS)); 5773 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5774 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5775 MulOps.push_back(getSCEV(BO->LHS)); 5776 break; 5777 } 5778 BO = NewBO; 5779 } while (true); 5780 5781 return getMulExpr(MulOps); 5782 } 5783 case Instruction::UDiv: 5784 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5785 case Instruction::Sub: { 5786 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5787 if (BO->Op) 5788 Flags = getNoWrapFlagsFromUB(BO->Op); 5789 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5790 } 5791 case Instruction::And: 5792 // For an expression like x&255 that merely masks off the high bits, 5793 // use zext(trunc(x)) as the SCEV expression. 5794 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5795 if (CI->isZero()) 5796 return getSCEV(BO->RHS); 5797 if (CI->isMinusOne()) 5798 return getSCEV(BO->LHS); 5799 const APInt &A = CI->getValue(); 5800 5801 // Instcombine's ShrinkDemandedConstant may strip bits out of 5802 // constants, obscuring what would otherwise be a low-bits mask. 5803 // Use computeKnownBits to compute what ShrinkDemandedConstant 5804 // knew about to reconstruct a low-bits mask value. 5805 unsigned LZ = A.countLeadingZeros(); 5806 unsigned TZ = A.countTrailingZeros(); 5807 unsigned BitWidth = A.getBitWidth(); 5808 KnownBits Known(BitWidth); 5809 computeKnownBits(BO->LHS, Known, getDataLayout(), 5810 0, &AC, nullptr, &DT); 5811 5812 APInt EffectiveMask = 5813 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5814 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 5815 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5816 const SCEV *LHS = getSCEV(BO->LHS); 5817 const SCEV *ShiftedLHS = nullptr; 5818 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5819 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5820 // For an expression like (x * 8) & 8, simplify the multiply. 5821 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5822 unsigned GCD = std::min(MulZeros, TZ); 5823 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5824 SmallVector<const SCEV*, 4> MulOps; 5825 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5826 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5827 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5828 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5829 } 5830 } 5831 if (!ShiftedLHS) 5832 ShiftedLHS = getUDivExpr(LHS, MulCount); 5833 return getMulExpr( 5834 getZeroExtendExpr( 5835 getTruncateExpr(ShiftedLHS, 5836 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5837 BO->LHS->getType()), 5838 MulCount); 5839 } 5840 } 5841 break; 5842 5843 case Instruction::Or: 5844 // If the RHS of the Or is a constant, we may have something like: 5845 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5846 // optimizations will transparently handle this case. 5847 // 5848 // In order for this transformation to be safe, the LHS must be of the 5849 // form X*(2^n) and the Or constant must be less than 2^n. 5850 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5851 const SCEV *LHS = getSCEV(BO->LHS); 5852 const APInt &CIVal = CI->getValue(); 5853 if (GetMinTrailingZeros(LHS) >= 5854 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5855 // Build a plain add SCEV. 5856 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5857 // If the LHS of the add was an addrec and it has no-wrap flags, 5858 // transfer the no-wrap flags, since an or won't introduce a wrap. 5859 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5860 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5861 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5862 OldAR->getNoWrapFlags()); 5863 } 5864 return S; 5865 } 5866 } 5867 break; 5868 5869 case Instruction::Xor: 5870 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5871 // If the RHS of xor is -1, then this is a not operation. 5872 if (CI->isMinusOne()) 5873 return getNotSCEV(getSCEV(BO->LHS)); 5874 5875 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5876 // This is a variant of the check for xor with -1, and it handles 5877 // the case where instcombine has trimmed non-demanded bits out 5878 // of an xor with -1. 5879 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5880 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5881 if (LBO->getOpcode() == Instruction::And && 5882 LCI->getValue() == CI->getValue()) 5883 if (const SCEVZeroExtendExpr *Z = 5884 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5885 Type *UTy = BO->LHS->getType(); 5886 const SCEV *Z0 = Z->getOperand(); 5887 Type *Z0Ty = Z0->getType(); 5888 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5889 5890 // If C is a low-bits mask, the zero extend is serving to 5891 // mask off the high bits. Complement the operand and 5892 // re-apply the zext. 5893 if (CI->getValue().isMask(Z0TySize)) 5894 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5895 5896 // If C is a single bit, it may be in the sign-bit position 5897 // before the zero-extend. In this case, represent the xor 5898 // using an add, which is equivalent, and re-apply the zext. 5899 APInt Trunc = CI->getValue().trunc(Z0TySize); 5900 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5901 Trunc.isSignMask()) 5902 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5903 UTy); 5904 } 5905 } 5906 break; 5907 5908 case Instruction::Shl: 5909 // Turn shift left of a constant amount into a multiply. 5910 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5911 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5912 5913 // If the shift count is not less than the bitwidth, the result of 5914 // the shift is undefined. Don't try to analyze it, because the 5915 // resolution chosen here may differ from the resolution chosen in 5916 // other parts of the compiler. 5917 if (SA->getValue().uge(BitWidth)) 5918 break; 5919 5920 // It is currently not resolved how to interpret NSW for left 5921 // shift by BitWidth - 1, so we avoid applying flags in that 5922 // case. Remove this check (or this comment) once the situation 5923 // is resolved. See 5924 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5925 // and http://reviews.llvm.org/D8890 . 5926 auto Flags = SCEV::FlagAnyWrap; 5927 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5928 Flags = getNoWrapFlagsFromUB(BO->Op); 5929 5930 Constant *X = ConstantInt::get(getContext(), 5931 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5932 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5933 } 5934 break; 5935 5936 case Instruction::AShr: { 5937 // AShr X, C, where C is a constant. 5938 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5939 if (!CI) 5940 break; 5941 5942 Type *OuterTy = BO->LHS->getType(); 5943 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5944 // If the shift count is not less than the bitwidth, the result of 5945 // the shift is undefined. Don't try to analyze it, because the 5946 // resolution chosen here may differ from the resolution chosen in 5947 // other parts of the compiler. 5948 if (CI->getValue().uge(BitWidth)) 5949 break; 5950 5951 if (CI->isZero()) 5952 return getSCEV(BO->LHS); // shift by zero --> noop 5953 5954 uint64_t AShrAmt = CI->getZExtValue(); 5955 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5956 5957 Operator *L = dyn_cast<Operator>(BO->LHS); 5958 if (L && L->getOpcode() == Instruction::Shl) { 5959 // X = Shl A, n 5960 // Y = AShr X, m 5961 // Both n and m are constant. 5962 5963 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5964 if (L->getOperand(1) == BO->RHS) 5965 // For a two-shift sext-inreg, i.e. n = m, 5966 // use sext(trunc(x)) as the SCEV expression. 5967 return getSignExtendExpr( 5968 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5969 5970 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5971 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5972 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5973 if (ShlAmt > AShrAmt) { 5974 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5975 // expression. We already checked that ShlAmt < BitWidth, so 5976 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5977 // ShlAmt - AShrAmt < Amt. 5978 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5979 ShlAmt - AShrAmt); 5980 return getSignExtendExpr( 5981 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5982 getConstant(Mul)), OuterTy); 5983 } 5984 } 5985 } 5986 break; 5987 } 5988 } 5989 } 5990 5991 switch (U->getOpcode()) { 5992 case Instruction::Trunc: 5993 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5994 5995 case Instruction::ZExt: 5996 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5997 5998 case Instruction::SExt: 5999 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6000 // The NSW flag of a subtract does not always survive the conversion to 6001 // A + (-1)*B. By pushing sign extension onto its operands we are much 6002 // more likely to preserve NSW and allow later AddRec optimisations. 6003 // 6004 // NOTE: This is effectively duplicating this logic from getSignExtend: 6005 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6006 // but by that point the NSW information has potentially been lost. 6007 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6008 Type *Ty = U->getType(); 6009 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6010 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6011 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6012 } 6013 } 6014 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6015 6016 case Instruction::BitCast: 6017 // BitCasts are no-op casts so we just eliminate the cast. 6018 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6019 return getSCEV(U->getOperand(0)); 6020 break; 6021 6022 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6023 // lead to pointer expressions which cannot safely be expanded to GEPs, 6024 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6025 // simplifying integer expressions. 6026 6027 case Instruction::GetElementPtr: 6028 return createNodeForGEP(cast<GEPOperator>(U)); 6029 6030 case Instruction::PHI: 6031 return createNodeForPHI(cast<PHINode>(U)); 6032 6033 case Instruction::Select: 6034 // U can also be a select constant expr, which let fall through. Since 6035 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6036 // constant expressions cannot have instructions as operands, we'd have 6037 // returned getUnknown for a select constant expressions anyway. 6038 if (isa<Instruction>(U)) 6039 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6040 U->getOperand(1), U->getOperand(2)); 6041 break; 6042 6043 case Instruction::Call: 6044 case Instruction::Invoke: 6045 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6046 return getSCEV(RV); 6047 break; 6048 } 6049 6050 return getUnknown(V); 6051 } 6052 6053 //===----------------------------------------------------------------------===// 6054 // Iteration Count Computation Code 6055 // 6056 6057 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6058 if (!ExitCount) 6059 return 0; 6060 6061 ConstantInt *ExitConst = ExitCount->getValue(); 6062 6063 // Guard against huge trip counts. 6064 if (ExitConst->getValue().getActiveBits() > 32) 6065 return 0; 6066 6067 // In case of integer overflow, this returns 0, which is correct. 6068 return ((unsigned)ExitConst->getZExtValue()) + 1; 6069 } 6070 6071 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6072 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6073 return getSmallConstantTripCount(L, ExitingBB); 6074 6075 // No trip count information for multiple exits. 6076 return 0; 6077 } 6078 6079 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6080 BasicBlock *ExitingBlock) { 6081 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6082 assert(L->isLoopExiting(ExitingBlock) && 6083 "Exiting block must actually branch out of the loop!"); 6084 const SCEVConstant *ExitCount = 6085 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6086 return getConstantTripCount(ExitCount); 6087 } 6088 6089 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6090 const auto *MaxExitCount = 6091 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6092 return getConstantTripCount(MaxExitCount); 6093 } 6094 6095 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6096 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6097 return getSmallConstantTripMultiple(L, ExitingBB); 6098 6099 // No trip multiple information for multiple exits. 6100 return 0; 6101 } 6102 6103 /// Returns the largest constant divisor of the trip count of this loop as a 6104 /// normal unsigned value, if possible. This means that the actual trip count is 6105 /// always a multiple of the returned value (don't forget the trip count could 6106 /// very well be zero as well!). 6107 /// 6108 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6109 /// multiple of a constant (which is also the case if the trip count is simply 6110 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6111 /// if the trip count is very large (>= 2^32). 6112 /// 6113 /// As explained in the comments for getSmallConstantTripCount, this assumes 6114 /// that control exits the loop via ExitingBlock. 6115 unsigned 6116 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6117 BasicBlock *ExitingBlock) { 6118 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6119 assert(L->isLoopExiting(ExitingBlock) && 6120 "Exiting block must actually branch out of the loop!"); 6121 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6122 if (ExitCount == getCouldNotCompute()) 6123 return 1; 6124 6125 // Get the trip count from the BE count by adding 1. 6126 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6127 6128 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6129 if (!TC) 6130 // Attempt to factor more general cases. Returns the greatest power of 6131 // two divisor. If overflow happens, the trip count expression is still 6132 // divisible by the greatest power of 2 divisor returned. 6133 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6134 6135 ConstantInt *Result = TC->getValue(); 6136 6137 // Guard against huge trip counts (this requires checking 6138 // for zero to handle the case where the trip count == -1 and the 6139 // addition wraps). 6140 if (!Result || Result->getValue().getActiveBits() > 32 || 6141 Result->getValue().getActiveBits() == 0) 6142 return 1; 6143 6144 return (unsigned)Result->getZExtValue(); 6145 } 6146 6147 /// Get the expression for the number of loop iterations for which this loop is 6148 /// guaranteed not to exit via ExitingBlock. Otherwise return 6149 /// SCEVCouldNotCompute. 6150 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6151 BasicBlock *ExitingBlock) { 6152 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6153 } 6154 6155 const SCEV * 6156 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6157 SCEVUnionPredicate &Preds) { 6158 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6159 } 6160 6161 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6162 return getBackedgeTakenInfo(L).getExact(this); 6163 } 6164 6165 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6166 /// known never to be less than the actual backedge taken count. 6167 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6168 return getBackedgeTakenInfo(L).getMax(this); 6169 } 6170 6171 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6172 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6173 } 6174 6175 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6176 static void 6177 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6178 BasicBlock *Header = L->getHeader(); 6179 6180 // Push all Loop-header PHIs onto the Worklist stack. 6181 for (BasicBlock::iterator I = Header->begin(); 6182 PHINode *PN = dyn_cast<PHINode>(I); ++I) 6183 Worklist.push_back(PN); 6184 } 6185 6186 const ScalarEvolution::BackedgeTakenInfo & 6187 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6188 auto &BTI = getBackedgeTakenInfo(L); 6189 if (BTI.hasFullInfo()) 6190 return BTI; 6191 6192 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6193 6194 if (!Pair.second) 6195 return Pair.first->second; 6196 6197 BackedgeTakenInfo Result = 6198 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6199 6200 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6201 } 6202 6203 const ScalarEvolution::BackedgeTakenInfo & 6204 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6205 // Initially insert an invalid entry for this loop. If the insertion 6206 // succeeds, proceed to actually compute a backedge-taken count and 6207 // update the value. The temporary CouldNotCompute value tells SCEV 6208 // code elsewhere that it shouldn't attempt to request a new 6209 // backedge-taken count, which could result in infinite recursion. 6210 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6211 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6212 if (!Pair.second) 6213 return Pair.first->second; 6214 6215 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6216 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6217 // must be cleared in this scope. 6218 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6219 6220 if (Result.getExact(this) != getCouldNotCompute()) { 6221 assert(isLoopInvariant(Result.getExact(this), L) && 6222 isLoopInvariant(Result.getMax(this), L) && 6223 "Computed backedge-taken count isn't loop invariant for loop!"); 6224 ++NumTripCountsComputed; 6225 } 6226 else if (Result.getMax(this) == getCouldNotCompute() && 6227 isa<PHINode>(L->getHeader()->begin())) { 6228 // Only count loops that have phi nodes as not being computable. 6229 ++NumTripCountsNotComputed; 6230 } 6231 6232 // Now that we know more about the trip count for this loop, forget any 6233 // existing SCEV values for PHI nodes in this loop since they are only 6234 // conservative estimates made without the benefit of trip count 6235 // information. This is similar to the code in forgetLoop, except that 6236 // it handles SCEVUnknown PHI nodes specially. 6237 if (Result.hasAnyInfo()) { 6238 SmallVector<Instruction *, 16> Worklist; 6239 PushLoopPHIs(L, Worklist); 6240 6241 SmallPtrSet<Instruction *, 8> Visited; 6242 while (!Worklist.empty()) { 6243 Instruction *I = Worklist.pop_back_val(); 6244 if (!Visited.insert(I).second) 6245 continue; 6246 6247 ValueExprMapType::iterator It = 6248 ValueExprMap.find_as(static_cast<Value *>(I)); 6249 if (It != ValueExprMap.end()) { 6250 const SCEV *Old = It->second; 6251 6252 // SCEVUnknown for a PHI either means that it has an unrecognized 6253 // structure, or it's a PHI that's in the progress of being computed 6254 // by createNodeForPHI. In the former case, additional loop trip 6255 // count information isn't going to change anything. In the later 6256 // case, createNodeForPHI will perform the necessary updates on its 6257 // own when it gets to that point. 6258 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6259 eraseValueFromMap(It->first); 6260 forgetMemoizedResults(Old, false); 6261 } 6262 if (PHINode *PN = dyn_cast<PHINode>(I)) 6263 ConstantEvolutionLoopExitValue.erase(PN); 6264 } 6265 6266 PushDefUseChildren(I, Worklist); 6267 } 6268 } 6269 6270 // Re-lookup the insert position, since the call to 6271 // computeBackedgeTakenCount above could result in a 6272 // recusive call to getBackedgeTakenInfo (on a different 6273 // loop), which would invalidate the iterator computed 6274 // earlier. 6275 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6276 } 6277 6278 void ScalarEvolution::forgetLoop(const Loop *L) { 6279 // Drop any stored trip count value. 6280 auto RemoveLoopFromBackedgeMap = 6281 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 6282 auto BTCPos = Map.find(L); 6283 if (BTCPos != Map.end()) { 6284 BTCPos->second.clear(); 6285 Map.erase(BTCPos); 6286 } 6287 }; 6288 6289 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 6290 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 6291 6292 // Drop information about predicated SCEV rewrites for this loop. 6293 for (auto I = PredicatedSCEVRewrites.begin(); 6294 I != PredicatedSCEVRewrites.end();) { 6295 std::pair<const SCEV *, const Loop *> Entry = I->first; 6296 if (Entry.second == L) 6297 PredicatedSCEVRewrites.erase(I++); 6298 else 6299 ++I; 6300 } 6301 6302 // Drop information about expressions based on loop-header PHIs. 6303 SmallVector<Instruction *, 16> Worklist; 6304 PushLoopPHIs(L, Worklist); 6305 6306 SmallPtrSet<Instruction *, 8> Visited; 6307 while (!Worklist.empty()) { 6308 Instruction *I = Worklist.pop_back_val(); 6309 if (!Visited.insert(I).second) 6310 continue; 6311 6312 ValueExprMapType::iterator It = 6313 ValueExprMap.find_as(static_cast<Value *>(I)); 6314 if (It != ValueExprMap.end()) { 6315 eraseValueFromMap(It->first); 6316 forgetMemoizedResults(It->second); 6317 if (PHINode *PN = dyn_cast<PHINode>(I)) 6318 ConstantEvolutionLoopExitValue.erase(PN); 6319 } 6320 6321 PushDefUseChildren(I, Worklist); 6322 } 6323 6324 for (auto I = ExitLimits.begin(); I != ExitLimits.end(); ++I) { 6325 auto &Query = I->first; 6326 if (Query.L == L) 6327 ExitLimits.erase(I); 6328 } 6329 6330 // Forget all contained loops too, to avoid dangling entries in the 6331 // ValuesAtScopes map. 6332 for (Loop *I : *L) 6333 forgetLoop(I); 6334 6335 LoopPropertiesCache.erase(L); 6336 } 6337 6338 void ScalarEvolution::forgetValue(Value *V) { 6339 Instruction *I = dyn_cast<Instruction>(V); 6340 if (!I) return; 6341 6342 // Drop information about expressions based on loop-header PHIs. 6343 SmallVector<Instruction *, 16> Worklist; 6344 Worklist.push_back(I); 6345 6346 SmallPtrSet<Instruction *, 8> Visited; 6347 while (!Worklist.empty()) { 6348 I = Worklist.pop_back_val(); 6349 if (!Visited.insert(I).second) 6350 continue; 6351 6352 ValueExprMapType::iterator It = 6353 ValueExprMap.find_as(static_cast<Value *>(I)); 6354 if (It != ValueExprMap.end()) { 6355 eraseValueFromMap(It->first); 6356 forgetMemoizedResults(It->second); 6357 if (PHINode *PN = dyn_cast<PHINode>(I)) 6358 ConstantEvolutionLoopExitValue.erase(PN); 6359 } 6360 6361 PushDefUseChildren(I, Worklist); 6362 } 6363 } 6364 6365 /// Get the exact loop backedge taken count considering all loop exits. A 6366 /// computable result can only be returned for loops with a single exit. 6367 /// Returning the minimum taken count among all exits is incorrect because one 6368 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6369 /// the limit of each loop test is never skipped. This is a valid assumption as 6370 /// long as the loop exits via that test. For precise results, it is the 6371 /// caller's responsibility to specify the relevant loop exit using 6372 /// getExact(ExitingBlock, SE). 6373 const SCEV * 6374 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6375 SCEVUnionPredicate *Preds) const { 6376 // If any exits were not computable, the loop is not computable. 6377 if (!isComplete() || ExitNotTaken.empty()) 6378 return SE->getCouldNotCompute(); 6379 6380 const SCEV *BECount = nullptr; 6381 for (auto &ENT : ExitNotTaken) { 6382 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6383 6384 if (!BECount) 6385 BECount = ENT.ExactNotTaken; 6386 else if (BECount != ENT.ExactNotTaken) 6387 return SE->getCouldNotCompute(); 6388 if (Preds && !ENT.hasAlwaysTruePredicate()) 6389 Preds->add(ENT.Predicate.get()); 6390 6391 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6392 "Predicate should be always true!"); 6393 } 6394 6395 assert(BECount && "Invalid not taken count for loop exit"); 6396 return BECount; 6397 } 6398 6399 /// Get the exact not taken count for this loop exit. 6400 const SCEV * 6401 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6402 ScalarEvolution *SE) const { 6403 for (auto &ENT : ExitNotTaken) 6404 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6405 return ENT.ExactNotTaken; 6406 6407 return SE->getCouldNotCompute(); 6408 } 6409 6410 /// getMax - Get the max backedge taken count for the loop. 6411 const SCEV * 6412 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6413 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6414 return !ENT.hasAlwaysTruePredicate(); 6415 }; 6416 6417 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6418 return SE->getCouldNotCompute(); 6419 6420 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6421 "No point in having a non-constant max backedge taken count!"); 6422 return getMax(); 6423 } 6424 6425 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6426 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6427 return !ENT.hasAlwaysTruePredicate(); 6428 }; 6429 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6430 } 6431 6432 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6433 ScalarEvolution *SE) const { 6434 if (getMax() && getMax() != SE->getCouldNotCompute() && 6435 SE->hasOperand(getMax(), S)) 6436 return true; 6437 6438 for (auto &ENT : ExitNotTaken) 6439 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6440 SE->hasOperand(ENT.ExactNotTaken, S)) 6441 return true; 6442 6443 return false; 6444 } 6445 6446 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6447 : ExactNotTaken(E), MaxNotTaken(E) { 6448 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6449 isa<SCEVConstant>(MaxNotTaken)) && 6450 "No point in having a non-constant max backedge taken count!"); 6451 } 6452 6453 ScalarEvolution::ExitLimit::ExitLimit( 6454 const SCEV *E, const SCEV *M, bool MaxOrZero, 6455 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6456 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6457 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6458 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6459 "Exact is not allowed to be less precise than Max"); 6460 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6461 isa<SCEVConstant>(MaxNotTaken)) && 6462 "No point in having a non-constant max backedge taken count!"); 6463 for (auto *PredSet : PredSetList) 6464 for (auto *P : *PredSet) 6465 addPredicate(P); 6466 } 6467 6468 ScalarEvolution::ExitLimit::ExitLimit( 6469 const SCEV *E, const SCEV *M, bool MaxOrZero, 6470 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6471 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6472 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6473 isa<SCEVConstant>(MaxNotTaken)) && 6474 "No point in having a non-constant max backedge taken count!"); 6475 } 6476 6477 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6478 bool MaxOrZero) 6479 : ExitLimit(E, M, MaxOrZero, None) { 6480 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6481 isa<SCEVConstant>(MaxNotTaken)) && 6482 "No point in having a non-constant max backedge taken count!"); 6483 } 6484 6485 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6486 /// computable exit into a persistent ExitNotTakenInfo array. 6487 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6488 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6489 &&ExitCounts, 6490 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6491 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6492 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6493 6494 ExitNotTaken.reserve(ExitCounts.size()); 6495 std::transform( 6496 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6497 [&](const EdgeExitInfo &EEI) { 6498 BasicBlock *ExitBB = EEI.first; 6499 const ExitLimit &EL = EEI.second; 6500 if (EL.Predicates.empty()) 6501 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6502 6503 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6504 for (auto *Pred : EL.Predicates) 6505 Predicate->add(Pred); 6506 6507 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6508 }); 6509 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6510 "No point in having a non-constant max backedge taken count!"); 6511 } 6512 6513 /// Invalidate this result and free the ExitNotTakenInfo array. 6514 void ScalarEvolution::BackedgeTakenInfo::clear() { 6515 ExitNotTaken.clear(); 6516 } 6517 6518 /// Compute the number of times the backedge of the specified loop will execute. 6519 ScalarEvolution::BackedgeTakenInfo 6520 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6521 bool AllowPredicates) { 6522 SmallVector<BasicBlock *, 8> ExitingBlocks; 6523 L->getExitingBlocks(ExitingBlocks); 6524 6525 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6526 6527 SmallVector<EdgeExitInfo, 4> ExitCounts; 6528 bool CouldComputeBECount = true; 6529 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6530 const SCEV *MustExitMaxBECount = nullptr; 6531 const SCEV *MayExitMaxBECount = nullptr; 6532 bool MustExitMaxOrZero = false; 6533 6534 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6535 // and compute maxBECount. 6536 // Do a union of all the predicates here. 6537 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6538 BasicBlock *ExitBB = ExitingBlocks[i]; 6539 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6540 6541 assert((AllowPredicates || EL.Predicates.empty()) && 6542 "Predicated exit limit when predicates are not allowed!"); 6543 6544 // 1. For each exit that can be computed, add an entry to ExitCounts. 6545 // CouldComputeBECount is true only if all exits can be computed. 6546 if (EL.ExactNotTaken == getCouldNotCompute()) 6547 // We couldn't compute an exact value for this exit, so 6548 // we won't be able to compute an exact value for the loop. 6549 CouldComputeBECount = false; 6550 else 6551 ExitCounts.emplace_back(ExitBB, EL); 6552 6553 // 2. Derive the loop's MaxBECount from each exit's max number of 6554 // non-exiting iterations. Partition the loop exits into two kinds: 6555 // LoopMustExits and LoopMayExits. 6556 // 6557 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6558 // is a LoopMayExit. If any computable LoopMustExit is found, then 6559 // MaxBECount is the minimum EL.MaxNotTaken of computable 6560 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6561 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6562 // computable EL.MaxNotTaken. 6563 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6564 DT.dominates(ExitBB, Latch)) { 6565 if (!MustExitMaxBECount) { 6566 MustExitMaxBECount = EL.MaxNotTaken; 6567 MustExitMaxOrZero = EL.MaxOrZero; 6568 } else { 6569 MustExitMaxBECount = 6570 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6571 } 6572 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6573 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6574 MayExitMaxBECount = EL.MaxNotTaken; 6575 else { 6576 MayExitMaxBECount = 6577 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6578 } 6579 } 6580 } 6581 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6582 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6583 // The loop backedge will be taken the maximum or zero times if there's 6584 // a single exit that must be taken the maximum or zero times. 6585 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6586 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6587 MaxBECount, MaxOrZero); 6588 } 6589 6590 ScalarEvolution::ExitLimit 6591 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6592 bool AllowPredicates) { 6593 ExitLimitQuery Query(L, ExitingBlock, AllowPredicates); 6594 auto MaybeEL = ExitLimits.find(Query); 6595 if (MaybeEL != ExitLimits.end()) 6596 return MaybeEL->second; 6597 ExitLimit EL = computeExitLimitImpl(L, ExitingBlock, AllowPredicates); 6598 ExitLimits.insert({Query, EL}); 6599 return EL; 6600 } 6601 6602 ScalarEvolution::ExitLimit 6603 ScalarEvolution::computeExitLimitImpl(const Loop *L, BasicBlock *ExitingBlock, 6604 bool AllowPredicates) { 6605 // Okay, we've chosen an exiting block. See what condition causes us to exit 6606 // at this block and remember the exit block and whether all other targets 6607 // lead to the loop header. 6608 bool MustExecuteLoopHeader = true; 6609 BasicBlock *Exit = nullptr; 6610 for (auto *SBB : successors(ExitingBlock)) 6611 if (!L->contains(SBB)) { 6612 if (Exit) // Multiple exit successors. 6613 return getCouldNotCompute(); 6614 Exit = SBB; 6615 } else if (SBB != L->getHeader()) { 6616 MustExecuteLoopHeader = false; 6617 } 6618 6619 // At this point, we know we have a conditional branch that determines whether 6620 // the loop is exited. However, we don't know if the branch is executed each 6621 // time through the loop. If not, then the execution count of the branch will 6622 // not be equal to the trip count of the loop. 6623 // 6624 // Currently we check for this by checking to see if the Exit branch goes to 6625 // the loop header. If so, we know it will always execute the same number of 6626 // times as the loop. We also handle the case where the exit block *is* the 6627 // loop header. This is common for un-rotated loops. 6628 // 6629 // If both of those tests fail, walk up the unique predecessor chain to the 6630 // header, stopping if there is an edge that doesn't exit the loop. If the 6631 // header is reached, the execution count of the branch will be equal to the 6632 // trip count of the loop. 6633 // 6634 // More extensive analysis could be done to handle more cases here. 6635 // 6636 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6637 // The simple checks failed, try climbing the unique predecessor chain 6638 // up to the header. 6639 bool Ok = false; 6640 for (BasicBlock *BB = ExitingBlock; BB; ) { 6641 BasicBlock *Pred = BB->getUniquePredecessor(); 6642 if (!Pred) 6643 return getCouldNotCompute(); 6644 TerminatorInst *PredTerm = Pred->getTerminator(); 6645 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6646 if (PredSucc == BB) 6647 continue; 6648 // If the predecessor has a successor that isn't BB and isn't 6649 // outside the loop, assume the worst. 6650 if (L->contains(PredSucc)) 6651 return getCouldNotCompute(); 6652 } 6653 if (Pred == L->getHeader()) { 6654 Ok = true; 6655 break; 6656 } 6657 BB = Pred; 6658 } 6659 if (!Ok) 6660 return getCouldNotCompute(); 6661 } 6662 6663 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6664 TerminatorInst *Term = ExitingBlock->getTerminator(); 6665 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6666 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6667 // Proceed to the next level to examine the exit condition expression. 6668 return computeExitLimitFromCond( 6669 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6670 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6671 } 6672 6673 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6674 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6675 /*ControlsExit=*/IsOnlyExit); 6676 6677 return getCouldNotCompute(); 6678 } 6679 6680 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6681 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6682 bool ControlsExit, bool AllowPredicates) { 6683 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6684 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6685 ControlsExit, AllowPredicates); 6686 } 6687 6688 Optional<ScalarEvolution::ExitLimit> 6689 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6690 BasicBlock *TBB, BasicBlock *FBB, 6691 bool ControlsExit, bool AllowPredicates) { 6692 (void)this->L; 6693 (void)this->TBB; 6694 (void)this->FBB; 6695 (void)this->AllowPredicates; 6696 6697 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6698 this->AllowPredicates == AllowPredicates && 6699 "Variance in assumed invariant key components!"); 6700 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6701 if (Itr == TripCountMap.end()) 6702 return None; 6703 return Itr->second; 6704 } 6705 6706 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6707 BasicBlock *TBB, BasicBlock *FBB, 6708 bool ControlsExit, 6709 bool AllowPredicates, 6710 const ExitLimit &EL) { 6711 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6712 this->AllowPredicates == AllowPredicates && 6713 "Variance in assumed invariant key components!"); 6714 6715 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6716 assert(InsertResult.second && "Expected successful insertion!"); 6717 (void)InsertResult; 6718 } 6719 6720 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6721 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6722 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6723 6724 if (auto MaybeEL = 6725 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6726 return *MaybeEL; 6727 6728 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6729 ControlsExit, AllowPredicates); 6730 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6731 return EL; 6732 } 6733 6734 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6735 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6736 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6737 // Check if the controlling expression for this loop is an And or Or. 6738 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6739 if (BO->getOpcode() == Instruction::And) { 6740 // Recurse on the operands of the and. 6741 bool EitherMayExit = L->contains(TBB); 6742 ExitLimit EL0 = computeExitLimitFromCondCached( 6743 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6744 AllowPredicates); 6745 ExitLimit EL1 = computeExitLimitFromCondCached( 6746 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6747 AllowPredicates); 6748 const SCEV *BECount = getCouldNotCompute(); 6749 const SCEV *MaxBECount = getCouldNotCompute(); 6750 if (EitherMayExit) { 6751 // Both conditions must be true for the loop to continue executing. 6752 // Choose the less conservative count. 6753 if (EL0.ExactNotTaken == getCouldNotCompute() || 6754 EL1.ExactNotTaken == getCouldNotCompute()) 6755 BECount = getCouldNotCompute(); 6756 else 6757 BECount = 6758 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6759 if (EL0.MaxNotTaken == getCouldNotCompute()) 6760 MaxBECount = EL1.MaxNotTaken; 6761 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6762 MaxBECount = EL0.MaxNotTaken; 6763 else 6764 MaxBECount = 6765 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6766 } else { 6767 // Both conditions must be true at the same time for the loop to exit. 6768 // For now, be conservative. 6769 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6770 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6771 MaxBECount = EL0.MaxNotTaken; 6772 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6773 BECount = EL0.ExactNotTaken; 6774 } 6775 6776 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6777 // to be more aggressive when computing BECount than when computing 6778 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6779 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6780 // to not. 6781 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6782 !isa<SCEVCouldNotCompute>(BECount)) 6783 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 6784 6785 return ExitLimit(BECount, MaxBECount, false, 6786 {&EL0.Predicates, &EL1.Predicates}); 6787 } 6788 if (BO->getOpcode() == Instruction::Or) { 6789 // Recurse on the operands of the or. 6790 bool EitherMayExit = L->contains(FBB); 6791 ExitLimit EL0 = computeExitLimitFromCondCached( 6792 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6793 AllowPredicates); 6794 ExitLimit EL1 = computeExitLimitFromCondCached( 6795 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6796 AllowPredicates); 6797 const SCEV *BECount = getCouldNotCompute(); 6798 const SCEV *MaxBECount = getCouldNotCompute(); 6799 if (EitherMayExit) { 6800 // Both conditions must be false for the loop to continue executing. 6801 // Choose the less conservative count. 6802 if (EL0.ExactNotTaken == getCouldNotCompute() || 6803 EL1.ExactNotTaken == getCouldNotCompute()) 6804 BECount = getCouldNotCompute(); 6805 else 6806 BECount = 6807 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6808 if (EL0.MaxNotTaken == getCouldNotCompute()) 6809 MaxBECount = EL1.MaxNotTaken; 6810 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6811 MaxBECount = EL0.MaxNotTaken; 6812 else 6813 MaxBECount = 6814 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6815 } else { 6816 // Both conditions must be false at the same time for the loop to exit. 6817 // For now, be conservative. 6818 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6819 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6820 MaxBECount = EL0.MaxNotTaken; 6821 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6822 BECount = EL0.ExactNotTaken; 6823 } 6824 6825 return ExitLimit(BECount, MaxBECount, false, 6826 {&EL0.Predicates, &EL1.Predicates}); 6827 } 6828 } 6829 6830 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6831 // Proceed to the next level to examine the icmp. 6832 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6833 ExitLimit EL = 6834 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6835 if (EL.hasFullInfo() || !AllowPredicates) 6836 return EL; 6837 6838 // Try again, but use SCEV predicates this time. 6839 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6840 /*AllowPredicates=*/true); 6841 } 6842 6843 // Check for a constant condition. These are normally stripped out by 6844 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6845 // preserve the CFG and is temporarily leaving constant conditions 6846 // in place. 6847 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6848 if (L->contains(FBB) == !CI->getZExtValue()) 6849 // The backedge is always taken. 6850 return getCouldNotCompute(); 6851 else 6852 // The backedge is never taken. 6853 return getZero(CI->getType()); 6854 } 6855 6856 // If it's not an integer or pointer comparison then compute it the hard way. 6857 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6858 } 6859 6860 ScalarEvolution::ExitLimit 6861 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6862 ICmpInst *ExitCond, 6863 BasicBlock *TBB, 6864 BasicBlock *FBB, 6865 bool ControlsExit, 6866 bool AllowPredicates) { 6867 // If the condition was exit on true, convert the condition to exit on false 6868 ICmpInst::Predicate Cond; 6869 if (!L->contains(FBB)) 6870 Cond = ExitCond->getPredicate(); 6871 else 6872 Cond = ExitCond->getInversePredicate(); 6873 6874 // Handle common loops like: for (X = "string"; *X; ++X) 6875 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6876 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6877 ExitLimit ItCnt = 6878 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6879 if (ItCnt.hasAnyInfo()) 6880 return ItCnt; 6881 } 6882 6883 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6884 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6885 6886 // Try to evaluate any dependencies out of the loop. 6887 LHS = getSCEVAtScope(LHS, L); 6888 RHS = getSCEVAtScope(RHS, L); 6889 6890 // At this point, we would like to compute how many iterations of the 6891 // loop the predicate will return true for these inputs. 6892 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6893 // If there is a loop-invariant, force it into the RHS. 6894 std::swap(LHS, RHS); 6895 Cond = ICmpInst::getSwappedPredicate(Cond); 6896 } 6897 6898 // Simplify the operands before analyzing them. 6899 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6900 6901 // If we have a comparison of a chrec against a constant, try to use value 6902 // ranges to answer this query. 6903 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6904 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6905 if (AddRec->getLoop() == L) { 6906 // Form the constant range. 6907 ConstantRange CompRange = 6908 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6909 6910 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6911 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6912 } 6913 6914 switch (Cond) { 6915 case ICmpInst::ICMP_NE: { // while (X != Y) 6916 // Convert to: while (X-Y != 0) 6917 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6918 AllowPredicates); 6919 if (EL.hasAnyInfo()) return EL; 6920 break; 6921 } 6922 case ICmpInst::ICMP_EQ: { // while (X == Y) 6923 // Convert to: while (X-Y == 0) 6924 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6925 if (EL.hasAnyInfo()) return EL; 6926 break; 6927 } 6928 case ICmpInst::ICMP_SLT: 6929 case ICmpInst::ICMP_ULT: { // while (X < Y) 6930 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6931 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6932 AllowPredicates); 6933 if (EL.hasAnyInfo()) return EL; 6934 break; 6935 } 6936 case ICmpInst::ICMP_SGT: 6937 case ICmpInst::ICMP_UGT: { // while (X > Y) 6938 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6939 ExitLimit EL = 6940 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6941 AllowPredicates); 6942 if (EL.hasAnyInfo()) return EL; 6943 break; 6944 } 6945 default: 6946 break; 6947 } 6948 6949 auto *ExhaustiveCount = 6950 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6951 6952 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6953 return ExhaustiveCount; 6954 6955 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6956 ExitCond->getOperand(1), L, Cond); 6957 } 6958 6959 ScalarEvolution::ExitLimit 6960 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6961 SwitchInst *Switch, 6962 BasicBlock *ExitingBlock, 6963 bool ControlsExit) { 6964 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6965 6966 // Give up if the exit is the default dest of a switch. 6967 if (Switch->getDefaultDest() == ExitingBlock) 6968 return getCouldNotCompute(); 6969 6970 assert(L->contains(Switch->getDefaultDest()) && 6971 "Default case must not exit the loop!"); 6972 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6973 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6974 6975 // while (X != Y) --> while (X-Y != 0) 6976 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6977 if (EL.hasAnyInfo()) 6978 return EL; 6979 6980 return getCouldNotCompute(); 6981 } 6982 6983 static ConstantInt * 6984 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6985 ScalarEvolution &SE) { 6986 const SCEV *InVal = SE.getConstant(C); 6987 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6988 assert(isa<SCEVConstant>(Val) && 6989 "Evaluation of SCEV at constant didn't fold correctly?"); 6990 return cast<SCEVConstant>(Val)->getValue(); 6991 } 6992 6993 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6994 /// compute the backedge execution count. 6995 ScalarEvolution::ExitLimit 6996 ScalarEvolution::computeLoadConstantCompareExitLimit( 6997 LoadInst *LI, 6998 Constant *RHS, 6999 const Loop *L, 7000 ICmpInst::Predicate predicate) { 7001 if (LI->isVolatile()) return getCouldNotCompute(); 7002 7003 // Check to see if the loaded pointer is a getelementptr of a global. 7004 // TODO: Use SCEV instead of manually grubbing with GEPs. 7005 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7006 if (!GEP) return getCouldNotCompute(); 7007 7008 // Make sure that it is really a constant global we are gepping, with an 7009 // initializer, and make sure the first IDX is really 0. 7010 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7011 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7012 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7013 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7014 return getCouldNotCompute(); 7015 7016 // Okay, we allow one non-constant index into the GEP instruction. 7017 Value *VarIdx = nullptr; 7018 std::vector<Constant*> Indexes; 7019 unsigned VarIdxNum = 0; 7020 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7021 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7022 Indexes.push_back(CI); 7023 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7024 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7025 VarIdx = GEP->getOperand(i); 7026 VarIdxNum = i-2; 7027 Indexes.push_back(nullptr); 7028 } 7029 7030 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7031 if (!VarIdx) 7032 return getCouldNotCompute(); 7033 7034 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7035 // Check to see if X is a loop variant variable value now. 7036 const SCEV *Idx = getSCEV(VarIdx); 7037 Idx = getSCEVAtScope(Idx, L); 7038 7039 // We can only recognize very limited forms of loop index expressions, in 7040 // particular, only affine AddRec's like {C1,+,C2}. 7041 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7042 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7043 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7044 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7045 return getCouldNotCompute(); 7046 7047 unsigned MaxSteps = MaxBruteForceIterations; 7048 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7049 ConstantInt *ItCst = ConstantInt::get( 7050 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7051 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7052 7053 // Form the GEP offset. 7054 Indexes[VarIdxNum] = Val; 7055 7056 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7057 Indexes); 7058 if (!Result) break; // Cannot compute! 7059 7060 // Evaluate the condition for this iteration. 7061 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7062 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7063 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7064 ++NumArrayLenItCounts; 7065 return getConstant(ItCst); // Found terminating iteration! 7066 } 7067 } 7068 return getCouldNotCompute(); 7069 } 7070 7071 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7072 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7073 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7074 if (!RHS) 7075 return getCouldNotCompute(); 7076 7077 const BasicBlock *Latch = L->getLoopLatch(); 7078 if (!Latch) 7079 return getCouldNotCompute(); 7080 7081 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7082 if (!Predecessor) 7083 return getCouldNotCompute(); 7084 7085 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7086 // Return LHS in OutLHS and shift_opt in OutOpCode. 7087 auto MatchPositiveShift = 7088 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7089 7090 using namespace PatternMatch; 7091 7092 ConstantInt *ShiftAmt; 7093 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7094 OutOpCode = Instruction::LShr; 7095 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7096 OutOpCode = Instruction::AShr; 7097 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7098 OutOpCode = Instruction::Shl; 7099 else 7100 return false; 7101 7102 return ShiftAmt->getValue().isStrictlyPositive(); 7103 }; 7104 7105 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7106 // 7107 // loop: 7108 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7109 // %iv.shifted = lshr i32 %iv, <positive constant> 7110 // 7111 // Return true on a successful match. Return the corresponding PHI node (%iv 7112 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7113 auto MatchShiftRecurrence = 7114 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7115 Optional<Instruction::BinaryOps> PostShiftOpCode; 7116 7117 { 7118 Instruction::BinaryOps OpC; 7119 Value *V; 7120 7121 // If we encounter a shift instruction, "peel off" the shift operation, 7122 // and remember that we did so. Later when we inspect %iv's backedge 7123 // value, we will make sure that the backedge value uses the same 7124 // operation. 7125 // 7126 // Note: the peeled shift operation does not have to be the same 7127 // instruction as the one feeding into the PHI's backedge value. We only 7128 // really care about it being the same *kind* of shift instruction -- 7129 // that's all that is required for our later inferences to hold. 7130 if (MatchPositiveShift(LHS, V, OpC)) { 7131 PostShiftOpCode = OpC; 7132 LHS = V; 7133 } 7134 } 7135 7136 PNOut = dyn_cast<PHINode>(LHS); 7137 if (!PNOut || PNOut->getParent() != L->getHeader()) 7138 return false; 7139 7140 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7141 Value *OpLHS; 7142 7143 return 7144 // The backedge value for the PHI node must be a shift by a positive 7145 // amount 7146 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7147 7148 // of the PHI node itself 7149 OpLHS == PNOut && 7150 7151 // and the kind of shift should be match the kind of shift we peeled 7152 // off, if any. 7153 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7154 }; 7155 7156 PHINode *PN; 7157 Instruction::BinaryOps OpCode; 7158 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7159 return getCouldNotCompute(); 7160 7161 const DataLayout &DL = getDataLayout(); 7162 7163 // The key rationale for this optimization is that for some kinds of shift 7164 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7165 // within a finite number of iterations. If the condition guarding the 7166 // backedge (in the sense that the backedge is taken if the condition is true) 7167 // is false for the value the shift recurrence stabilizes to, then we know 7168 // that the backedge is taken only a finite number of times. 7169 7170 ConstantInt *StableValue = nullptr; 7171 switch (OpCode) { 7172 default: 7173 llvm_unreachable("Impossible case!"); 7174 7175 case Instruction::AShr: { 7176 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7177 // bitwidth(K) iterations. 7178 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7179 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7180 Predecessor->getTerminator(), &DT); 7181 auto *Ty = cast<IntegerType>(RHS->getType()); 7182 if (Known.isNonNegative()) 7183 StableValue = ConstantInt::get(Ty, 0); 7184 else if (Known.isNegative()) 7185 StableValue = ConstantInt::get(Ty, -1, true); 7186 else 7187 return getCouldNotCompute(); 7188 7189 break; 7190 } 7191 case Instruction::LShr: 7192 case Instruction::Shl: 7193 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7194 // stabilize to 0 in at most bitwidth(K) iterations. 7195 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7196 break; 7197 } 7198 7199 auto *Result = 7200 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7201 assert(Result->getType()->isIntegerTy(1) && 7202 "Otherwise cannot be an operand to a branch instruction"); 7203 7204 if (Result->isZeroValue()) { 7205 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7206 const SCEV *UpperBound = 7207 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7208 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7209 } 7210 7211 return getCouldNotCompute(); 7212 } 7213 7214 /// Return true if we can constant fold an instruction of the specified type, 7215 /// assuming that all operands were constants. 7216 static bool CanConstantFold(const Instruction *I) { 7217 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7218 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7219 isa<LoadInst>(I)) 7220 return true; 7221 7222 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7223 if (const Function *F = CI->getCalledFunction()) 7224 return canConstantFoldCallTo(CI, F); 7225 return false; 7226 } 7227 7228 /// Determine whether this instruction can constant evolve within this loop 7229 /// assuming its operands can all constant evolve. 7230 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7231 // An instruction outside of the loop can't be derived from a loop PHI. 7232 if (!L->contains(I)) return false; 7233 7234 if (isa<PHINode>(I)) { 7235 // We don't currently keep track of the control flow needed to evaluate 7236 // PHIs, so we cannot handle PHIs inside of loops. 7237 return L->getHeader() == I->getParent(); 7238 } 7239 7240 // If we won't be able to constant fold this expression even if the operands 7241 // are constants, bail early. 7242 return CanConstantFold(I); 7243 } 7244 7245 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7246 /// recursing through each instruction operand until reaching a loop header phi. 7247 static PHINode * 7248 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7249 DenseMap<Instruction *, PHINode *> &PHIMap, 7250 unsigned Depth) { 7251 if (Depth > MaxConstantEvolvingDepth) 7252 return nullptr; 7253 7254 // Otherwise, we can evaluate this instruction if all of its operands are 7255 // constant or derived from a PHI node themselves. 7256 PHINode *PHI = nullptr; 7257 for (Value *Op : UseInst->operands()) { 7258 if (isa<Constant>(Op)) continue; 7259 7260 Instruction *OpInst = dyn_cast<Instruction>(Op); 7261 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7262 7263 PHINode *P = dyn_cast<PHINode>(OpInst); 7264 if (!P) 7265 // If this operand is already visited, reuse the prior result. 7266 // We may have P != PHI if this is the deepest point at which the 7267 // inconsistent paths meet. 7268 P = PHIMap.lookup(OpInst); 7269 if (!P) { 7270 // Recurse and memoize the results, whether a phi is found or not. 7271 // This recursive call invalidates pointers into PHIMap. 7272 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7273 PHIMap[OpInst] = P; 7274 } 7275 if (!P) 7276 return nullptr; // Not evolving from PHI 7277 if (PHI && PHI != P) 7278 return nullptr; // Evolving from multiple different PHIs. 7279 PHI = P; 7280 } 7281 // This is a expression evolving from a constant PHI! 7282 return PHI; 7283 } 7284 7285 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7286 /// in the loop that V is derived from. We allow arbitrary operations along the 7287 /// way, but the operands of an operation must either be constants or a value 7288 /// derived from a constant PHI. If this expression does not fit with these 7289 /// constraints, return null. 7290 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7291 Instruction *I = dyn_cast<Instruction>(V); 7292 if (!I || !canConstantEvolve(I, L)) return nullptr; 7293 7294 if (PHINode *PN = dyn_cast<PHINode>(I)) 7295 return PN; 7296 7297 // Record non-constant instructions contained by the loop. 7298 DenseMap<Instruction *, PHINode *> PHIMap; 7299 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7300 } 7301 7302 /// EvaluateExpression - Given an expression that passes the 7303 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7304 /// in the loop has the value PHIVal. If we can't fold this expression for some 7305 /// reason, return null. 7306 static Constant *EvaluateExpression(Value *V, const Loop *L, 7307 DenseMap<Instruction *, Constant *> &Vals, 7308 const DataLayout &DL, 7309 const TargetLibraryInfo *TLI) { 7310 // Convenient constant check, but redundant for recursive calls. 7311 if (Constant *C = dyn_cast<Constant>(V)) return C; 7312 Instruction *I = dyn_cast<Instruction>(V); 7313 if (!I) return nullptr; 7314 7315 if (Constant *C = Vals.lookup(I)) return C; 7316 7317 // An instruction inside the loop depends on a value outside the loop that we 7318 // weren't given a mapping for, or a value such as a call inside the loop. 7319 if (!canConstantEvolve(I, L)) return nullptr; 7320 7321 // An unmapped PHI can be due to a branch or another loop inside this loop, 7322 // or due to this not being the initial iteration through a loop where we 7323 // couldn't compute the evolution of this particular PHI last time. 7324 if (isa<PHINode>(I)) return nullptr; 7325 7326 std::vector<Constant*> Operands(I->getNumOperands()); 7327 7328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7329 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7330 if (!Operand) { 7331 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7332 if (!Operands[i]) return nullptr; 7333 continue; 7334 } 7335 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7336 Vals[Operand] = C; 7337 if (!C) return nullptr; 7338 Operands[i] = C; 7339 } 7340 7341 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7342 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7343 Operands[1], DL, TLI); 7344 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7345 if (!LI->isVolatile()) 7346 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7347 } 7348 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7349 } 7350 7351 7352 // If every incoming value to PN except the one for BB is a specific Constant, 7353 // return that, else return nullptr. 7354 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7355 Constant *IncomingVal = nullptr; 7356 7357 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7358 if (PN->getIncomingBlock(i) == BB) 7359 continue; 7360 7361 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7362 if (!CurrentVal) 7363 return nullptr; 7364 7365 if (IncomingVal != CurrentVal) { 7366 if (IncomingVal) 7367 return nullptr; 7368 IncomingVal = CurrentVal; 7369 } 7370 } 7371 7372 return IncomingVal; 7373 } 7374 7375 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7376 /// in the header of its containing loop, we know the loop executes a 7377 /// constant number of times, and the PHI node is just a recurrence 7378 /// involving constants, fold it. 7379 Constant * 7380 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7381 const APInt &BEs, 7382 const Loop *L) { 7383 auto I = ConstantEvolutionLoopExitValue.find(PN); 7384 if (I != ConstantEvolutionLoopExitValue.end()) 7385 return I->second; 7386 7387 if (BEs.ugt(MaxBruteForceIterations)) 7388 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7389 7390 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7391 7392 DenseMap<Instruction *, Constant *> CurrentIterVals; 7393 BasicBlock *Header = L->getHeader(); 7394 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7395 7396 BasicBlock *Latch = L->getLoopLatch(); 7397 if (!Latch) 7398 return nullptr; 7399 7400 for (auto &I : *Header) { 7401 PHINode *PHI = dyn_cast<PHINode>(&I); 7402 if (!PHI) break; 7403 auto *StartCST = getOtherIncomingValue(PHI, Latch); 7404 if (!StartCST) continue; 7405 CurrentIterVals[PHI] = StartCST; 7406 } 7407 if (!CurrentIterVals.count(PN)) 7408 return RetVal = nullptr; 7409 7410 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7411 7412 // Execute the loop symbolically to determine the exit value. 7413 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7414 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7415 7416 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7417 unsigned IterationNum = 0; 7418 const DataLayout &DL = getDataLayout(); 7419 for (; ; ++IterationNum) { 7420 if (IterationNum == NumIterations) 7421 return RetVal = CurrentIterVals[PN]; // Got exit value! 7422 7423 // Compute the value of the PHIs for the next iteration. 7424 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7425 DenseMap<Instruction *, Constant *> NextIterVals; 7426 Constant *NextPHI = 7427 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7428 if (!NextPHI) 7429 return nullptr; // Couldn't evaluate! 7430 NextIterVals[PN] = NextPHI; 7431 7432 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7433 7434 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7435 // cease to be able to evaluate one of them or if they stop evolving, 7436 // because that doesn't necessarily prevent us from computing PN. 7437 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7438 for (const auto &I : CurrentIterVals) { 7439 PHINode *PHI = dyn_cast<PHINode>(I.first); 7440 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7441 PHIsToCompute.emplace_back(PHI, I.second); 7442 } 7443 // We use two distinct loops because EvaluateExpression may invalidate any 7444 // iterators into CurrentIterVals. 7445 for (const auto &I : PHIsToCompute) { 7446 PHINode *PHI = I.first; 7447 Constant *&NextPHI = NextIterVals[PHI]; 7448 if (!NextPHI) { // Not already computed. 7449 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7450 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7451 } 7452 if (NextPHI != I.second) 7453 StoppedEvolving = false; 7454 } 7455 7456 // If all entries in CurrentIterVals == NextIterVals then we can stop 7457 // iterating, the loop can't continue to change. 7458 if (StoppedEvolving) 7459 return RetVal = CurrentIterVals[PN]; 7460 7461 CurrentIterVals.swap(NextIterVals); 7462 } 7463 } 7464 7465 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7466 Value *Cond, 7467 bool ExitWhen) { 7468 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7469 if (!PN) return getCouldNotCompute(); 7470 7471 // If the loop is canonicalized, the PHI will have exactly two entries. 7472 // That's the only form we support here. 7473 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7474 7475 DenseMap<Instruction *, Constant *> CurrentIterVals; 7476 BasicBlock *Header = L->getHeader(); 7477 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7478 7479 BasicBlock *Latch = L->getLoopLatch(); 7480 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7481 7482 for (auto &I : *Header) { 7483 PHINode *PHI = dyn_cast<PHINode>(&I); 7484 if (!PHI) 7485 break; 7486 auto *StartCST = getOtherIncomingValue(PHI, Latch); 7487 if (!StartCST) continue; 7488 CurrentIterVals[PHI] = StartCST; 7489 } 7490 if (!CurrentIterVals.count(PN)) 7491 return getCouldNotCompute(); 7492 7493 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7494 // the loop symbolically to determine when the condition gets a value of 7495 // "ExitWhen". 7496 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7497 const DataLayout &DL = getDataLayout(); 7498 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7499 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7500 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7501 7502 // Couldn't symbolically evaluate. 7503 if (!CondVal) return getCouldNotCompute(); 7504 7505 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7506 ++NumBruteForceTripCountsComputed; 7507 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7508 } 7509 7510 // Update all the PHI nodes for the next iteration. 7511 DenseMap<Instruction *, Constant *> NextIterVals; 7512 7513 // Create a list of which PHIs we need to compute. We want to do this before 7514 // calling EvaluateExpression on them because that may invalidate iterators 7515 // into CurrentIterVals. 7516 SmallVector<PHINode *, 8> PHIsToCompute; 7517 for (const auto &I : CurrentIterVals) { 7518 PHINode *PHI = dyn_cast<PHINode>(I.first); 7519 if (!PHI || PHI->getParent() != Header) continue; 7520 PHIsToCompute.push_back(PHI); 7521 } 7522 for (PHINode *PHI : PHIsToCompute) { 7523 Constant *&NextPHI = NextIterVals[PHI]; 7524 if (NextPHI) continue; // Already computed! 7525 7526 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7527 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7528 } 7529 CurrentIterVals.swap(NextIterVals); 7530 } 7531 7532 // Too many iterations were needed to evaluate. 7533 return getCouldNotCompute(); 7534 } 7535 7536 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7537 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7538 ValuesAtScopes[V]; 7539 // Check to see if we've folded this expression at this loop before. 7540 for (auto &LS : Values) 7541 if (LS.first == L) 7542 return LS.second ? LS.second : V; 7543 7544 Values.emplace_back(L, nullptr); 7545 7546 // Otherwise compute it. 7547 const SCEV *C = computeSCEVAtScope(V, L); 7548 for (auto &LS : reverse(ValuesAtScopes[V])) 7549 if (LS.first == L) { 7550 LS.second = C; 7551 break; 7552 } 7553 return C; 7554 } 7555 7556 /// This builds up a Constant using the ConstantExpr interface. That way, we 7557 /// will return Constants for objects which aren't represented by a 7558 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7559 /// Returns NULL if the SCEV isn't representable as a Constant. 7560 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7561 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7562 case scCouldNotCompute: 7563 case scAddRecExpr: 7564 break; 7565 case scConstant: 7566 return cast<SCEVConstant>(V)->getValue(); 7567 case scUnknown: 7568 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7569 case scSignExtend: { 7570 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7571 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7572 return ConstantExpr::getSExt(CastOp, SS->getType()); 7573 break; 7574 } 7575 case scZeroExtend: { 7576 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7577 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7578 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7579 break; 7580 } 7581 case scTruncate: { 7582 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7583 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7584 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7585 break; 7586 } 7587 case scAddExpr: { 7588 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7589 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7590 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7591 unsigned AS = PTy->getAddressSpace(); 7592 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7593 C = ConstantExpr::getBitCast(C, DestPtrTy); 7594 } 7595 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7596 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7597 if (!C2) return nullptr; 7598 7599 // First pointer! 7600 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7601 unsigned AS = C2->getType()->getPointerAddressSpace(); 7602 std::swap(C, C2); 7603 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7604 // The offsets have been converted to bytes. We can add bytes to an 7605 // i8* by GEP with the byte count in the first index. 7606 C = ConstantExpr::getBitCast(C, DestPtrTy); 7607 } 7608 7609 // Don't bother trying to sum two pointers. We probably can't 7610 // statically compute a load that results from it anyway. 7611 if (C2->getType()->isPointerTy()) 7612 return nullptr; 7613 7614 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7615 if (PTy->getElementType()->isStructTy()) 7616 C2 = ConstantExpr::getIntegerCast( 7617 C2, Type::getInt32Ty(C->getContext()), true); 7618 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7619 } else 7620 C = ConstantExpr::getAdd(C, C2); 7621 } 7622 return C; 7623 } 7624 break; 7625 } 7626 case scMulExpr: { 7627 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7628 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7629 // Don't bother with pointers at all. 7630 if (C->getType()->isPointerTy()) return nullptr; 7631 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7632 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7633 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7634 C = ConstantExpr::getMul(C, C2); 7635 } 7636 return C; 7637 } 7638 break; 7639 } 7640 case scUDivExpr: { 7641 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7642 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7643 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7644 if (LHS->getType() == RHS->getType()) 7645 return ConstantExpr::getUDiv(LHS, RHS); 7646 break; 7647 } 7648 case scSMaxExpr: 7649 case scUMaxExpr: 7650 break; // TODO: smax, umax. 7651 } 7652 return nullptr; 7653 } 7654 7655 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7656 if (isa<SCEVConstant>(V)) return V; 7657 7658 // If this instruction is evolved from a constant-evolving PHI, compute the 7659 // exit value from the loop without using SCEVs. 7660 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7661 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7662 const Loop *LI = this->LI[I->getParent()]; 7663 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7664 if (PHINode *PN = dyn_cast<PHINode>(I)) 7665 if (PN->getParent() == LI->getHeader()) { 7666 // Okay, there is no closed form solution for the PHI node. Check 7667 // to see if the loop that contains it has a known backedge-taken 7668 // count. If so, we may be able to force computation of the exit 7669 // value. 7670 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7671 if (const SCEVConstant *BTCC = 7672 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7673 7674 // This trivial case can show up in some degenerate cases where 7675 // the incoming IR has not yet been fully simplified. 7676 if (BTCC->getValue()->isZero()) { 7677 Value *InitValue = nullptr; 7678 bool MultipleInitValues = false; 7679 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 7680 if (!LI->contains(PN->getIncomingBlock(i))) { 7681 if (!InitValue) 7682 InitValue = PN->getIncomingValue(i); 7683 else if (InitValue != PN->getIncomingValue(i)) { 7684 MultipleInitValues = true; 7685 break; 7686 } 7687 } 7688 if (!MultipleInitValues && InitValue) 7689 return getSCEV(InitValue); 7690 } 7691 } 7692 // Okay, we know how many times the containing loop executes. If 7693 // this is a constant evolving PHI node, get the final value at 7694 // the specified iteration number. 7695 Constant *RV = 7696 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7697 if (RV) return getSCEV(RV); 7698 } 7699 } 7700 7701 // Okay, this is an expression that we cannot symbolically evaluate 7702 // into a SCEV. Check to see if it's possible to symbolically evaluate 7703 // the arguments into constants, and if so, try to constant propagate the 7704 // result. This is particularly useful for computing loop exit values. 7705 if (CanConstantFold(I)) { 7706 SmallVector<Constant *, 4> Operands; 7707 bool MadeImprovement = false; 7708 for (Value *Op : I->operands()) { 7709 if (Constant *C = dyn_cast<Constant>(Op)) { 7710 Operands.push_back(C); 7711 continue; 7712 } 7713 7714 // If any of the operands is non-constant and if they are 7715 // non-integer and non-pointer, don't even try to analyze them 7716 // with scev techniques. 7717 if (!isSCEVable(Op->getType())) 7718 return V; 7719 7720 const SCEV *OrigV = getSCEV(Op); 7721 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7722 MadeImprovement |= OrigV != OpV; 7723 7724 Constant *C = BuildConstantFromSCEV(OpV); 7725 if (!C) return V; 7726 if (C->getType() != Op->getType()) 7727 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7728 Op->getType(), 7729 false), 7730 C, Op->getType()); 7731 Operands.push_back(C); 7732 } 7733 7734 // Check to see if getSCEVAtScope actually made an improvement. 7735 if (MadeImprovement) { 7736 Constant *C = nullptr; 7737 const DataLayout &DL = getDataLayout(); 7738 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7739 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7740 Operands[1], DL, &TLI); 7741 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7742 if (!LI->isVolatile()) 7743 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7744 } else 7745 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7746 if (!C) return V; 7747 return getSCEV(C); 7748 } 7749 } 7750 } 7751 7752 // This is some other type of SCEVUnknown, just return it. 7753 return V; 7754 } 7755 7756 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7757 // Avoid performing the look-up in the common case where the specified 7758 // expression has no loop-variant portions. 7759 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7760 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7761 if (OpAtScope != Comm->getOperand(i)) { 7762 // Okay, at least one of these operands is loop variant but might be 7763 // foldable. Build a new instance of the folded commutative expression. 7764 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7765 Comm->op_begin()+i); 7766 NewOps.push_back(OpAtScope); 7767 7768 for (++i; i != e; ++i) { 7769 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7770 NewOps.push_back(OpAtScope); 7771 } 7772 if (isa<SCEVAddExpr>(Comm)) 7773 return getAddExpr(NewOps); 7774 if (isa<SCEVMulExpr>(Comm)) 7775 return getMulExpr(NewOps); 7776 if (isa<SCEVSMaxExpr>(Comm)) 7777 return getSMaxExpr(NewOps); 7778 if (isa<SCEVUMaxExpr>(Comm)) 7779 return getUMaxExpr(NewOps); 7780 llvm_unreachable("Unknown commutative SCEV type!"); 7781 } 7782 } 7783 // If we got here, all operands are loop invariant. 7784 return Comm; 7785 } 7786 7787 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7788 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7789 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7790 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7791 return Div; // must be loop invariant 7792 return getUDivExpr(LHS, RHS); 7793 } 7794 7795 // If this is a loop recurrence for a loop that does not contain L, then we 7796 // are dealing with the final value computed by the loop. 7797 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7798 // First, attempt to evaluate each operand. 7799 // Avoid performing the look-up in the common case where the specified 7800 // expression has no loop-variant portions. 7801 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7802 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7803 if (OpAtScope == AddRec->getOperand(i)) 7804 continue; 7805 7806 // Okay, at least one of these operands is loop variant but might be 7807 // foldable. Build a new instance of the folded commutative expression. 7808 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7809 AddRec->op_begin()+i); 7810 NewOps.push_back(OpAtScope); 7811 for (++i; i != e; ++i) 7812 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7813 7814 const SCEV *FoldedRec = 7815 getAddRecExpr(NewOps, AddRec->getLoop(), 7816 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7817 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7818 // The addrec may be folded to a nonrecurrence, for example, if the 7819 // induction variable is multiplied by zero after constant folding. Go 7820 // ahead and return the folded value. 7821 if (!AddRec) 7822 return FoldedRec; 7823 break; 7824 } 7825 7826 // If the scope is outside the addrec's loop, evaluate it by using the 7827 // loop exit value of the addrec. 7828 if (!AddRec->getLoop()->contains(L)) { 7829 // To evaluate this recurrence, we need to know how many times the AddRec 7830 // loop iterates. Compute this now. 7831 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7832 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7833 7834 // Then, evaluate the AddRec. 7835 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7836 } 7837 7838 return AddRec; 7839 } 7840 7841 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7842 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7843 if (Op == Cast->getOperand()) 7844 return Cast; // must be loop invariant 7845 return getZeroExtendExpr(Op, Cast->getType()); 7846 } 7847 7848 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7849 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7850 if (Op == Cast->getOperand()) 7851 return Cast; // must be loop invariant 7852 return getSignExtendExpr(Op, Cast->getType()); 7853 } 7854 7855 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7856 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7857 if (Op == Cast->getOperand()) 7858 return Cast; // must be loop invariant 7859 return getTruncateExpr(Op, Cast->getType()); 7860 } 7861 7862 llvm_unreachable("Unknown SCEV type!"); 7863 } 7864 7865 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7866 return getSCEVAtScope(getSCEV(V), L); 7867 } 7868 7869 /// Finds the minimum unsigned root of the following equation: 7870 /// 7871 /// A * X = B (mod N) 7872 /// 7873 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7874 /// A and B isn't important. 7875 /// 7876 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7877 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7878 ScalarEvolution &SE) { 7879 uint32_t BW = A.getBitWidth(); 7880 assert(BW == SE.getTypeSizeInBits(B->getType())); 7881 assert(A != 0 && "A must be non-zero."); 7882 7883 // 1. D = gcd(A, N) 7884 // 7885 // The gcd of A and N may have only one prime factor: 2. The number of 7886 // trailing zeros in A is its multiplicity 7887 uint32_t Mult2 = A.countTrailingZeros(); 7888 // D = 2^Mult2 7889 7890 // 2. Check if B is divisible by D. 7891 // 7892 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7893 // is not less than multiplicity of this prime factor for D. 7894 if (SE.GetMinTrailingZeros(B) < Mult2) 7895 return SE.getCouldNotCompute(); 7896 7897 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7898 // modulo (N / D). 7899 // 7900 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7901 // (N / D) in general. The inverse itself always fits into BW bits, though, 7902 // so we immediately truncate it. 7903 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7904 APInt Mod(BW + 1, 0); 7905 Mod.setBit(BW - Mult2); // Mod = N / D 7906 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7907 7908 // 4. Compute the minimum unsigned root of the equation: 7909 // I * (B / D) mod (N / D) 7910 // To simplify the computation, we factor out the divide by D: 7911 // (I * B mod N) / D 7912 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7913 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7914 } 7915 7916 /// Find the roots of the quadratic equation for the given quadratic chrec 7917 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7918 /// two SCEVCouldNotCompute objects. 7919 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7920 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7921 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7922 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7923 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7924 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7925 7926 // We currently can only solve this if the coefficients are constants. 7927 if (!LC || !MC || !NC) 7928 return None; 7929 7930 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7931 const APInt &L = LC->getAPInt(); 7932 const APInt &M = MC->getAPInt(); 7933 const APInt &N = NC->getAPInt(); 7934 APInt Two(BitWidth, 2); 7935 7936 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7937 7938 // The A coefficient is N/2 7939 APInt A = N.sdiv(Two); 7940 7941 // The B coefficient is M-N/2 7942 APInt B = M; 7943 B -= A; // A is the same as N/2. 7944 7945 // The C coefficient is L. 7946 const APInt& C = L; 7947 7948 // Compute the B^2-4ac term. 7949 APInt SqrtTerm = B; 7950 SqrtTerm *= B; 7951 SqrtTerm -= 4 * (A * C); 7952 7953 if (SqrtTerm.isNegative()) { 7954 // The loop is provably infinite. 7955 return None; 7956 } 7957 7958 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7959 // integer value or else APInt::sqrt() will assert. 7960 APInt SqrtVal = SqrtTerm.sqrt(); 7961 7962 // Compute the two solutions for the quadratic formula. 7963 // The divisions must be performed as signed divisions. 7964 APInt NegB = -std::move(B); 7965 APInt TwoA = std::move(A); 7966 TwoA <<= 1; 7967 if (TwoA.isNullValue()) 7968 return None; 7969 7970 LLVMContext &Context = SE.getContext(); 7971 7972 ConstantInt *Solution1 = 7973 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7974 ConstantInt *Solution2 = 7975 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7976 7977 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7978 cast<SCEVConstant>(SE.getConstant(Solution2))); 7979 } 7980 7981 ScalarEvolution::ExitLimit 7982 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7983 bool AllowPredicates) { 7984 7985 // This is only used for loops with a "x != y" exit test. The exit condition 7986 // is now expressed as a single expression, V = x-y. So the exit test is 7987 // effectively V != 0. We know and take advantage of the fact that this 7988 // expression only being used in a comparison by zero context. 7989 7990 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7991 // If the value is a constant 7992 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7993 // If the value is already zero, the branch will execute zero times. 7994 if (C->getValue()->isZero()) return C; 7995 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7996 } 7997 7998 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7999 if (!AddRec && AllowPredicates) 8000 // Try to make this an AddRec using runtime tests, in the first X 8001 // iterations of this loop, where X is the SCEV expression found by the 8002 // algorithm below. 8003 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8004 8005 if (!AddRec || AddRec->getLoop() != L) 8006 return getCouldNotCompute(); 8007 8008 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8009 // the quadratic equation to solve it. 8010 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8011 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8012 const SCEVConstant *R1 = Roots->first; 8013 const SCEVConstant *R2 = Roots->second; 8014 // Pick the smallest positive root value. 8015 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8016 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8017 if (!CB->getZExtValue()) 8018 std::swap(R1, R2); // R1 is the minimum root now. 8019 8020 // We can only use this value if the chrec ends up with an exact zero 8021 // value at this index. When solving for "X*X != 5", for example, we 8022 // should not accept a root of 2. 8023 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8024 if (Val->isZero()) 8025 // We found a quadratic root! 8026 return ExitLimit(R1, R1, false, Predicates); 8027 } 8028 } 8029 return getCouldNotCompute(); 8030 } 8031 8032 // Otherwise we can only handle this if it is affine. 8033 if (!AddRec->isAffine()) 8034 return getCouldNotCompute(); 8035 8036 // If this is an affine expression, the execution count of this branch is 8037 // the minimum unsigned root of the following equation: 8038 // 8039 // Start + Step*N = 0 (mod 2^BW) 8040 // 8041 // equivalent to: 8042 // 8043 // Step*N = -Start (mod 2^BW) 8044 // 8045 // where BW is the common bit width of Start and Step. 8046 8047 // Get the initial value for the loop. 8048 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8049 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8050 8051 // For now we handle only constant steps. 8052 // 8053 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8054 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8055 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8056 // We have not yet seen any such cases. 8057 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8058 if (!StepC || StepC->getValue()->isZero()) 8059 return getCouldNotCompute(); 8060 8061 // For positive steps (counting up until unsigned overflow): 8062 // N = -Start/Step (as unsigned) 8063 // For negative steps (counting down to zero): 8064 // N = Start/-Step 8065 // First compute the unsigned distance from zero in the direction of Step. 8066 bool CountDown = StepC->getAPInt().isNegative(); 8067 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8068 8069 // Handle unitary steps, which cannot wraparound. 8070 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8071 // N = Distance (as unsigned) 8072 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8073 APInt MaxBECount = getUnsignedRangeMax(Distance); 8074 8075 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8076 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8077 // case, and see if we can improve the bound. 8078 // 8079 // Explicitly handling this here is necessary because getUnsignedRange 8080 // isn't context-sensitive; it doesn't know that we only care about the 8081 // range inside the loop. 8082 const SCEV *Zero = getZero(Distance->getType()); 8083 const SCEV *One = getOne(Distance->getType()); 8084 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8085 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8086 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8087 // as "unsigned_max(Distance + 1) - 1". 8088 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8089 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8090 } 8091 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8092 } 8093 8094 // If the condition controls loop exit (the loop exits only if the expression 8095 // is true) and the addition is no-wrap we can use unsigned divide to 8096 // compute the backedge count. In this case, the step may not divide the 8097 // distance, but we don't care because if the condition is "missed" the loop 8098 // will have undefined behavior due to wrapping. 8099 if (ControlsExit && AddRec->hasNoSelfWrap() && 8100 loopHasNoAbnormalExits(AddRec->getLoop())) { 8101 const SCEV *Exact = 8102 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8103 const SCEV *Max = 8104 Exact == getCouldNotCompute() 8105 ? Exact 8106 : getConstant(getUnsignedRangeMax(Exact)); 8107 return ExitLimit(Exact, Max, false, Predicates); 8108 } 8109 8110 // Solve the general equation. 8111 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8112 getNegativeSCEV(Start), *this); 8113 const SCEV *M = E == getCouldNotCompute() 8114 ? E 8115 : getConstant(getUnsignedRangeMax(E)); 8116 return ExitLimit(E, M, false, Predicates); 8117 } 8118 8119 ScalarEvolution::ExitLimit 8120 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8121 // Loops that look like: while (X == 0) are very strange indeed. We don't 8122 // handle them yet except for the trivial case. This could be expanded in the 8123 // future as needed. 8124 8125 // If the value is a constant, check to see if it is known to be non-zero 8126 // already. If so, the backedge will execute zero times. 8127 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8128 if (!C->getValue()->isZero()) 8129 return getZero(C->getType()); 8130 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8131 } 8132 8133 // We could implement others, but I really doubt anyone writes loops like 8134 // this, and if they did, they would already be constant folded. 8135 return getCouldNotCompute(); 8136 } 8137 8138 std::pair<BasicBlock *, BasicBlock *> 8139 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8140 // If the block has a unique predecessor, then there is no path from the 8141 // predecessor to the block that does not go through the direct edge 8142 // from the predecessor to the block. 8143 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8144 return {Pred, BB}; 8145 8146 // A loop's header is defined to be a block that dominates the loop. 8147 // If the header has a unique predecessor outside the loop, it must be 8148 // a block that has exactly one successor that can reach the loop. 8149 if (Loop *L = LI.getLoopFor(BB)) 8150 return {L->getLoopPredecessor(), L->getHeader()}; 8151 8152 return {nullptr, nullptr}; 8153 } 8154 8155 /// SCEV structural equivalence is usually sufficient for testing whether two 8156 /// expressions are equal, however for the purposes of looking for a condition 8157 /// guarding a loop, it can be useful to be a little more general, since a 8158 /// front-end may have replicated the controlling expression. 8159 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8160 // Quick check to see if they are the same SCEV. 8161 if (A == B) return true; 8162 8163 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8164 // Not all instructions that are "identical" compute the same value. For 8165 // instance, two distinct alloca instructions allocating the same type are 8166 // identical and do not read memory; but compute distinct values. 8167 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8168 }; 8169 8170 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8171 // two different instructions with the same value. Check for this case. 8172 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8173 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8174 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8175 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8176 if (ComputesEqualValues(AI, BI)) 8177 return true; 8178 8179 // Otherwise assume they may have a different value. 8180 return false; 8181 } 8182 8183 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8184 const SCEV *&LHS, const SCEV *&RHS, 8185 unsigned Depth) { 8186 bool Changed = false; 8187 8188 // If we hit the max recursion limit bail out. 8189 if (Depth >= 3) 8190 return false; 8191 8192 // Canonicalize a constant to the right side. 8193 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8194 // Check for both operands constant. 8195 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8196 if (ConstantExpr::getICmp(Pred, 8197 LHSC->getValue(), 8198 RHSC->getValue())->isNullValue()) 8199 goto trivially_false; 8200 else 8201 goto trivially_true; 8202 } 8203 // Otherwise swap the operands to put the constant on the right. 8204 std::swap(LHS, RHS); 8205 Pred = ICmpInst::getSwappedPredicate(Pred); 8206 Changed = true; 8207 } 8208 8209 // If we're comparing an addrec with a value which is loop-invariant in the 8210 // addrec's loop, put the addrec on the left. Also make a dominance check, 8211 // as both operands could be addrecs loop-invariant in each other's loop. 8212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8213 const Loop *L = AR->getLoop(); 8214 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8215 std::swap(LHS, RHS); 8216 Pred = ICmpInst::getSwappedPredicate(Pred); 8217 Changed = true; 8218 } 8219 } 8220 8221 // If there's a constant operand, canonicalize comparisons with boundary 8222 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8223 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8224 const APInt &RA = RC->getAPInt(); 8225 8226 bool SimplifiedByConstantRange = false; 8227 8228 if (!ICmpInst::isEquality(Pred)) { 8229 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8230 if (ExactCR.isFullSet()) 8231 goto trivially_true; 8232 else if (ExactCR.isEmptySet()) 8233 goto trivially_false; 8234 8235 APInt NewRHS; 8236 CmpInst::Predicate NewPred; 8237 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8238 ICmpInst::isEquality(NewPred)) { 8239 // We were able to convert an inequality to an equality. 8240 Pred = NewPred; 8241 RHS = getConstant(NewRHS); 8242 Changed = SimplifiedByConstantRange = true; 8243 } 8244 } 8245 8246 if (!SimplifiedByConstantRange) { 8247 switch (Pred) { 8248 default: 8249 break; 8250 case ICmpInst::ICMP_EQ: 8251 case ICmpInst::ICMP_NE: 8252 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8253 if (!RA) 8254 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8255 if (const SCEVMulExpr *ME = 8256 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8257 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8258 ME->getOperand(0)->isAllOnesValue()) { 8259 RHS = AE->getOperand(1); 8260 LHS = ME->getOperand(1); 8261 Changed = true; 8262 } 8263 break; 8264 8265 8266 // The "Should have been caught earlier!" messages refer to the fact 8267 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8268 // should have fired on the corresponding cases, and canonicalized the 8269 // check to trivially_true or trivially_false. 8270 8271 case ICmpInst::ICMP_UGE: 8272 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8273 Pred = ICmpInst::ICMP_UGT; 8274 RHS = getConstant(RA - 1); 8275 Changed = true; 8276 break; 8277 case ICmpInst::ICMP_ULE: 8278 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8279 Pred = ICmpInst::ICMP_ULT; 8280 RHS = getConstant(RA + 1); 8281 Changed = true; 8282 break; 8283 case ICmpInst::ICMP_SGE: 8284 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8285 Pred = ICmpInst::ICMP_SGT; 8286 RHS = getConstant(RA - 1); 8287 Changed = true; 8288 break; 8289 case ICmpInst::ICMP_SLE: 8290 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8291 Pred = ICmpInst::ICMP_SLT; 8292 RHS = getConstant(RA + 1); 8293 Changed = true; 8294 break; 8295 } 8296 } 8297 } 8298 8299 // Check for obvious equality. 8300 if (HasSameValue(LHS, RHS)) { 8301 if (ICmpInst::isTrueWhenEqual(Pred)) 8302 goto trivially_true; 8303 if (ICmpInst::isFalseWhenEqual(Pred)) 8304 goto trivially_false; 8305 } 8306 8307 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8308 // adding or subtracting 1 from one of the operands. 8309 switch (Pred) { 8310 case ICmpInst::ICMP_SLE: 8311 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8312 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8313 SCEV::FlagNSW); 8314 Pred = ICmpInst::ICMP_SLT; 8315 Changed = true; 8316 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8317 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8318 SCEV::FlagNSW); 8319 Pred = ICmpInst::ICMP_SLT; 8320 Changed = true; 8321 } 8322 break; 8323 case ICmpInst::ICMP_SGE: 8324 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8325 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8326 SCEV::FlagNSW); 8327 Pred = ICmpInst::ICMP_SGT; 8328 Changed = true; 8329 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8330 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8331 SCEV::FlagNSW); 8332 Pred = ICmpInst::ICMP_SGT; 8333 Changed = true; 8334 } 8335 break; 8336 case ICmpInst::ICMP_ULE: 8337 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8338 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8339 SCEV::FlagNUW); 8340 Pred = ICmpInst::ICMP_ULT; 8341 Changed = true; 8342 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8343 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8344 Pred = ICmpInst::ICMP_ULT; 8345 Changed = true; 8346 } 8347 break; 8348 case ICmpInst::ICMP_UGE: 8349 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8350 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8351 Pred = ICmpInst::ICMP_UGT; 8352 Changed = true; 8353 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8354 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8355 SCEV::FlagNUW); 8356 Pred = ICmpInst::ICMP_UGT; 8357 Changed = true; 8358 } 8359 break; 8360 default: 8361 break; 8362 } 8363 8364 // TODO: More simplifications are possible here. 8365 8366 // Recursively simplify until we either hit a recursion limit or nothing 8367 // changes. 8368 if (Changed) 8369 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8370 8371 return Changed; 8372 8373 trivially_true: 8374 // Return 0 == 0. 8375 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8376 Pred = ICmpInst::ICMP_EQ; 8377 return true; 8378 8379 trivially_false: 8380 // Return 0 != 0. 8381 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8382 Pred = ICmpInst::ICMP_NE; 8383 return true; 8384 } 8385 8386 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8387 return getSignedRangeMax(S).isNegative(); 8388 } 8389 8390 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8391 return getSignedRangeMin(S).isStrictlyPositive(); 8392 } 8393 8394 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8395 return !getSignedRangeMin(S).isNegative(); 8396 } 8397 8398 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8399 return !getSignedRangeMax(S).isStrictlyPositive(); 8400 } 8401 8402 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8403 return isKnownNegative(S) || isKnownPositive(S); 8404 } 8405 8406 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8407 const SCEV *LHS, const SCEV *RHS) { 8408 // Canonicalize the inputs first. 8409 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8410 8411 // If LHS or RHS is an addrec, check to see if the condition is true in 8412 // every iteration of the loop. 8413 // If LHS and RHS are both addrec, both conditions must be true in 8414 // every iteration of the loop. 8415 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8416 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8417 bool LeftGuarded = false; 8418 bool RightGuarded = false; 8419 if (LAR) { 8420 const Loop *L = LAR->getLoop(); 8421 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 8422 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 8423 if (!RAR) return true; 8424 LeftGuarded = true; 8425 } 8426 } 8427 if (RAR) { 8428 const Loop *L = RAR->getLoop(); 8429 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 8430 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 8431 if (!LAR) return true; 8432 RightGuarded = true; 8433 } 8434 } 8435 if (LeftGuarded && RightGuarded) 8436 return true; 8437 8438 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8439 return true; 8440 8441 // Otherwise see what can be done with known constant ranges. 8442 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 8443 } 8444 8445 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8446 ICmpInst::Predicate Pred, 8447 bool &Increasing) { 8448 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8449 8450 #ifndef NDEBUG 8451 // Verify an invariant: inverting the predicate should turn a monotonically 8452 // increasing change to a monotonically decreasing one, and vice versa. 8453 bool IncreasingSwapped; 8454 bool ResultSwapped = isMonotonicPredicateImpl( 8455 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8456 8457 assert(Result == ResultSwapped && "should be able to analyze both!"); 8458 if (ResultSwapped) 8459 assert(Increasing == !IncreasingSwapped && 8460 "monotonicity should flip as we flip the predicate"); 8461 #endif 8462 8463 return Result; 8464 } 8465 8466 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8467 ICmpInst::Predicate Pred, 8468 bool &Increasing) { 8469 8470 // A zero step value for LHS means the induction variable is essentially a 8471 // loop invariant value. We don't really depend on the predicate actually 8472 // flipping from false to true (for increasing predicates, and the other way 8473 // around for decreasing predicates), all we care about is that *if* the 8474 // predicate changes then it only changes from false to true. 8475 // 8476 // A zero step value in itself is not very useful, but there may be places 8477 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8478 // as general as possible. 8479 8480 switch (Pred) { 8481 default: 8482 return false; // Conservative answer 8483 8484 case ICmpInst::ICMP_UGT: 8485 case ICmpInst::ICMP_UGE: 8486 case ICmpInst::ICMP_ULT: 8487 case ICmpInst::ICMP_ULE: 8488 if (!LHS->hasNoUnsignedWrap()) 8489 return false; 8490 8491 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8492 return true; 8493 8494 case ICmpInst::ICMP_SGT: 8495 case ICmpInst::ICMP_SGE: 8496 case ICmpInst::ICMP_SLT: 8497 case ICmpInst::ICMP_SLE: { 8498 if (!LHS->hasNoSignedWrap()) 8499 return false; 8500 8501 const SCEV *Step = LHS->getStepRecurrence(*this); 8502 8503 if (isKnownNonNegative(Step)) { 8504 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8505 return true; 8506 } 8507 8508 if (isKnownNonPositive(Step)) { 8509 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8510 return true; 8511 } 8512 8513 return false; 8514 } 8515 8516 } 8517 8518 llvm_unreachable("switch has default clause!"); 8519 } 8520 8521 bool ScalarEvolution::isLoopInvariantPredicate( 8522 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8523 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8524 const SCEV *&InvariantRHS) { 8525 8526 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8527 if (!isLoopInvariant(RHS, L)) { 8528 if (!isLoopInvariant(LHS, L)) 8529 return false; 8530 8531 std::swap(LHS, RHS); 8532 Pred = ICmpInst::getSwappedPredicate(Pred); 8533 } 8534 8535 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8536 if (!ArLHS || ArLHS->getLoop() != L) 8537 return false; 8538 8539 bool Increasing; 8540 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8541 return false; 8542 8543 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8544 // true as the loop iterates, and the backedge is control dependent on 8545 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8546 // 8547 // * if the predicate was false in the first iteration then the predicate 8548 // is never evaluated again, since the loop exits without taking the 8549 // backedge. 8550 // * if the predicate was true in the first iteration then it will 8551 // continue to be true for all future iterations since it is 8552 // monotonically increasing. 8553 // 8554 // For both the above possibilities, we can replace the loop varying 8555 // predicate with its value on the first iteration of the loop (which is 8556 // loop invariant). 8557 // 8558 // A similar reasoning applies for a monotonically decreasing predicate, by 8559 // replacing true with false and false with true in the above two bullets. 8560 8561 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8562 8563 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8564 return false; 8565 8566 InvariantPred = Pred; 8567 InvariantLHS = ArLHS->getStart(); 8568 InvariantRHS = RHS; 8569 return true; 8570 } 8571 8572 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8573 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8574 if (HasSameValue(LHS, RHS)) 8575 return ICmpInst::isTrueWhenEqual(Pred); 8576 8577 // This code is split out from isKnownPredicate because it is called from 8578 // within isLoopEntryGuardedByCond. 8579 8580 auto CheckRanges = 8581 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8582 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8583 .contains(RangeLHS); 8584 }; 8585 8586 // The check at the top of the function catches the case where the values are 8587 // known to be equal. 8588 if (Pred == CmpInst::ICMP_EQ) 8589 return false; 8590 8591 if (Pred == CmpInst::ICMP_NE) 8592 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8593 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8594 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8595 8596 if (CmpInst::isSigned(Pred)) 8597 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8598 8599 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8600 } 8601 8602 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8603 const SCEV *LHS, 8604 const SCEV *RHS) { 8605 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8606 // Return Y via OutY. 8607 auto MatchBinaryAddToConst = 8608 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8609 SCEV::NoWrapFlags ExpectedFlags) { 8610 const SCEV *NonConstOp, *ConstOp; 8611 SCEV::NoWrapFlags FlagsPresent; 8612 8613 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8614 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8615 return false; 8616 8617 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8618 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8619 }; 8620 8621 APInt C; 8622 8623 switch (Pred) { 8624 default: 8625 break; 8626 8627 case ICmpInst::ICMP_SGE: 8628 std::swap(LHS, RHS); 8629 LLVM_FALLTHROUGH; 8630 case ICmpInst::ICMP_SLE: 8631 // X s<= (X + C)<nsw> if C >= 0 8632 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8633 return true; 8634 8635 // (X + C)<nsw> s<= X if C <= 0 8636 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8637 !C.isStrictlyPositive()) 8638 return true; 8639 break; 8640 8641 case ICmpInst::ICMP_SGT: 8642 std::swap(LHS, RHS); 8643 LLVM_FALLTHROUGH; 8644 case ICmpInst::ICMP_SLT: 8645 // X s< (X + C)<nsw> if C > 0 8646 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8647 C.isStrictlyPositive()) 8648 return true; 8649 8650 // (X + C)<nsw> s< X if C < 0 8651 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8652 return true; 8653 break; 8654 } 8655 8656 return false; 8657 } 8658 8659 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8660 const SCEV *LHS, 8661 const SCEV *RHS) { 8662 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8663 return false; 8664 8665 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8666 // the stack can result in exponential time complexity. 8667 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8668 8669 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8670 // 8671 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8672 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8673 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8674 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8675 // use isKnownPredicate later if needed. 8676 return isKnownNonNegative(RHS) && 8677 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8678 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8679 } 8680 8681 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8682 ICmpInst::Predicate Pred, 8683 const SCEV *LHS, const SCEV *RHS) { 8684 // No need to even try if we know the module has no guards. 8685 if (!HasGuards) 8686 return false; 8687 8688 return any_of(*BB, [&](Instruction &I) { 8689 using namespace llvm::PatternMatch; 8690 8691 Value *Condition; 8692 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8693 m_Value(Condition))) && 8694 isImpliedCond(Pred, LHS, RHS, Condition, false); 8695 }); 8696 } 8697 8698 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8699 /// protected by a conditional between LHS and RHS. This is used to 8700 /// to eliminate casts. 8701 bool 8702 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8703 ICmpInst::Predicate Pred, 8704 const SCEV *LHS, const SCEV *RHS) { 8705 // Interpret a null as meaning no loop, where there is obviously no guard 8706 // (interprocedural conditions notwithstanding). 8707 if (!L) return true; 8708 8709 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8710 return true; 8711 8712 BasicBlock *Latch = L->getLoopLatch(); 8713 if (!Latch) 8714 return false; 8715 8716 BranchInst *LoopContinuePredicate = 8717 dyn_cast<BranchInst>(Latch->getTerminator()); 8718 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8719 isImpliedCond(Pred, LHS, RHS, 8720 LoopContinuePredicate->getCondition(), 8721 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8722 return true; 8723 8724 // We don't want more than one activation of the following loops on the stack 8725 // -- that can lead to O(n!) time complexity. 8726 if (WalkingBEDominatingConds) 8727 return false; 8728 8729 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8730 8731 // See if we can exploit a trip count to prove the predicate. 8732 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8733 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8734 if (LatchBECount != getCouldNotCompute()) { 8735 // We know that Latch branches back to the loop header exactly 8736 // LatchBECount times. This means the backdege condition at Latch is 8737 // equivalent to "{0,+,1} u< LatchBECount". 8738 Type *Ty = LatchBECount->getType(); 8739 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8740 const SCEV *LoopCounter = 8741 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8742 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8743 LatchBECount)) 8744 return true; 8745 } 8746 8747 // Check conditions due to any @llvm.assume intrinsics. 8748 for (auto &AssumeVH : AC.assumptions()) { 8749 if (!AssumeVH) 8750 continue; 8751 auto *CI = cast<CallInst>(AssumeVH); 8752 if (!DT.dominates(CI, Latch->getTerminator())) 8753 continue; 8754 8755 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8756 return true; 8757 } 8758 8759 // If the loop is not reachable from the entry block, we risk running into an 8760 // infinite loop as we walk up into the dom tree. These loops do not matter 8761 // anyway, so we just return a conservative answer when we see them. 8762 if (!DT.isReachableFromEntry(L->getHeader())) 8763 return false; 8764 8765 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8766 return true; 8767 8768 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8769 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8770 assert(DTN && "should reach the loop header before reaching the root!"); 8771 8772 BasicBlock *BB = DTN->getBlock(); 8773 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8774 return true; 8775 8776 BasicBlock *PBB = BB->getSinglePredecessor(); 8777 if (!PBB) 8778 continue; 8779 8780 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8781 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8782 continue; 8783 8784 Value *Condition = ContinuePredicate->getCondition(); 8785 8786 // If we have an edge `E` within the loop body that dominates the only 8787 // latch, the condition guarding `E` also guards the backedge. This 8788 // reasoning works only for loops with a single latch. 8789 8790 BasicBlockEdge DominatingEdge(PBB, BB); 8791 if (DominatingEdge.isSingleEdge()) { 8792 // We're constructively (and conservatively) enumerating edges within the 8793 // loop body that dominate the latch. The dominator tree better agree 8794 // with us on this: 8795 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8796 8797 if (isImpliedCond(Pred, LHS, RHS, Condition, 8798 BB != ContinuePredicate->getSuccessor(0))) 8799 return true; 8800 } 8801 } 8802 8803 return false; 8804 } 8805 8806 bool 8807 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8808 ICmpInst::Predicate Pred, 8809 const SCEV *LHS, const SCEV *RHS) { 8810 // Interpret a null as meaning no loop, where there is obviously no guard 8811 // (interprocedural conditions notwithstanding). 8812 if (!L) return false; 8813 8814 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8815 return true; 8816 8817 // Starting at the loop predecessor, climb up the predecessor chain, as long 8818 // as there are predecessors that can be found that have unique successors 8819 // leading to the original header. 8820 for (std::pair<BasicBlock *, BasicBlock *> 8821 Pair(L->getLoopPredecessor(), L->getHeader()); 8822 Pair.first; 8823 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8824 8825 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8826 return true; 8827 8828 BranchInst *LoopEntryPredicate = 8829 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8830 if (!LoopEntryPredicate || 8831 LoopEntryPredicate->isUnconditional()) 8832 continue; 8833 8834 if (isImpliedCond(Pred, LHS, RHS, 8835 LoopEntryPredicate->getCondition(), 8836 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8837 return true; 8838 } 8839 8840 // Check conditions due to any @llvm.assume intrinsics. 8841 for (auto &AssumeVH : AC.assumptions()) { 8842 if (!AssumeVH) 8843 continue; 8844 auto *CI = cast<CallInst>(AssumeVH); 8845 if (!DT.dominates(CI, L->getHeader())) 8846 continue; 8847 8848 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8849 return true; 8850 } 8851 8852 return false; 8853 } 8854 8855 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8856 const SCEV *LHS, const SCEV *RHS, 8857 Value *FoundCondValue, 8858 bool Inverse) { 8859 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8860 return false; 8861 8862 auto ClearOnExit = 8863 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8864 8865 // Recursively handle And and Or conditions. 8866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8867 if (BO->getOpcode() == Instruction::And) { 8868 if (!Inverse) 8869 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8870 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8871 } else if (BO->getOpcode() == Instruction::Or) { 8872 if (Inverse) 8873 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8874 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8875 } 8876 } 8877 8878 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8879 if (!ICI) return false; 8880 8881 // Now that we found a conditional branch that dominates the loop or controls 8882 // the loop latch. Check to see if it is the comparison we are looking for. 8883 ICmpInst::Predicate FoundPred; 8884 if (Inverse) 8885 FoundPred = ICI->getInversePredicate(); 8886 else 8887 FoundPred = ICI->getPredicate(); 8888 8889 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8890 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8891 8892 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8893 } 8894 8895 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8896 const SCEV *RHS, 8897 ICmpInst::Predicate FoundPred, 8898 const SCEV *FoundLHS, 8899 const SCEV *FoundRHS) { 8900 // Balance the types. 8901 if (getTypeSizeInBits(LHS->getType()) < 8902 getTypeSizeInBits(FoundLHS->getType())) { 8903 if (CmpInst::isSigned(Pred)) { 8904 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8905 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8906 } else { 8907 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8908 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8909 } 8910 } else if (getTypeSizeInBits(LHS->getType()) > 8911 getTypeSizeInBits(FoundLHS->getType())) { 8912 if (CmpInst::isSigned(FoundPred)) { 8913 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8914 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8915 } else { 8916 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8917 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8918 } 8919 } 8920 8921 // Canonicalize the query to match the way instcombine will have 8922 // canonicalized the comparison. 8923 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8924 if (LHS == RHS) 8925 return CmpInst::isTrueWhenEqual(Pred); 8926 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8927 if (FoundLHS == FoundRHS) 8928 return CmpInst::isFalseWhenEqual(FoundPred); 8929 8930 // Check to see if we can make the LHS or RHS match. 8931 if (LHS == FoundRHS || RHS == FoundLHS) { 8932 if (isa<SCEVConstant>(RHS)) { 8933 std::swap(FoundLHS, FoundRHS); 8934 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8935 } else { 8936 std::swap(LHS, RHS); 8937 Pred = ICmpInst::getSwappedPredicate(Pred); 8938 } 8939 } 8940 8941 // Check whether the found predicate is the same as the desired predicate. 8942 if (FoundPred == Pred) 8943 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8944 8945 // Check whether swapping the found predicate makes it the same as the 8946 // desired predicate. 8947 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8948 if (isa<SCEVConstant>(RHS)) 8949 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8950 else 8951 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8952 RHS, LHS, FoundLHS, FoundRHS); 8953 } 8954 8955 // Unsigned comparison is the same as signed comparison when both the operands 8956 // are non-negative. 8957 if (CmpInst::isUnsigned(FoundPred) && 8958 CmpInst::getSignedPredicate(FoundPred) == Pred && 8959 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8960 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8961 8962 // Check if we can make progress by sharpening ranges. 8963 if (FoundPred == ICmpInst::ICMP_NE && 8964 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8965 8966 const SCEVConstant *C = nullptr; 8967 const SCEV *V = nullptr; 8968 8969 if (isa<SCEVConstant>(FoundLHS)) { 8970 C = cast<SCEVConstant>(FoundLHS); 8971 V = FoundRHS; 8972 } else { 8973 C = cast<SCEVConstant>(FoundRHS); 8974 V = FoundLHS; 8975 } 8976 8977 // The guarding predicate tells us that C != V. If the known range 8978 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8979 // range we consider has to correspond to same signedness as the 8980 // predicate we're interested in folding. 8981 8982 APInt Min = ICmpInst::isSigned(Pred) ? 8983 getSignedRangeMin(V) : getUnsignedRangeMin(V); 8984 8985 if (Min == C->getAPInt()) { 8986 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8987 // This is true even if (Min + 1) wraps around -- in case of 8988 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8989 8990 APInt SharperMin = Min + 1; 8991 8992 switch (Pred) { 8993 case ICmpInst::ICMP_SGE: 8994 case ICmpInst::ICMP_UGE: 8995 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8996 // RHS, we're done. 8997 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8998 getConstant(SharperMin))) 8999 return true; 9000 LLVM_FALLTHROUGH; 9001 9002 case ICmpInst::ICMP_SGT: 9003 case ICmpInst::ICMP_UGT: 9004 // We know from the range information that (V `Pred` Min || 9005 // V == Min). We know from the guarding condition that !(V 9006 // == Min). This gives us 9007 // 9008 // V `Pred` Min || V == Min && !(V == Min) 9009 // => V `Pred` Min 9010 // 9011 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9012 9013 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9014 return true; 9015 LLVM_FALLTHROUGH; 9016 9017 default: 9018 // No change 9019 break; 9020 } 9021 } 9022 } 9023 9024 // Check whether the actual condition is beyond sufficient. 9025 if (FoundPred == ICmpInst::ICMP_EQ) 9026 if (ICmpInst::isTrueWhenEqual(Pred)) 9027 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9028 return true; 9029 if (Pred == ICmpInst::ICMP_NE) 9030 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9031 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9032 return true; 9033 9034 // Otherwise assume the worst. 9035 return false; 9036 } 9037 9038 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9039 const SCEV *&L, const SCEV *&R, 9040 SCEV::NoWrapFlags &Flags) { 9041 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9042 if (!AE || AE->getNumOperands() != 2) 9043 return false; 9044 9045 L = AE->getOperand(0); 9046 R = AE->getOperand(1); 9047 Flags = AE->getNoWrapFlags(); 9048 return true; 9049 } 9050 9051 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9052 const SCEV *Less) { 9053 // We avoid subtracting expressions here because this function is usually 9054 // fairly deep in the call stack (i.e. is called many times). 9055 9056 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9057 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9058 const auto *MAR = cast<SCEVAddRecExpr>(More); 9059 9060 if (LAR->getLoop() != MAR->getLoop()) 9061 return None; 9062 9063 // We look at affine expressions only; not for correctness but to keep 9064 // getStepRecurrence cheap. 9065 if (!LAR->isAffine() || !MAR->isAffine()) 9066 return None; 9067 9068 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9069 return None; 9070 9071 Less = LAR->getStart(); 9072 More = MAR->getStart(); 9073 9074 // fall through 9075 } 9076 9077 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9078 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9079 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9080 return M - L; 9081 } 9082 9083 const SCEV *L, *R; 9084 SCEV::NoWrapFlags Flags; 9085 if (splitBinaryAdd(Less, L, R, Flags)) 9086 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9087 if (R == More) 9088 return -(LC->getAPInt()); 9089 9090 if (splitBinaryAdd(More, L, R, Flags)) 9091 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9092 if (R == Less) 9093 return LC->getAPInt(); 9094 9095 return None; 9096 } 9097 9098 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9099 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9100 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9101 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9102 return false; 9103 9104 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9105 if (!AddRecLHS) 9106 return false; 9107 9108 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9109 if (!AddRecFoundLHS) 9110 return false; 9111 9112 // We'd like to let SCEV reason about control dependencies, so we constrain 9113 // both the inequalities to be about add recurrences on the same loop. This 9114 // way we can use isLoopEntryGuardedByCond later. 9115 9116 const Loop *L = AddRecFoundLHS->getLoop(); 9117 if (L != AddRecLHS->getLoop()) 9118 return false; 9119 9120 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9121 // 9122 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9123 // ... (2) 9124 // 9125 // Informal proof for (2), assuming (1) [*]: 9126 // 9127 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9128 // 9129 // Then 9130 // 9131 // FoundLHS s< FoundRHS s< INT_MIN - C 9132 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9133 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9134 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9135 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9136 // <=> FoundLHS + C s< FoundRHS + C 9137 // 9138 // [*]: (1) can be proved by ruling out overflow. 9139 // 9140 // [**]: This can be proved by analyzing all the four possibilities: 9141 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9142 // (A s>= 0, B s>= 0). 9143 // 9144 // Note: 9145 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9146 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9147 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9148 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9149 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9150 // C)". 9151 9152 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9153 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9154 if (!LDiff || !RDiff || *LDiff != *RDiff) 9155 return false; 9156 9157 if (LDiff->isMinValue()) 9158 return true; 9159 9160 APInt FoundRHSLimit; 9161 9162 if (Pred == CmpInst::ICMP_ULT) { 9163 FoundRHSLimit = -(*RDiff); 9164 } else { 9165 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9166 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9167 } 9168 9169 // Try to prove (1) or (2), as needed. 9170 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9171 getConstant(FoundRHSLimit)); 9172 } 9173 9174 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9175 const SCEV *LHS, const SCEV *RHS, 9176 const SCEV *FoundLHS, 9177 const SCEV *FoundRHS) { 9178 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9179 return true; 9180 9181 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9182 return true; 9183 9184 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9185 FoundLHS, FoundRHS) || 9186 // ~x < ~y --> x > y 9187 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9188 getNotSCEV(FoundRHS), 9189 getNotSCEV(FoundLHS)); 9190 } 9191 9192 /// If Expr computes ~A, return A else return nullptr 9193 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9194 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9195 if (!Add || Add->getNumOperands() != 2 || 9196 !Add->getOperand(0)->isAllOnesValue()) 9197 return nullptr; 9198 9199 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9200 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9201 !AddRHS->getOperand(0)->isAllOnesValue()) 9202 return nullptr; 9203 9204 return AddRHS->getOperand(1); 9205 } 9206 9207 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9208 template<typename MaxExprType> 9209 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9210 const SCEV *Candidate) { 9211 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9212 if (!MaxExpr) return false; 9213 9214 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9215 } 9216 9217 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9218 template<typename MaxExprType> 9219 static bool IsMinConsistingOf(ScalarEvolution &SE, 9220 const SCEV *MaybeMinExpr, 9221 const SCEV *Candidate) { 9222 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9223 if (!MaybeMaxExpr) 9224 return false; 9225 9226 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9227 } 9228 9229 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9230 ICmpInst::Predicate Pred, 9231 const SCEV *LHS, const SCEV *RHS) { 9232 // If both sides are affine addrecs for the same loop, with equal 9233 // steps, and we know the recurrences don't wrap, then we only 9234 // need to check the predicate on the starting values. 9235 9236 if (!ICmpInst::isRelational(Pred)) 9237 return false; 9238 9239 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9240 if (!LAR) 9241 return false; 9242 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9243 if (!RAR) 9244 return false; 9245 if (LAR->getLoop() != RAR->getLoop()) 9246 return false; 9247 if (!LAR->isAffine() || !RAR->isAffine()) 9248 return false; 9249 9250 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9251 return false; 9252 9253 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9254 SCEV::FlagNSW : SCEV::FlagNUW; 9255 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9256 return false; 9257 9258 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9259 } 9260 9261 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9262 /// expression? 9263 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9264 ICmpInst::Predicate Pred, 9265 const SCEV *LHS, const SCEV *RHS) { 9266 switch (Pred) { 9267 default: 9268 return false; 9269 9270 case ICmpInst::ICMP_SGE: 9271 std::swap(LHS, RHS); 9272 LLVM_FALLTHROUGH; 9273 case ICmpInst::ICMP_SLE: 9274 return 9275 // min(A, ...) <= A 9276 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9277 // A <= max(A, ...) 9278 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9279 9280 case ICmpInst::ICMP_UGE: 9281 std::swap(LHS, RHS); 9282 LLVM_FALLTHROUGH; 9283 case ICmpInst::ICMP_ULE: 9284 return 9285 // min(A, ...) <= A 9286 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9287 // A <= max(A, ...) 9288 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9289 } 9290 9291 llvm_unreachable("covered switch fell through?!"); 9292 } 9293 9294 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9295 const SCEV *LHS, const SCEV *RHS, 9296 const SCEV *FoundLHS, 9297 const SCEV *FoundRHS, 9298 unsigned Depth) { 9299 assert(getTypeSizeInBits(LHS->getType()) == 9300 getTypeSizeInBits(RHS->getType()) && 9301 "LHS and RHS have different sizes?"); 9302 assert(getTypeSizeInBits(FoundLHS->getType()) == 9303 getTypeSizeInBits(FoundRHS->getType()) && 9304 "FoundLHS and FoundRHS have different sizes?"); 9305 // We want to avoid hurting the compile time with analysis of too big trees. 9306 if (Depth > MaxSCEVOperationsImplicationDepth) 9307 return false; 9308 // We only want to work with ICMP_SGT comparison so far. 9309 // TODO: Extend to ICMP_UGT? 9310 if (Pred == ICmpInst::ICMP_SLT) { 9311 Pred = ICmpInst::ICMP_SGT; 9312 std::swap(LHS, RHS); 9313 std::swap(FoundLHS, FoundRHS); 9314 } 9315 if (Pred != ICmpInst::ICMP_SGT) 9316 return false; 9317 9318 auto GetOpFromSExt = [&](const SCEV *S) { 9319 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9320 return Ext->getOperand(); 9321 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9322 // the constant in some cases. 9323 return S; 9324 }; 9325 9326 // Acquire values from extensions. 9327 auto *OrigFoundLHS = FoundLHS; 9328 LHS = GetOpFromSExt(LHS); 9329 FoundLHS = GetOpFromSExt(FoundLHS); 9330 9331 // Is the SGT predicate can be proved trivially or using the found context. 9332 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9333 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9334 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9335 FoundRHS, Depth + 1); 9336 }; 9337 9338 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9339 // We want to avoid creation of any new non-constant SCEV. Since we are 9340 // going to compare the operands to RHS, we should be certain that we don't 9341 // need any size extensions for this. So let's decline all cases when the 9342 // sizes of types of LHS and RHS do not match. 9343 // TODO: Maybe try to get RHS from sext to catch more cases? 9344 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9345 return false; 9346 9347 // Should not overflow. 9348 if (!LHSAddExpr->hasNoSignedWrap()) 9349 return false; 9350 9351 auto *LL = LHSAddExpr->getOperand(0); 9352 auto *LR = LHSAddExpr->getOperand(1); 9353 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9354 9355 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9356 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9357 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9358 }; 9359 // Try to prove the following rule: 9360 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9361 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9362 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9363 return true; 9364 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9365 Value *LL, *LR; 9366 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9367 9368 using namespace llvm::PatternMatch; 9369 9370 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9371 // Rules for division. 9372 // We are going to perform some comparisons with Denominator and its 9373 // derivative expressions. In general case, creating a SCEV for it may 9374 // lead to a complex analysis of the entire graph, and in particular it 9375 // can request trip count recalculation for the same loop. This would 9376 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9377 // this, we only want to create SCEVs that are constants in this section. 9378 // So we bail if Denominator is not a constant. 9379 if (!isa<ConstantInt>(LR)) 9380 return false; 9381 9382 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9383 9384 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9385 // then a SCEV for the numerator already exists and matches with FoundLHS. 9386 auto *Numerator = getExistingSCEV(LL); 9387 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9388 return false; 9389 9390 // Make sure that the numerator matches with FoundLHS and the denominator 9391 // is positive. 9392 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9393 return false; 9394 9395 auto *DTy = Denominator->getType(); 9396 auto *FRHSTy = FoundRHS->getType(); 9397 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9398 // One of types is a pointer and another one is not. We cannot extend 9399 // them properly to a wider type, so let us just reject this case. 9400 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9401 // to avoid this check. 9402 return false; 9403 9404 // Given that: 9405 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9406 auto *WTy = getWiderType(DTy, FRHSTy); 9407 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9408 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9409 9410 // Try to prove the following rule: 9411 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9412 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9413 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9414 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9415 if (isKnownNonPositive(RHS) && 9416 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9417 return true; 9418 9419 // Try to prove the following rule: 9420 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9421 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9422 // If we divide it by Denominator > 2, then: 9423 // 1. If FoundLHS is negative, then the result is 0. 9424 // 2. If FoundLHS is non-negative, then the result is non-negative. 9425 // Anyways, the result is non-negative. 9426 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9427 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9428 if (isKnownNegative(RHS) && 9429 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9430 return true; 9431 } 9432 } 9433 9434 return false; 9435 } 9436 9437 bool 9438 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 9439 const SCEV *LHS, const SCEV *RHS) { 9440 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9441 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9442 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9443 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9444 } 9445 9446 bool 9447 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9448 const SCEV *LHS, const SCEV *RHS, 9449 const SCEV *FoundLHS, 9450 const SCEV *FoundRHS) { 9451 switch (Pred) { 9452 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9453 case ICmpInst::ICMP_EQ: 9454 case ICmpInst::ICMP_NE: 9455 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9456 return true; 9457 break; 9458 case ICmpInst::ICMP_SLT: 9459 case ICmpInst::ICMP_SLE: 9460 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9461 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9462 return true; 9463 break; 9464 case ICmpInst::ICMP_SGT: 9465 case ICmpInst::ICMP_SGE: 9466 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9467 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9468 return true; 9469 break; 9470 case ICmpInst::ICMP_ULT: 9471 case ICmpInst::ICMP_ULE: 9472 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9473 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9474 return true; 9475 break; 9476 case ICmpInst::ICMP_UGT: 9477 case ICmpInst::ICMP_UGE: 9478 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9479 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9480 return true; 9481 break; 9482 } 9483 9484 // Maybe it can be proved via operations? 9485 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9486 return true; 9487 9488 return false; 9489 } 9490 9491 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9492 const SCEV *LHS, 9493 const SCEV *RHS, 9494 const SCEV *FoundLHS, 9495 const SCEV *FoundRHS) { 9496 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9497 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9498 // reduce the compile time impact of this optimization. 9499 return false; 9500 9501 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9502 if (!Addend) 9503 return false; 9504 9505 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9506 9507 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9508 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9509 ConstantRange FoundLHSRange = 9510 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9511 9512 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9513 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9514 9515 // We can also compute the range of values for `LHS` that satisfy the 9516 // consequent, "`LHS` `Pred` `RHS`": 9517 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9518 ConstantRange SatisfyingLHSRange = 9519 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9520 9521 // The antecedent implies the consequent if every value of `LHS` that 9522 // satisfies the antecedent also satisfies the consequent. 9523 return SatisfyingLHSRange.contains(LHSRange); 9524 } 9525 9526 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9527 bool IsSigned, bool NoWrap) { 9528 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9529 9530 if (NoWrap) return false; 9531 9532 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9533 const SCEV *One = getOne(Stride->getType()); 9534 9535 if (IsSigned) { 9536 APInt MaxRHS = getSignedRangeMax(RHS); 9537 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9538 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9539 9540 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9541 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9542 } 9543 9544 APInt MaxRHS = getUnsignedRangeMax(RHS); 9545 APInt MaxValue = APInt::getMaxValue(BitWidth); 9546 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9547 9548 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9549 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9550 } 9551 9552 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9553 bool IsSigned, bool NoWrap) { 9554 if (NoWrap) return false; 9555 9556 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9557 const SCEV *One = getOne(Stride->getType()); 9558 9559 if (IsSigned) { 9560 APInt MinRHS = getSignedRangeMin(RHS); 9561 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9562 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9563 9564 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9565 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9566 } 9567 9568 APInt MinRHS = getUnsignedRangeMin(RHS); 9569 APInt MinValue = APInt::getMinValue(BitWidth); 9570 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9571 9572 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9573 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9574 } 9575 9576 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9577 bool Equality) { 9578 const SCEV *One = getOne(Step->getType()); 9579 Delta = Equality ? getAddExpr(Delta, Step) 9580 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9581 return getUDivExpr(Delta, Step); 9582 } 9583 9584 ScalarEvolution::ExitLimit 9585 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9586 const Loop *L, bool IsSigned, 9587 bool ControlsExit, bool AllowPredicates) { 9588 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9589 // We handle only IV < Invariant 9590 if (!isLoopInvariant(RHS, L)) 9591 return getCouldNotCompute(); 9592 9593 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9594 bool PredicatedIV = false; 9595 9596 if (!IV && AllowPredicates) { 9597 // Try to make this an AddRec using runtime tests, in the first X 9598 // iterations of this loop, where X is the SCEV expression found by the 9599 // algorithm below. 9600 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9601 PredicatedIV = true; 9602 } 9603 9604 // Avoid weird loops 9605 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9606 return getCouldNotCompute(); 9607 9608 bool NoWrap = ControlsExit && 9609 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9610 9611 const SCEV *Stride = IV->getStepRecurrence(*this); 9612 9613 bool PositiveStride = isKnownPositive(Stride); 9614 9615 // Avoid negative or zero stride values. 9616 if (!PositiveStride) { 9617 // We can compute the correct backedge taken count for loops with unknown 9618 // strides if we can prove that the loop is not an infinite loop with side 9619 // effects. Here's the loop structure we are trying to handle - 9620 // 9621 // i = start 9622 // do { 9623 // A[i] = i; 9624 // i += s; 9625 // } while (i < end); 9626 // 9627 // The backedge taken count for such loops is evaluated as - 9628 // (max(end, start + stride) - start - 1) /u stride 9629 // 9630 // The additional preconditions that we need to check to prove correctness 9631 // of the above formula is as follows - 9632 // 9633 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9634 // NoWrap flag). 9635 // b) loop is single exit with no side effects. 9636 // 9637 // 9638 // Precondition a) implies that if the stride is negative, this is a single 9639 // trip loop. The backedge taken count formula reduces to zero in this case. 9640 // 9641 // Precondition b) implies that the unknown stride cannot be zero otherwise 9642 // we have UB. 9643 // 9644 // The positive stride case is the same as isKnownPositive(Stride) returning 9645 // true (original behavior of the function). 9646 // 9647 // We want to make sure that the stride is truly unknown as there are edge 9648 // cases where ScalarEvolution propagates no wrap flags to the 9649 // post-increment/decrement IV even though the increment/decrement operation 9650 // itself is wrapping. The computed backedge taken count may be wrong in 9651 // such cases. This is prevented by checking that the stride is not known to 9652 // be either positive or non-positive. For example, no wrap flags are 9653 // propagated to the post-increment IV of this loop with a trip count of 2 - 9654 // 9655 // unsigned char i; 9656 // for(i=127; i<128; i+=129) 9657 // A[i] = i; 9658 // 9659 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9660 !loopHasNoSideEffects(L)) 9661 return getCouldNotCompute(); 9662 } else if (!Stride->isOne() && 9663 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9664 // Avoid proven overflow cases: this will ensure that the backedge taken 9665 // count will not generate any unsigned overflow. Relaxed no-overflow 9666 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9667 // undefined behaviors like the case of C language. 9668 return getCouldNotCompute(); 9669 9670 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9671 : ICmpInst::ICMP_ULT; 9672 const SCEV *Start = IV->getStart(); 9673 const SCEV *End = RHS; 9674 // If the backedge is taken at least once, then it will be taken 9675 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9676 // is the LHS value of the less-than comparison the first time it is evaluated 9677 // and End is the RHS. 9678 const SCEV *BECountIfBackedgeTaken = 9679 computeBECount(getMinusSCEV(End, Start), Stride, false); 9680 // If the loop entry is guarded by the result of the backedge test of the 9681 // first loop iteration, then we know the backedge will be taken at least 9682 // once and so the backedge taken count is as above. If not then we use the 9683 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9684 // as if the backedge is taken at least once max(End,Start) is End and so the 9685 // result is as above, and if not max(End,Start) is Start so we get a backedge 9686 // count of zero. 9687 const SCEV *BECount; 9688 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9689 BECount = BECountIfBackedgeTaken; 9690 else { 9691 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9692 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9693 } 9694 9695 const SCEV *MaxBECount; 9696 bool MaxOrZero = false; 9697 if (isa<SCEVConstant>(BECount)) 9698 MaxBECount = BECount; 9699 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9700 // If we know exactly how many times the backedge will be taken if it's 9701 // taken at least once, then the backedge count will either be that or 9702 // zero. 9703 MaxBECount = BECountIfBackedgeTaken; 9704 MaxOrZero = true; 9705 } else { 9706 // Calculate the maximum backedge count based on the range of values 9707 // permitted by Start, End, and Stride. 9708 APInt MinStart = IsSigned ? getSignedRangeMin(Start) 9709 : getUnsignedRangeMin(Start); 9710 9711 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9712 9713 APInt StrideForMaxBECount; 9714 9715 if (PositiveStride) 9716 StrideForMaxBECount = 9717 IsSigned ? getSignedRangeMin(Stride) 9718 : getUnsignedRangeMin(Stride); 9719 else 9720 // Using a stride of 1 is safe when computing max backedge taken count for 9721 // a loop with unknown stride. 9722 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9723 9724 APInt Limit = 9725 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9726 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9727 9728 // Although End can be a MAX expression we estimate MaxEnd considering only 9729 // the case End = RHS. This is safe because in the other case (End - Start) 9730 // is zero, leading to a zero maximum backedge taken count. 9731 APInt MaxEnd = 9732 IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit) 9733 : APIntOps::umin(getUnsignedRangeMax(RHS), Limit); 9734 9735 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9736 getConstant(StrideForMaxBECount), false); 9737 } 9738 9739 if (isa<SCEVCouldNotCompute>(MaxBECount) && 9740 !isa<SCEVCouldNotCompute>(BECount)) 9741 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 9742 9743 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9744 } 9745 9746 ScalarEvolution::ExitLimit 9747 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9748 const Loop *L, bool IsSigned, 9749 bool ControlsExit, bool AllowPredicates) { 9750 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9751 // We handle only IV > Invariant 9752 if (!isLoopInvariant(RHS, L)) 9753 return getCouldNotCompute(); 9754 9755 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9756 if (!IV && AllowPredicates) 9757 // Try to make this an AddRec using runtime tests, in the first X 9758 // iterations of this loop, where X is the SCEV expression found by the 9759 // algorithm below. 9760 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9761 9762 // Avoid weird loops 9763 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9764 return getCouldNotCompute(); 9765 9766 bool NoWrap = ControlsExit && 9767 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9768 9769 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9770 9771 // Avoid negative or zero stride values 9772 if (!isKnownPositive(Stride)) 9773 return getCouldNotCompute(); 9774 9775 // Avoid proven overflow cases: this will ensure that the backedge taken count 9776 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9777 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9778 // behaviors like the case of C language. 9779 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9780 return getCouldNotCompute(); 9781 9782 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9783 : ICmpInst::ICMP_UGT; 9784 9785 const SCEV *Start = IV->getStart(); 9786 const SCEV *End = RHS; 9787 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9788 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9789 9790 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9791 9792 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 9793 : getUnsignedRangeMax(Start); 9794 9795 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 9796 : getUnsignedRangeMin(Stride); 9797 9798 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9799 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9800 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9801 9802 // Although End can be a MIN expression we estimate MinEnd considering only 9803 // the case End = RHS. This is safe because in the other case (Start - End) 9804 // is zero, leading to a zero maximum backedge taken count. 9805 APInt MinEnd = 9806 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 9807 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 9808 9809 9810 const SCEV *MaxBECount = getCouldNotCompute(); 9811 if (isa<SCEVConstant>(BECount)) 9812 MaxBECount = BECount; 9813 else 9814 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9815 getConstant(MinStride), false); 9816 9817 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9818 MaxBECount = BECount; 9819 9820 return ExitLimit(BECount, MaxBECount, false, Predicates); 9821 } 9822 9823 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9824 ScalarEvolution &SE) const { 9825 if (Range.isFullSet()) // Infinite loop. 9826 return SE.getCouldNotCompute(); 9827 9828 // If the start is a non-zero constant, shift the range to simplify things. 9829 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9830 if (!SC->getValue()->isZero()) { 9831 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9832 Operands[0] = SE.getZero(SC->getType()); 9833 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9834 getNoWrapFlags(FlagNW)); 9835 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9836 return ShiftedAddRec->getNumIterationsInRange( 9837 Range.subtract(SC->getAPInt()), SE); 9838 // This is strange and shouldn't happen. 9839 return SE.getCouldNotCompute(); 9840 } 9841 9842 // The only time we can solve this is when we have all constant indices. 9843 // Otherwise, we cannot determine the overflow conditions. 9844 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9845 return SE.getCouldNotCompute(); 9846 9847 // Okay at this point we know that all elements of the chrec are constants and 9848 // that the start element is zero. 9849 9850 // First check to see if the range contains zero. If not, the first 9851 // iteration exits. 9852 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9853 if (!Range.contains(APInt(BitWidth, 0))) 9854 return SE.getZero(getType()); 9855 9856 if (isAffine()) { 9857 // If this is an affine expression then we have this situation: 9858 // Solve {0,+,A} in Range === Ax in Range 9859 9860 // We know that zero is in the range. If A is positive then we know that 9861 // the upper value of the range must be the first possible exit value. 9862 // If A is negative then the lower of the range is the last possible loop 9863 // value. Also note that we already checked for a full range. 9864 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9865 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 9866 9867 // The exit value should be (End+A)/A. 9868 APInt ExitVal = (End + A).udiv(A); 9869 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9870 9871 // Evaluate at the exit value. If we really did fall out of the valid 9872 // range, then we computed our trip count, otherwise wrap around or other 9873 // things must have happened. 9874 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9875 if (Range.contains(Val->getValue())) 9876 return SE.getCouldNotCompute(); // Something strange happened 9877 9878 // Ensure that the previous value is in the range. This is a sanity check. 9879 assert(Range.contains( 9880 EvaluateConstantChrecAtConstant(this, 9881 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 9882 "Linear scev computation is off in a bad way!"); 9883 return SE.getConstant(ExitValue); 9884 } else if (isQuadratic()) { 9885 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9886 // quadratic equation to solve it. To do this, we must frame our problem in 9887 // terms of figuring out when zero is crossed, instead of when 9888 // Range.getUpper() is crossed. 9889 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9890 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9891 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9892 9893 // Next, solve the constructed addrec 9894 if (auto Roots = 9895 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9896 const SCEVConstant *R1 = Roots->first; 9897 const SCEVConstant *R2 = Roots->second; 9898 // Pick the smallest positive root value. 9899 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9900 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9901 if (!CB->getZExtValue()) 9902 std::swap(R1, R2); // R1 is the minimum root now. 9903 9904 // Make sure the root is not off by one. The returned iteration should 9905 // not be in the range, but the previous one should be. When solving 9906 // for "X*X < 5", for example, we should not return a root of 2. 9907 ConstantInt *R1Val = 9908 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9909 if (Range.contains(R1Val->getValue())) { 9910 // The next iteration must be out of the range... 9911 ConstantInt *NextVal = 9912 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9913 9914 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9915 if (!Range.contains(R1Val->getValue())) 9916 return SE.getConstant(NextVal); 9917 return SE.getCouldNotCompute(); // Something strange happened 9918 } 9919 9920 // If R1 was not in the range, then it is a good return value. Make 9921 // sure that R1-1 WAS in the range though, just in case. 9922 ConstantInt *NextVal = 9923 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9924 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9925 if (Range.contains(R1Val->getValue())) 9926 return R1; 9927 return SE.getCouldNotCompute(); // Something strange happened 9928 } 9929 } 9930 } 9931 9932 return SE.getCouldNotCompute(); 9933 } 9934 9935 // Return true when S contains at least an undef value. 9936 static inline bool containsUndefs(const SCEV *S) { 9937 return SCEVExprContains(S, [](const SCEV *S) { 9938 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9939 return isa<UndefValue>(SU->getValue()); 9940 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9941 return isa<UndefValue>(SC->getValue()); 9942 return false; 9943 }); 9944 } 9945 9946 namespace { 9947 9948 // Collect all steps of SCEV expressions. 9949 struct SCEVCollectStrides { 9950 ScalarEvolution &SE; 9951 SmallVectorImpl<const SCEV *> &Strides; 9952 9953 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9954 : SE(SE), Strides(S) {} 9955 9956 bool follow(const SCEV *S) { 9957 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9958 Strides.push_back(AR->getStepRecurrence(SE)); 9959 return true; 9960 } 9961 9962 bool isDone() const { return false; } 9963 }; 9964 9965 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9966 struct SCEVCollectTerms { 9967 SmallVectorImpl<const SCEV *> &Terms; 9968 9969 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 9970 9971 bool follow(const SCEV *S) { 9972 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9973 isa<SCEVSignExtendExpr>(S)) { 9974 if (!containsUndefs(S)) 9975 Terms.push_back(S); 9976 9977 // Stop recursion: once we collected a term, do not walk its operands. 9978 return false; 9979 } 9980 9981 // Keep looking. 9982 return true; 9983 } 9984 9985 bool isDone() const { return false; } 9986 }; 9987 9988 // Check if a SCEV contains an AddRecExpr. 9989 struct SCEVHasAddRec { 9990 bool &ContainsAddRec; 9991 9992 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9993 ContainsAddRec = false; 9994 } 9995 9996 bool follow(const SCEV *S) { 9997 if (isa<SCEVAddRecExpr>(S)) { 9998 ContainsAddRec = true; 9999 10000 // Stop recursion: once we collected a term, do not walk its operands. 10001 return false; 10002 } 10003 10004 // Keep looking. 10005 return true; 10006 } 10007 10008 bool isDone() const { return false; } 10009 }; 10010 10011 // Find factors that are multiplied with an expression that (possibly as a 10012 // subexpression) contains an AddRecExpr. In the expression: 10013 // 10014 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10015 // 10016 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10017 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10018 // parameters as they form a product with an induction variable. 10019 // 10020 // This collector expects all array size parameters to be in the same MulExpr. 10021 // It might be necessary to later add support for collecting parameters that are 10022 // spread over different nested MulExpr. 10023 struct SCEVCollectAddRecMultiplies { 10024 SmallVectorImpl<const SCEV *> &Terms; 10025 ScalarEvolution &SE; 10026 10027 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10028 : Terms(T), SE(SE) {} 10029 10030 bool follow(const SCEV *S) { 10031 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10032 bool HasAddRec = false; 10033 SmallVector<const SCEV *, 0> Operands; 10034 for (auto Op : Mul->operands()) { 10035 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10036 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10037 Operands.push_back(Op); 10038 } else if (Unknown) { 10039 HasAddRec = true; 10040 } else { 10041 bool ContainsAddRec; 10042 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10043 visitAll(Op, ContiansAddRec); 10044 HasAddRec |= ContainsAddRec; 10045 } 10046 } 10047 if (Operands.size() == 0) 10048 return true; 10049 10050 if (!HasAddRec) 10051 return false; 10052 10053 Terms.push_back(SE.getMulExpr(Operands)); 10054 // Stop recursion: once we collected a term, do not walk its operands. 10055 return false; 10056 } 10057 10058 // Keep looking. 10059 return true; 10060 } 10061 10062 bool isDone() const { return false; } 10063 }; 10064 10065 } // end anonymous namespace 10066 10067 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10068 /// two places: 10069 /// 1) The strides of AddRec expressions. 10070 /// 2) Unknowns that are multiplied with AddRec expressions. 10071 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10072 SmallVectorImpl<const SCEV *> &Terms) { 10073 SmallVector<const SCEV *, 4> Strides; 10074 SCEVCollectStrides StrideCollector(*this, Strides); 10075 visitAll(Expr, StrideCollector); 10076 10077 DEBUG({ 10078 dbgs() << "Strides:\n"; 10079 for (const SCEV *S : Strides) 10080 dbgs() << *S << "\n"; 10081 }); 10082 10083 for (const SCEV *S : Strides) { 10084 SCEVCollectTerms TermCollector(Terms); 10085 visitAll(S, TermCollector); 10086 } 10087 10088 DEBUG({ 10089 dbgs() << "Terms:\n"; 10090 for (const SCEV *T : Terms) 10091 dbgs() << *T << "\n"; 10092 }); 10093 10094 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10095 visitAll(Expr, MulCollector); 10096 } 10097 10098 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10099 SmallVectorImpl<const SCEV *> &Terms, 10100 SmallVectorImpl<const SCEV *> &Sizes) { 10101 int Last = Terms.size() - 1; 10102 const SCEV *Step = Terms[Last]; 10103 10104 // End of recursion. 10105 if (Last == 0) { 10106 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10107 SmallVector<const SCEV *, 2> Qs; 10108 for (const SCEV *Op : M->operands()) 10109 if (!isa<SCEVConstant>(Op)) 10110 Qs.push_back(Op); 10111 10112 Step = SE.getMulExpr(Qs); 10113 } 10114 10115 Sizes.push_back(Step); 10116 return true; 10117 } 10118 10119 for (const SCEV *&Term : Terms) { 10120 // Normalize the terms before the next call to findArrayDimensionsRec. 10121 const SCEV *Q, *R; 10122 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10123 10124 // Bail out when GCD does not evenly divide one of the terms. 10125 if (!R->isZero()) 10126 return false; 10127 10128 Term = Q; 10129 } 10130 10131 // Remove all SCEVConstants. 10132 Terms.erase( 10133 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10134 Terms.end()); 10135 10136 if (Terms.size() > 0) 10137 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10138 return false; 10139 10140 Sizes.push_back(Step); 10141 return true; 10142 } 10143 10144 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10145 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10146 for (const SCEV *T : Terms) 10147 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10148 return true; 10149 return false; 10150 } 10151 10152 // Return the number of product terms in S. 10153 static inline int numberOfTerms(const SCEV *S) { 10154 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10155 return Expr->getNumOperands(); 10156 return 1; 10157 } 10158 10159 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10160 if (isa<SCEVConstant>(T)) 10161 return nullptr; 10162 10163 if (isa<SCEVUnknown>(T)) 10164 return T; 10165 10166 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10167 SmallVector<const SCEV *, 2> Factors; 10168 for (const SCEV *Op : M->operands()) 10169 if (!isa<SCEVConstant>(Op)) 10170 Factors.push_back(Op); 10171 10172 return SE.getMulExpr(Factors); 10173 } 10174 10175 return T; 10176 } 10177 10178 /// Return the size of an element read or written by Inst. 10179 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10180 Type *Ty; 10181 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10182 Ty = Store->getValueOperand()->getType(); 10183 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10184 Ty = Load->getType(); 10185 else 10186 return nullptr; 10187 10188 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10189 return getSizeOfExpr(ETy, Ty); 10190 } 10191 10192 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10193 SmallVectorImpl<const SCEV *> &Sizes, 10194 const SCEV *ElementSize) { 10195 if (Terms.size() < 1 || !ElementSize) 10196 return; 10197 10198 // Early return when Terms do not contain parameters: we do not delinearize 10199 // non parametric SCEVs. 10200 if (!containsParameters(Terms)) 10201 return; 10202 10203 DEBUG({ 10204 dbgs() << "Terms:\n"; 10205 for (const SCEV *T : Terms) 10206 dbgs() << *T << "\n"; 10207 }); 10208 10209 // Remove duplicates. 10210 array_pod_sort(Terms.begin(), Terms.end()); 10211 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10212 10213 // Put larger terms first. 10214 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10215 return numberOfTerms(LHS) > numberOfTerms(RHS); 10216 }); 10217 10218 // Try to divide all terms by the element size. If term is not divisible by 10219 // element size, proceed with the original term. 10220 for (const SCEV *&Term : Terms) { 10221 const SCEV *Q, *R; 10222 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10223 if (!Q->isZero()) 10224 Term = Q; 10225 } 10226 10227 SmallVector<const SCEV *, 4> NewTerms; 10228 10229 // Remove constant factors. 10230 for (const SCEV *T : Terms) 10231 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10232 NewTerms.push_back(NewT); 10233 10234 DEBUG({ 10235 dbgs() << "Terms after sorting:\n"; 10236 for (const SCEV *T : NewTerms) 10237 dbgs() << *T << "\n"; 10238 }); 10239 10240 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10241 Sizes.clear(); 10242 return; 10243 } 10244 10245 // The last element to be pushed into Sizes is the size of an element. 10246 Sizes.push_back(ElementSize); 10247 10248 DEBUG({ 10249 dbgs() << "Sizes:\n"; 10250 for (const SCEV *S : Sizes) 10251 dbgs() << *S << "\n"; 10252 }); 10253 } 10254 10255 void ScalarEvolution::computeAccessFunctions( 10256 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10257 SmallVectorImpl<const SCEV *> &Sizes) { 10258 // Early exit in case this SCEV is not an affine multivariate function. 10259 if (Sizes.empty()) 10260 return; 10261 10262 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10263 if (!AR->isAffine()) 10264 return; 10265 10266 const SCEV *Res = Expr; 10267 int Last = Sizes.size() - 1; 10268 for (int i = Last; i >= 0; i--) { 10269 const SCEV *Q, *R; 10270 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10271 10272 DEBUG({ 10273 dbgs() << "Res: " << *Res << "\n"; 10274 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10275 dbgs() << "Res divided by Sizes[i]:\n"; 10276 dbgs() << "Quotient: " << *Q << "\n"; 10277 dbgs() << "Remainder: " << *R << "\n"; 10278 }); 10279 10280 Res = Q; 10281 10282 // Do not record the last subscript corresponding to the size of elements in 10283 // the array. 10284 if (i == Last) { 10285 10286 // Bail out if the remainder is too complex. 10287 if (isa<SCEVAddRecExpr>(R)) { 10288 Subscripts.clear(); 10289 Sizes.clear(); 10290 return; 10291 } 10292 10293 continue; 10294 } 10295 10296 // Record the access function for the current subscript. 10297 Subscripts.push_back(R); 10298 } 10299 10300 // Also push in last position the remainder of the last division: it will be 10301 // the access function of the innermost dimension. 10302 Subscripts.push_back(Res); 10303 10304 std::reverse(Subscripts.begin(), Subscripts.end()); 10305 10306 DEBUG({ 10307 dbgs() << "Subscripts:\n"; 10308 for (const SCEV *S : Subscripts) 10309 dbgs() << *S << "\n"; 10310 }); 10311 } 10312 10313 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10314 /// sizes of an array access. Returns the remainder of the delinearization that 10315 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10316 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10317 /// expressions in the stride and base of a SCEV corresponding to the 10318 /// computation of a GCD (greatest common divisor) of base and stride. When 10319 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10320 /// 10321 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10322 /// 10323 /// void foo(long n, long m, long o, double A[n][m][o]) { 10324 /// 10325 /// for (long i = 0; i < n; i++) 10326 /// for (long j = 0; j < m; j++) 10327 /// for (long k = 0; k < o; k++) 10328 /// A[i][j][k] = 1.0; 10329 /// } 10330 /// 10331 /// the delinearization input is the following AddRec SCEV: 10332 /// 10333 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10334 /// 10335 /// From this SCEV, we are able to say that the base offset of the access is %A 10336 /// because it appears as an offset that does not divide any of the strides in 10337 /// the loops: 10338 /// 10339 /// CHECK: Base offset: %A 10340 /// 10341 /// and then SCEV->delinearize determines the size of some of the dimensions of 10342 /// the array as these are the multiples by which the strides are happening: 10343 /// 10344 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10345 /// 10346 /// Note that the outermost dimension remains of UnknownSize because there are 10347 /// no strides that would help identifying the size of the last dimension: when 10348 /// the array has been statically allocated, one could compute the size of that 10349 /// dimension by dividing the overall size of the array by the size of the known 10350 /// dimensions: %m * %o * 8. 10351 /// 10352 /// Finally delinearize provides the access functions for the array reference 10353 /// that does correspond to A[i][j][k] of the above C testcase: 10354 /// 10355 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10356 /// 10357 /// The testcases are checking the output of a function pass: 10358 /// DelinearizationPass that walks through all loads and stores of a function 10359 /// asking for the SCEV of the memory access with respect to all enclosing 10360 /// loops, calling SCEV->delinearize on that and printing the results. 10361 void ScalarEvolution::delinearize(const SCEV *Expr, 10362 SmallVectorImpl<const SCEV *> &Subscripts, 10363 SmallVectorImpl<const SCEV *> &Sizes, 10364 const SCEV *ElementSize) { 10365 // First step: collect parametric terms. 10366 SmallVector<const SCEV *, 4> Terms; 10367 collectParametricTerms(Expr, Terms); 10368 10369 if (Terms.empty()) 10370 return; 10371 10372 // Second step: find subscript sizes. 10373 findArrayDimensions(Terms, Sizes, ElementSize); 10374 10375 if (Sizes.empty()) 10376 return; 10377 10378 // Third step: compute the access functions for each subscript. 10379 computeAccessFunctions(Expr, Subscripts, Sizes); 10380 10381 if (Subscripts.empty()) 10382 return; 10383 10384 DEBUG({ 10385 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10386 dbgs() << "ArrayDecl[UnknownSize]"; 10387 for (const SCEV *S : Sizes) 10388 dbgs() << "[" << *S << "]"; 10389 10390 dbgs() << "\nArrayRef"; 10391 for (const SCEV *S : Subscripts) 10392 dbgs() << "[" << *S << "]"; 10393 dbgs() << "\n"; 10394 }); 10395 } 10396 10397 //===----------------------------------------------------------------------===// 10398 // SCEVCallbackVH Class Implementation 10399 //===----------------------------------------------------------------------===// 10400 10401 void ScalarEvolution::SCEVCallbackVH::deleted() { 10402 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10403 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10404 SE->ConstantEvolutionLoopExitValue.erase(PN); 10405 SE->eraseValueFromMap(getValPtr()); 10406 // this now dangles! 10407 } 10408 10409 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10410 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10411 10412 // Forget all the expressions associated with users of the old value, 10413 // so that future queries will recompute the expressions using the new 10414 // value. 10415 Value *Old = getValPtr(); 10416 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10417 SmallPtrSet<User *, 8> Visited; 10418 while (!Worklist.empty()) { 10419 User *U = Worklist.pop_back_val(); 10420 // Deleting the Old value will cause this to dangle. Postpone 10421 // that until everything else is done. 10422 if (U == Old) 10423 continue; 10424 if (!Visited.insert(U).second) 10425 continue; 10426 if (PHINode *PN = dyn_cast<PHINode>(U)) 10427 SE->ConstantEvolutionLoopExitValue.erase(PN); 10428 SE->eraseValueFromMap(U); 10429 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10430 } 10431 // Delete the Old value. 10432 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10433 SE->ConstantEvolutionLoopExitValue.erase(PN); 10434 SE->eraseValueFromMap(Old); 10435 // this now dangles! 10436 } 10437 10438 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10439 : CallbackVH(V), SE(se) {} 10440 10441 //===----------------------------------------------------------------------===// 10442 // ScalarEvolution Class Implementation 10443 //===----------------------------------------------------------------------===// 10444 10445 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10446 AssumptionCache &AC, DominatorTree &DT, 10447 LoopInfo &LI) 10448 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10449 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 10450 LoopDispositions(64), BlockDispositions(64) { 10451 // To use guards for proving predicates, we need to scan every instruction in 10452 // relevant basic blocks, and not just terminators. Doing this is a waste of 10453 // time if the IR does not actually contain any calls to 10454 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10455 // 10456 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10457 // to _add_ guards to the module when there weren't any before, and wants 10458 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10459 // efficient in lieu of being smart in that rather obscure case. 10460 10461 auto *GuardDecl = F.getParent()->getFunction( 10462 Intrinsic::getName(Intrinsic::experimental_guard)); 10463 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10464 } 10465 10466 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10467 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10468 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10469 ValueExprMap(std::move(Arg.ValueExprMap)), 10470 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10471 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10472 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10473 PredicatedBackedgeTakenCounts( 10474 std::move(Arg.PredicatedBackedgeTakenCounts)), 10475 ExitLimits(std::move(Arg.ExitLimits)), 10476 ConstantEvolutionLoopExitValue( 10477 std::move(Arg.ConstantEvolutionLoopExitValue)), 10478 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10479 LoopDispositions(std::move(Arg.LoopDispositions)), 10480 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10481 BlockDispositions(std::move(Arg.BlockDispositions)), 10482 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10483 SignedRanges(std::move(Arg.SignedRanges)), 10484 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10485 UniquePreds(std::move(Arg.UniquePreds)), 10486 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10487 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10488 FirstUnknown(Arg.FirstUnknown) { 10489 Arg.FirstUnknown = nullptr; 10490 } 10491 10492 ScalarEvolution::~ScalarEvolution() { 10493 // Iterate through all the SCEVUnknown instances and call their 10494 // destructors, so that they release their references to their values. 10495 for (SCEVUnknown *U = FirstUnknown; U;) { 10496 SCEVUnknown *Tmp = U; 10497 U = U->Next; 10498 Tmp->~SCEVUnknown(); 10499 } 10500 FirstUnknown = nullptr; 10501 10502 ExprValueMap.clear(); 10503 ValueExprMap.clear(); 10504 HasRecMap.clear(); 10505 10506 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10507 // that a loop had multiple computable exits. 10508 for (auto &BTCI : BackedgeTakenCounts) 10509 BTCI.second.clear(); 10510 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10511 BTCI.second.clear(); 10512 10513 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10514 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10515 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10516 } 10517 10518 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10519 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10520 } 10521 10522 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10523 const Loop *L) { 10524 // Print all inner loops first 10525 for (Loop *I : *L) 10526 PrintLoopInfo(OS, SE, I); 10527 10528 OS << "Loop "; 10529 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10530 OS << ": "; 10531 10532 SmallVector<BasicBlock *, 8> ExitBlocks; 10533 L->getExitBlocks(ExitBlocks); 10534 if (ExitBlocks.size() != 1) 10535 OS << "<multiple exits> "; 10536 10537 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10538 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10539 } else { 10540 OS << "Unpredictable backedge-taken count. "; 10541 } 10542 10543 OS << "\n" 10544 "Loop "; 10545 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10546 OS << ": "; 10547 10548 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10549 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10550 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10551 OS << ", actual taken count either this or zero."; 10552 } else { 10553 OS << "Unpredictable max backedge-taken count. "; 10554 } 10555 10556 OS << "\n" 10557 "Loop "; 10558 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10559 OS << ": "; 10560 10561 SCEVUnionPredicate Pred; 10562 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10563 if (!isa<SCEVCouldNotCompute>(PBT)) { 10564 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10565 OS << " Predicates:\n"; 10566 Pred.print(OS, 4); 10567 } else { 10568 OS << "Unpredictable predicated backedge-taken count. "; 10569 } 10570 OS << "\n"; 10571 10572 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10573 OS << "Loop "; 10574 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10575 OS << ": "; 10576 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10577 } 10578 } 10579 10580 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 10581 switch (LD) { 10582 case ScalarEvolution::LoopVariant: 10583 return "Variant"; 10584 case ScalarEvolution::LoopInvariant: 10585 return "Invariant"; 10586 case ScalarEvolution::LoopComputable: 10587 return "Computable"; 10588 } 10589 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 10590 } 10591 10592 void ScalarEvolution::print(raw_ostream &OS) const { 10593 // ScalarEvolution's implementation of the print method is to print 10594 // out SCEV values of all instructions that are interesting. Doing 10595 // this potentially causes it to create new SCEV objects though, 10596 // which technically conflicts with the const qualifier. This isn't 10597 // observable from outside the class though, so casting away the 10598 // const isn't dangerous. 10599 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10600 10601 OS << "Classifying expressions for: "; 10602 F.printAsOperand(OS, /*PrintType=*/false); 10603 OS << "\n"; 10604 for (Instruction &I : instructions(F)) 10605 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 10606 OS << I << '\n'; 10607 OS << " --> "; 10608 const SCEV *SV = SE.getSCEV(&I); 10609 SV->print(OS); 10610 if (!isa<SCEVCouldNotCompute>(SV)) { 10611 OS << " U: "; 10612 SE.getUnsignedRange(SV).print(OS); 10613 OS << " S: "; 10614 SE.getSignedRange(SV).print(OS); 10615 } 10616 10617 const Loop *L = LI.getLoopFor(I.getParent()); 10618 10619 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10620 if (AtUse != SV) { 10621 OS << " --> "; 10622 AtUse->print(OS); 10623 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10624 OS << " U: "; 10625 SE.getUnsignedRange(AtUse).print(OS); 10626 OS << " S: "; 10627 SE.getSignedRange(AtUse).print(OS); 10628 } 10629 } 10630 10631 if (L) { 10632 OS << "\t\t" "Exits: "; 10633 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10634 if (!SE.isLoopInvariant(ExitValue, L)) { 10635 OS << "<<Unknown>>"; 10636 } else { 10637 OS << *ExitValue; 10638 } 10639 10640 bool First = true; 10641 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10642 if (First) { 10643 OS << "\t\t" "LoopDispositions: { "; 10644 First = false; 10645 } else { 10646 OS << ", "; 10647 } 10648 10649 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10650 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10651 } 10652 10653 for (auto *InnerL : depth_first(L)) { 10654 if (InnerL == L) 10655 continue; 10656 if (First) { 10657 OS << "\t\t" "LoopDispositions: { "; 10658 First = false; 10659 } else { 10660 OS << ", "; 10661 } 10662 10663 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10664 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10665 } 10666 10667 OS << " }"; 10668 } 10669 10670 OS << "\n"; 10671 } 10672 10673 OS << "Determining loop execution counts for: "; 10674 F.printAsOperand(OS, /*PrintType=*/false); 10675 OS << "\n"; 10676 for (Loop *I : LI) 10677 PrintLoopInfo(OS, &SE, I); 10678 } 10679 10680 ScalarEvolution::LoopDisposition 10681 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10682 auto &Values = LoopDispositions[S]; 10683 for (auto &V : Values) { 10684 if (V.getPointer() == L) 10685 return V.getInt(); 10686 } 10687 Values.emplace_back(L, LoopVariant); 10688 LoopDisposition D = computeLoopDisposition(S, L); 10689 auto &Values2 = LoopDispositions[S]; 10690 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10691 if (V.getPointer() == L) { 10692 V.setInt(D); 10693 break; 10694 } 10695 } 10696 return D; 10697 } 10698 10699 ScalarEvolution::LoopDisposition 10700 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10701 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10702 case scConstant: 10703 return LoopInvariant; 10704 case scTruncate: 10705 case scZeroExtend: 10706 case scSignExtend: 10707 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10708 case scAddRecExpr: { 10709 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10710 10711 // If L is the addrec's loop, it's computable. 10712 if (AR->getLoop() == L) 10713 return LoopComputable; 10714 10715 // Add recurrences are never invariant in the function-body (null loop). 10716 if (!L) 10717 return LoopVariant; 10718 10719 // This recurrence is variant w.r.t. L if L contains AR's loop. 10720 if (L->contains(AR->getLoop())) 10721 return LoopVariant; 10722 10723 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10724 if (AR->getLoop()->contains(L)) 10725 return LoopInvariant; 10726 10727 // This recurrence is variant w.r.t. L if any of its operands 10728 // are variant. 10729 for (auto *Op : AR->operands()) 10730 if (!isLoopInvariant(Op, L)) 10731 return LoopVariant; 10732 10733 // Otherwise it's loop-invariant. 10734 return LoopInvariant; 10735 } 10736 case scAddExpr: 10737 case scMulExpr: 10738 case scUMaxExpr: 10739 case scSMaxExpr: { 10740 bool HasVarying = false; 10741 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10742 LoopDisposition D = getLoopDisposition(Op, L); 10743 if (D == LoopVariant) 10744 return LoopVariant; 10745 if (D == LoopComputable) 10746 HasVarying = true; 10747 } 10748 return HasVarying ? LoopComputable : LoopInvariant; 10749 } 10750 case scUDivExpr: { 10751 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10752 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10753 if (LD == LoopVariant) 10754 return LoopVariant; 10755 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10756 if (RD == LoopVariant) 10757 return LoopVariant; 10758 return (LD == LoopInvariant && RD == LoopInvariant) ? 10759 LoopInvariant : LoopComputable; 10760 } 10761 case scUnknown: 10762 // All non-instruction values are loop invariant. All instructions are loop 10763 // invariant if they are not contained in the specified loop. 10764 // Instructions are never considered invariant in the function body 10765 // (null loop) because they are defined within the "loop". 10766 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10767 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10768 return LoopInvariant; 10769 case scCouldNotCompute: 10770 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10771 } 10772 llvm_unreachable("Unknown SCEV kind!"); 10773 } 10774 10775 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10776 return getLoopDisposition(S, L) == LoopInvariant; 10777 } 10778 10779 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10780 return getLoopDisposition(S, L) == LoopComputable; 10781 } 10782 10783 ScalarEvolution::BlockDisposition 10784 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10785 auto &Values = BlockDispositions[S]; 10786 for (auto &V : Values) { 10787 if (V.getPointer() == BB) 10788 return V.getInt(); 10789 } 10790 Values.emplace_back(BB, DoesNotDominateBlock); 10791 BlockDisposition D = computeBlockDisposition(S, BB); 10792 auto &Values2 = BlockDispositions[S]; 10793 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10794 if (V.getPointer() == BB) { 10795 V.setInt(D); 10796 break; 10797 } 10798 } 10799 return D; 10800 } 10801 10802 ScalarEvolution::BlockDisposition 10803 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10804 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10805 case scConstant: 10806 return ProperlyDominatesBlock; 10807 case scTruncate: 10808 case scZeroExtend: 10809 case scSignExtend: 10810 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10811 case scAddRecExpr: { 10812 // This uses a "dominates" query instead of "properly dominates" query 10813 // to test for proper dominance too, because the instruction which 10814 // produces the addrec's value is a PHI, and a PHI effectively properly 10815 // dominates its entire containing block. 10816 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10817 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10818 return DoesNotDominateBlock; 10819 10820 // Fall through into SCEVNAryExpr handling. 10821 LLVM_FALLTHROUGH; 10822 } 10823 case scAddExpr: 10824 case scMulExpr: 10825 case scUMaxExpr: 10826 case scSMaxExpr: { 10827 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10828 bool Proper = true; 10829 for (const SCEV *NAryOp : NAry->operands()) { 10830 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10831 if (D == DoesNotDominateBlock) 10832 return DoesNotDominateBlock; 10833 if (D == DominatesBlock) 10834 Proper = false; 10835 } 10836 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10837 } 10838 case scUDivExpr: { 10839 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10840 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10841 BlockDisposition LD = getBlockDisposition(LHS, BB); 10842 if (LD == DoesNotDominateBlock) 10843 return DoesNotDominateBlock; 10844 BlockDisposition RD = getBlockDisposition(RHS, BB); 10845 if (RD == DoesNotDominateBlock) 10846 return DoesNotDominateBlock; 10847 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10848 ProperlyDominatesBlock : DominatesBlock; 10849 } 10850 case scUnknown: 10851 if (Instruction *I = 10852 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10853 if (I->getParent() == BB) 10854 return DominatesBlock; 10855 if (DT.properlyDominates(I->getParent(), BB)) 10856 return ProperlyDominatesBlock; 10857 return DoesNotDominateBlock; 10858 } 10859 return ProperlyDominatesBlock; 10860 case scCouldNotCompute: 10861 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10862 } 10863 llvm_unreachable("Unknown SCEV kind!"); 10864 } 10865 10866 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10867 return getBlockDisposition(S, BB) >= DominatesBlock; 10868 } 10869 10870 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10871 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10872 } 10873 10874 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10875 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10876 } 10877 10878 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 10879 auto IsS = [&](const SCEV *X) { return S == X; }; 10880 auto ContainsS = [&](const SCEV *X) { 10881 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 10882 }; 10883 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 10884 } 10885 10886 void 10887 ScalarEvolution::forgetMemoizedResults(const SCEV *S, bool EraseExitLimit) { 10888 ValuesAtScopes.erase(S); 10889 LoopDispositions.erase(S); 10890 BlockDispositions.erase(S); 10891 UnsignedRanges.erase(S); 10892 SignedRanges.erase(S); 10893 ExprValueMap.erase(S); 10894 HasRecMap.erase(S); 10895 MinTrailingZerosCache.erase(S); 10896 10897 for (auto I = PredicatedSCEVRewrites.begin(); 10898 I != PredicatedSCEVRewrites.end();) { 10899 std::pair<const SCEV *, const Loop *> Entry = I->first; 10900 if (Entry.first == S) 10901 PredicatedSCEVRewrites.erase(I++); 10902 else 10903 ++I; 10904 } 10905 10906 auto RemoveSCEVFromBackedgeMap = 10907 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10908 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10909 BackedgeTakenInfo &BEInfo = I->second; 10910 if (BEInfo.hasOperand(S, this)) { 10911 BEInfo.clear(); 10912 Map.erase(I++); 10913 } else 10914 ++I; 10915 } 10916 }; 10917 10918 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10919 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10920 10921 // TODO: There is a suspicion that we only need to do it when there is a 10922 // SCEVUnknown somewhere inside S. Need to check this. 10923 if (EraseExitLimit) 10924 for (auto I = ExitLimits.begin(), E = ExitLimits.end(); I != E; ++I) 10925 if (I->second.hasOperand(S)) 10926 ExitLimits.erase(I); 10927 } 10928 10929 void ScalarEvolution::verify() const { 10930 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10931 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10932 10933 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 10934 10935 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 10936 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 10937 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 10938 10939 const SCEV *visitConstant(const SCEVConstant *Constant) { 10940 return SE.getConstant(Constant->getAPInt()); 10941 } 10942 10943 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10944 return SE.getUnknown(Expr->getValue()); 10945 } 10946 10947 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 10948 return SE.getCouldNotCompute(); 10949 } 10950 }; 10951 10952 SCEVMapper SCM(SE2); 10953 10954 while (!LoopStack.empty()) { 10955 auto *L = LoopStack.pop_back_val(); 10956 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 10957 10958 auto *CurBECount = SCM.visit( 10959 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 10960 auto *NewBECount = SE2.getBackedgeTakenCount(L); 10961 10962 if (CurBECount == SE2.getCouldNotCompute() || 10963 NewBECount == SE2.getCouldNotCompute()) { 10964 // NB! This situation is legal, but is very suspicious -- whatever pass 10965 // change the loop to make a trip count go from could not compute to 10966 // computable or vice-versa *should have* invalidated SCEV. However, we 10967 // choose not to assert here (for now) since we don't want false 10968 // positives. 10969 continue; 10970 } 10971 10972 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 10973 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 10974 // not propagate undef aggressively). This means we can (and do) fail 10975 // verification in cases where a transform makes the trip count of a loop 10976 // go from "undef" to "undef+1" (say). The transform is fine, since in 10977 // both cases the loop iterates "undef" times, but SCEV thinks we 10978 // increased the trip count of the loop by 1 incorrectly. 10979 continue; 10980 } 10981 10982 if (SE.getTypeSizeInBits(CurBECount->getType()) > 10983 SE.getTypeSizeInBits(NewBECount->getType())) 10984 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 10985 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 10986 SE.getTypeSizeInBits(NewBECount->getType())) 10987 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 10988 10989 auto *ConstantDelta = 10990 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 10991 10992 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 10993 dbgs() << "Trip Count Changed!\n"; 10994 dbgs() << "Old: " << *CurBECount << "\n"; 10995 dbgs() << "New: " << *NewBECount << "\n"; 10996 dbgs() << "Delta: " << *ConstantDelta << "\n"; 10997 std::abort(); 10998 } 10999 } 11000 } 11001 11002 bool ScalarEvolution::invalidate( 11003 Function &F, const PreservedAnalyses &PA, 11004 FunctionAnalysisManager::Invalidator &Inv) { 11005 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11006 // of its dependencies is invalidated. 11007 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11008 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11009 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11010 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11011 Inv.invalidate<LoopAnalysis>(F, PA); 11012 } 11013 11014 AnalysisKey ScalarEvolutionAnalysis::Key; 11015 11016 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11017 FunctionAnalysisManager &AM) { 11018 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11019 AM.getResult<AssumptionAnalysis>(F), 11020 AM.getResult<DominatorTreeAnalysis>(F), 11021 AM.getResult<LoopAnalysis>(F)); 11022 } 11023 11024 PreservedAnalyses 11025 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11026 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11027 return PreservedAnalyses::all(); 11028 } 11029 11030 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11031 "Scalar Evolution Analysis", false, true) 11032 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11033 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11034 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11035 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11036 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11037 "Scalar Evolution Analysis", false, true) 11038 11039 char ScalarEvolutionWrapperPass::ID = 0; 11040 11041 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11042 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11043 } 11044 11045 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11046 SE.reset(new ScalarEvolution( 11047 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11048 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11049 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11050 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11051 return false; 11052 } 11053 11054 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11055 11056 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11057 SE->print(OS); 11058 } 11059 11060 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11061 if (!VerifySCEV) 11062 return; 11063 11064 SE->verify(); 11065 } 11066 11067 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11068 AU.setPreservesAll(); 11069 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11070 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11071 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11072 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11073 } 11074 11075 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11076 const SCEV *RHS) { 11077 FoldingSetNodeID ID; 11078 assert(LHS->getType() == RHS->getType() && 11079 "Type mismatch between LHS and RHS"); 11080 // Unique this node based on the arguments 11081 ID.AddInteger(SCEVPredicate::P_Equal); 11082 ID.AddPointer(LHS); 11083 ID.AddPointer(RHS); 11084 void *IP = nullptr; 11085 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11086 return S; 11087 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11088 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11089 UniquePreds.InsertNode(Eq, IP); 11090 return Eq; 11091 } 11092 11093 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11094 const SCEVAddRecExpr *AR, 11095 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11096 FoldingSetNodeID ID; 11097 // Unique this node based on the arguments 11098 ID.AddInteger(SCEVPredicate::P_Wrap); 11099 ID.AddPointer(AR); 11100 ID.AddInteger(AddedFlags); 11101 void *IP = nullptr; 11102 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11103 return S; 11104 auto *OF = new (SCEVAllocator) 11105 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11106 UniquePreds.InsertNode(OF, IP); 11107 return OF; 11108 } 11109 11110 namespace { 11111 11112 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11113 public: 11114 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11115 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11116 SCEVUnionPredicate *Pred) 11117 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11118 11119 /// Rewrites \p S in the context of a loop L and the SCEV predication 11120 /// infrastructure. 11121 /// 11122 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11123 /// equivalences present in \p Pred. 11124 /// 11125 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11126 /// \p NewPreds such that the result will be an AddRecExpr. 11127 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11128 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11129 SCEVUnionPredicate *Pred) { 11130 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11131 return Rewriter.visit(S); 11132 } 11133 11134 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11135 if (Pred) { 11136 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11137 for (auto *Pred : ExprPreds) 11138 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11139 if (IPred->getLHS() == Expr) 11140 return IPred->getRHS(); 11141 } 11142 return convertToAddRecWithPreds(Expr); 11143 } 11144 11145 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11146 const SCEV *Operand = visit(Expr->getOperand()); 11147 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11148 if (AR && AR->getLoop() == L && AR->isAffine()) { 11149 // This couldn't be folded because the operand didn't have the nuw 11150 // flag. Add the nusw flag as an assumption that we could make. 11151 const SCEV *Step = AR->getStepRecurrence(SE); 11152 Type *Ty = Expr->getType(); 11153 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11154 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11155 SE.getSignExtendExpr(Step, Ty), L, 11156 AR->getNoWrapFlags()); 11157 } 11158 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11159 } 11160 11161 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11162 const SCEV *Operand = visit(Expr->getOperand()); 11163 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11164 if (AR && AR->getLoop() == L && AR->isAffine()) { 11165 // This couldn't be folded because the operand didn't have the nsw 11166 // flag. Add the nssw flag as an assumption that we could make. 11167 const SCEV *Step = AR->getStepRecurrence(SE); 11168 Type *Ty = Expr->getType(); 11169 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11170 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11171 SE.getSignExtendExpr(Step, Ty), L, 11172 AR->getNoWrapFlags()); 11173 } 11174 return SE.getSignExtendExpr(Operand, Expr->getType()); 11175 } 11176 11177 private: 11178 bool addOverflowAssumption(const SCEVPredicate *P) { 11179 if (!NewPreds) { 11180 // Check if we've already made this assumption. 11181 return Pred && Pred->implies(P); 11182 } 11183 NewPreds->insert(P); 11184 return true; 11185 } 11186 11187 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11188 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11189 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11190 return addOverflowAssumption(A); 11191 } 11192 11193 // If \p Expr represents a PHINode, we try to see if it can be represented 11194 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11195 // to add this predicate as a runtime overflow check, we return the AddRec. 11196 // If \p Expr does not meet these conditions (is not a PHI node, or we 11197 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11198 // return \p Expr. 11199 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11200 if (!isa<PHINode>(Expr->getValue())) 11201 return Expr; 11202 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11203 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11204 if (!PredicatedRewrite) 11205 return Expr; 11206 for (auto *P : PredicatedRewrite->second){ 11207 if (!addOverflowAssumption(P)) 11208 return Expr; 11209 } 11210 return PredicatedRewrite->first; 11211 } 11212 11213 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11214 SCEVUnionPredicate *Pred; 11215 const Loop *L; 11216 }; 11217 11218 } // end anonymous namespace 11219 11220 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11221 SCEVUnionPredicate &Preds) { 11222 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11223 } 11224 11225 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11226 const SCEV *S, const Loop *L, 11227 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11228 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11229 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11230 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11231 11232 if (!AddRec) 11233 return nullptr; 11234 11235 // Since the transformation was successful, we can now transfer the SCEV 11236 // predicates. 11237 for (auto *P : TransformPreds) 11238 Preds.insert(P); 11239 11240 return AddRec; 11241 } 11242 11243 /// SCEV predicates 11244 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11245 SCEVPredicateKind Kind) 11246 : FastID(ID), Kind(Kind) {} 11247 11248 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11249 const SCEV *LHS, const SCEV *RHS) 11250 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11251 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11252 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11253 } 11254 11255 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11256 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11257 11258 if (!Op) 11259 return false; 11260 11261 return Op->LHS == LHS && Op->RHS == RHS; 11262 } 11263 11264 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11265 11266 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11267 11268 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11269 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11270 } 11271 11272 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11273 const SCEVAddRecExpr *AR, 11274 IncrementWrapFlags Flags) 11275 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11276 11277 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11278 11279 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11280 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11281 11282 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11283 } 11284 11285 bool SCEVWrapPredicate::isAlwaysTrue() const { 11286 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11287 IncrementWrapFlags IFlags = Flags; 11288 11289 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11290 IFlags = clearFlags(IFlags, IncrementNSSW); 11291 11292 return IFlags == IncrementAnyWrap; 11293 } 11294 11295 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11296 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11297 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11298 OS << "<nusw>"; 11299 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11300 OS << "<nssw>"; 11301 OS << "\n"; 11302 } 11303 11304 SCEVWrapPredicate::IncrementWrapFlags 11305 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11306 ScalarEvolution &SE) { 11307 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11308 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11309 11310 // We can safely transfer the NSW flag as NSSW. 11311 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11312 ImpliedFlags = IncrementNSSW; 11313 11314 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11315 // If the increment is positive, the SCEV NUW flag will also imply the 11316 // WrapPredicate NUSW flag. 11317 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11318 if (Step->getValue()->getValue().isNonNegative()) 11319 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11320 } 11321 11322 return ImpliedFlags; 11323 } 11324 11325 /// Union predicates don't get cached so create a dummy set ID for it. 11326 SCEVUnionPredicate::SCEVUnionPredicate() 11327 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11328 11329 bool SCEVUnionPredicate::isAlwaysTrue() const { 11330 return all_of(Preds, 11331 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11332 } 11333 11334 ArrayRef<const SCEVPredicate *> 11335 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11336 auto I = SCEVToPreds.find(Expr); 11337 if (I == SCEVToPreds.end()) 11338 return ArrayRef<const SCEVPredicate *>(); 11339 return I->second; 11340 } 11341 11342 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11343 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11344 return all_of(Set->Preds, 11345 [this](const SCEVPredicate *I) { return this->implies(I); }); 11346 11347 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11348 if (ScevPredsIt == SCEVToPreds.end()) 11349 return false; 11350 auto &SCEVPreds = ScevPredsIt->second; 11351 11352 return any_of(SCEVPreds, 11353 [N](const SCEVPredicate *I) { return I->implies(N); }); 11354 } 11355 11356 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11357 11358 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11359 for (auto Pred : Preds) 11360 Pred->print(OS, Depth); 11361 } 11362 11363 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11364 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11365 for (auto Pred : Set->Preds) 11366 add(Pred); 11367 return; 11368 } 11369 11370 if (implies(N)) 11371 return; 11372 11373 const SCEV *Key = N->getExpr(); 11374 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11375 " associated expression!"); 11376 11377 SCEVToPreds[Key].push_back(N); 11378 Preds.push_back(N); 11379 } 11380 11381 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11382 Loop &L) 11383 : SE(SE), L(L) {} 11384 11385 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11386 const SCEV *Expr = SE.getSCEV(V); 11387 RewriteEntry &Entry = RewriteMap[Expr]; 11388 11389 // If we already have an entry and the version matches, return it. 11390 if (Entry.second && Generation == Entry.first) 11391 return Entry.second; 11392 11393 // We found an entry but it's stale. Rewrite the stale entry 11394 // according to the current predicate. 11395 if (Entry.second) 11396 Expr = Entry.second; 11397 11398 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11399 Entry = {Generation, NewSCEV}; 11400 11401 return NewSCEV; 11402 } 11403 11404 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11405 if (!BackedgeCount) { 11406 SCEVUnionPredicate BackedgePred; 11407 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11408 addPredicate(BackedgePred); 11409 } 11410 return BackedgeCount; 11411 } 11412 11413 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11414 if (Preds.implies(&Pred)) 11415 return; 11416 Preds.add(&Pred); 11417 updateGeneration(); 11418 } 11419 11420 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11421 return Preds; 11422 } 11423 11424 void PredicatedScalarEvolution::updateGeneration() { 11425 // If the generation number wrapped recompute everything. 11426 if (++Generation == 0) { 11427 for (auto &II : RewriteMap) { 11428 const SCEV *Rewritten = II.second.second; 11429 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11430 } 11431 } 11432 } 11433 11434 void PredicatedScalarEvolution::setNoOverflow( 11435 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11436 const SCEV *Expr = getSCEV(V); 11437 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11438 11439 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11440 11441 // Clear the statically implied flags. 11442 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11443 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11444 11445 auto II = FlagsMap.insert({V, Flags}); 11446 if (!II.second) 11447 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11448 } 11449 11450 bool PredicatedScalarEvolution::hasNoOverflow( 11451 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11452 const SCEV *Expr = getSCEV(V); 11453 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11454 11455 Flags = SCEVWrapPredicate::clearFlags( 11456 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11457 11458 auto II = FlagsMap.find(V); 11459 11460 if (II != FlagsMap.end()) 11461 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11462 11463 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11464 } 11465 11466 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11467 const SCEV *Expr = this->getSCEV(V); 11468 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11469 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11470 11471 if (!New) 11472 return nullptr; 11473 11474 for (auto *P : NewPreds) 11475 Preds.add(P); 11476 11477 updateGeneration(); 11478 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11479 return New; 11480 } 11481 11482 PredicatedScalarEvolution::PredicatedScalarEvolution( 11483 const PredicatedScalarEvolution &Init) 11484 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11485 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11486 for (const auto &I : Init.FlagsMap) 11487 FlagsMap.insert(I); 11488 } 11489 11490 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11491 // For each block. 11492 for (auto *BB : L.getBlocks()) 11493 for (auto &I : *BB) { 11494 if (!SE.isSCEVable(I.getType())) 11495 continue; 11496 11497 auto *Expr = SE.getSCEV(&I); 11498 auto II = RewriteMap.find(Expr); 11499 11500 if (II == RewriteMap.end()) 11501 continue; 11502 11503 // Don't print things that are not interesting. 11504 if (II->second.second == Expr) 11505 continue; 11506 11507 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11508 OS.indent(Depth + 2) << *Expr << "\n"; 11509 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11510 } 11511 } 11512