1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/MathExtras.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include <algorithm> 96 using namespace llvm; 97 98 #define DEBUG_TYPE "scalar-evolution" 99 100 STATISTIC(NumArrayLenItCounts, 101 "Number of trip counts computed with array length"); 102 STATISTIC(NumTripCountsComputed, 103 "Number of loops with predictable loop counts"); 104 STATISTIC(NumTripCountsNotComputed, 105 "Number of loops without predictable loop counts"); 106 STATISTIC(NumBruteForceTripCountsComputed, 107 "Number of loops with trip counts computed by force"); 108 109 static cl::opt<unsigned> 110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 111 cl::desc("Maximum number of iterations SCEV will " 112 "symbolically execute a constant " 113 "derived loop"), 114 cl::init(100)); 115 116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 117 static cl::opt<bool> 118 VerifySCEV("verify-scev", 119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 120 static cl::opt<bool> 121 VerifySCEVMap("verify-scev-maps", 122 cl::desc("Verify no dangling value in ScalarEvolution's " 123 "ExprValueMap (slow)")); 124 125 static cl::opt<unsigned> MulOpsInlineThreshold( 126 "scev-mulops-inline-threshold", cl::Hidden, 127 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 128 cl::init(1000)); 129 130 static cl::opt<unsigned> AddOpsInlineThreshold( 131 "scev-addops-inline-threshold", cl::Hidden, 132 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 133 cl::init(500)); 134 135 static cl::opt<unsigned> MaxSCEVCompareDepth( 136 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 137 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 138 cl::init(32)); 139 140 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 141 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 142 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 143 cl::init(2)); 144 145 static cl::opt<unsigned> MaxValueCompareDepth( 146 "scalar-evolution-max-value-compare-depth", cl::Hidden, 147 cl::desc("Maximum depth of recursive value complexity comparisons"), 148 cl::init(2)); 149 150 static cl::opt<unsigned> 151 MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden, 152 cl::desc("Maximum depth of recursive AddExpr"), 153 cl::init(32)); 154 155 static cl::opt<unsigned> MaxConstantEvolvingDepth( 156 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 157 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 158 159 //===----------------------------------------------------------------------===// 160 // SCEV class definitions 161 //===----------------------------------------------------------------------===// 162 163 //===----------------------------------------------------------------------===// 164 // Implementation of the SCEV class. 165 // 166 167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 168 LLVM_DUMP_METHOD void SCEV::dump() const { 169 print(dbgs()); 170 dbgs() << '\n'; 171 } 172 #endif 173 174 void SCEV::print(raw_ostream &OS) const { 175 switch (static_cast<SCEVTypes>(getSCEVType())) { 176 case scConstant: 177 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 178 return; 179 case scTruncate: { 180 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 181 const SCEV *Op = Trunc->getOperand(); 182 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 183 << *Trunc->getType() << ")"; 184 return; 185 } 186 case scZeroExtend: { 187 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 188 const SCEV *Op = ZExt->getOperand(); 189 OS << "(zext " << *Op->getType() << " " << *Op << " to " 190 << *ZExt->getType() << ")"; 191 return; 192 } 193 case scSignExtend: { 194 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 195 const SCEV *Op = SExt->getOperand(); 196 OS << "(sext " << *Op->getType() << " " << *Op << " to " 197 << *SExt->getType() << ")"; 198 return; 199 } 200 case scAddRecExpr: { 201 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 202 OS << "{" << *AR->getOperand(0); 203 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 204 OS << ",+," << *AR->getOperand(i); 205 OS << "}<"; 206 if (AR->hasNoUnsignedWrap()) 207 OS << "nuw><"; 208 if (AR->hasNoSignedWrap()) 209 OS << "nsw><"; 210 if (AR->hasNoSelfWrap() && 211 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 212 OS << "nw><"; 213 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 214 OS << ">"; 215 return; 216 } 217 case scAddExpr: 218 case scMulExpr: 219 case scUMaxExpr: 220 case scSMaxExpr: { 221 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 222 const char *OpStr = nullptr; 223 switch (NAry->getSCEVType()) { 224 case scAddExpr: OpStr = " + "; break; 225 case scMulExpr: OpStr = " * "; break; 226 case scUMaxExpr: OpStr = " umax "; break; 227 case scSMaxExpr: OpStr = " smax "; break; 228 } 229 OS << "("; 230 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 231 I != E; ++I) { 232 OS << **I; 233 if (std::next(I) != E) 234 OS << OpStr; 235 } 236 OS << ")"; 237 switch (NAry->getSCEVType()) { 238 case scAddExpr: 239 case scMulExpr: 240 if (NAry->hasNoUnsignedWrap()) 241 OS << "<nuw>"; 242 if (NAry->hasNoSignedWrap()) 243 OS << "<nsw>"; 244 } 245 return; 246 } 247 case scUDivExpr: { 248 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 249 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 250 return; 251 } 252 case scUnknown: { 253 const SCEVUnknown *U = cast<SCEVUnknown>(this); 254 Type *AllocTy; 255 if (U->isSizeOf(AllocTy)) { 256 OS << "sizeof(" << *AllocTy << ")"; 257 return; 258 } 259 if (U->isAlignOf(AllocTy)) { 260 OS << "alignof(" << *AllocTy << ")"; 261 return; 262 } 263 264 Type *CTy; 265 Constant *FieldNo; 266 if (U->isOffsetOf(CTy, FieldNo)) { 267 OS << "offsetof(" << *CTy << ", "; 268 FieldNo->printAsOperand(OS, false); 269 OS << ")"; 270 return; 271 } 272 273 // Otherwise just print it normally. 274 U->getValue()->printAsOperand(OS, false); 275 return; 276 } 277 case scCouldNotCompute: 278 OS << "***COULDNOTCOMPUTE***"; 279 return; 280 } 281 llvm_unreachable("Unknown SCEV kind!"); 282 } 283 284 Type *SCEV::getType() const { 285 switch (static_cast<SCEVTypes>(getSCEVType())) { 286 case scConstant: 287 return cast<SCEVConstant>(this)->getType(); 288 case scTruncate: 289 case scZeroExtend: 290 case scSignExtend: 291 return cast<SCEVCastExpr>(this)->getType(); 292 case scAddRecExpr: 293 case scMulExpr: 294 case scUMaxExpr: 295 case scSMaxExpr: 296 return cast<SCEVNAryExpr>(this)->getType(); 297 case scAddExpr: 298 return cast<SCEVAddExpr>(this)->getType(); 299 case scUDivExpr: 300 return cast<SCEVUDivExpr>(this)->getType(); 301 case scUnknown: 302 return cast<SCEVUnknown>(this)->getType(); 303 case scCouldNotCompute: 304 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 305 } 306 llvm_unreachable("Unknown SCEV kind!"); 307 } 308 309 bool SCEV::isZero() const { 310 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 311 return SC->getValue()->isZero(); 312 return false; 313 } 314 315 bool SCEV::isOne() const { 316 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 317 return SC->getValue()->isOne(); 318 return false; 319 } 320 321 bool SCEV::isAllOnesValue() const { 322 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 323 return SC->getValue()->isAllOnesValue(); 324 return false; 325 } 326 327 bool SCEV::isNonConstantNegative() const { 328 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 329 if (!Mul) return false; 330 331 // If there is a constant factor, it will be first. 332 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 333 if (!SC) return false; 334 335 // Return true if the value is negative, this matches things like (-42 * V). 336 return SC->getAPInt().isNegative(); 337 } 338 339 SCEVCouldNotCompute::SCEVCouldNotCompute() : 340 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 341 342 bool SCEVCouldNotCompute::classof(const SCEV *S) { 343 return S->getSCEVType() == scCouldNotCompute; 344 } 345 346 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 347 FoldingSetNodeID ID; 348 ID.AddInteger(scConstant); 349 ID.AddPointer(V); 350 void *IP = nullptr; 351 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 352 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 353 UniqueSCEVs.InsertNode(S, IP); 354 return S; 355 } 356 357 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 358 return getConstant(ConstantInt::get(getContext(), Val)); 359 } 360 361 const SCEV * 362 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 363 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 364 return getConstant(ConstantInt::get(ITy, V, isSigned)); 365 } 366 367 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 368 unsigned SCEVTy, const SCEV *op, Type *ty) 369 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 370 371 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 372 const SCEV *op, Type *ty) 373 : SCEVCastExpr(ID, scTruncate, op, ty) { 374 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 375 (Ty->isIntegerTy() || Ty->isPointerTy()) && 376 "Cannot truncate non-integer value!"); 377 } 378 379 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 380 const SCEV *op, Type *ty) 381 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 382 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 383 (Ty->isIntegerTy() || Ty->isPointerTy()) && 384 "Cannot zero extend non-integer value!"); 385 } 386 387 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 388 const SCEV *op, Type *ty) 389 : SCEVCastExpr(ID, scSignExtend, op, ty) { 390 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 391 (Ty->isIntegerTy() || Ty->isPointerTy()) && 392 "Cannot sign extend non-integer value!"); 393 } 394 395 void SCEVUnknown::deleted() { 396 // Clear this SCEVUnknown from various maps. 397 SE->forgetMemoizedResults(this); 398 399 // Remove this SCEVUnknown from the uniquing map. 400 SE->UniqueSCEVs.RemoveNode(this); 401 402 // Release the value. 403 setValPtr(nullptr); 404 } 405 406 void SCEVUnknown::allUsesReplacedWith(Value *New) { 407 // Clear this SCEVUnknown from various maps. 408 SE->forgetMemoizedResults(this); 409 410 // Remove this SCEVUnknown from the uniquing map. 411 SE->UniqueSCEVs.RemoveNode(this); 412 413 // Update this SCEVUnknown to point to the new value. This is needed 414 // because there may still be outstanding SCEVs which still point to 415 // this SCEVUnknown. 416 setValPtr(New); 417 } 418 419 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 420 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 421 if (VCE->getOpcode() == Instruction::PtrToInt) 422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 423 if (CE->getOpcode() == Instruction::GetElementPtr && 424 CE->getOperand(0)->isNullValue() && 425 CE->getNumOperands() == 2) 426 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 427 if (CI->isOne()) { 428 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 429 ->getElementType(); 430 return true; 431 } 432 433 return false; 434 } 435 436 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 437 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 438 if (VCE->getOpcode() == Instruction::PtrToInt) 439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 440 if (CE->getOpcode() == Instruction::GetElementPtr && 441 CE->getOperand(0)->isNullValue()) { 442 Type *Ty = 443 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 444 if (StructType *STy = dyn_cast<StructType>(Ty)) 445 if (!STy->isPacked() && 446 CE->getNumOperands() == 3 && 447 CE->getOperand(1)->isNullValue()) { 448 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 449 if (CI->isOne() && 450 STy->getNumElements() == 2 && 451 STy->getElementType(0)->isIntegerTy(1)) { 452 AllocTy = STy->getElementType(1); 453 return true; 454 } 455 } 456 } 457 458 return false; 459 } 460 461 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 462 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 463 if (VCE->getOpcode() == Instruction::PtrToInt) 464 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 465 if (CE->getOpcode() == Instruction::GetElementPtr && 466 CE->getNumOperands() == 3 && 467 CE->getOperand(0)->isNullValue() && 468 CE->getOperand(1)->isNullValue()) { 469 Type *Ty = 470 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 471 // Ignore vector types here so that ScalarEvolutionExpander doesn't 472 // emit getelementptrs that index into vectors. 473 if (Ty->isStructTy() || Ty->isArrayTy()) { 474 CTy = Ty; 475 FieldNo = CE->getOperand(2); 476 return true; 477 } 478 } 479 480 return false; 481 } 482 483 //===----------------------------------------------------------------------===// 484 // SCEV Utilities 485 //===----------------------------------------------------------------------===// 486 487 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 488 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 489 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 490 /// have been previously deemed to be "equally complex" by this routine. It is 491 /// intended to avoid exponential time complexity in cases like: 492 /// 493 /// %a = f(%x, %y) 494 /// %b = f(%a, %a) 495 /// %c = f(%b, %b) 496 /// 497 /// %d = f(%x, %y) 498 /// %e = f(%d, %d) 499 /// %f = f(%e, %e) 500 /// 501 /// CompareValueComplexity(%f, %c) 502 /// 503 /// Since we do not continue running this routine on expression trees once we 504 /// have seen unequal values, there is no need to track them in the cache. 505 static int 506 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 507 const LoopInfo *const LI, Value *LV, Value *RV, 508 unsigned Depth) { 509 if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV})) 510 return 0; 511 512 // Order pointer values after integer values. This helps SCEVExpander form 513 // GEPs. 514 bool LIsPointer = LV->getType()->isPointerTy(), 515 RIsPointer = RV->getType()->isPointerTy(); 516 if (LIsPointer != RIsPointer) 517 return (int)LIsPointer - (int)RIsPointer; 518 519 // Compare getValueID values. 520 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 521 if (LID != RID) 522 return (int)LID - (int)RID; 523 524 // Sort arguments by their position. 525 if (const auto *LA = dyn_cast<Argument>(LV)) { 526 const auto *RA = cast<Argument>(RV); 527 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 528 return (int)LArgNo - (int)RArgNo; 529 } 530 531 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 532 const auto *RGV = cast<GlobalValue>(RV); 533 534 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 535 auto LT = GV->getLinkage(); 536 return !(GlobalValue::isPrivateLinkage(LT) || 537 GlobalValue::isInternalLinkage(LT)); 538 }; 539 540 // Use the names to distinguish the two values, but only if the 541 // names are semantically important. 542 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 543 return LGV->getName().compare(RGV->getName()); 544 } 545 546 // For instructions, compare their loop depth, and their operand count. This 547 // is pretty loose. 548 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 549 const auto *RInst = cast<Instruction>(RV); 550 551 // Compare loop depths. 552 const BasicBlock *LParent = LInst->getParent(), 553 *RParent = RInst->getParent(); 554 if (LParent != RParent) { 555 unsigned LDepth = LI->getLoopDepth(LParent), 556 RDepth = LI->getLoopDepth(RParent); 557 if (LDepth != RDepth) 558 return (int)LDepth - (int)RDepth; 559 } 560 561 // Compare the number of operands. 562 unsigned LNumOps = LInst->getNumOperands(), 563 RNumOps = RInst->getNumOperands(); 564 if (LNumOps != RNumOps) 565 return (int)LNumOps - (int)RNumOps; 566 567 for (unsigned Idx : seq(0u, LNumOps)) { 568 int Result = 569 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 570 RInst->getOperand(Idx), Depth + 1); 571 if (Result != 0) 572 return Result; 573 } 574 } 575 576 EqCache.insert({LV, RV}); 577 return 0; 578 } 579 580 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 581 // than RHS, respectively. A three-way result allows recursive comparisons to be 582 // more efficient. 583 static int CompareSCEVComplexity( 584 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, 585 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 586 unsigned Depth = 0) { 587 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 588 if (LHS == RHS) 589 return 0; 590 591 // Primarily, sort the SCEVs by their getSCEVType(). 592 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 593 if (LType != RType) 594 return (int)LType - (int)RType; 595 596 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS})) 597 return 0; 598 // Aside from the getSCEVType() ordering, the particular ordering 599 // isn't very important except that it's beneficial to be consistent, 600 // so that (a + b) and (b + a) don't end up as different expressions. 601 switch (static_cast<SCEVTypes>(LType)) { 602 case scUnknown: { 603 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 604 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 605 606 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 607 int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), 608 Depth + 1); 609 if (X == 0) 610 EqCacheSCEV.insert({LHS, RHS}); 611 return X; 612 } 613 614 case scConstant: { 615 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 616 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 617 618 // Compare constant values. 619 const APInt &LA = LC->getAPInt(); 620 const APInt &RA = RC->getAPInt(); 621 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 622 if (LBitWidth != RBitWidth) 623 return (int)LBitWidth - (int)RBitWidth; 624 return LA.ult(RA) ? -1 : 1; 625 } 626 627 case scAddRecExpr: { 628 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 629 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 630 631 // Compare addrec loop depths. 632 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 633 if (LLoop != RLoop) { 634 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 635 if (LDepth != RDepth) 636 return (int)LDepth - (int)RDepth; 637 } 638 639 // Addrec complexity grows with operand count. 640 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 641 if (LNumOps != RNumOps) 642 return (int)LNumOps - (int)RNumOps; 643 644 // Lexicographically compare. 645 for (unsigned i = 0; i != LNumOps; ++i) { 646 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), 647 RA->getOperand(i), Depth + 1); 648 if (X != 0) 649 return X; 650 } 651 EqCacheSCEV.insert({LHS, RHS}); 652 return 0; 653 } 654 655 case scAddExpr: 656 case scMulExpr: 657 case scSMaxExpr: 658 case scUMaxExpr: { 659 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 660 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 661 662 // Lexicographically compare n-ary expressions. 663 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 664 if (LNumOps != RNumOps) 665 return (int)LNumOps - (int)RNumOps; 666 667 for (unsigned i = 0; i != LNumOps; ++i) { 668 if (i >= RNumOps) 669 return 1; 670 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), 671 RC->getOperand(i), Depth + 1); 672 if (X != 0) 673 return X; 674 } 675 EqCacheSCEV.insert({LHS, RHS}); 676 return 0; 677 } 678 679 case scUDivExpr: { 680 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 681 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 682 683 // Lexicographically compare udiv expressions. 684 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), 685 Depth + 1); 686 if (X != 0) 687 return X; 688 X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), 689 Depth + 1); 690 if (X == 0) 691 EqCacheSCEV.insert({LHS, RHS}); 692 return X; 693 } 694 695 case scTruncate: 696 case scZeroExtend: 697 case scSignExtend: { 698 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 699 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 700 701 // Compare cast expressions by operand. 702 int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), 703 RC->getOperand(), Depth + 1); 704 if (X == 0) 705 EqCacheSCEV.insert({LHS, RHS}); 706 return X; 707 } 708 709 case scCouldNotCompute: 710 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 711 } 712 llvm_unreachable("Unknown SCEV kind!"); 713 } 714 715 /// Given a list of SCEV objects, order them by their complexity, and group 716 /// objects of the same complexity together by value. When this routine is 717 /// finished, we know that any duplicates in the vector are consecutive and that 718 /// complexity is monotonically increasing. 719 /// 720 /// Note that we go take special precautions to ensure that we get deterministic 721 /// results from this routine. In other words, we don't want the results of 722 /// this to depend on where the addresses of various SCEV objects happened to 723 /// land in memory. 724 /// 725 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 726 LoopInfo *LI) { 727 if (Ops.size() < 2) return; // Noop 728 729 SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; 730 if (Ops.size() == 2) { 731 // This is the common case, which also happens to be trivially simple. 732 // Special case it. 733 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 734 if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) 735 std::swap(LHS, RHS); 736 return; 737 } 738 739 // Do the rough sort by complexity. 740 std::stable_sort(Ops.begin(), Ops.end(), 741 [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { 742 return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; 743 }); 744 745 // Now that we are sorted by complexity, group elements of the same 746 // complexity. Note that this is, at worst, N^2, but the vector is likely to 747 // be extremely short in practice. Note that we take this approach because we 748 // do not want to depend on the addresses of the objects we are grouping. 749 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 750 const SCEV *S = Ops[i]; 751 unsigned Complexity = S->getSCEVType(); 752 753 // If there are any objects of the same complexity and same value as this 754 // one, group them. 755 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 756 if (Ops[j] == S) { // Found a duplicate. 757 // Move it to immediately after i'th element. 758 std::swap(Ops[i+1], Ops[j]); 759 ++i; // no need to rescan it. 760 if (i == e-2) return; // Done! 761 } 762 } 763 } 764 } 765 766 // Returns the size of the SCEV S. 767 static inline int sizeOfSCEV(const SCEV *S) { 768 struct FindSCEVSize { 769 int Size; 770 FindSCEVSize() : Size(0) {} 771 772 bool follow(const SCEV *S) { 773 ++Size; 774 // Keep looking at all operands of S. 775 return true; 776 } 777 bool isDone() const { 778 return false; 779 } 780 }; 781 782 FindSCEVSize F; 783 SCEVTraversal<FindSCEVSize> ST(F); 784 ST.visitAll(S); 785 return F.Size; 786 } 787 788 namespace { 789 790 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 791 public: 792 // Computes the Quotient and Remainder of the division of Numerator by 793 // Denominator. 794 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 795 const SCEV *Denominator, const SCEV **Quotient, 796 const SCEV **Remainder) { 797 assert(Numerator && Denominator && "Uninitialized SCEV"); 798 799 SCEVDivision D(SE, Numerator, Denominator); 800 801 // Check for the trivial case here to avoid having to check for it in the 802 // rest of the code. 803 if (Numerator == Denominator) { 804 *Quotient = D.One; 805 *Remainder = D.Zero; 806 return; 807 } 808 809 if (Numerator->isZero()) { 810 *Quotient = D.Zero; 811 *Remainder = D.Zero; 812 return; 813 } 814 815 // A simple case when N/1. The quotient is N. 816 if (Denominator->isOne()) { 817 *Quotient = Numerator; 818 *Remainder = D.Zero; 819 return; 820 } 821 822 // Split the Denominator when it is a product. 823 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 824 const SCEV *Q, *R; 825 *Quotient = Numerator; 826 for (const SCEV *Op : T->operands()) { 827 divide(SE, *Quotient, Op, &Q, &R); 828 *Quotient = Q; 829 830 // Bail out when the Numerator is not divisible by one of the terms of 831 // the Denominator. 832 if (!R->isZero()) { 833 *Quotient = D.Zero; 834 *Remainder = Numerator; 835 return; 836 } 837 } 838 *Remainder = D.Zero; 839 return; 840 } 841 842 D.visit(Numerator); 843 *Quotient = D.Quotient; 844 *Remainder = D.Remainder; 845 } 846 847 // Except in the trivial case described above, we do not know how to divide 848 // Expr by Denominator for the following functions with empty implementation. 849 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 850 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 851 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 852 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 853 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 854 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 855 void visitUnknown(const SCEVUnknown *Numerator) {} 856 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 857 858 void visitConstant(const SCEVConstant *Numerator) { 859 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 860 APInt NumeratorVal = Numerator->getAPInt(); 861 APInt DenominatorVal = D->getAPInt(); 862 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 863 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 864 865 if (NumeratorBW > DenominatorBW) 866 DenominatorVal = DenominatorVal.sext(NumeratorBW); 867 else if (NumeratorBW < DenominatorBW) 868 NumeratorVal = NumeratorVal.sext(DenominatorBW); 869 870 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 871 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 872 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 873 Quotient = SE.getConstant(QuotientVal); 874 Remainder = SE.getConstant(RemainderVal); 875 return; 876 } 877 } 878 879 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 880 const SCEV *StartQ, *StartR, *StepQ, *StepR; 881 if (!Numerator->isAffine()) 882 return cannotDivide(Numerator); 883 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 884 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 885 // Bail out if the types do not match. 886 Type *Ty = Denominator->getType(); 887 if (Ty != StartQ->getType() || Ty != StartR->getType() || 888 Ty != StepQ->getType() || Ty != StepR->getType()) 889 return cannotDivide(Numerator); 890 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 891 Numerator->getNoWrapFlags()); 892 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 893 Numerator->getNoWrapFlags()); 894 } 895 896 void visitAddExpr(const SCEVAddExpr *Numerator) { 897 SmallVector<const SCEV *, 2> Qs, Rs; 898 Type *Ty = Denominator->getType(); 899 900 for (const SCEV *Op : Numerator->operands()) { 901 const SCEV *Q, *R; 902 divide(SE, Op, Denominator, &Q, &R); 903 904 // Bail out if types do not match. 905 if (Ty != Q->getType() || Ty != R->getType()) 906 return cannotDivide(Numerator); 907 908 Qs.push_back(Q); 909 Rs.push_back(R); 910 } 911 912 if (Qs.size() == 1) { 913 Quotient = Qs[0]; 914 Remainder = Rs[0]; 915 return; 916 } 917 918 Quotient = SE.getAddExpr(Qs); 919 Remainder = SE.getAddExpr(Rs); 920 } 921 922 void visitMulExpr(const SCEVMulExpr *Numerator) { 923 SmallVector<const SCEV *, 2> Qs; 924 Type *Ty = Denominator->getType(); 925 926 bool FoundDenominatorTerm = false; 927 for (const SCEV *Op : Numerator->operands()) { 928 // Bail out if types do not match. 929 if (Ty != Op->getType()) 930 return cannotDivide(Numerator); 931 932 if (FoundDenominatorTerm) { 933 Qs.push_back(Op); 934 continue; 935 } 936 937 // Check whether Denominator divides one of the product operands. 938 const SCEV *Q, *R; 939 divide(SE, Op, Denominator, &Q, &R); 940 if (!R->isZero()) { 941 Qs.push_back(Op); 942 continue; 943 } 944 945 // Bail out if types do not match. 946 if (Ty != Q->getType()) 947 return cannotDivide(Numerator); 948 949 FoundDenominatorTerm = true; 950 Qs.push_back(Q); 951 } 952 953 if (FoundDenominatorTerm) { 954 Remainder = Zero; 955 if (Qs.size() == 1) 956 Quotient = Qs[0]; 957 else 958 Quotient = SE.getMulExpr(Qs); 959 return; 960 } 961 962 if (!isa<SCEVUnknown>(Denominator)) 963 return cannotDivide(Numerator); 964 965 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 966 ValueToValueMap RewriteMap; 967 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 968 cast<SCEVConstant>(Zero)->getValue(); 969 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 970 971 if (Remainder->isZero()) { 972 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 973 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 974 cast<SCEVConstant>(One)->getValue(); 975 Quotient = 976 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 977 return; 978 } 979 980 // Quotient is (Numerator - Remainder) divided by Denominator. 981 const SCEV *Q, *R; 982 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 983 // This SCEV does not seem to simplify: fail the division here. 984 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 985 return cannotDivide(Numerator); 986 divide(SE, Diff, Denominator, &Q, &R); 987 if (R != Zero) 988 return cannotDivide(Numerator); 989 Quotient = Q; 990 } 991 992 private: 993 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 994 const SCEV *Denominator) 995 : SE(S), Denominator(Denominator) { 996 Zero = SE.getZero(Denominator->getType()); 997 One = SE.getOne(Denominator->getType()); 998 999 // We generally do not know how to divide Expr by Denominator. We 1000 // initialize the division to a "cannot divide" state to simplify the rest 1001 // of the code. 1002 cannotDivide(Numerator); 1003 } 1004 1005 // Convenience function for giving up on the division. We set the quotient to 1006 // be equal to zero and the remainder to be equal to the numerator. 1007 void cannotDivide(const SCEV *Numerator) { 1008 Quotient = Zero; 1009 Remainder = Numerator; 1010 } 1011 1012 ScalarEvolution &SE; 1013 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1014 }; 1015 1016 } 1017 1018 //===----------------------------------------------------------------------===// 1019 // Simple SCEV method implementations 1020 //===----------------------------------------------------------------------===// 1021 1022 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1023 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1024 ScalarEvolution &SE, 1025 Type *ResultTy) { 1026 // Handle the simplest case efficiently. 1027 if (K == 1) 1028 return SE.getTruncateOrZeroExtend(It, ResultTy); 1029 1030 // We are using the following formula for BC(It, K): 1031 // 1032 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1033 // 1034 // Suppose, W is the bitwidth of the return value. We must be prepared for 1035 // overflow. Hence, we must assure that the result of our computation is 1036 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1037 // safe in modular arithmetic. 1038 // 1039 // However, this code doesn't use exactly that formula; the formula it uses 1040 // is something like the following, where T is the number of factors of 2 in 1041 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1042 // exponentiation: 1043 // 1044 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1045 // 1046 // This formula is trivially equivalent to the previous formula. However, 1047 // this formula can be implemented much more efficiently. The trick is that 1048 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1049 // arithmetic. To do exact division in modular arithmetic, all we have 1050 // to do is multiply by the inverse. Therefore, this step can be done at 1051 // width W. 1052 // 1053 // The next issue is how to safely do the division by 2^T. The way this 1054 // is done is by doing the multiplication step at a width of at least W + T 1055 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1056 // when we perform the division by 2^T (which is equivalent to a right shift 1057 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1058 // truncated out after the division by 2^T. 1059 // 1060 // In comparison to just directly using the first formula, this technique 1061 // is much more efficient; using the first formula requires W * K bits, 1062 // but this formula less than W + K bits. Also, the first formula requires 1063 // a division step, whereas this formula only requires multiplies and shifts. 1064 // 1065 // It doesn't matter whether the subtraction step is done in the calculation 1066 // width or the input iteration count's width; if the subtraction overflows, 1067 // the result must be zero anyway. We prefer here to do it in the width of 1068 // the induction variable because it helps a lot for certain cases; CodeGen 1069 // isn't smart enough to ignore the overflow, which leads to much less 1070 // efficient code if the width of the subtraction is wider than the native 1071 // register width. 1072 // 1073 // (It's possible to not widen at all by pulling out factors of 2 before 1074 // the multiplication; for example, K=2 can be calculated as 1075 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1076 // extra arithmetic, so it's not an obvious win, and it gets 1077 // much more complicated for K > 3.) 1078 1079 // Protection from insane SCEVs; this bound is conservative, 1080 // but it probably doesn't matter. 1081 if (K > 1000) 1082 return SE.getCouldNotCompute(); 1083 1084 unsigned W = SE.getTypeSizeInBits(ResultTy); 1085 1086 // Calculate K! / 2^T and T; we divide out the factors of two before 1087 // multiplying for calculating K! / 2^T to avoid overflow. 1088 // Other overflow doesn't matter because we only care about the bottom 1089 // W bits of the result. 1090 APInt OddFactorial(W, 1); 1091 unsigned T = 1; 1092 for (unsigned i = 3; i <= K; ++i) { 1093 APInt Mult(W, i); 1094 unsigned TwoFactors = Mult.countTrailingZeros(); 1095 T += TwoFactors; 1096 Mult = Mult.lshr(TwoFactors); 1097 OddFactorial *= Mult; 1098 } 1099 1100 // We need at least W + T bits for the multiplication step 1101 unsigned CalculationBits = W + T; 1102 1103 // Calculate 2^T, at width T+W. 1104 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1105 1106 // Calculate the multiplicative inverse of K! / 2^T; 1107 // this multiplication factor will perform the exact division by 1108 // K! / 2^T. 1109 APInt Mod = APInt::getSignedMinValue(W+1); 1110 APInt MultiplyFactor = OddFactorial.zext(W+1); 1111 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1112 MultiplyFactor = MultiplyFactor.trunc(W); 1113 1114 // Calculate the product, at width T+W 1115 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1116 CalculationBits); 1117 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1118 for (unsigned i = 1; i != K; ++i) { 1119 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1120 Dividend = SE.getMulExpr(Dividend, 1121 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1122 } 1123 1124 // Divide by 2^T 1125 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1126 1127 // Truncate the result, and divide by K! / 2^T. 1128 1129 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1130 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1131 } 1132 1133 /// Return the value of this chain of recurrences at the specified iteration 1134 /// number. We can evaluate this recurrence by multiplying each element in the 1135 /// chain by the binomial coefficient corresponding to it. In other words, we 1136 /// can evaluate {A,+,B,+,C,+,D} as: 1137 /// 1138 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1139 /// 1140 /// where BC(It, k) stands for binomial coefficient. 1141 /// 1142 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1143 ScalarEvolution &SE) const { 1144 const SCEV *Result = getStart(); 1145 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1146 // The computation is correct in the face of overflow provided that the 1147 // multiplication is performed _after_ the evaluation of the binomial 1148 // coefficient. 1149 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1150 if (isa<SCEVCouldNotCompute>(Coeff)) 1151 return Coeff; 1152 1153 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1154 } 1155 return Result; 1156 } 1157 1158 //===----------------------------------------------------------------------===// 1159 // SCEV Expression folder implementations 1160 //===----------------------------------------------------------------------===// 1161 1162 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1163 Type *Ty) { 1164 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1165 "This is not a truncating conversion!"); 1166 assert(isSCEVable(Ty) && 1167 "This is not a conversion to a SCEVable type!"); 1168 Ty = getEffectiveSCEVType(Ty); 1169 1170 FoldingSetNodeID ID; 1171 ID.AddInteger(scTruncate); 1172 ID.AddPointer(Op); 1173 ID.AddPointer(Ty); 1174 void *IP = nullptr; 1175 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1176 1177 // Fold if the operand is constant. 1178 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1179 return getConstant( 1180 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1181 1182 // trunc(trunc(x)) --> trunc(x) 1183 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1184 return getTruncateExpr(ST->getOperand(), Ty); 1185 1186 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1187 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1188 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1189 1190 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1191 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1192 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1193 1194 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1195 // eliminate all the truncates, or we replace other casts with truncates. 1196 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1197 SmallVector<const SCEV *, 4> Operands; 1198 bool hasTrunc = false; 1199 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1200 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1201 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1202 hasTrunc = isa<SCEVTruncateExpr>(S); 1203 Operands.push_back(S); 1204 } 1205 if (!hasTrunc) 1206 return getAddExpr(Operands); 1207 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1208 } 1209 1210 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1211 // eliminate all the truncates, or we replace other casts with truncates. 1212 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1213 SmallVector<const SCEV *, 4> Operands; 1214 bool hasTrunc = false; 1215 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1216 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1217 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1218 hasTrunc = isa<SCEVTruncateExpr>(S); 1219 Operands.push_back(S); 1220 } 1221 if (!hasTrunc) 1222 return getMulExpr(Operands); 1223 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1224 } 1225 1226 // If the input value is a chrec scev, truncate the chrec's operands. 1227 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1228 SmallVector<const SCEV *, 4> Operands; 1229 for (const SCEV *Op : AddRec->operands()) 1230 Operands.push_back(getTruncateExpr(Op, Ty)); 1231 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1232 } 1233 1234 // The cast wasn't folded; create an explicit cast node. We can reuse 1235 // the existing insert position since if we get here, we won't have 1236 // made any changes which would invalidate it. 1237 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1238 Op, Ty); 1239 UniqueSCEVs.InsertNode(S, IP); 1240 return S; 1241 } 1242 1243 // Get the limit of a recurrence such that incrementing by Step cannot cause 1244 // signed overflow as long as the value of the recurrence within the 1245 // loop does not exceed this limit before incrementing. 1246 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1247 ICmpInst::Predicate *Pred, 1248 ScalarEvolution *SE) { 1249 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1250 if (SE->isKnownPositive(Step)) { 1251 *Pred = ICmpInst::ICMP_SLT; 1252 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1253 SE->getSignedRange(Step).getSignedMax()); 1254 } 1255 if (SE->isKnownNegative(Step)) { 1256 *Pred = ICmpInst::ICMP_SGT; 1257 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1258 SE->getSignedRange(Step).getSignedMin()); 1259 } 1260 return nullptr; 1261 } 1262 1263 // Get the limit of a recurrence such that incrementing by Step cannot cause 1264 // unsigned overflow as long as the value of the recurrence within the loop does 1265 // not exceed this limit before incrementing. 1266 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1267 ICmpInst::Predicate *Pred, 1268 ScalarEvolution *SE) { 1269 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1270 *Pred = ICmpInst::ICMP_ULT; 1271 1272 return SE->getConstant(APInt::getMinValue(BitWidth) - 1273 SE->getUnsignedRange(Step).getUnsignedMax()); 1274 } 1275 1276 namespace { 1277 1278 struct ExtendOpTraitsBase { 1279 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1280 }; 1281 1282 // Used to make code generic over signed and unsigned overflow. 1283 template <typename ExtendOp> struct ExtendOpTraits { 1284 // Members present: 1285 // 1286 // static const SCEV::NoWrapFlags WrapType; 1287 // 1288 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1289 // 1290 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1291 // ICmpInst::Predicate *Pred, 1292 // ScalarEvolution *SE); 1293 }; 1294 1295 template <> 1296 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1297 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1298 1299 static const GetExtendExprTy GetExtendExpr; 1300 1301 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1302 ICmpInst::Predicate *Pred, 1303 ScalarEvolution *SE) { 1304 return getSignedOverflowLimitForStep(Step, Pred, SE); 1305 } 1306 }; 1307 1308 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1309 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1310 1311 template <> 1312 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1313 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1314 1315 static const GetExtendExprTy GetExtendExpr; 1316 1317 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1318 ICmpInst::Predicate *Pred, 1319 ScalarEvolution *SE) { 1320 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1321 } 1322 }; 1323 1324 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1325 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1326 } 1327 1328 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1329 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1330 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1331 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1332 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1333 // expression "Step + sext/zext(PreIncAR)" is congruent with 1334 // "sext/zext(PostIncAR)" 1335 template <typename ExtendOpTy> 1336 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1337 ScalarEvolution *SE) { 1338 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1339 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1340 1341 const Loop *L = AR->getLoop(); 1342 const SCEV *Start = AR->getStart(); 1343 const SCEV *Step = AR->getStepRecurrence(*SE); 1344 1345 // Check for a simple looking step prior to loop entry. 1346 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1347 if (!SA) 1348 return nullptr; 1349 1350 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1351 // subtraction is expensive. For this purpose, perform a quick and dirty 1352 // difference, by checking for Step in the operand list. 1353 SmallVector<const SCEV *, 4> DiffOps; 1354 for (const SCEV *Op : SA->operands()) 1355 if (Op != Step) 1356 DiffOps.push_back(Op); 1357 1358 if (DiffOps.size() == SA->getNumOperands()) 1359 return nullptr; 1360 1361 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1362 // `Step`: 1363 1364 // 1. NSW/NUW flags on the step increment. 1365 auto PreStartFlags = 1366 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1367 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1368 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1369 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1370 1371 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1372 // "S+X does not sign/unsign-overflow". 1373 // 1374 1375 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1376 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1377 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1378 return PreStart; 1379 1380 // 2. Direct overflow check on the step operation's expression. 1381 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1382 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1383 const SCEV *OperandExtendedStart = 1384 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1385 (SE->*GetExtendExpr)(Step, WideTy)); 1386 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1387 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1388 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1389 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1390 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1391 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1392 } 1393 return PreStart; 1394 } 1395 1396 // 3. Loop precondition. 1397 ICmpInst::Predicate Pred; 1398 const SCEV *OverflowLimit = 1399 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1400 1401 if (OverflowLimit && 1402 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1403 return PreStart; 1404 1405 return nullptr; 1406 } 1407 1408 // Get the normalized zero or sign extended expression for this AddRec's Start. 1409 template <typename ExtendOpTy> 1410 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1411 ScalarEvolution *SE) { 1412 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1413 1414 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1415 if (!PreStart) 1416 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1417 1418 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1419 (SE->*GetExtendExpr)(PreStart, Ty)); 1420 } 1421 1422 // Try to prove away overflow by looking at "nearby" add recurrences. A 1423 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1424 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1425 // 1426 // Formally: 1427 // 1428 // {S,+,X} == {S-T,+,X} + T 1429 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1430 // 1431 // If ({S-T,+,X} + T) does not overflow ... (1) 1432 // 1433 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1434 // 1435 // If {S-T,+,X} does not overflow ... (2) 1436 // 1437 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1438 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1439 // 1440 // If (S-T)+T does not overflow ... (3) 1441 // 1442 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1443 // == {Ext(S),+,Ext(X)} == LHS 1444 // 1445 // Thus, if (1), (2) and (3) are true for some T, then 1446 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1447 // 1448 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1449 // does not overflow" restricted to the 0th iteration. Therefore we only need 1450 // to check for (1) and (2). 1451 // 1452 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1453 // is `Delta` (defined below). 1454 // 1455 template <typename ExtendOpTy> 1456 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1457 const SCEV *Step, 1458 const Loop *L) { 1459 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1460 1461 // We restrict `Start` to a constant to prevent SCEV from spending too much 1462 // time here. It is correct (but more expensive) to continue with a 1463 // non-constant `Start` and do a general SCEV subtraction to compute 1464 // `PreStart` below. 1465 // 1466 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1467 if (!StartC) 1468 return false; 1469 1470 APInt StartAI = StartC->getAPInt(); 1471 1472 for (unsigned Delta : {-2, -1, 1, 2}) { 1473 const SCEV *PreStart = getConstant(StartAI - Delta); 1474 1475 FoldingSetNodeID ID; 1476 ID.AddInteger(scAddRecExpr); 1477 ID.AddPointer(PreStart); 1478 ID.AddPointer(Step); 1479 ID.AddPointer(L); 1480 void *IP = nullptr; 1481 const auto *PreAR = 1482 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1483 1484 // Give up if we don't already have the add recurrence we need because 1485 // actually constructing an add recurrence is relatively expensive. 1486 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1487 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1488 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1489 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1490 DeltaS, &Pred, this); 1491 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1492 return true; 1493 } 1494 } 1495 1496 return false; 1497 } 1498 1499 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1500 Type *Ty) { 1501 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1502 "This is not an extending conversion!"); 1503 assert(isSCEVable(Ty) && 1504 "This is not a conversion to a SCEVable type!"); 1505 Ty = getEffectiveSCEVType(Ty); 1506 1507 // Fold if the operand is constant. 1508 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1509 return getConstant( 1510 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1511 1512 // zext(zext(x)) --> zext(x) 1513 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1514 return getZeroExtendExpr(SZ->getOperand(), Ty); 1515 1516 // Before doing any expensive analysis, check to see if we've already 1517 // computed a SCEV for this Op and Ty. 1518 FoldingSetNodeID ID; 1519 ID.AddInteger(scZeroExtend); 1520 ID.AddPointer(Op); 1521 ID.AddPointer(Ty); 1522 void *IP = nullptr; 1523 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1524 1525 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1526 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1527 // It's possible the bits taken off by the truncate were all zero bits. If 1528 // so, we should be able to simplify this further. 1529 const SCEV *X = ST->getOperand(); 1530 ConstantRange CR = getUnsignedRange(X); 1531 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1532 unsigned NewBits = getTypeSizeInBits(Ty); 1533 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1534 CR.zextOrTrunc(NewBits))) 1535 return getTruncateOrZeroExtend(X, Ty); 1536 } 1537 1538 // If the input value is a chrec scev, and we can prove that the value 1539 // did not overflow the old, smaller, value, we can zero extend all of the 1540 // operands (often constants). This allows analysis of something like 1541 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1542 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1543 if (AR->isAffine()) { 1544 const SCEV *Start = AR->getStart(); 1545 const SCEV *Step = AR->getStepRecurrence(*this); 1546 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1547 const Loop *L = AR->getLoop(); 1548 1549 if (!AR->hasNoUnsignedWrap()) { 1550 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1551 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1552 } 1553 1554 // If we have special knowledge that this addrec won't overflow, 1555 // we don't need to do any further analysis. 1556 if (AR->hasNoUnsignedWrap()) 1557 return getAddRecExpr( 1558 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1559 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1560 1561 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1562 // Note that this serves two purposes: It filters out loops that are 1563 // simply not analyzable, and it covers the case where this code is 1564 // being called from within backedge-taken count analysis, such that 1565 // attempting to ask for the backedge-taken count would likely result 1566 // in infinite recursion. In the later case, the analysis code will 1567 // cope with a conservative value, and it will take care to purge 1568 // that value once it has finished. 1569 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1570 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1571 // Manually compute the final value for AR, checking for 1572 // overflow. 1573 1574 // Check whether the backedge-taken count can be losslessly casted to 1575 // the addrec's type. The count is always unsigned. 1576 const SCEV *CastedMaxBECount = 1577 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1578 const SCEV *RecastedMaxBECount = 1579 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1580 if (MaxBECount == RecastedMaxBECount) { 1581 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1582 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1583 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1584 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1585 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1586 const SCEV *WideMaxBECount = 1587 getZeroExtendExpr(CastedMaxBECount, WideTy); 1588 const SCEV *OperandExtendedAdd = 1589 getAddExpr(WideStart, 1590 getMulExpr(WideMaxBECount, 1591 getZeroExtendExpr(Step, WideTy))); 1592 if (ZAdd == OperandExtendedAdd) { 1593 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1594 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1595 // Return the expression with the addrec on the outside. 1596 return getAddRecExpr( 1597 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1598 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1599 } 1600 // Similar to above, only this time treat the step value as signed. 1601 // This covers loops that count down. 1602 OperandExtendedAdd = 1603 getAddExpr(WideStart, 1604 getMulExpr(WideMaxBECount, 1605 getSignExtendExpr(Step, WideTy))); 1606 if (ZAdd == OperandExtendedAdd) { 1607 // Cache knowledge of AR NW, which is propagated to this AddRec. 1608 // Negative step causes unsigned wrap, but it still can't self-wrap. 1609 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1610 // Return the expression with the addrec on the outside. 1611 return getAddRecExpr( 1612 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1613 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1614 } 1615 } 1616 } 1617 1618 // Normally, in the cases we can prove no-overflow via a 1619 // backedge guarding condition, we can also compute a backedge 1620 // taken count for the loop. The exceptions are assumptions and 1621 // guards present in the loop -- SCEV is not great at exploiting 1622 // these to compute max backedge taken counts, but can still use 1623 // these to prove lack of overflow. Use this fact to avoid 1624 // doing extra work that may not pay off. 1625 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1626 !AC.assumptions().empty()) { 1627 // If the backedge is guarded by a comparison with the pre-inc 1628 // value the addrec is safe. Also, if the entry is guarded by 1629 // a comparison with the start value and the backedge is 1630 // guarded by a comparison with the post-inc value, the addrec 1631 // is safe. 1632 if (isKnownPositive(Step)) { 1633 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1634 getUnsignedRange(Step).getUnsignedMax()); 1635 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1636 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1637 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1638 AR->getPostIncExpr(*this), N))) { 1639 // Cache knowledge of AR NUW, which is propagated to this 1640 // AddRec. 1641 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1642 // Return the expression with the addrec on the outside. 1643 return getAddRecExpr( 1644 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1645 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1646 } 1647 } else if (isKnownNegative(Step)) { 1648 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1649 getSignedRange(Step).getSignedMin()); 1650 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1651 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1652 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1653 AR->getPostIncExpr(*this), N))) { 1654 // Cache knowledge of AR NW, which is propagated to this 1655 // AddRec. Negative step causes unsigned wrap, but it 1656 // still can't self-wrap. 1657 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1658 // Return the expression with the addrec on the outside. 1659 return getAddRecExpr( 1660 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1661 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1662 } 1663 } 1664 } 1665 1666 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1667 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1668 return getAddRecExpr( 1669 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1670 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1671 } 1672 } 1673 1674 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1675 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1676 if (SA->hasNoUnsignedWrap()) { 1677 // If the addition does not unsign overflow then we can, by definition, 1678 // commute the zero extension with the addition operation. 1679 SmallVector<const SCEV *, 4> Ops; 1680 for (const auto *Op : SA->operands()) 1681 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1682 return getAddExpr(Ops, SCEV::FlagNUW); 1683 } 1684 } 1685 1686 // The cast wasn't folded; create an explicit cast node. 1687 // Recompute the insert position, as it may have been invalidated. 1688 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1689 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1690 Op, Ty); 1691 UniqueSCEVs.InsertNode(S, IP); 1692 return S; 1693 } 1694 1695 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1696 Type *Ty) { 1697 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1698 "This is not an extending conversion!"); 1699 assert(isSCEVable(Ty) && 1700 "This is not a conversion to a SCEVable type!"); 1701 Ty = getEffectiveSCEVType(Ty); 1702 1703 // Fold if the operand is constant. 1704 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1705 return getConstant( 1706 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1707 1708 // sext(sext(x)) --> sext(x) 1709 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1710 return getSignExtendExpr(SS->getOperand(), Ty); 1711 1712 // sext(zext(x)) --> zext(x) 1713 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1714 return getZeroExtendExpr(SZ->getOperand(), Ty); 1715 1716 // Before doing any expensive analysis, check to see if we've already 1717 // computed a SCEV for this Op and Ty. 1718 FoldingSetNodeID ID; 1719 ID.AddInteger(scSignExtend); 1720 ID.AddPointer(Op); 1721 ID.AddPointer(Ty); 1722 void *IP = nullptr; 1723 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1724 1725 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1726 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1727 // It's possible the bits taken off by the truncate were all sign bits. If 1728 // so, we should be able to simplify this further. 1729 const SCEV *X = ST->getOperand(); 1730 ConstantRange CR = getSignedRange(X); 1731 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1732 unsigned NewBits = getTypeSizeInBits(Ty); 1733 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1734 CR.sextOrTrunc(NewBits))) 1735 return getTruncateOrSignExtend(X, Ty); 1736 } 1737 1738 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1739 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1740 if (SA->getNumOperands() == 2) { 1741 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1742 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1743 if (SMul && SC1) { 1744 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1745 const APInt &C1 = SC1->getAPInt(); 1746 const APInt &C2 = SC2->getAPInt(); 1747 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1748 C2.ugt(C1) && C2.isPowerOf2()) 1749 return getAddExpr(getSignExtendExpr(SC1, Ty), 1750 getSignExtendExpr(SMul, Ty)); 1751 } 1752 } 1753 } 1754 1755 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1756 if (SA->hasNoSignedWrap()) { 1757 // If the addition does not sign overflow then we can, by definition, 1758 // commute the sign extension with the addition operation. 1759 SmallVector<const SCEV *, 4> Ops; 1760 for (const auto *Op : SA->operands()) 1761 Ops.push_back(getSignExtendExpr(Op, Ty)); 1762 return getAddExpr(Ops, SCEV::FlagNSW); 1763 } 1764 } 1765 // If the input value is a chrec scev, and we can prove that the value 1766 // did not overflow the old, smaller, value, we can sign extend all of the 1767 // operands (often constants). This allows analysis of something like 1768 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1769 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1770 if (AR->isAffine()) { 1771 const SCEV *Start = AR->getStart(); 1772 const SCEV *Step = AR->getStepRecurrence(*this); 1773 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1774 const Loop *L = AR->getLoop(); 1775 1776 if (!AR->hasNoSignedWrap()) { 1777 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1778 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1779 } 1780 1781 // If we have special knowledge that this addrec won't overflow, 1782 // we don't need to do any further analysis. 1783 if (AR->hasNoSignedWrap()) 1784 return getAddRecExpr( 1785 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1786 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1787 1788 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1789 // Note that this serves two purposes: It filters out loops that are 1790 // simply not analyzable, and it covers the case where this code is 1791 // being called from within backedge-taken count analysis, such that 1792 // attempting to ask for the backedge-taken count would likely result 1793 // in infinite recursion. In the later case, the analysis code will 1794 // cope with a conservative value, and it will take care to purge 1795 // that value once it has finished. 1796 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1797 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1798 // Manually compute the final value for AR, checking for 1799 // overflow. 1800 1801 // Check whether the backedge-taken count can be losslessly casted to 1802 // the addrec's type. The count is always unsigned. 1803 const SCEV *CastedMaxBECount = 1804 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1805 const SCEV *RecastedMaxBECount = 1806 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1807 if (MaxBECount == RecastedMaxBECount) { 1808 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1809 // Check whether Start+Step*MaxBECount has no signed overflow. 1810 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1811 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1812 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1813 const SCEV *WideMaxBECount = 1814 getZeroExtendExpr(CastedMaxBECount, WideTy); 1815 const SCEV *OperandExtendedAdd = 1816 getAddExpr(WideStart, 1817 getMulExpr(WideMaxBECount, 1818 getSignExtendExpr(Step, WideTy))); 1819 if (SAdd == OperandExtendedAdd) { 1820 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1821 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1822 // Return the expression with the addrec on the outside. 1823 return getAddRecExpr( 1824 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1825 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1826 } 1827 // Similar to above, only this time treat the step value as unsigned. 1828 // This covers loops that count up with an unsigned step. 1829 OperandExtendedAdd = 1830 getAddExpr(WideStart, 1831 getMulExpr(WideMaxBECount, 1832 getZeroExtendExpr(Step, WideTy))); 1833 if (SAdd == OperandExtendedAdd) { 1834 // If AR wraps around then 1835 // 1836 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1837 // => SAdd != OperandExtendedAdd 1838 // 1839 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1840 // (SAdd == OperandExtendedAdd => AR is NW) 1841 1842 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1843 1844 // Return the expression with the addrec on the outside. 1845 return getAddRecExpr( 1846 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1847 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1848 } 1849 } 1850 } 1851 1852 // Normally, in the cases we can prove no-overflow via a 1853 // backedge guarding condition, we can also compute a backedge 1854 // taken count for the loop. The exceptions are assumptions and 1855 // guards present in the loop -- SCEV is not great at exploiting 1856 // these to compute max backedge taken counts, but can still use 1857 // these to prove lack of overflow. Use this fact to avoid 1858 // doing extra work that may not pay off. 1859 1860 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1861 !AC.assumptions().empty()) { 1862 // If the backedge is guarded by a comparison with the pre-inc 1863 // value the addrec is safe. Also, if the entry is guarded by 1864 // a comparison with the start value and the backedge is 1865 // guarded by a comparison with the post-inc value, the addrec 1866 // is safe. 1867 ICmpInst::Predicate Pred; 1868 const SCEV *OverflowLimit = 1869 getSignedOverflowLimitForStep(Step, &Pred, this); 1870 if (OverflowLimit && 1871 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1872 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1873 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1874 OverflowLimit)))) { 1875 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1876 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1877 return getAddRecExpr( 1878 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1879 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1880 } 1881 } 1882 1883 // If Start and Step are constants, check if we can apply this 1884 // transformation: 1885 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1886 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1887 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1888 if (SC1 && SC2) { 1889 const APInt &C1 = SC1->getAPInt(); 1890 const APInt &C2 = SC2->getAPInt(); 1891 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1892 C2.isPowerOf2()) { 1893 Start = getSignExtendExpr(Start, Ty); 1894 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1895 AR->getNoWrapFlags()); 1896 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1897 } 1898 } 1899 1900 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1901 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1902 return getAddRecExpr( 1903 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1904 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1905 } 1906 } 1907 1908 // If the input value is provably positive and we could not simplify 1909 // away the sext build a zext instead. 1910 if (isKnownNonNegative(Op)) 1911 return getZeroExtendExpr(Op, Ty); 1912 1913 // The cast wasn't folded; create an explicit cast node. 1914 // Recompute the insert position, as it may have been invalidated. 1915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1916 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1917 Op, Ty); 1918 UniqueSCEVs.InsertNode(S, IP); 1919 return S; 1920 } 1921 1922 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1923 /// unspecified bits out to the given type. 1924 /// 1925 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1926 Type *Ty) { 1927 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1928 "This is not an extending conversion!"); 1929 assert(isSCEVable(Ty) && 1930 "This is not a conversion to a SCEVable type!"); 1931 Ty = getEffectiveSCEVType(Ty); 1932 1933 // Sign-extend negative constants. 1934 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1935 if (SC->getAPInt().isNegative()) 1936 return getSignExtendExpr(Op, Ty); 1937 1938 // Peel off a truncate cast. 1939 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1940 const SCEV *NewOp = T->getOperand(); 1941 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1942 return getAnyExtendExpr(NewOp, Ty); 1943 return getTruncateOrNoop(NewOp, Ty); 1944 } 1945 1946 // Next try a zext cast. If the cast is folded, use it. 1947 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1948 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1949 return ZExt; 1950 1951 // Next try a sext cast. If the cast is folded, use it. 1952 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1953 if (!isa<SCEVSignExtendExpr>(SExt)) 1954 return SExt; 1955 1956 // Force the cast to be folded into the operands of an addrec. 1957 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1958 SmallVector<const SCEV *, 4> Ops; 1959 for (const SCEV *Op : AR->operands()) 1960 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1961 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1962 } 1963 1964 // If the expression is obviously signed, use the sext cast value. 1965 if (isa<SCEVSMaxExpr>(Op)) 1966 return SExt; 1967 1968 // Absent any other information, use the zext cast value. 1969 return ZExt; 1970 } 1971 1972 /// Process the given Ops list, which is a list of operands to be added under 1973 /// the given scale, update the given map. This is a helper function for 1974 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1975 /// that would form an add expression like this: 1976 /// 1977 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1978 /// 1979 /// where A and B are constants, update the map with these values: 1980 /// 1981 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1982 /// 1983 /// and add 13 + A*B*29 to AccumulatedConstant. 1984 /// This will allow getAddRecExpr to produce this: 1985 /// 1986 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1987 /// 1988 /// This form often exposes folding opportunities that are hidden in 1989 /// the original operand list. 1990 /// 1991 /// Return true iff it appears that any interesting folding opportunities 1992 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1993 /// the common case where no interesting opportunities are present, and 1994 /// is also used as a check to avoid infinite recursion. 1995 /// 1996 static bool 1997 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1998 SmallVectorImpl<const SCEV *> &NewOps, 1999 APInt &AccumulatedConstant, 2000 const SCEV *const *Ops, size_t NumOperands, 2001 const APInt &Scale, 2002 ScalarEvolution &SE) { 2003 bool Interesting = false; 2004 2005 // Iterate over the add operands. They are sorted, with constants first. 2006 unsigned i = 0; 2007 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2008 ++i; 2009 // Pull a buried constant out to the outside. 2010 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2011 Interesting = true; 2012 AccumulatedConstant += Scale * C->getAPInt(); 2013 } 2014 2015 // Next comes everything else. We're especially interested in multiplies 2016 // here, but they're in the middle, so just visit the rest with one loop. 2017 for (; i != NumOperands; ++i) { 2018 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2019 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2020 APInt NewScale = 2021 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2022 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2023 // A multiplication of a constant with another add; recurse. 2024 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2025 Interesting |= 2026 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2027 Add->op_begin(), Add->getNumOperands(), 2028 NewScale, SE); 2029 } else { 2030 // A multiplication of a constant with some other value. Update 2031 // the map. 2032 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2033 const SCEV *Key = SE.getMulExpr(MulOps); 2034 auto Pair = M.insert({Key, NewScale}); 2035 if (Pair.second) { 2036 NewOps.push_back(Pair.first->first); 2037 } else { 2038 Pair.first->second += NewScale; 2039 // The map already had an entry for this value, which may indicate 2040 // a folding opportunity. 2041 Interesting = true; 2042 } 2043 } 2044 } else { 2045 // An ordinary operand. Update the map. 2046 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2047 M.insert({Ops[i], Scale}); 2048 if (Pair.second) { 2049 NewOps.push_back(Pair.first->first); 2050 } else { 2051 Pair.first->second += Scale; 2052 // The map already had an entry for this value, which may indicate 2053 // a folding opportunity. 2054 Interesting = true; 2055 } 2056 } 2057 } 2058 2059 return Interesting; 2060 } 2061 2062 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2063 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2064 // can't-overflow flags for the operation if possible. 2065 static SCEV::NoWrapFlags 2066 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2067 const SmallVectorImpl<const SCEV *> &Ops, 2068 SCEV::NoWrapFlags Flags) { 2069 using namespace std::placeholders; 2070 typedef OverflowingBinaryOperator OBO; 2071 2072 bool CanAnalyze = 2073 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2074 (void)CanAnalyze; 2075 assert(CanAnalyze && "don't call from other places!"); 2076 2077 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2078 SCEV::NoWrapFlags SignOrUnsignWrap = 2079 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2080 2081 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2082 auto IsKnownNonNegative = [&](const SCEV *S) { 2083 return SE->isKnownNonNegative(S); 2084 }; 2085 2086 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2087 Flags = 2088 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2089 2090 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2091 2092 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2093 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2094 2095 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2096 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2097 2098 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2099 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2100 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2101 Instruction::Add, C, OBO::NoSignedWrap); 2102 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2103 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2104 } 2105 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2106 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2107 Instruction::Add, C, OBO::NoUnsignedWrap); 2108 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2109 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2110 } 2111 } 2112 2113 return Flags; 2114 } 2115 2116 /// Get a canonical add expression, or something simpler if possible. 2117 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2118 SCEV::NoWrapFlags Flags, 2119 unsigned Depth) { 2120 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2121 "only nuw or nsw allowed"); 2122 assert(!Ops.empty() && "Cannot get empty add!"); 2123 if (Ops.size() == 1) return Ops[0]; 2124 #ifndef NDEBUG 2125 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2126 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2127 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2128 "SCEVAddExpr operand types don't match!"); 2129 #endif 2130 2131 // Sort by complexity, this groups all similar expression types together. 2132 GroupByComplexity(Ops, &LI); 2133 2134 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2135 2136 // If there are any constants, fold them together. 2137 unsigned Idx = 0; 2138 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2139 ++Idx; 2140 assert(Idx < Ops.size()); 2141 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2142 // We found two constants, fold them together! 2143 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2144 if (Ops.size() == 2) return Ops[0]; 2145 Ops.erase(Ops.begin()+1); // Erase the folded element 2146 LHSC = cast<SCEVConstant>(Ops[0]); 2147 } 2148 2149 // If we are left with a constant zero being added, strip it off. 2150 if (LHSC->getValue()->isZero()) { 2151 Ops.erase(Ops.begin()); 2152 --Idx; 2153 } 2154 2155 if (Ops.size() == 1) return Ops[0]; 2156 } 2157 2158 // Limit recursion calls depth 2159 if (Depth > MaxAddExprDepth) 2160 return getOrCreateAddExpr(Ops, Flags); 2161 2162 // Okay, check to see if the same value occurs in the operand list more than 2163 // once. If so, merge them together into an multiply expression. Since we 2164 // sorted the list, these values are required to be adjacent. 2165 Type *Ty = Ops[0]->getType(); 2166 bool FoundMatch = false; 2167 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2168 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2169 // Scan ahead to count how many equal operands there are. 2170 unsigned Count = 2; 2171 while (i+Count != e && Ops[i+Count] == Ops[i]) 2172 ++Count; 2173 // Merge the values into a multiply. 2174 const SCEV *Scale = getConstant(Ty, Count); 2175 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2176 if (Ops.size() == Count) 2177 return Mul; 2178 Ops[i] = Mul; 2179 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2180 --i; e -= Count - 1; 2181 FoundMatch = true; 2182 } 2183 if (FoundMatch) 2184 return getAddExpr(Ops, Flags); 2185 2186 // Check for truncates. If all the operands are truncated from the same 2187 // type, see if factoring out the truncate would permit the result to be 2188 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2189 // if the contents of the resulting outer trunc fold to something simple. 2190 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2191 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2192 Type *DstType = Trunc->getType(); 2193 Type *SrcType = Trunc->getOperand()->getType(); 2194 SmallVector<const SCEV *, 8> LargeOps; 2195 bool Ok = true; 2196 // Check all the operands to see if they can be represented in the 2197 // source type of the truncate. 2198 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2199 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2200 if (T->getOperand()->getType() != SrcType) { 2201 Ok = false; 2202 break; 2203 } 2204 LargeOps.push_back(T->getOperand()); 2205 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2206 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2207 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2208 SmallVector<const SCEV *, 8> LargeMulOps; 2209 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2210 if (const SCEVTruncateExpr *T = 2211 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2212 if (T->getOperand()->getType() != SrcType) { 2213 Ok = false; 2214 break; 2215 } 2216 LargeMulOps.push_back(T->getOperand()); 2217 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2218 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2219 } else { 2220 Ok = false; 2221 break; 2222 } 2223 } 2224 if (Ok) 2225 LargeOps.push_back(getMulExpr(LargeMulOps)); 2226 } else { 2227 Ok = false; 2228 break; 2229 } 2230 } 2231 if (Ok) { 2232 // Evaluate the expression in the larger type. 2233 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2234 // If it folds to something simple, use it. Otherwise, don't. 2235 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2236 return getTruncateExpr(Fold, DstType); 2237 } 2238 } 2239 2240 // Skip past any other cast SCEVs. 2241 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2242 ++Idx; 2243 2244 // If there are add operands they would be next. 2245 if (Idx < Ops.size()) { 2246 bool DeletedAdd = false; 2247 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2248 if (Ops.size() > AddOpsInlineThreshold || 2249 Add->getNumOperands() > AddOpsInlineThreshold) 2250 break; 2251 // If we have an add, expand the add operands onto the end of the operands 2252 // list. 2253 Ops.erase(Ops.begin()+Idx); 2254 Ops.append(Add->op_begin(), Add->op_end()); 2255 DeletedAdd = true; 2256 } 2257 2258 // If we deleted at least one add, we added operands to the end of the list, 2259 // and they are not necessarily sorted. Recurse to resort and resimplify 2260 // any operands we just acquired. 2261 if (DeletedAdd) 2262 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2263 } 2264 2265 // Skip over the add expression until we get to a multiply. 2266 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2267 ++Idx; 2268 2269 // Check to see if there are any folding opportunities present with 2270 // operands multiplied by constant values. 2271 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2272 uint64_t BitWidth = getTypeSizeInBits(Ty); 2273 DenseMap<const SCEV *, APInt> M; 2274 SmallVector<const SCEV *, 8> NewOps; 2275 APInt AccumulatedConstant(BitWidth, 0); 2276 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2277 Ops.data(), Ops.size(), 2278 APInt(BitWidth, 1), *this)) { 2279 struct APIntCompare { 2280 bool operator()(const APInt &LHS, const APInt &RHS) const { 2281 return LHS.ult(RHS); 2282 } 2283 }; 2284 2285 // Some interesting folding opportunity is present, so its worthwhile to 2286 // re-generate the operands list. Group the operands by constant scale, 2287 // to avoid multiplying by the same constant scale multiple times. 2288 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2289 for (const SCEV *NewOp : NewOps) 2290 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2291 // Re-generate the operands list. 2292 Ops.clear(); 2293 if (AccumulatedConstant != 0) 2294 Ops.push_back(getConstant(AccumulatedConstant)); 2295 for (auto &MulOp : MulOpLists) 2296 if (MulOp.first != 0) 2297 Ops.push_back(getMulExpr( 2298 getConstant(MulOp.first), 2299 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1))); 2300 if (Ops.empty()) 2301 return getZero(Ty); 2302 if (Ops.size() == 1) 2303 return Ops[0]; 2304 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2305 } 2306 } 2307 2308 // If we are adding something to a multiply expression, make sure the 2309 // something is not already an operand of the multiply. If so, merge it into 2310 // the multiply. 2311 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2312 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2313 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2314 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2315 if (isa<SCEVConstant>(MulOpSCEV)) 2316 continue; 2317 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2318 if (MulOpSCEV == Ops[AddOp]) { 2319 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2320 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2321 if (Mul->getNumOperands() != 2) { 2322 // If the multiply has more than two operands, we must get the 2323 // Y*Z term. 2324 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2325 Mul->op_begin()+MulOp); 2326 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2327 InnerMul = getMulExpr(MulOps); 2328 } 2329 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2330 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2331 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2332 if (Ops.size() == 2) return OuterMul; 2333 if (AddOp < Idx) { 2334 Ops.erase(Ops.begin()+AddOp); 2335 Ops.erase(Ops.begin()+Idx-1); 2336 } else { 2337 Ops.erase(Ops.begin()+Idx); 2338 Ops.erase(Ops.begin()+AddOp-1); 2339 } 2340 Ops.push_back(OuterMul); 2341 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2342 } 2343 2344 // Check this multiply against other multiplies being added together. 2345 for (unsigned OtherMulIdx = Idx+1; 2346 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2347 ++OtherMulIdx) { 2348 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2349 // If MulOp occurs in OtherMul, we can fold the two multiplies 2350 // together. 2351 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2352 OMulOp != e; ++OMulOp) 2353 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2354 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2355 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2356 if (Mul->getNumOperands() != 2) { 2357 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2358 Mul->op_begin()+MulOp); 2359 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2360 InnerMul1 = getMulExpr(MulOps); 2361 } 2362 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2363 if (OtherMul->getNumOperands() != 2) { 2364 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2365 OtherMul->op_begin()+OMulOp); 2366 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2367 InnerMul2 = getMulExpr(MulOps); 2368 } 2369 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2370 const SCEV *InnerMulSum = 2371 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2372 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2373 if (Ops.size() == 2) return OuterMul; 2374 Ops.erase(Ops.begin()+Idx); 2375 Ops.erase(Ops.begin()+OtherMulIdx-1); 2376 Ops.push_back(OuterMul); 2377 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2378 } 2379 } 2380 } 2381 } 2382 2383 // If there are any add recurrences in the operands list, see if any other 2384 // added values are loop invariant. If so, we can fold them into the 2385 // recurrence. 2386 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2387 ++Idx; 2388 2389 // Scan over all recurrences, trying to fold loop invariants into them. 2390 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2391 // Scan all of the other operands to this add and add them to the vector if 2392 // they are loop invariant w.r.t. the recurrence. 2393 SmallVector<const SCEV *, 8> LIOps; 2394 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2395 const Loop *AddRecLoop = AddRec->getLoop(); 2396 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2397 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2398 LIOps.push_back(Ops[i]); 2399 Ops.erase(Ops.begin()+i); 2400 --i; --e; 2401 } 2402 2403 // If we found some loop invariants, fold them into the recurrence. 2404 if (!LIOps.empty()) { 2405 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2406 LIOps.push_back(AddRec->getStart()); 2407 2408 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2409 AddRec->op_end()); 2410 // This follows from the fact that the no-wrap flags on the outer add 2411 // expression are applicable on the 0th iteration, when the add recurrence 2412 // will be equal to its start value. 2413 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2414 2415 // Build the new addrec. Propagate the NUW and NSW flags if both the 2416 // outer add and the inner addrec are guaranteed to have no overflow. 2417 // Always propagate NW. 2418 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2419 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2420 2421 // If all of the other operands were loop invariant, we are done. 2422 if (Ops.size() == 1) return NewRec; 2423 2424 // Otherwise, add the folded AddRec by the non-invariant parts. 2425 for (unsigned i = 0;; ++i) 2426 if (Ops[i] == AddRec) { 2427 Ops[i] = NewRec; 2428 break; 2429 } 2430 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2431 } 2432 2433 // Okay, if there weren't any loop invariants to be folded, check to see if 2434 // there are multiple AddRec's with the same loop induction variable being 2435 // added together. If so, we can fold them. 2436 for (unsigned OtherIdx = Idx+1; 2437 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2438 ++OtherIdx) 2439 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2440 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2441 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2442 AddRec->op_end()); 2443 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2444 ++OtherIdx) 2445 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2446 if (OtherAddRec->getLoop() == AddRecLoop) { 2447 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2448 i != e; ++i) { 2449 if (i >= AddRecOps.size()) { 2450 AddRecOps.append(OtherAddRec->op_begin()+i, 2451 OtherAddRec->op_end()); 2452 break; 2453 } 2454 SmallVector<const SCEV *, 2> TwoOps = { 2455 AddRecOps[i], OtherAddRec->getOperand(i)}; 2456 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2457 } 2458 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2459 } 2460 // Step size has changed, so we cannot guarantee no self-wraparound. 2461 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2462 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2463 } 2464 2465 // Otherwise couldn't fold anything into this recurrence. Move onto the 2466 // next one. 2467 } 2468 2469 // Okay, it looks like we really DO need an add expr. Check to see if we 2470 // already have one, otherwise create a new one. 2471 return getOrCreateAddExpr(Ops, Flags); 2472 } 2473 2474 const SCEV * 2475 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2476 SCEV::NoWrapFlags Flags) { 2477 FoldingSetNodeID ID; 2478 ID.AddInteger(scAddExpr); 2479 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2480 ID.AddPointer(Ops[i]); 2481 void *IP = nullptr; 2482 SCEVAddExpr *S = 2483 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2484 if (!S) { 2485 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2486 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2487 S = new (SCEVAllocator) 2488 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2489 UniqueSCEVs.InsertNode(S, IP); 2490 } 2491 S->setNoWrapFlags(Flags); 2492 return S; 2493 } 2494 2495 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2496 uint64_t k = i*j; 2497 if (j > 1 && k / j != i) Overflow = true; 2498 return k; 2499 } 2500 2501 /// Compute the result of "n choose k", the binomial coefficient. If an 2502 /// intermediate computation overflows, Overflow will be set and the return will 2503 /// be garbage. Overflow is not cleared on absence of overflow. 2504 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2505 // We use the multiplicative formula: 2506 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2507 // At each iteration, we take the n-th term of the numeral and divide by the 2508 // (k-n)th term of the denominator. This division will always produce an 2509 // integral result, and helps reduce the chance of overflow in the 2510 // intermediate computations. However, we can still overflow even when the 2511 // final result would fit. 2512 2513 if (n == 0 || n == k) return 1; 2514 if (k > n) return 0; 2515 2516 if (k > n/2) 2517 k = n-k; 2518 2519 uint64_t r = 1; 2520 for (uint64_t i = 1; i <= k; ++i) { 2521 r = umul_ov(r, n-(i-1), Overflow); 2522 r /= i; 2523 } 2524 return r; 2525 } 2526 2527 /// Determine if any of the operands in this SCEV are a constant or if 2528 /// any of the add or multiply expressions in this SCEV contain a constant. 2529 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2530 SmallVector<const SCEV *, 4> Ops; 2531 Ops.push_back(StartExpr); 2532 while (!Ops.empty()) { 2533 const SCEV *CurrentExpr = Ops.pop_back_val(); 2534 if (isa<SCEVConstant>(*CurrentExpr)) 2535 return true; 2536 2537 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2538 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2539 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2540 } 2541 } 2542 return false; 2543 } 2544 2545 /// Get a canonical multiply expression, or something simpler if possible. 2546 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2547 SCEV::NoWrapFlags Flags) { 2548 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2549 "only nuw or nsw allowed"); 2550 assert(!Ops.empty() && "Cannot get empty mul!"); 2551 if (Ops.size() == 1) return Ops[0]; 2552 #ifndef NDEBUG 2553 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2554 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2555 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2556 "SCEVMulExpr operand types don't match!"); 2557 #endif 2558 2559 // Sort by complexity, this groups all similar expression types together. 2560 GroupByComplexity(Ops, &LI); 2561 2562 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2563 2564 // If there are any constants, fold them together. 2565 unsigned Idx = 0; 2566 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2567 2568 // C1*(C2+V) -> C1*C2 + C1*V 2569 if (Ops.size() == 2) 2570 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2571 // If any of Add's ops are Adds or Muls with a constant, 2572 // apply this transformation as well. 2573 if (Add->getNumOperands() == 2) 2574 if (containsConstantSomewhere(Add)) 2575 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2576 getMulExpr(LHSC, Add->getOperand(1))); 2577 2578 ++Idx; 2579 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2580 // We found two constants, fold them together! 2581 ConstantInt *Fold = 2582 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2583 Ops[0] = getConstant(Fold); 2584 Ops.erase(Ops.begin()+1); // Erase the folded element 2585 if (Ops.size() == 1) return Ops[0]; 2586 LHSC = cast<SCEVConstant>(Ops[0]); 2587 } 2588 2589 // If we are left with a constant one being multiplied, strip it off. 2590 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2591 Ops.erase(Ops.begin()); 2592 --Idx; 2593 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2594 // If we have a multiply of zero, it will always be zero. 2595 return Ops[0]; 2596 } else if (Ops[0]->isAllOnesValue()) { 2597 // If we have a mul by -1 of an add, try distributing the -1 among the 2598 // add operands. 2599 if (Ops.size() == 2) { 2600 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2601 SmallVector<const SCEV *, 4> NewOps; 2602 bool AnyFolded = false; 2603 for (const SCEV *AddOp : Add->operands()) { 2604 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2605 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2606 NewOps.push_back(Mul); 2607 } 2608 if (AnyFolded) 2609 return getAddExpr(NewOps); 2610 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2611 // Negation preserves a recurrence's no self-wrap property. 2612 SmallVector<const SCEV *, 4> Operands; 2613 for (const SCEV *AddRecOp : AddRec->operands()) 2614 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2615 2616 return getAddRecExpr(Operands, AddRec->getLoop(), 2617 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2618 } 2619 } 2620 } 2621 2622 if (Ops.size() == 1) 2623 return Ops[0]; 2624 } 2625 2626 // Skip over the add expression until we get to a multiply. 2627 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2628 ++Idx; 2629 2630 // If there are mul operands inline them all into this expression. 2631 if (Idx < Ops.size()) { 2632 bool DeletedMul = false; 2633 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2634 if (Ops.size() > MulOpsInlineThreshold) 2635 break; 2636 // If we have an mul, expand the mul operands onto the end of the operands 2637 // list. 2638 Ops.erase(Ops.begin()+Idx); 2639 Ops.append(Mul->op_begin(), Mul->op_end()); 2640 DeletedMul = true; 2641 } 2642 2643 // If we deleted at least one mul, we added operands to the end of the list, 2644 // and they are not necessarily sorted. Recurse to resort and resimplify 2645 // any operands we just acquired. 2646 if (DeletedMul) 2647 return getMulExpr(Ops); 2648 } 2649 2650 // If there are any add recurrences in the operands list, see if any other 2651 // added values are loop invariant. If so, we can fold them into the 2652 // recurrence. 2653 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2654 ++Idx; 2655 2656 // Scan over all recurrences, trying to fold loop invariants into them. 2657 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2658 // Scan all of the other operands to this mul and add them to the vector if 2659 // they are loop invariant w.r.t. the recurrence. 2660 SmallVector<const SCEV *, 8> LIOps; 2661 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2662 const Loop *AddRecLoop = AddRec->getLoop(); 2663 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2664 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2665 LIOps.push_back(Ops[i]); 2666 Ops.erase(Ops.begin()+i); 2667 --i; --e; 2668 } 2669 2670 // If we found some loop invariants, fold them into the recurrence. 2671 if (!LIOps.empty()) { 2672 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2673 SmallVector<const SCEV *, 4> NewOps; 2674 NewOps.reserve(AddRec->getNumOperands()); 2675 const SCEV *Scale = getMulExpr(LIOps); 2676 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2677 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2678 2679 // Build the new addrec. Propagate the NUW and NSW flags if both the 2680 // outer mul and the inner addrec are guaranteed to have no overflow. 2681 // 2682 // No self-wrap cannot be guaranteed after changing the step size, but 2683 // will be inferred if either NUW or NSW is true. 2684 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2685 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2686 2687 // If all of the other operands were loop invariant, we are done. 2688 if (Ops.size() == 1) return NewRec; 2689 2690 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2691 for (unsigned i = 0;; ++i) 2692 if (Ops[i] == AddRec) { 2693 Ops[i] = NewRec; 2694 break; 2695 } 2696 return getMulExpr(Ops); 2697 } 2698 2699 // Okay, if there weren't any loop invariants to be folded, check to see if 2700 // there are multiple AddRec's with the same loop induction variable being 2701 // multiplied together. If so, we can fold them. 2702 2703 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2704 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2705 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2706 // ]]],+,...up to x=2n}. 2707 // Note that the arguments to choose() are always integers with values 2708 // known at compile time, never SCEV objects. 2709 // 2710 // The implementation avoids pointless extra computations when the two 2711 // addrec's are of different length (mathematically, it's equivalent to 2712 // an infinite stream of zeros on the right). 2713 bool OpsModified = false; 2714 for (unsigned OtherIdx = Idx+1; 2715 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2716 ++OtherIdx) { 2717 const SCEVAddRecExpr *OtherAddRec = 2718 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2719 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2720 continue; 2721 2722 bool Overflow = false; 2723 Type *Ty = AddRec->getType(); 2724 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2725 SmallVector<const SCEV*, 7> AddRecOps; 2726 for (int x = 0, xe = AddRec->getNumOperands() + 2727 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2728 const SCEV *Term = getZero(Ty); 2729 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2730 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2731 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2732 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2733 z < ze && !Overflow; ++z) { 2734 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2735 uint64_t Coeff; 2736 if (LargerThan64Bits) 2737 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2738 else 2739 Coeff = Coeff1*Coeff2; 2740 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2741 const SCEV *Term1 = AddRec->getOperand(y-z); 2742 const SCEV *Term2 = OtherAddRec->getOperand(z); 2743 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2744 } 2745 } 2746 AddRecOps.push_back(Term); 2747 } 2748 if (!Overflow) { 2749 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2750 SCEV::FlagAnyWrap); 2751 if (Ops.size() == 2) return NewAddRec; 2752 Ops[Idx] = NewAddRec; 2753 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2754 OpsModified = true; 2755 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2756 if (!AddRec) 2757 break; 2758 } 2759 } 2760 if (OpsModified) 2761 return getMulExpr(Ops); 2762 2763 // Otherwise couldn't fold anything into this recurrence. Move onto the 2764 // next one. 2765 } 2766 2767 // Okay, it looks like we really DO need an mul expr. Check to see if we 2768 // already have one, otherwise create a new one. 2769 FoldingSetNodeID ID; 2770 ID.AddInteger(scMulExpr); 2771 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2772 ID.AddPointer(Ops[i]); 2773 void *IP = nullptr; 2774 SCEVMulExpr *S = 2775 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2776 if (!S) { 2777 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2778 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2779 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2780 O, Ops.size()); 2781 UniqueSCEVs.InsertNode(S, IP); 2782 } 2783 S->setNoWrapFlags(Flags); 2784 return S; 2785 } 2786 2787 /// Get a canonical unsigned division expression, or something simpler if 2788 /// possible. 2789 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2790 const SCEV *RHS) { 2791 assert(getEffectiveSCEVType(LHS->getType()) == 2792 getEffectiveSCEVType(RHS->getType()) && 2793 "SCEVUDivExpr operand types don't match!"); 2794 2795 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2796 if (RHSC->getValue()->equalsInt(1)) 2797 return LHS; // X udiv 1 --> x 2798 // If the denominator is zero, the result of the udiv is undefined. Don't 2799 // try to analyze it, because the resolution chosen here may differ from 2800 // the resolution chosen in other parts of the compiler. 2801 if (!RHSC->getValue()->isZero()) { 2802 // Determine if the division can be folded into the operands of 2803 // its operands. 2804 // TODO: Generalize this to non-constants by using known-bits information. 2805 Type *Ty = LHS->getType(); 2806 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2807 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2808 // For non-power-of-two values, effectively round the value up to the 2809 // nearest power of two. 2810 if (!RHSC->getAPInt().isPowerOf2()) 2811 ++MaxShiftAmt; 2812 IntegerType *ExtTy = 2813 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2814 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2815 if (const SCEVConstant *Step = 2816 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2817 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2818 const APInt &StepInt = Step->getAPInt(); 2819 const APInt &DivInt = RHSC->getAPInt(); 2820 if (!StepInt.urem(DivInt) && 2821 getZeroExtendExpr(AR, ExtTy) == 2822 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2823 getZeroExtendExpr(Step, ExtTy), 2824 AR->getLoop(), SCEV::FlagAnyWrap)) { 2825 SmallVector<const SCEV *, 4> Operands; 2826 for (const SCEV *Op : AR->operands()) 2827 Operands.push_back(getUDivExpr(Op, RHS)); 2828 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2829 } 2830 /// Get a canonical UDivExpr for a recurrence. 2831 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2832 // We can currently only fold X%N if X is constant. 2833 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2834 if (StartC && !DivInt.urem(StepInt) && 2835 getZeroExtendExpr(AR, ExtTy) == 2836 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2837 getZeroExtendExpr(Step, ExtTy), 2838 AR->getLoop(), SCEV::FlagAnyWrap)) { 2839 const APInt &StartInt = StartC->getAPInt(); 2840 const APInt &StartRem = StartInt.urem(StepInt); 2841 if (StartRem != 0) 2842 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2843 AR->getLoop(), SCEV::FlagNW); 2844 } 2845 } 2846 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2847 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2848 SmallVector<const SCEV *, 4> Operands; 2849 for (const SCEV *Op : M->operands()) 2850 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2851 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2852 // Find an operand that's safely divisible. 2853 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2854 const SCEV *Op = M->getOperand(i); 2855 const SCEV *Div = getUDivExpr(Op, RHSC); 2856 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2857 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2858 M->op_end()); 2859 Operands[i] = Div; 2860 return getMulExpr(Operands); 2861 } 2862 } 2863 } 2864 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2865 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2866 SmallVector<const SCEV *, 4> Operands; 2867 for (const SCEV *Op : A->operands()) 2868 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2869 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2870 Operands.clear(); 2871 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2872 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2873 if (isa<SCEVUDivExpr>(Op) || 2874 getMulExpr(Op, RHS) != A->getOperand(i)) 2875 break; 2876 Operands.push_back(Op); 2877 } 2878 if (Operands.size() == A->getNumOperands()) 2879 return getAddExpr(Operands); 2880 } 2881 } 2882 2883 // Fold if both operands are constant. 2884 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2885 Constant *LHSCV = LHSC->getValue(); 2886 Constant *RHSCV = RHSC->getValue(); 2887 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2888 RHSCV))); 2889 } 2890 } 2891 } 2892 2893 FoldingSetNodeID ID; 2894 ID.AddInteger(scUDivExpr); 2895 ID.AddPointer(LHS); 2896 ID.AddPointer(RHS); 2897 void *IP = nullptr; 2898 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2899 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2900 LHS, RHS); 2901 UniqueSCEVs.InsertNode(S, IP); 2902 return S; 2903 } 2904 2905 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2906 APInt A = C1->getAPInt().abs(); 2907 APInt B = C2->getAPInt().abs(); 2908 uint32_t ABW = A.getBitWidth(); 2909 uint32_t BBW = B.getBitWidth(); 2910 2911 if (ABW > BBW) 2912 B = B.zext(ABW); 2913 else if (ABW < BBW) 2914 A = A.zext(BBW); 2915 2916 return APIntOps::GreatestCommonDivisor(A, B); 2917 } 2918 2919 /// Get a canonical unsigned division expression, or something simpler if 2920 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2921 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2922 /// it's not exact because the udiv may be clearing bits. 2923 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2924 const SCEV *RHS) { 2925 // TODO: we could try to find factors in all sorts of things, but for now we 2926 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2927 // end of this file for inspiration. 2928 2929 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2930 if (!Mul || !Mul->hasNoUnsignedWrap()) 2931 return getUDivExpr(LHS, RHS); 2932 2933 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2934 // If the mulexpr multiplies by a constant, then that constant must be the 2935 // first element of the mulexpr. 2936 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2937 if (LHSCst == RHSCst) { 2938 SmallVector<const SCEV *, 2> Operands; 2939 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2940 return getMulExpr(Operands); 2941 } 2942 2943 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2944 // that there's a factor provided by one of the other terms. We need to 2945 // check. 2946 APInt Factor = gcd(LHSCst, RHSCst); 2947 if (!Factor.isIntN(1)) { 2948 LHSCst = 2949 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2950 RHSCst = 2951 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2952 SmallVector<const SCEV *, 2> Operands; 2953 Operands.push_back(LHSCst); 2954 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2955 LHS = getMulExpr(Operands); 2956 RHS = RHSCst; 2957 Mul = dyn_cast<SCEVMulExpr>(LHS); 2958 if (!Mul) 2959 return getUDivExactExpr(LHS, RHS); 2960 } 2961 } 2962 } 2963 2964 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2965 if (Mul->getOperand(i) == RHS) { 2966 SmallVector<const SCEV *, 2> Operands; 2967 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2968 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2969 return getMulExpr(Operands); 2970 } 2971 } 2972 2973 return getUDivExpr(LHS, RHS); 2974 } 2975 2976 /// Get an add recurrence expression for the specified loop. Simplify the 2977 /// expression as much as possible. 2978 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2979 const Loop *L, 2980 SCEV::NoWrapFlags Flags) { 2981 SmallVector<const SCEV *, 4> Operands; 2982 Operands.push_back(Start); 2983 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2984 if (StepChrec->getLoop() == L) { 2985 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2986 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2987 } 2988 2989 Operands.push_back(Step); 2990 return getAddRecExpr(Operands, L, Flags); 2991 } 2992 2993 /// Get an add recurrence expression for the specified loop. Simplify the 2994 /// expression as much as possible. 2995 const SCEV * 2996 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2997 const Loop *L, SCEV::NoWrapFlags Flags) { 2998 if (Operands.size() == 1) return Operands[0]; 2999 #ifndef NDEBUG 3000 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3001 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3002 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3003 "SCEVAddRecExpr operand types don't match!"); 3004 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3005 assert(isLoopInvariant(Operands[i], L) && 3006 "SCEVAddRecExpr operand is not loop-invariant!"); 3007 #endif 3008 3009 if (Operands.back()->isZero()) { 3010 Operands.pop_back(); 3011 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3012 } 3013 3014 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3015 // use that information to infer NUW and NSW flags. However, computing a 3016 // BE count requires calling getAddRecExpr, so we may not yet have a 3017 // meaningful BE count at this point (and if we don't, we'd be stuck 3018 // with a SCEVCouldNotCompute as the cached BE count). 3019 3020 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3021 3022 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3023 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3024 const Loop *NestedLoop = NestedAR->getLoop(); 3025 if (L->contains(NestedLoop) 3026 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3027 : (!NestedLoop->contains(L) && 3028 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3029 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3030 NestedAR->op_end()); 3031 Operands[0] = NestedAR->getStart(); 3032 // AddRecs require their operands be loop-invariant with respect to their 3033 // loops. Don't perform this transformation if it would break this 3034 // requirement. 3035 bool AllInvariant = all_of( 3036 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3037 3038 if (AllInvariant) { 3039 // Create a recurrence for the outer loop with the same step size. 3040 // 3041 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3042 // inner recurrence has the same property. 3043 SCEV::NoWrapFlags OuterFlags = 3044 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3045 3046 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3047 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3048 return isLoopInvariant(Op, NestedLoop); 3049 }); 3050 3051 if (AllInvariant) { 3052 // Ok, both add recurrences are valid after the transformation. 3053 // 3054 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3055 // the outer recurrence has the same property. 3056 SCEV::NoWrapFlags InnerFlags = 3057 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3058 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3059 } 3060 } 3061 // Reset Operands to its original state. 3062 Operands[0] = NestedAR; 3063 } 3064 } 3065 3066 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3067 // already have one, otherwise create a new one. 3068 FoldingSetNodeID ID; 3069 ID.AddInteger(scAddRecExpr); 3070 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3071 ID.AddPointer(Operands[i]); 3072 ID.AddPointer(L); 3073 void *IP = nullptr; 3074 SCEVAddRecExpr *S = 3075 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3076 if (!S) { 3077 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3078 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3079 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3080 O, Operands.size(), L); 3081 UniqueSCEVs.InsertNode(S, IP); 3082 } 3083 S->setNoWrapFlags(Flags); 3084 return S; 3085 } 3086 3087 const SCEV * 3088 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3089 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3090 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3091 // getSCEV(Base)->getType() has the same address space as Base->getType() 3092 // because SCEV::getType() preserves the address space. 3093 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3094 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3095 // instruction to its SCEV, because the Instruction may be guarded by control 3096 // flow and the no-overflow bits may not be valid for the expression in any 3097 // context. This can be fixed similarly to how these flags are handled for 3098 // adds. 3099 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3100 : SCEV::FlagAnyWrap; 3101 3102 const SCEV *TotalOffset = getZero(IntPtrTy); 3103 // The array size is unimportant. The first thing we do on CurTy is getting 3104 // its element type. 3105 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3106 for (const SCEV *IndexExpr : IndexExprs) { 3107 // Compute the (potentially symbolic) offset in bytes for this index. 3108 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3109 // For a struct, add the member offset. 3110 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3111 unsigned FieldNo = Index->getZExtValue(); 3112 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3113 3114 // Add the field offset to the running total offset. 3115 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3116 3117 // Update CurTy to the type of the field at Index. 3118 CurTy = STy->getTypeAtIndex(Index); 3119 } else { 3120 // Update CurTy to its element type. 3121 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3122 // For an array, add the element offset, explicitly scaled. 3123 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3124 // Getelementptr indices are signed. 3125 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3126 3127 // Multiply the index by the element size to compute the element offset. 3128 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3129 3130 // Add the element offset to the running total offset. 3131 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3132 } 3133 } 3134 3135 // Add the total offset from all the GEP indices to the base. 3136 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3137 } 3138 3139 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3140 const SCEV *RHS) { 3141 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3142 return getSMaxExpr(Ops); 3143 } 3144 3145 const SCEV * 3146 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3147 assert(!Ops.empty() && "Cannot get empty smax!"); 3148 if (Ops.size() == 1) return Ops[0]; 3149 #ifndef NDEBUG 3150 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3151 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3152 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3153 "SCEVSMaxExpr operand types don't match!"); 3154 #endif 3155 3156 // Sort by complexity, this groups all similar expression types together. 3157 GroupByComplexity(Ops, &LI); 3158 3159 // If there are any constants, fold them together. 3160 unsigned Idx = 0; 3161 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3162 ++Idx; 3163 assert(Idx < Ops.size()); 3164 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3165 // We found two constants, fold them together! 3166 ConstantInt *Fold = ConstantInt::get( 3167 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3168 Ops[0] = getConstant(Fold); 3169 Ops.erase(Ops.begin()+1); // Erase the folded element 3170 if (Ops.size() == 1) return Ops[0]; 3171 LHSC = cast<SCEVConstant>(Ops[0]); 3172 } 3173 3174 // If we are left with a constant minimum-int, strip it off. 3175 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3176 Ops.erase(Ops.begin()); 3177 --Idx; 3178 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3179 // If we have an smax with a constant maximum-int, it will always be 3180 // maximum-int. 3181 return Ops[0]; 3182 } 3183 3184 if (Ops.size() == 1) return Ops[0]; 3185 } 3186 3187 // Find the first SMax 3188 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3189 ++Idx; 3190 3191 // Check to see if one of the operands is an SMax. If so, expand its operands 3192 // onto our operand list, and recurse to simplify. 3193 if (Idx < Ops.size()) { 3194 bool DeletedSMax = false; 3195 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3196 Ops.erase(Ops.begin()+Idx); 3197 Ops.append(SMax->op_begin(), SMax->op_end()); 3198 DeletedSMax = true; 3199 } 3200 3201 if (DeletedSMax) 3202 return getSMaxExpr(Ops); 3203 } 3204 3205 // Okay, check to see if the same value occurs in the operand list twice. If 3206 // so, delete one. Since we sorted the list, these values are required to 3207 // be adjacent. 3208 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3209 // X smax Y smax Y --> X smax Y 3210 // X smax Y --> X, if X is always greater than Y 3211 if (Ops[i] == Ops[i+1] || 3212 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3213 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3214 --i; --e; 3215 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3216 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3217 --i; --e; 3218 } 3219 3220 if (Ops.size() == 1) return Ops[0]; 3221 3222 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3223 3224 // Okay, it looks like we really DO need an smax expr. Check to see if we 3225 // already have one, otherwise create a new one. 3226 FoldingSetNodeID ID; 3227 ID.AddInteger(scSMaxExpr); 3228 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3229 ID.AddPointer(Ops[i]); 3230 void *IP = nullptr; 3231 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3232 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3233 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3234 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3235 O, Ops.size()); 3236 UniqueSCEVs.InsertNode(S, IP); 3237 return S; 3238 } 3239 3240 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3241 const SCEV *RHS) { 3242 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3243 return getUMaxExpr(Ops); 3244 } 3245 3246 const SCEV * 3247 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3248 assert(!Ops.empty() && "Cannot get empty umax!"); 3249 if (Ops.size() == 1) return Ops[0]; 3250 #ifndef NDEBUG 3251 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3252 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3253 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3254 "SCEVUMaxExpr operand types don't match!"); 3255 #endif 3256 3257 // Sort by complexity, this groups all similar expression types together. 3258 GroupByComplexity(Ops, &LI); 3259 3260 // If there are any constants, fold them together. 3261 unsigned Idx = 0; 3262 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3263 ++Idx; 3264 assert(Idx < Ops.size()); 3265 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3266 // We found two constants, fold them together! 3267 ConstantInt *Fold = ConstantInt::get( 3268 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3269 Ops[0] = getConstant(Fold); 3270 Ops.erase(Ops.begin()+1); // Erase the folded element 3271 if (Ops.size() == 1) return Ops[0]; 3272 LHSC = cast<SCEVConstant>(Ops[0]); 3273 } 3274 3275 // If we are left with a constant minimum-int, strip it off. 3276 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3277 Ops.erase(Ops.begin()); 3278 --Idx; 3279 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3280 // If we have an umax with a constant maximum-int, it will always be 3281 // maximum-int. 3282 return Ops[0]; 3283 } 3284 3285 if (Ops.size() == 1) return Ops[0]; 3286 } 3287 3288 // Find the first UMax 3289 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3290 ++Idx; 3291 3292 // Check to see if one of the operands is a UMax. If so, expand its operands 3293 // onto our operand list, and recurse to simplify. 3294 if (Idx < Ops.size()) { 3295 bool DeletedUMax = false; 3296 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3297 Ops.erase(Ops.begin()+Idx); 3298 Ops.append(UMax->op_begin(), UMax->op_end()); 3299 DeletedUMax = true; 3300 } 3301 3302 if (DeletedUMax) 3303 return getUMaxExpr(Ops); 3304 } 3305 3306 // Okay, check to see if the same value occurs in the operand list twice. If 3307 // so, delete one. Since we sorted the list, these values are required to 3308 // be adjacent. 3309 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3310 // X umax Y umax Y --> X umax Y 3311 // X umax Y --> X, if X is always greater than Y 3312 if (Ops[i] == Ops[i+1] || 3313 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3314 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3315 --i; --e; 3316 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3317 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3318 --i; --e; 3319 } 3320 3321 if (Ops.size() == 1) return Ops[0]; 3322 3323 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3324 3325 // Okay, it looks like we really DO need a umax expr. Check to see if we 3326 // already have one, otherwise create a new one. 3327 FoldingSetNodeID ID; 3328 ID.AddInteger(scUMaxExpr); 3329 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3330 ID.AddPointer(Ops[i]); 3331 void *IP = nullptr; 3332 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3333 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3334 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3335 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3336 O, Ops.size()); 3337 UniqueSCEVs.InsertNode(S, IP); 3338 return S; 3339 } 3340 3341 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3342 const SCEV *RHS) { 3343 // ~smax(~x, ~y) == smin(x, y). 3344 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3345 } 3346 3347 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3348 const SCEV *RHS) { 3349 // ~umax(~x, ~y) == umin(x, y) 3350 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3351 } 3352 3353 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3354 // We can bypass creating a target-independent 3355 // constant expression and then folding it back into a ConstantInt. 3356 // This is just a compile-time optimization. 3357 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3358 } 3359 3360 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3361 StructType *STy, 3362 unsigned FieldNo) { 3363 // We can bypass creating a target-independent 3364 // constant expression and then folding it back into a ConstantInt. 3365 // This is just a compile-time optimization. 3366 return getConstant( 3367 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3368 } 3369 3370 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3371 // Don't attempt to do anything other than create a SCEVUnknown object 3372 // here. createSCEV only calls getUnknown after checking for all other 3373 // interesting possibilities, and any other code that calls getUnknown 3374 // is doing so in order to hide a value from SCEV canonicalization. 3375 3376 FoldingSetNodeID ID; 3377 ID.AddInteger(scUnknown); 3378 ID.AddPointer(V); 3379 void *IP = nullptr; 3380 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3381 assert(cast<SCEVUnknown>(S)->getValue() == V && 3382 "Stale SCEVUnknown in uniquing map!"); 3383 return S; 3384 } 3385 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3386 FirstUnknown); 3387 FirstUnknown = cast<SCEVUnknown>(S); 3388 UniqueSCEVs.InsertNode(S, IP); 3389 return S; 3390 } 3391 3392 //===----------------------------------------------------------------------===// 3393 // Basic SCEV Analysis and PHI Idiom Recognition Code 3394 // 3395 3396 /// Test if values of the given type are analyzable within the SCEV 3397 /// framework. This primarily includes integer types, and it can optionally 3398 /// include pointer types if the ScalarEvolution class has access to 3399 /// target-specific information. 3400 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3401 // Integers and pointers are always SCEVable. 3402 return Ty->isIntegerTy() || Ty->isPointerTy(); 3403 } 3404 3405 /// Return the size in bits of the specified type, for which isSCEVable must 3406 /// return true. 3407 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3408 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3409 return getDataLayout().getTypeSizeInBits(Ty); 3410 } 3411 3412 /// Return a type with the same bitwidth as the given type and which represents 3413 /// how SCEV will treat the given type, for which isSCEVable must return 3414 /// true. For pointer types, this is the pointer-sized integer type. 3415 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3416 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3417 3418 if (Ty->isIntegerTy()) 3419 return Ty; 3420 3421 // The only other support type is pointer. 3422 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3423 return getDataLayout().getIntPtrType(Ty); 3424 } 3425 3426 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3427 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3428 } 3429 3430 const SCEV *ScalarEvolution::getCouldNotCompute() { 3431 return CouldNotCompute.get(); 3432 } 3433 3434 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3435 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3436 auto *SU = dyn_cast<SCEVUnknown>(S); 3437 return SU && SU->getValue() == nullptr; 3438 }); 3439 3440 return !ContainsNulls; 3441 } 3442 3443 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3444 HasRecMapType::iterator I = HasRecMap.find(S); 3445 if (I != HasRecMap.end()) 3446 return I->second; 3447 3448 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3449 HasRecMap.insert({S, FoundAddRec}); 3450 return FoundAddRec; 3451 } 3452 3453 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3454 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3455 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3456 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3457 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3458 if (!Add) 3459 return {S, nullptr}; 3460 3461 if (Add->getNumOperands() != 2) 3462 return {S, nullptr}; 3463 3464 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3465 if (!ConstOp) 3466 return {S, nullptr}; 3467 3468 return {Add->getOperand(1), ConstOp->getValue()}; 3469 } 3470 3471 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3472 /// by the value and offset from any ValueOffsetPair in the set. 3473 SetVector<ScalarEvolution::ValueOffsetPair> * 3474 ScalarEvolution::getSCEVValues(const SCEV *S) { 3475 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3476 if (SI == ExprValueMap.end()) 3477 return nullptr; 3478 #ifndef NDEBUG 3479 if (VerifySCEVMap) { 3480 // Check there is no dangling Value in the set returned. 3481 for (const auto &VE : SI->second) 3482 assert(ValueExprMap.count(VE.first)); 3483 } 3484 #endif 3485 return &SI->second; 3486 } 3487 3488 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3489 /// cannot be used separately. eraseValueFromMap should be used to remove 3490 /// V from ValueExprMap and ExprValueMap at the same time. 3491 void ScalarEvolution::eraseValueFromMap(Value *V) { 3492 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3493 if (I != ValueExprMap.end()) { 3494 const SCEV *S = I->second; 3495 // Remove {V, 0} from the set of ExprValueMap[S] 3496 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3497 SV->remove({V, nullptr}); 3498 3499 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3500 const SCEV *Stripped; 3501 ConstantInt *Offset; 3502 std::tie(Stripped, Offset) = splitAddExpr(S); 3503 if (Offset != nullptr) { 3504 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3505 SV->remove({V, Offset}); 3506 } 3507 ValueExprMap.erase(V); 3508 } 3509 } 3510 3511 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3512 /// create a new one. 3513 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3514 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3515 3516 const SCEV *S = getExistingSCEV(V); 3517 if (S == nullptr) { 3518 S = createSCEV(V); 3519 // During PHI resolution, it is possible to create two SCEVs for the same 3520 // V, so it is needed to double check whether V->S is inserted into 3521 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3522 std::pair<ValueExprMapType::iterator, bool> Pair = 3523 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3524 if (Pair.second) { 3525 ExprValueMap[S].insert({V, nullptr}); 3526 3527 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3528 // ExprValueMap. 3529 const SCEV *Stripped = S; 3530 ConstantInt *Offset = nullptr; 3531 std::tie(Stripped, Offset) = splitAddExpr(S); 3532 // If stripped is SCEVUnknown, don't bother to save 3533 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3534 // increase the complexity of the expansion code. 3535 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3536 // because it may generate add/sub instead of GEP in SCEV expansion. 3537 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3538 !isa<GetElementPtrInst>(V)) 3539 ExprValueMap[Stripped].insert({V, Offset}); 3540 } 3541 } 3542 return S; 3543 } 3544 3545 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3546 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3547 3548 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3549 if (I != ValueExprMap.end()) { 3550 const SCEV *S = I->second; 3551 if (checkValidity(S)) 3552 return S; 3553 eraseValueFromMap(V); 3554 forgetMemoizedResults(S); 3555 } 3556 return nullptr; 3557 } 3558 3559 /// Return a SCEV corresponding to -V = -1*V 3560 /// 3561 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3562 SCEV::NoWrapFlags Flags) { 3563 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3564 return getConstant( 3565 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3566 3567 Type *Ty = V->getType(); 3568 Ty = getEffectiveSCEVType(Ty); 3569 return getMulExpr( 3570 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3571 } 3572 3573 /// Return a SCEV corresponding to ~V = -1-V 3574 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3575 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3576 return getConstant( 3577 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3578 3579 Type *Ty = V->getType(); 3580 Ty = getEffectiveSCEVType(Ty); 3581 const SCEV *AllOnes = 3582 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3583 return getMinusSCEV(AllOnes, V); 3584 } 3585 3586 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3587 SCEV::NoWrapFlags Flags) { 3588 // Fast path: X - X --> 0. 3589 if (LHS == RHS) 3590 return getZero(LHS->getType()); 3591 3592 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3593 // makes it so that we cannot make much use of NUW. 3594 auto AddFlags = SCEV::FlagAnyWrap; 3595 const bool RHSIsNotMinSigned = 3596 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3597 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3598 // Let M be the minimum representable signed value. Then (-1)*RHS 3599 // signed-wraps if and only if RHS is M. That can happen even for 3600 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3601 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3602 // (-1)*RHS, we need to prove that RHS != M. 3603 // 3604 // If LHS is non-negative and we know that LHS - RHS does not 3605 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3606 // either by proving that RHS > M or that LHS >= 0. 3607 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3608 AddFlags = SCEV::FlagNSW; 3609 } 3610 } 3611 3612 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3613 // RHS is NSW and LHS >= 0. 3614 // 3615 // The difficulty here is that the NSW flag may have been proven 3616 // relative to a loop that is to be found in a recurrence in LHS and 3617 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3618 // larger scope than intended. 3619 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3620 3621 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3622 } 3623 3624 const SCEV * 3625 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3626 Type *SrcTy = V->getType(); 3627 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3628 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3629 "Cannot truncate or zero extend with non-integer arguments!"); 3630 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3631 return V; // No conversion 3632 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3633 return getTruncateExpr(V, Ty); 3634 return getZeroExtendExpr(V, Ty); 3635 } 3636 3637 const SCEV * 3638 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3639 Type *Ty) { 3640 Type *SrcTy = V->getType(); 3641 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3642 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3643 "Cannot truncate or zero extend with non-integer arguments!"); 3644 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3645 return V; // No conversion 3646 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3647 return getTruncateExpr(V, Ty); 3648 return getSignExtendExpr(V, Ty); 3649 } 3650 3651 const SCEV * 3652 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3653 Type *SrcTy = V->getType(); 3654 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3655 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3656 "Cannot noop or zero extend with non-integer arguments!"); 3657 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3658 "getNoopOrZeroExtend cannot truncate!"); 3659 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3660 return V; // No conversion 3661 return getZeroExtendExpr(V, Ty); 3662 } 3663 3664 const SCEV * 3665 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3666 Type *SrcTy = V->getType(); 3667 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3668 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3669 "Cannot noop or sign extend with non-integer arguments!"); 3670 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3671 "getNoopOrSignExtend cannot truncate!"); 3672 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3673 return V; // No conversion 3674 return getSignExtendExpr(V, Ty); 3675 } 3676 3677 const SCEV * 3678 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3679 Type *SrcTy = V->getType(); 3680 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3681 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3682 "Cannot noop or any extend with non-integer arguments!"); 3683 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3684 "getNoopOrAnyExtend cannot truncate!"); 3685 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3686 return V; // No conversion 3687 return getAnyExtendExpr(V, Ty); 3688 } 3689 3690 const SCEV * 3691 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3692 Type *SrcTy = V->getType(); 3693 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3694 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3695 "Cannot truncate or noop with non-integer arguments!"); 3696 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3697 "getTruncateOrNoop cannot extend!"); 3698 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3699 return V; // No conversion 3700 return getTruncateExpr(V, Ty); 3701 } 3702 3703 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3704 const SCEV *RHS) { 3705 const SCEV *PromotedLHS = LHS; 3706 const SCEV *PromotedRHS = RHS; 3707 3708 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3709 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3710 else 3711 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3712 3713 return getUMaxExpr(PromotedLHS, PromotedRHS); 3714 } 3715 3716 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3717 const SCEV *RHS) { 3718 const SCEV *PromotedLHS = LHS; 3719 const SCEV *PromotedRHS = RHS; 3720 3721 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3722 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3723 else 3724 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3725 3726 return getUMinExpr(PromotedLHS, PromotedRHS); 3727 } 3728 3729 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3730 // A pointer operand may evaluate to a nonpointer expression, such as null. 3731 if (!V->getType()->isPointerTy()) 3732 return V; 3733 3734 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3735 return getPointerBase(Cast->getOperand()); 3736 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3737 const SCEV *PtrOp = nullptr; 3738 for (const SCEV *NAryOp : NAry->operands()) { 3739 if (NAryOp->getType()->isPointerTy()) { 3740 // Cannot find the base of an expression with multiple pointer operands. 3741 if (PtrOp) 3742 return V; 3743 PtrOp = NAryOp; 3744 } 3745 } 3746 if (!PtrOp) 3747 return V; 3748 return getPointerBase(PtrOp); 3749 } 3750 return V; 3751 } 3752 3753 /// Push users of the given Instruction onto the given Worklist. 3754 static void 3755 PushDefUseChildren(Instruction *I, 3756 SmallVectorImpl<Instruction *> &Worklist) { 3757 // Push the def-use children onto the Worklist stack. 3758 for (User *U : I->users()) 3759 Worklist.push_back(cast<Instruction>(U)); 3760 } 3761 3762 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3763 SmallVector<Instruction *, 16> Worklist; 3764 PushDefUseChildren(PN, Worklist); 3765 3766 SmallPtrSet<Instruction *, 8> Visited; 3767 Visited.insert(PN); 3768 while (!Worklist.empty()) { 3769 Instruction *I = Worklist.pop_back_val(); 3770 if (!Visited.insert(I).second) 3771 continue; 3772 3773 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3774 if (It != ValueExprMap.end()) { 3775 const SCEV *Old = It->second; 3776 3777 // Short-circuit the def-use traversal if the symbolic name 3778 // ceases to appear in expressions. 3779 if (Old != SymName && !hasOperand(Old, SymName)) 3780 continue; 3781 3782 // SCEVUnknown for a PHI either means that it has an unrecognized 3783 // structure, it's a PHI that's in the progress of being computed 3784 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3785 // additional loop trip count information isn't going to change anything. 3786 // In the second case, createNodeForPHI will perform the necessary 3787 // updates on its own when it gets to that point. In the third, we do 3788 // want to forget the SCEVUnknown. 3789 if (!isa<PHINode>(I) || 3790 !isa<SCEVUnknown>(Old) || 3791 (I != PN && Old == SymName)) { 3792 eraseValueFromMap(It->first); 3793 forgetMemoizedResults(Old); 3794 } 3795 } 3796 3797 PushDefUseChildren(I, Worklist); 3798 } 3799 } 3800 3801 namespace { 3802 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3803 public: 3804 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3805 ScalarEvolution &SE) { 3806 SCEVInitRewriter Rewriter(L, SE); 3807 const SCEV *Result = Rewriter.visit(S); 3808 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3809 } 3810 3811 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3812 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3813 3814 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3815 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3816 Valid = false; 3817 return Expr; 3818 } 3819 3820 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3821 // Only allow AddRecExprs for this loop. 3822 if (Expr->getLoop() == L) 3823 return Expr->getStart(); 3824 Valid = false; 3825 return Expr; 3826 } 3827 3828 bool isValid() { return Valid; } 3829 3830 private: 3831 const Loop *L; 3832 bool Valid; 3833 }; 3834 3835 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3836 public: 3837 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3838 ScalarEvolution &SE) { 3839 SCEVShiftRewriter Rewriter(L, SE); 3840 const SCEV *Result = Rewriter.visit(S); 3841 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3842 } 3843 3844 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3845 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3846 3847 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3848 // Only allow AddRecExprs for this loop. 3849 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3850 Valid = false; 3851 return Expr; 3852 } 3853 3854 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3855 if (Expr->getLoop() == L && Expr->isAffine()) 3856 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3857 Valid = false; 3858 return Expr; 3859 } 3860 bool isValid() { return Valid; } 3861 3862 private: 3863 const Loop *L; 3864 bool Valid; 3865 }; 3866 } // end anonymous namespace 3867 3868 SCEV::NoWrapFlags 3869 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3870 if (!AR->isAffine()) 3871 return SCEV::FlagAnyWrap; 3872 3873 typedef OverflowingBinaryOperator OBO; 3874 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3875 3876 if (!AR->hasNoSignedWrap()) { 3877 ConstantRange AddRecRange = getSignedRange(AR); 3878 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3879 3880 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3881 Instruction::Add, IncRange, OBO::NoSignedWrap); 3882 if (NSWRegion.contains(AddRecRange)) 3883 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3884 } 3885 3886 if (!AR->hasNoUnsignedWrap()) { 3887 ConstantRange AddRecRange = getUnsignedRange(AR); 3888 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3889 3890 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3891 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3892 if (NUWRegion.contains(AddRecRange)) 3893 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3894 } 3895 3896 return Result; 3897 } 3898 3899 namespace { 3900 /// Represents an abstract binary operation. This may exist as a 3901 /// normal instruction or constant expression, or may have been 3902 /// derived from an expression tree. 3903 struct BinaryOp { 3904 unsigned Opcode; 3905 Value *LHS; 3906 Value *RHS; 3907 bool IsNSW; 3908 bool IsNUW; 3909 3910 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3911 /// constant expression. 3912 Operator *Op; 3913 3914 explicit BinaryOp(Operator *Op) 3915 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3916 IsNSW(false), IsNUW(false), Op(Op) { 3917 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3918 IsNSW = OBO->hasNoSignedWrap(); 3919 IsNUW = OBO->hasNoUnsignedWrap(); 3920 } 3921 } 3922 3923 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3924 bool IsNUW = false) 3925 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3926 Op(nullptr) {} 3927 }; 3928 } 3929 3930 3931 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3932 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3933 auto *Op = dyn_cast<Operator>(V); 3934 if (!Op) 3935 return None; 3936 3937 // Implementation detail: all the cleverness here should happen without 3938 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3939 // SCEV expressions when possible, and we should not break that. 3940 3941 switch (Op->getOpcode()) { 3942 case Instruction::Add: 3943 case Instruction::Sub: 3944 case Instruction::Mul: 3945 case Instruction::UDiv: 3946 case Instruction::And: 3947 case Instruction::Or: 3948 case Instruction::AShr: 3949 case Instruction::Shl: 3950 return BinaryOp(Op); 3951 3952 case Instruction::Xor: 3953 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3954 // If the RHS of the xor is a signbit, then this is just an add. 3955 // Instcombine turns add of signbit into xor as a strength reduction step. 3956 if (RHSC->getValue().isSignBit()) 3957 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3958 return BinaryOp(Op); 3959 3960 case Instruction::LShr: 3961 // Turn logical shift right of a constant into a unsigned divide. 3962 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3963 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3964 3965 // If the shift count is not less than the bitwidth, the result of 3966 // the shift is undefined. Don't try to analyze it, because the 3967 // resolution chosen here may differ from the resolution chosen in 3968 // other parts of the compiler. 3969 if (SA->getValue().ult(BitWidth)) { 3970 Constant *X = 3971 ConstantInt::get(SA->getContext(), 3972 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3973 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3974 } 3975 } 3976 return BinaryOp(Op); 3977 3978 case Instruction::ExtractValue: { 3979 auto *EVI = cast<ExtractValueInst>(Op); 3980 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3981 break; 3982 3983 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3984 if (!CI) 3985 break; 3986 3987 if (auto *F = CI->getCalledFunction()) 3988 switch (F->getIntrinsicID()) { 3989 case Intrinsic::sadd_with_overflow: 3990 case Intrinsic::uadd_with_overflow: { 3991 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3992 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3993 CI->getArgOperand(1)); 3994 3995 // Now that we know that all uses of the arithmetic-result component of 3996 // CI are guarded by the overflow check, we can go ahead and pretend 3997 // that the arithmetic is non-overflowing. 3998 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3999 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4000 CI->getArgOperand(1), /* IsNSW = */ true, 4001 /* IsNUW = */ false); 4002 else 4003 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4004 CI->getArgOperand(1), /* IsNSW = */ false, 4005 /* IsNUW*/ true); 4006 } 4007 4008 case Intrinsic::ssub_with_overflow: 4009 case Intrinsic::usub_with_overflow: 4010 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4011 CI->getArgOperand(1)); 4012 4013 case Intrinsic::smul_with_overflow: 4014 case Intrinsic::umul_with_overflow: 4015 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4016 CI->getArgOperand(1)); 4017 default: 4018 break; 4019 } 4020 } 4021 4022 default: 4023 break; 4024 } 4025 4026 return None; 4027 } 4028 4029 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4030 const Loop *L = LI.getLoopFor(PN->getParent()); 4031 if (!L || L->getHeader() != PN->getParent()) 4032 return nullptr; 4033 4034 // The loop may have multiple entrances or multiple exits; we can analyze 4035 // this phi as an addrec if it has a unique entry value and a unique 4036 // backedge value. 4037 Value *BEValueV = nullptr, *StartValueV = nullptr; 4038 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4039 Value *V = PN->getIncomingValue(i); 4040 if (L->contains(PN->getIncomingBlock(i))) { 4041 if (!BEValueV) { 4042 BEValueV = V; 4043 } else if (BEValueV != V) { 4044 BEValueV = nullptr; 4045 break; 4046 } 4047 } else if (!StartValueV) { 4048 StartValueV = V; 4049 } else if (StartValueV != V) { 4050 StartValueV = nullptr; 4051 break; 4052 } 4053 } 4054 if (BEValueV && StartValueV) { 4055 // While we are analyzing this PHI node, handle its value symbolically. 4056 const SCEV *SymbolicName = getUnknown(PN); 4057 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4058 "PHI node already processed?"); 4059 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4060 4061 // Using this symbolic name for the PHI, analyze the value coming around 4062 // the back-edge. 4063 const SCEV *BEValue = getSCEV(BEValueV); 4064 4065 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4066 // has a special value for the first iteration of the loop. 4067 4068 // If the value coming around the backedge is an add with the symbolic 4069 // value we just inserted, then we found a simple induction variable! 4070 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4071 // If there is a single occurrence of the symbolic value, replace it 4072 // with a recurrence. 4073 unsigned FoundIndex = Add->getNumOperands(); 4074 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4075 if (Add->getOperand(i) == SymbolicName) 4076 if (FoundIndex == e) { 4077 FoundIndex = i; 4078 break; 4079 } 4080 4081 if (FoundIndex != Add->getNumOperands()) { 4082 // Create an add with everything but the specified operand. 4083 SmallVector<const SCEV *, 8> Ops; 4084 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4085 if (i != FoundIndex) 4086 Ops.push_back(Add->getOperand(i)); 4087 const SCEV *Accum = getAddExpr(Ops); 4088 4089 // This is not a valid addrec if the step amount is varying each 4090 // loop iteration, but is not itself an addrec in this loop. 4091 if (isLoopInvariant(Accum, L) || 4092 (isa<SCEVAddRecExpr>(Accum) && 4093 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4094 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4095 4096 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4097 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4098 if (BO->IsNUW) 4099 Flags = setFlags(Flags, SCEV::FlagNUW); 4100 if (BO->IsNSW) 4101 Flags = setFlags(Flags, SCEV::FlagNSW); 4102 } 4103 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4104 // If the increment is an inbounds GEP, then we know the address 4105 // space cannot be wrapped around. We cannot make any guarantee 4106 // about signed or unsigned overflow because pointers are 4107 // unsigned but we may have a negative index from the base 4108 // pointer. We can guarantee that no unsigned wrap occurs if the 4109 // indices form a positive value. 4110 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4111 Flags = setFlags(Flags, SCEV::FlagNW); 4112 4113 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4114 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4115 Flags = setFlags(Flags, SCEV::FlagNUW); 4116 } 4117 4118 // We cannot transfer nuw and nsw flags from subtraction 4119 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4120 // for instance. 4121 } 4122 4123 const SCEV *StartVal = getSCEV(StartValueV); 4124 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4125 4126 // Okay, for the entire analysis of this edge we assumed the PHI 4127 // to be symbolic. We now need to go back and purge all of the 4128 // entries for the scalars that use the symbolic expression. 4129 forgetSymbolicName(PN, SymbolicName); 4130 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4131 4132 // We can add Flags to the post-inc expression only if we 4133 // know that it us *undefined behavior* for BEValueV to 4134 // overflow. 4135 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4136 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4137 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4138 4139 return PHISCEV; 4140 } 4141 } 4142 } else { 4143 // Otherwise, this could be a loop like this: 4144 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4145 // In this case, j = {1,+,1} and BEValue is j. 4146 // Because the other in-value of i (0) fits the evolution of BEValue 4147 // i really is an addrec evolution. 4148 // 4149 // We can generalize this saying that i is the shifted value of BEValue 4150 // by one iteration: 4151 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4152 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4153 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4154 if (Shifted != getCouldNotCompute() && 4155 Start != getCouldNotCompute()) { 4156 const SCEV *StartVal = getSCEV(StartValueV); 4157 if (Start == StartVal) { 4158 // Okay, for the entire analysis of this edge we assumed the PHI 4159 // to be symbolic. We now need to go back and purge all of the 4160 // entries for the scalars that use the symbolic expression. 4161 forgetSymbolicName(PN, SymbolicName); 4162 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4163 return Shifted; 4164 } 4165 } 4166 } 4167 4168 // Remove the temporary PHI node SCEV that has been inserted while intending 4169 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4170 // as it will prevent later (possibly simpler) SCEV expressions to be added 4171 // to the ValueExprMap. 4172 eraseValueFromMap(PN); 4173 } 4174 4175 return nullptr; 4176 } 4177 4178 // Checks if the SCEV S is available at BB. S is considered available at BB 4179 // if S can be materialized at BB without introducing a fault. 4180 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4181 BasicBlock *BB) { 4182 struct CheckAvailable { 4183 bool TraversalDone = false; 4184 bool Available = true; 4185 4186 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4187 BasicBlock *BB = nullptr; 4188 DominatorTree &DT; 4189 4190 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4191 : L(L), BB(BB), DT(DT) {} 4192 4193 bool setUnavailable() { 4194 TraversalDone = true; 4195 Available = false; 4196 return false; 4197 } 4198 4199 bool follow(const SCEV *S) { 4200 switch (S->getSCEVType()) { 4201 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4202 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4203 // These expressions are available if their operand(s) is/are. 4204 return true; 4205 4206 case scAddRecExpr: { 4207 // We allow add recurrences that are on the loop BB is in, or some 4208 // outer loop. This guarantees availability because the value of the 4209 // add recurrence at BB is simply the "current" value of the induction 4210 // variable. We can relax this in the future; for instance an add 4211 // recurrence on a sibling dominating loop is also available at BB. 4212 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4213 if (L && (ARLoop == L || ARLoop->contains(L))) 4214 return true; 4215 4216 return setUnavailable(); 4217 } 4218 4219 case scUnknown: { 4220 // For SCEVUnknown, we check for simple dominance. 4221 const auto *SU = cast<SCEVUnknown>(S); 4222 Value *V = SU->getValue(); 4223 4224 if (isa<Argument>(V)) 4225 return false; 4226 4227 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4228 return false; 4229 4230 return setUnavailable(); 4231 } 4232 4233 case scUDivExpr: 4234 case scCouldNotCompute: 4235 // We do not try to smart about these at all. 4236 return setUnavailable(); 4237 } 4238 llvm_unreachable("switch should be fully covered!"); 4239 } 4240 4241 bool isDone() { return TraversalDone; } 4242 }; 4243 4244 CheckAvailable CA(L, BB, DT); 4245 SCEVTraversal<CheckAvailable> ST(CA); 4246 4247 ST.visitAll(S); 4248 return CA.Available; 4249 } 4250 4251 // Try to match a control flow sequence that branches out at BI and merges back 4252 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4253 // match. 4254 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4255 Value *&C, Value *&LHS, Value *&RHS) { 4256 C = BI->getCondition(); 4257 4258 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4259 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4260 4261 if (!LeftEdge.isSingleEdge()) 4262 return false; 4263 4264 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4265 4266 Use &LeftUse = Merge->getOperandUse(0); 4267 Use &RightUse = Merge->getOperandUse(1); 4268 4269 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4270 LHS = LeftUse; 4271 RHS = RightUse; 4272 return true; 4273 } 4274 4275 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4276 LHS = RightUse; 4277 RHS = LeftUse; 4278 return true; 4279 } 4280 4281 return false; 4282 } 4283 4284 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4285 auto IsReachable = 4286 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4287 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4288 const Loop *L = LI.getLoopFor(PN->getParent()); 4289 4290 // We don't want to break LCSSA, even in a SCEV expression tree. 4291 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4292 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4293 return nullptr; 4294 4295 // Try to match 4296 // 4297 // br %cond, label %left, label %right 4298 // left: 4299 // br label %merge 4300 // right: 4301 // br label %merge 4302 // merge: 4303 // V = phi [ %x, %left ], [ %y, %right ] 4304 // 4305 // as "select %cond, %x, %y" 4306 4307 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4308 assert(IDom && "At least the entry block should dominate PN"); 4309 4310 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4311 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4312 4313 if (BI && BI->isConditional() && 4314 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4315 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4316 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4317 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4318 } 4319 4320 return nullptr; 4321 } 4322 4323 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4324 if (const SCEV *S = createAddRecFromPHI(PN)) 4325 return S; 4326 4327 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4328 return S; 4329 4330 // If the PHI has a single incoming value, follow that value, unless the 4331 // PHI's incoming blocks are in a different loop, in which case doing so 4332 // risks breaking LCSSA form. Instcombine would normally zap these, but 4333 // it doesn't have DominatorTree information, so it may miss cases. 4334 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4335 if (LI.replacementPreservesLCSSAForm(PN, V)) 4336 return getSCEV(V); 4337 4338 // If it's not a loop phi, we can't handle it yet. 4339 return getUnknown(PN); 4340 } 4341 4342 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4343 Value *Cond, 4344 Value *TrueVal, 4345 Value *FalseVal) { 4346 // Handle "constant" branch or select. This can occur for instance when a 4347 // loop pass transforms an inner loop and moves on to process the outer loop. 4348 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4349 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4350 4351 // Try to match some simple smax or umax patterns. 4352 auto *ICI = dyn_cast<ICmpInst>(Cond); 4353 if (!ICI) 4354 return getUnknown(I); 4355 4356 Value *LHS = ICI->getOperand(0); 4357 Value *RHS = ICI->getOperand(1); 4358 4359 switch (ICI->getPredicate()) { 4360 case ICmpInst::ICMP_SLT: 4361 case ICmpInst::ICMP_SLE: 4362 std::swap(LHS, RHS); 4363 LLVM_FALLTHROUGH; 4364 case ICmpInst::ICMP_SGT: 4365 case ICmpInst::ICMP_SGE: 4366 // a >s b ? a+x : b+x -> smax(a, b)+x 4367 // a >s b ? b+x : a+x -> smin(a, b)+x 4368 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4369 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4370 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4371 const SCEV *LA = getSCEV(TrueVal); 4372 const SCEV *RA = getSCEV(FalseVal); 4373 const SCEV *LDiff = getMinusSCEV(LA, LS); 4374 const SCEV *RDiff = getMinusSCEV(RA, RS); 4375 if (LDiff == RDiff) 4376 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4377 LDiff = getMinusSCEV(LA, RS); 4378 RDiff = getMinusSCEV(RA, LS); 4379 if (LDiff == RDiff) 4380 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4381 } 4382 break; 4383 case ICmpInst::ICMP_ULT: 4384 case ICmpInst::ICMP_ULE: 4385 std::swap(LHS, RHS); 4386 LLVM_FALLTHROUGH; 4387 case ICmpInst::ICMP_UGT: 4388 case ICmpInst::ICMP_UGE: 4389 // a >u b ? a+x : b+x -> umax(a, b)+x 4390 // a >u b ? b+x : a+x -> umin(a, b)+x 4391 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4392 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4393 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4394 const SCEV *LA = getSCEV(TrueVal); 4395 const SCEV *RA = getSCEV(FalseVal); 4396 const SCEV *LDiff = getMinusSCEV(LA, LS); 4397 const SCEV *RDiff = getMinusSCEV(RA, RS); 4398 if (LDiff == RDiff) 4399 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4400 LDiff = getMinusSCEV(LA, RS); 4401 RDiff = getMinusSCEV(RA, LS); 4402 if (LDiff == RDiff) 4403 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4404 } 4405 break; 4406 case ICmpInst::ICMP_NE: 4407 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4408 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4409 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4410 const SCEV *One = getOne(I->getType()); 4411 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4412 const SCEV *LA = getSCEV(TrueVal); 4413 const SCEV *RA = getSCEV(FalseVal); 4414 const SCEV *LDiff = getMinusSCEV(LA, LS); 4415 const SCEV *RDiff = getMinusSCEV(RA, One); 4416 if (LDiff == RDiff) 4417 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4418 } 4419 break; 4420 case ICmpInst::ICMP_EQ: 4421 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4422 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4423 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4424 const SCEV *One = getOne(I->getType()); 4425 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4426 const SCEV *LA = getSCEV(TrueVal); 4427 const SCEV *RA = getSCEV(FalseVal); 4428 const SCEV *LDiff = getMinusSCEV(LA, One); 4429 const SCEV *RDiff = getMinusSCEV(RA, LS); 4430 if (LDiff == RDiff) 4431 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4432 } 4433 break; 4434 default: 4435 break; 4436 } 4437 4438 return getUnknown(I); 4439 } 4440 4441 /// Expand GEP instructions into add and multiply operations. This allows them 4442 /// to be analyzed by regular SCEV code. 4443 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4444 // Don't attempt to analyze GEPs over unsized objects. 4445 if (!GEP->getSourceElementType()->isSized()) 4446 return getUnknown(GEP); 4447 4448 SmallVector<const SCEV *, 4> IndexExprs; 4449 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4450 IndexExprs.push_back(getSCEV(*Index)); 4451 return getGEPExpr(GEP, IndexExprs); 4452 } 4453 4454 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 4455 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4456 return C->getAPInt().countTrailingZeros(); 4457 4458 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4459 return std::min(GetMinTrailingZeros(T->getOperand()), 4460 (uint32_t)getTypeSizeInBits(T->getType())); 4461 4462 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4463 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4464 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4465 ? getTypeSizeInBits(E->getType()) 4466 : OpRes; 4467 } 4468 4469 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4470 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4471 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 4472 ? getTypeSizeInBits(E->getType()) 4473 : OpRes; 4474 } 4475 4476 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4477 // The result is the min of all operands results. 4478 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4479 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4480 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4481 return MinOpRes; 4482 } 4483 4484 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4485 // The result is the sum of all operands results. 4486 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4487 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4488 for (unsigned i = 1, e = M->getNumOperands(); 4489 SumOpRes != BitWidth && i != e; ++i) 4490 SumOpRes = 4491 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 4492 return SumOpRes; 4493 } 4494 4495 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4496 // The result is the min of all operands results. 4497 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4498 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4500 return MinOpRes; 4501 } 4502 4503 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4504 // The result is the min of all operands results. 4505 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4506 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4507 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4508 return MinOpRes; 4509 } 4510 4511 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4512 // The result is the min of all operands results. 4513 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4514 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4515 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4516 return MinOpRes; 4517 } 4518 4519 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4520 // For a SCEVUnknown, ask ValueTracking. 4521 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4522 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4523 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4524 nullptr, &DT); 4525 return Zeros.countTrailingOnes(); 4526 } 4527 4528 // SCEVUDivExpr 4529 return 0; 4530 } 4531 4532 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4533 auto I = MinTrailingZerosCache.find(S); 4534 if (I != MinTrailingZerosCache.end()) 4535 return I->second; 4536 4537 uint32_t Result = GetMinTrailingZerosImpl(S); 4538 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 4539 assert(InsertPair.second && "Should insert a new key"); 4540 return InsertPair.first->second; 4541 } 4542 4543 /// Helper method to assign a range to V from metadata present in the IR. 4544 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4545 if (Instruction *I = dyn_cast<Instruction>(V)) 4546 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4547 return getConstantRangeFromMetadata(*MD); 4548 4549 return None; 4550 } 4551 4552 /// Determine the range for a particular SCEV. If SignHint is 4553 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4554 /// with a "cleaner" unsigned (resp. signed) representation. 4555 ConstantRange 4556 ScalarEvolution::getRange(const SCEV *S, 4557 ScalarEvolution::RangeSignHint SignHint) { 4558 DenseMap<const SCEV *, ConstantRange> &Cache = 4559 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4560 : SignedRanges; 4561 4562 // See if we've computed this range already. 4563 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4564 if (I != Cache.end()) 4565 return I->second; 4566 4567 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4568 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4569 4570 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4571 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4572 4573 // If the value has known zeros, the maximum value will have those known zeros 4574 // as well. 4575 uint32_t TZ = GetMinTrailingZeros(S); 4576 if (TZ != 0) { 4577 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4578 ConservativeResult = 4579 ConstantRange(APInt::getMinValue(BitWidth), 4580 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4581 else 4582 ConservativeResult = ConstantRange( 4583 APInt::getSignedMinValue(BitWidth), 4584 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4585 } 4586 4587 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4588 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4589 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4590 X = X.add(getRange(Add->getOperand(i), SignHint)); 4591 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4592 } 4593 4594 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4595 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4596 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4597 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4598 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4599 } 4600 4601 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4602 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4603 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4604 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4605 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4606 } 4607 4608 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4609 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4610 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4611 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4612 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4613 } 4614 4615 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4616 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4617 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4618 return setRange(UDiv, SignHint, 4619 ConservativeResult.intersectWith(X.udiv(Y))); 4620 } 4621 4622 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4623 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4624 return setRange(ZExt, SignHint, 4625 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4626 } 4627 4628 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4629 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4630 return setRange(SExt, SignHint, 4631 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4632 } 4633 4634 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4635 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4636 return setRange(Trunc, SignHint, 4637 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4638 } 4639 4640 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4641 // If there's no unsigned wrap, the value will never be less than its 4642 // initial value. 4643 if (AddRec->hasNoUnsignedWrap()) 4644 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4645 if (!C->getValue()->isZero()) 4646 ConservativeResult = ConservativeResult.intersectWith( 4647 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4648 4649 // If there's no signed wrap, and all the operands have the same sign or 4650 // zero, the value won't ever change sign. 4651 if (AddRec->hasNoSignedWrap()) { 4652 bool AllNonNeg = true; 4653 bool AllNonPos = true; 4654 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4655 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4656 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4657 } 4658 if (AllNonNeg) 4659 ConservativeResult = ConservativeResult.intersectWith( 4660 ConstantRange(APInt(BitWidth, 0), 4661 APInt::getSignedMinValue(BitWidth))); 4662 else if (AllNonPos) 4663 ConservativeResult = ConservativeResult.intersectWith( 4664 ConstantRange(APInt::getSignedMinValue(BitWidth), 4665 APInt(BitWidth, 1))); 4666 } 4667 4668 // TODO: non-affine addrec 4669 if (AddRec->isAffine()) { 4670 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4671 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4672 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4673 auto RangeFromAffine = getRangeForAffineAR( 4674 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4675 BitWidth); 4676 if (!RangeFromAffine.isFullSet()) 4677 ConservativeResult = 4678 ConservativeResult.intersectWith(RangeFromAffine); 4679 4680 auto RangeFromFactoring = getRangeViaFactoring( 4681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4682 BitWidth); 4683 if (!RangeFromFactoring.isFullSet()) 4684 ConservativeResult = 4685 ConservativeResult.intersectWith(RangeFromFactoring); 4686 } 4687 } 4688 4689 return setRange(AddRec, SignHint, ConservativeResult); 4690 } 4691 4692 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4693 // Check if the IR explicitly contains !range metadata. 4694 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4695 if (MDRange.hasValue()) 4696 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4697 4698 // Split here to avoid paying the compile-time cost of calling both 4699 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4700 // if needed. 4701 const DataLayout &DL = getDataLayout(); 4702 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4703 // For a SCEVUnknown, ask ValueTracking. 4704 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4705 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4706 if (Ones != ~Zeros + 1) 4707 ConservativeResult = 4708 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4709 } else { 4710 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4711 "generalize as needed!"); 4712 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4713 if (NS > 1) 4714 ConservativeResult = ConservativeResult.intersectWith( 4715 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4716 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4717 } 4718 4719 return setRange(U, SignHint, ConservativeResult); 4720 } 4721 4722 return setRange(S, SignHint, ConservativeResult); 4723 } 4724 4725 // Given a StartRange, Step and MaxBECount for an expression compute a range of 4726 // values that the expression can take. Initially, the expression has a value 4727 // from StartRange and then is changed by Step up to MaxBECount times. Signed 4728 // argument defines if we treat Step as signed or unsigned. 4729 static ConstantRange getRangeForAffineARHelper(APInt Step, 4730 ConstantRange StartRange, 4731 APInt MaxBECount, 4732 unsigned BitWidth, bool Signed) { 4733 // If either Step or MaxBECount is 0, then the expression won't change, and we 4734 // just need to return the initial range. 4735 if (Step == 0 || MaxBECount == 0) 4736 return StartRange; 4737 4738 // If we don't know anything about the initial value (i.e. StartRange is 4739 // FullRange), then we don't know anything about the final range either. 4740 // Return FullRange. 4741 if (StartRange.isFullSet()) 4742 return ConstantRange(BitWidth, /* isFullSet = */ true); 4743 4744 // If Step is signed and negative, then we use its absolute value, but we also 4745 // note that we're moving in the opposite direction. 4746 bool Descending = Signed && Step.isNegative(); 4747 4748 if (Signed) 4749 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 4750 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 4751 // This equations hold true due to the well-defined wrap-around behavior of 4752 // APInt. 4753 Step = Step.abs(); 4754 4755 // Check if Offset is more than full span of BitWidth. If it is, the 4756 // expression is guaranteed to overflow. 4757 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 4758 return ConstantRange(BitWidth, /* isFullSet = */ true); 4759 4760 // Offset is by how much the expression can change. Checks above guarantee no 4761 // overflow here. 4762 APInt Offset = Step * MaxBECount; 4763 4764 // Minimum value of the final range will match the minimal value of StartRange 4765 // if the expression is increasing and will be decreased by Offset otherwise. 4766 // Maximum value of the final range will match the maximal value of StartRange 4767 // if the expression is decreasing and will be increased by Offset otherwise. 4768 APInt StartLower = StartRange.getLower(); 4769 APInt StartUpper = StartRange.getUpper() - 1; 4770 APInt MovedBoundary = 4771 Descending ? (StartLower - Offset) : (StartUpper + Offset); 4772 4773 // It's possible that the new minimum/maximum value will fall into the initial 4774 // range (due to wrap around). This means that the expression can take any 4775 // value in this bitwidth, and we have to return full range. 4776 if (StartRange.contains(MovedBoundary)) 4777 return ConstantRange(BitWidth, /* isFullSet = */ true); 4778 4779 APInt NewLower, NewUpper; 4780 if (Descending) { 4781 NewLower = MovedBoundary; 4782 NewUpper = StartUpper; 4783 } else { 4784 NewLower = StartLower; 4785 NewUpper = MovedBoundary; 4786 } 4787 4788 // If we end up with full range, return a proper full range. 4789 if (NewLower == NewUpper + 1) 4790 return ConstantRange(BitWidth, /* isFullSet = */ true); 4791 4792 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 4793 return ConstantRange(NewLower, NewUpper + 1); 4794 } 4795 4796 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4797 const SCEV *Step, 4798 const SCEV *MaxBECount, 4799 unsigned BitWidth) { 4800 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4801 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4802 "Precondition!"); 4803 4804 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4805 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4806 APInt MaxBECountValue = MaxBECountRange.getUnsignedMax(); 4807 4808 // First, consider step signed. 4809 ConstantRange StartSRange = getSignedRange(Start); 4810 ConstantRange StepSRange = getSignedRange(Step); 4811 4812 // If Step can be both positive and negative, we need to find ranges for the 4813 // maximum absolute step values in both directions and union them. 4814 ConstantRange SR = 4815 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 4816 MaxBECountValue, BitWidth, /* Signed = */ true); 4817 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 4818 StartSRange, MaxBECountValue, 4819 BitWidth, /* Signed = */ true)); 4820 4821 // Next, consider step unsigned. 4822 ConstantRange UR = getRangeForAffineARHelper( 4823 getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start), 4824 MaxBECountValue, BitWidth, /* Signed = */ false); 4825 4826 // Finally, intersect signed and unsigned ranges. 4827 return SR.intersectWith(UR); 4828 } 4829 4830 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4831 const SCEV *Step, 4832 const SCEV *MaxBECount, 4833 unsigned BitWidth) { 4834 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4835 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4836 4837 struct SelectPattern { 4838 Value *Condition = nullptr; 4839 APInt TrueValue; 4840 APInt FalseValue; 4841 4842 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4843 const SCEV *S) { 4844 Optional<unsigned> CastOp; 4845 APInt Offset(BitWidth, 0); 4846 4847 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4848 "Should be!"); 4849 4850 // Peel off a constant offset: 4851 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4852 // In the future we could consider being smarter here and handle 4853 // {Start+Step,+,Step} too. 4854 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4855 return; 4856 4857 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4858 S = SA->getOperand(1); 4859 } 4860 4861 // Peel off a cast operation 4862 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4863 CastOp = SCast->getSCEVType(); 4864 S = SCast->getOperand(); 4865 } 4866 4867 using namespace llvm::PatternMatch; 4868 4869 auto *SU = dyn_cast<SCEVUnknown>(S); 4870 const APInt *TrueVal, *FalseVal; 4871 if (!SU || 4872 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4873 m_APInt(FalseVal)))) { 4874 Condition = nullptr; 4875 return; 4876 } 4877 4878 TrueValue = *TrueVal; 4879 FalseValue = *FalseVal; 4880 4881 // Re-apply the cast we peeled off earlier 4882 if (CastOp.hasValue()) 4883 switch (*CastOp) { 4884 default: 4885 llvm_unreachable("Unknown SCEV cast type!"); 4886 4887 case scTruncate: 4888 TrueValue = TrueValue.trunc(BitWidth); 4889 FalseValue = FalseValue.trunc(BitWidth); 4890 break; 4891 case scZeroExtend: 4892 TrueValue = TrueValue.zext(BitWidth); 4893 FalseValue = FalseValue.zext(BitWidth); 4894 break; 4895 case scSignExtend: 4896 TrueValue = TrueValue.sext(BitWidth); 4897 FalseValue = FalseValue.sext(BitWidth); 4898 break; 4899 } 4900 4901 // Re-apply the constant offset we peeled off earlier 4902 TrueValue += Offset; 4903 FalseValue += Offset; 4904 } 4905 4906 bool isRecognized() { return Condition != nullptr; } 4907 }; 4908 4909 SelectPattern StartPattern(*this, BitWidth, Start); 4910 if (!StartPattern.isRecognized()) 4911 return ConstantRange(BitWidth, /* isFullSet = */ true); 4912 4913 SelectPattern StepPattern(*this, BitWidth, Step); 4914 if (!StepPattern.isRecognized()) 4915 return ConstantRange(BitWidth, /* isFullSet = */ true); 4916 4917 if (StartPattern.Condition != StepPattern.Condition) { 4918 // We don't handle this case today; but we could, by considering four 4919 // possibilities below instead of two. I'm not sure if there are cases where 4920 // that will help over what getRange already does, though. 4921 return ConstantRange(BitWidth, /* isFullSet = */ true); 4922 } 4923 4924 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4925 // construct arbitrary general SCEV expressions here. This function is called 4926 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4927 // say) can end up caching a suboptimal value. 4928 4929 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4930 // C2352 and C2512 (otherwise it isn't needed). 4931 4932 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4933 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4934 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4935 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4936 4937 ConstantRange TrueRange = 4938 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4939 ConstantRange FalseRange = 4940 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4941 4942 return TrueRange.unionWith(FalseRange); 4943 } 4944 4945 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4946 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4947 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4948 4949 // Return early if there are no flags to propagate to the SCEV. 4950 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4951 if (BinOp->hasNoUnsignedWrap()) 4952 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4953 if (BinOp->hasNoSignedWrap()) 4954 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4955 if (Flags == SCEV::FlagAnyWrap) 4956 return SCEV::FlagAnyWrap; 4957 4958 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4959 } 4960 4961 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4962 // Here we check that I is in the header of the innermost loop containing I, 4963 // since we only deal with instructions in the loop header. The actual loop we 4964 // need to check later will come from an add recurrence, but getting that 4965 // requires computing the SCEV of the operands, which can be expensive. This 4966 // check we can do cheaply to rule out some cases early. 4967 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4968 if (InnermostContainingLoop == nullptr || 4969 InnermostContainingLoop->getHeader() != I->getParent()) 4970 return false; 4971 4972 // Only proceed if we can prove that I does not yield poison. 4973 if (!isKnownNotFullPoison(I)) return false; 4974 4975 // At this point we know that if I is executed, then it does not wrap 4976 // according to at least one of NSW or NUW. If I is not executed, then we do 4977 // not know if the calculation that I represents would wrap. Multiple 4978 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4979 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4980 // derived from other instructions that map to the same SCEV. We cannot make 4981 // that guarantee for cases where I is not executed. So we need to find the 4982 // loop that I is considered in relation to and prove that I is executed for 4983 // every iteration of that loop. That implies that the value that I 4984 // calculates does not wrap anywhere in the loop, so then we can apply the 4985 // flags to the SCEV. 4986 // 4987 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4988 // from different loops, so that we know which loop to prove that I is 4989 // executed in. 4990 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4991 // I could be an extractvalue from a call to an overflow intrinsic. 4992 // TODO: We can do better here in some cases. 4993 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4994 return false; 4995 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4996 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4997 bool AllOtherOpsLoopInvariant = true; 4998 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4999 ++OtherOpIndex) { 5000 if (OtherOpIndex != OpIndex) { 5001 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5002 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5003 AllOtherOpsLoopInvariant = false; 5004 break; 5005 } 5006 } 5007 } 5008 if (AllOtherOpsLoopInvariant && 5009 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5010 return true; 5011 } 5012 } 5013 return false; 5014 } 5015 5016 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5017 // If we know that \c I can never be poison period, then that's enough. 5018 if (isSCEVExprNeverPoison(I)) 5019 return true; 5020 5021 // For an add recurrence specifically, we assume that infinite loops without 5022 // side effects are undefined behavior, and then reason as follows: 5023 // 5024 // If the add recurrence is poison in any iteration, it is poison on all 5025 // future iterations (since incrementing poison yields poison). If the result 5026 // of the add recurrence is fed into the loop latch condition and the loop 5027 // does not contain any throws or exiting blocks other than the latch, we now 5028 // have the ability to "choose" whether the backedge is taken or not (by 5029 // choosing a sufficiently evil value for the poison feeding into the branch) 5030 // for every iteration including and after the one in which \p I first became 5031 // poison. There are two possibilities (let's call the iteration in which \p 5032 // I first became poison as K): 5033 // 5034 // 1. In the set of iterations including and after K, the loop body executes 5035 // no side effects. In this case executing the backege an infinte number 5036 // of times will yield undefined behavior. 5037 // 5038 // 2. In the set of iterations including and after K, the loop body executes 5039 // at least one side effect. In this case, that specific instance of side 5040 // effect is control dependent on poison, which also yields undefined 5041 // behavior. 5042 5043 auto *ExitingBB = L->getExitingBlock(); 5044 auto *LatchBB = L->getLoopLatch(); 5045 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5046 return false; 5047 5048 SmallPtrSet<const Instruction *, 16> Pushed; 5049 SmallVector<const Instruction *, 8> PoisonStack; 5050 5051 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5052 // things that are known to be fully poison under that assumption go on the 5053 // PoisonStack. 5054 Pushed.insert(I); 5055 PoisonStack.push_back(I); 5056 5057 bool LatchControlDependentOnPoison = false; 5058 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5059 const Instruction *Poison = PoisonStack.pop_back_val(); 5060 5061 for (auto *PoisonUser : Poison->users()) { 5062 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5063 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5064 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5065 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5066 assert(BI->isConditional() && "Only possibility!"); 5067 if (BI->getParent() == LatchBB) { 5068 LatchControlDependentOnPoison = true; 5069 break; 5070 } 5071 } 5072 } 5073 } 5074 5075 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5076 } 5077 5078 ScalarEvolution::LoopProperties 5079 ScalarEvolution::getLoopProperties(const Loop *L) { 5080 typedef ScalarEvolution::LoopProperties LoopProperties; 5081 5082 auto Itr = LoopPropertiesCache.find(L); 5083 if (Itr == LoopPropertiesCache.end()) { 5084 auto HasSideEffects = [](Instruction *I) { 5085 if (auto *SI = dyn_cast<StoreInst>(I)) 5086 return !SI->isSimple(); 5087 5088 return I->mayHaveSideEffects(); 5089 }; 5090 5091 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5092 /*HasNoSideEffects*/ true}; 5093 5094 for (auto *BB : L->getBlocks()) 5095 for (auto &I : *BB) { 5096 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5097 LP.HasNoAbnormalExits = false; 5098 if (HasSideEffects(&I)) 5099 LP.HasNoSideEffects = false; 5100 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5101 break; // We're already as pessimistic as we can get. 5102 } 5103 5104 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5105 assert(InsertPair.second && "We just checked!"); 5106 Itr = InsertPair.first; 5107 } 5108 5109 return Itr->second; 5110 } 5111 5112 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5113 if (!isSCEVable(V->getType())) 5114 return getUnknown(V); 5115 5116 if (Instruction *I = dyn_cast<Instruction>(V)) { 5117 // Don't attempt to analyze instructions in blocks that aren't 5118 // reachable. Such instructions don't matter, and they aren't required 5119 // to obey basic rules for definitions dominating uses which this 5120 // analysis depends on. 5121 if (!DT.isReachableFromEntry(I->getParent())) 5122 return getUnknown(V); 5123 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5124 return getConstant(CI); 5125 else if (isa<ConstantPointerNull>(V)) 5126 return getZero(V->getType()); 5127 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5128 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5129 else if (!isa<ConstantExpr>(V)) 5130 return getUnknown(V); 5131 5132 Operator *U = cast<Operator>(V); 5133 if (auto BO = MatchBinaryOp(U, DT)) { 5134 switch (BO->Opcode) { 5135 case Instruction::Add: { 5136 // The simple thing to do would be to just call getSCEV on both operands 5137 // and call getAddExpr with the result. However if we're looking at a 5138 // bunch of things all added together, this can be quite inefficient, 5139 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5140 // Instead, gather up all the operands and make a single getAddExpr call. 5141 // LLVM IR canonical form means we need only traverse the left operands. 5142 SmallVector<const SCEV *, 4> AddOps; 5143 do { 5144 if (BO->Op) { 5145 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5146 AddOps.push_back(OpSCEV); 5147 break; 5148 } 5149 5150 // If a NUW or NSW flag can be applied to the SCEV for this 5151 // addition, then compute the SCEV for this addition by itself 5152 // with a separate call to getAddExpr. We need to do that 5153 // instead of pushing the operands of the addition onto AddOps, 5154 // since the flags are only known to apply to this particular 5155 // addition - they may not apply to other additions that can be 5156 // formed with operands from AddOps. 5157 const SCEV *RHS = getSCEV(BO->RHS); 5158 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5159 if (Flags != SCEV::FlagAnyWrap) { 5160 const SCEV *LHS = getSCEV(BO->LHS); 5161 if (BO->Opcode == Instruction::Sub) 5162 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5163 else 5164 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5165 break; 5166 } 5167 } 5168 5169 if (BO->Opcode == Instruction::Sub) 5170 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5171 else 5172 AddOps.push_back(getSCEV(BO->RHS)); 5173 5174 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5175 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5176 NewBO->Opcode != Instruction::Sub)) { 5177 AddOps.push_back(getSCEV(BO->LHS)); 5178 break; 5179 } 5180 BO = NewBO; 5181 } while (true); 5182 5183 return getAddExpr(AddOps); 5184 } 5185 5186 case Instruction::Mul: { 5187 SmallVector<const SCEV *, 4> MulOps; 5188 do { 5189 if (BO->Op) { 5190 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5191 MulOps.push_back(OpSCEV); 5192 break; 5193 } 5194 5195 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5196 if (Flags != SCEV::FlagAnyWrap) { 5197 MulOps.push_back( 5198 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5199 break; 5200 } 5201 } 5202 5203 MulOps.push_back(getSCEV(BO->RHS)); 5204 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5205 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5206 MulOps.push_back(getSCEV(BO->LHS)); 5207 break; 5208 } 5209 BO = NewBO; 5210 } while (true); 5211 5212 return getMulExpr(MulOps); 5213 } 5214 case Instruction::UDiv: 5215 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5216 case Instruction::Sub: { 5217 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5218 if (BO->Op) 5219 Flags = getNoWrapFlagsFromUB(BO->Op); 5220 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5221 } 5222 case Instruction::And: 5223 // For an expression like x&255 that merely masks off the high bits, 5224 // use zext(trunc(x)) as the SCEV expression. 5225 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5226 if (CI->isNullValue()) 5227 return getSCEV(BO->RHS); 5228 if (CI->isAllOnesValue()) 5229 return getSCEV(BO->LHS); 5230 const APInt &A = CI->getValue(); 5231 5232 // Instcombine's ShrinkDemandedConstant may strip bits out of 5233 // constants, obscuring what would otherwise be a low-bits mask. 5234 // Use computeKnownBits to compute what ShrinkDemandedConstant 5235 // knew about to reconstruct a low-bits mask value. 5236 unsigned LZ = A.countLeadingZeros(); 5237 unsigned TZ = A.countTrailingZeros(); 5238 unsigned BitWidth = A.getBitWidth(); 5239 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5240 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5241 0, &AC, nullptr, &DT); 5242 5243 APInt EffectiveMask = 5244 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5245 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5246 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 5247 const SCEV *LHS = getSCEV(BO->LHS); 5248 const SCEV *ShiftedLHS = nullptr; 5249 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 5250 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 5251 // For an expression like (x * 8) & 8, simplify the multiply. 5252 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 5253 unsigned GCD = std::min(MulZeros, TZ); 5254 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 5255 SmallVector<const SCEV*, 4> MulOps; 5256 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 5257 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 5258 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 5259 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 5260 } 5261 } 5262 if (!ShiftedLHS) 5263 ShiftedLHS = getUDivExpr(LHS, MulCount); 5264 return getMulExpr( 5265 getZeroExtendExpr( 5266 getTruncateExpr(ShiftedLHS, 5267 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5268 BO->LHS->getType()), 5269 MulCount); 5270 } 5271 } 5272 break; 5273 5274 case Instruction::Or: 5275 // If the RHS of the Or is a constant, we may have something like: 5276 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5277 // optimizations will transparently handle this case. 5278 // 5279 // In order for this transformation to be safe, the LHS must be of the 5280 // form X*(2^n) and the Or constant must be less than 2^n. 5281 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5282 const SCEV *LHS = getSCEV(BO->LHS); 5283 const APInt &CIVal = CI->getValue(); 5284 if (GetMinTrailingZeros(LHS) >= 5285 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5286 // Build a plain add SCEV. 5287 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5288 // If the LHS of the add was an addrec and it has no-wrap flags, 5289 // transfer the no-wrap flags, since an or won't introduce a wrap. 5290 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5291 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5292 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5293 OldAR->getNoWrapFlags()); 5294 } 5295 return S; 5296 } 5297 } 5298 break; 5299 5300 case Instruction::Xor: 5301 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5302 // If the RHS of xor is -1, then this is a not operation. 5303 if (CI->isAllOnesValue()) 5304 return getNotSCEV(getSCEV(BO->LHS)); 5305 5306 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5307 // This is a variant of the check for xor with -1, and it handles 5308 // the case where instcombine has trimmed non-demanded bits out 5309 // of an xor with -1. 5310 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5311 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5312 if (LBO->getOpcode() == Instruction::And && 5313 LCI->getValue() == CI->getValue()) 5314 if (const SCEVZeroExtendExpr *Z = 5315 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5316 Type *UTy = BO->LHS->getType(); 5317 const SCEV *Z0 = Z->getOperand(); 5318 Type *Z0Ty = Z0->getType(); 5319 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5320 5321 // If C is a low-bits mask, the zero extend is serving to 5322 // mask off the high bits. Complement the operand and 5323 // re-apply the zext. 5324 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5325 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5326 5327 // If C is a single bit, it may be in the sign-bit position 5328 // before the zero-extend. In this case, represent the xor 5329 // using an add, which is equivalent, and re-apply the zext. 5330 APInt Trunc = CI->getValue().trunc(Z0TySize); 5331 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5332 Trunc.isSignBit()) 5333 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5334 UTy); 5335 } 5336 } 5337 break; 5338 5339 case Instruction::Shl: 5340 // Turn shift left of a constant amount into a multiply. 5341 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5342 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5343 5344 // If the shift count is not less than the bitwidth, the result of 5345 // the shift is undefined. Don't try to analyze it, because the 5346 // resolution chosen here may differ from the resolution chosen in 5347 // other parts of the compiler. 5348 if (SA->getValue().uge(BitWidth)) 5349 break; 5350 5351 // It is currently not resolved how to interpret NSW for left 5352 // shift by BitWidth - 1, so we avoid applying flags in that 5353 // case. Remove this check (or this comment) once the situation 5354 // is resolved. See 5355 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5356 // and http://reviews.llvm.org/D8890 . 5357 auto Flags = SCEV::FlagAnyWrap; 5358 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5359 Flags = getNoWrapFlagsFromUB(BO->Op); 5360 5361 Constant *X = ConstantInt::get(getContext(), 5362 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5363 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5364 } 5365 break; 5366 5367 case Instruction::AShr: 5368 // AShr X, C, where C is a constant. 5369 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 5370 if (!CI) 5371 break; 5372 5373 Type *OuterTy = BO->LHS->getType(); 5374 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 5375 // If the shift count is not less than the bitwidth, the result of 5376 // the shift is undefined. Don't try to analyze it, because the 5377 // resolution chosen here may differ from the resolution chosen in 5378 // other parts of the compiler. 5379 if (CI->getValue().uge(BitWidth)) 5380 break; 5381 5382 if (CI->isNullValue()) 5383 return getSCEV(BO->LHS); // shift by zero --> noop 5384 5385 uint64_t AShrAmt = CI->getZExtValue(); 5386 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 5387 5388 Operator *L = dyn_cast<Operator>(BO->LHS); 5389 if (L && L->getOpcode() == Instruction::Shl) { 5390 // X = Shl A, n 5391 // Y = AShr X, m 5392 // Both n and m are constant. 5393 5394 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 5395 if (L->getOperand(1) == BO->RHS) 5396 // For a two-shift sext-inreg, i.e. n = m, 5397 // use sext(trunc(x)) as the SCEV expression. 5398 return getSignExtendExpr( 5399 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 5400 5401 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 5402 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 5403 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 5404 if (ShlAmt > AShrAmt) { 5405 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 5406 // expression. We already checked that ShlAmt < BitWidth, so 5407 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 5408 // ShlAmt - AShrAmt < Amt. 5409 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 5410 ShlAmt - AShrAmt); 5411 return getSignExtendExpr( 5412 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 5413 getConstant(Mul)), OuterTy); 5414 } 5415 } 5416 } 5417 break; 5418 } 5419 } 5420 5421 switch (U->getOpcode()) { 5422 case Instruction::Trunc: 5423 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5424 5425 case Instruction::ZExt: 5426 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5427 5428 case Instruction::SExt: 5429 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5430 5431 case Instruction::BitCast: 5432 // BitCasts are no-op casts so we just eliminate the cast. 5433 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5434 return getSCEV(U->getOperand(0)); 5435 break; 5436 5437 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5438 // lead to pointer expressions which cannot safely be expanded to GEPs, 5439 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5440 // simplifying integer expressions. 5441 5442 case Instruction::GetElementPtr: 5443 return createNodeForGEP(cast<GEPOperator>(U)); 5444 5445 case Instruction::PHI: 5446 return createNodeForPHI(cast<PHINode>(U)); 5447 5448 case Instruction::Select: 5449 // U can also be a select constant expr, which let fall through. Since 5450 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5451 // constant expressions cannot have instructions as operands, we'd have 5452 // returned getUnknown for a select constant expressions anyway. 5453 if (isa<Instruction>(U)) 5454 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5455 U->getOperand(1), U->getOperand(2)); 5456 break; 5457 5458 case Instruction::Call: 5459 case Instruction::Invoke: 5460 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5461 return getSCEV(RV); 5462 break; 5463 } 5464 5465 return getUnknown(V); 5466 } 5467 5468 5469 5470 //===----------------------------------------------------------------------===// 5471 // Iteration Count Computation Code 5472 // 5473 5474 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5475 if (!ExitCount) 5476 return 0; 5477 5478 ConstantInt *ExitConst = ExitCount->getValue(); 5479 5480 // Guard against huge trip counts. 5481 if (ExitConst->getValue().getActiveBits() > 32) 5482 return 0; 5483 5484 // In case of integer overflow, this returns 0, which is correct. 5485 return ((unsigned)ExitConst->getZExtValue()) + 1; 5486 } 5487 5488 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 5489 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5490 return getSmallConstantTripCount(L, ExitingBB); 5491 5492 // No trip count information for multiple exits. 5493 return 0; 5494 } 5495 5496 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 5497 BasicBlock *ExitingBlock) { 5498 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5499 assert(L->isLoopExiting(ExitingBlock) && 5500 "Exiting block must actually branch out of the loop!"); 5501 const SCEVConstant *ExitCount = 5502 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5503 return getConstantTripCount(ExitCount); 5504 } 5505 5506 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 5507 const auto *MaxExitCount = 5508 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5509 return getConstantTripCount(MaxExitCount); 5510 } 5511 5512 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 5513 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5514 return getSmallConstantTripMultiple(L, ExitingBB); 5515 5516 // No trip multiple information for multiple exits. 5517 return 0; 5518 } 5519 5520 /// Returns the largest constant divisor of the trip count of this loop as a 5521 /// normal unsigned value, if possible. This means that the actual trip count is 5522 /// always a multiple of the returned value (don't forget the trip count could 5523 /// very well be zero as well!). 5524 /// 5525 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5526 /// multiple of a constant (which is also the case if the trip count is simply 5527 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5528 /// if the trip count is very large (>= 2^32). 5529 /// 5530 /// As explained in the comments for getSmallConstantTripCount, this assumes 5531 /// that control exits the loop via ExitingBlock. 5532 unsigned 5533 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 5534 BasicBlock *ExitingBlock) { 5535 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5536 assert(L->isLoopExiting(ExitingBlock) && 5537 "Exiting block must actually branch out of the loop!"); 5538 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5539 if (ExitCount == getCouldNotCompute()) 5540 return 1; 5541 5542 // Get the trip count from the BE count by adding 1. 5543 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5544 5545 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 5546 if (!TC) 5547 // Attempt to factor more general cases. Returns the greatest power of 5548 // two divisor. If overflow happens, the trip count expression is still 5549 // divisible by the greatest power of 2 divisor returned. 5550 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 5551 5552 ConstantInt *Result = TC->getValue(); 5553 5554 // Guard against huge trip counts (this requires checking 5555 // for zero to handle the case where the trip count == -1 and the 5556 // addition wraps). 5557 if (!Result || Result->getValue().getActiveBits() > 32 || 5558 Result->getValue().getActiveBits() == 0) 5559 return 1; 5560 5561 return (unsigned)Result->getZExtValue(); 5562 } 5563 5564 /// Get the expression for the number of loop iterations for which this loop is 5565 /// guaranteed not to exit via ExitingBlock. Otherwise return 5566 /// SCEVCouldNotCompute. 5567 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 5568 BasicBlock *ExitingBlock) { 5569 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5570 } 5571 5572 const SCEV * 5573 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5574 SCEVUnionPredicate &Preds) { 5575 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5576 } 5577 5578 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5579 return getBackedgeTakenInfo(L).getExact(this); 5580 } 5581 5582 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5583 /// known never to be less than the actual backedge taken count. 5584 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5585 return getBackedgeTakenInfo(L).getMax(this); 5586 } 5587 5588 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5589 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5590 } 5591 5592 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5593 static void 5594 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5595 BasicBlock *Header = L->getHeader(); 5596 5597 // Push all Loop-header PHIs onto the Worklist stack. 5598 for (BasicBlock::iterator I = Header->begin(); 5599 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5600 Worklist.push_back(PN); 5601 } 5602 5603 const ScalarEvolution::BackedgeTakenInfo & 5604 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5605 auto &BTI = getBackedgeTakenInfo(L); 5606 if (BTI.hasFullInfo()) 5607 return BTI; 5608 5609 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5610 5611 if (!Pair.second) 5612 return Pair.first->second; 5613 5614 BackedgeTakenInfo Result = 5615 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5616 5617 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5618 } 5619 5620 const ScalarEvolution::BackedgeTakenInfo & 5621 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5622 // Initially insert an invalid entry for this loop. If the insertion 5623 // succeeds, proceed to actually compute a backedge-taken count and 5624 // update the value. The temporary CouldNotCompute value tells SCEV 5625 // code elsewhere that it shouldn't attempt to request a new 5626 // backedge-taken count, which could result in infinite recursion. 5627 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5628 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5629 if (!Pair.second) 5630 return Pair.first->second; 5631 5632 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5633 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5634 // must be cleared in this scope. 5635 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5636 5637 if (Result.getExact(this) != getCouldNotCompute()) { 5638 assert(isLoopInvariant(Result.getExact(this), L) && 5639 isLoopInvariant(Result.getMax(this), L) && 5640 "Computed backedge-taken count isn't loop invariant for loop!"); 5641 ++NumTripCountsComputed; 5642 } 5643 else if (Result.getMax(this) == getCouldNotCompute() && 5644 isa<PHINode>(L->getHeader()->begin())) { 5645 // Only count loops that have phi nodes as not being computable. 5646 ++NumTripCountsNotComputed; 5647 } 5648 5649 // Now that we know more about the trip count for this loop, forget any 5650 // existing SCEV values for PHI nodes in this loop since they are only 5651 // conservative estimates made without the benefit of trip count 5652 // information. This is similar to the code in forgetLoop, except that 5653 // it handles SCEVUnknown PHI nodes specially. 5654 if (Result.hasAnyInfo()) { 5655 SmallVector<Instruction *, 16> Worklist; 5656 PushLoopPHIs(L, Worklist); 5657 5658 SmallPtrSet<Instruction *, 8> Visited; 5659 while (!Worklist.empty()) { 5660 Instruction *I = Worklist.pop_back_val(); 5661 if (!Visited.insert(I).second) 5662 continue; 5663 5664 ValueExprMapType::iterator It = 5665 ValueExprMap.find_as(static_cast<Value *>(I)); 5666 if (It != ValueExprMap.end()) { 5667 const SCEV *Old = It->second; 5668 5669 // SCEVUnknown for a PHI either means that it has an unrecognized 5670 // structure, or it's a PHI that's in the progress of being computed 5671 // by createNodeForPHI. In the former case, additional loop trip 5672 // count information isn't going to change anything. In the later 5673 // case, createNodeForPHI will perform the necessary updates on its 5674 // own when it gets to that point. 5675 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5676 eraseValueFromMap(It->first); 5677 forgetMemoizedResults(Old); 5678 } 5679 if (PHINode *PN = dyn_cast<PHINode>(I)) 5680 ConstantEvolutionLoopExitValue.erase(PN); 5681 } 5682 5683 PushDefUseChildren(I, Worklist); 5684 } 5685 } 5686 5687 // Re-lookup the insert position, since the call to 5688 // computeBackedgeTakenCount above could result in a 5689 // recusive call to getBackedgeTakenInfo (on a different 5690 // loop), which would invalidate the iterator computed 5691 // earlier. 5692 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5693 } 5694 5695 void ScalarEvolution::forgetLoop(const Loop *L) { 5696 // Drop any stored trip count value. 5697 auto RemoveLoopFromBackedgeMap = 5698 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5699 auto BTCPos = Map.find(L); 5700 if (BTCPos != Map.end()) { 5701 BTCPos->second.clear(); 5702 Map.erase(BTCPos); 5703 } 5704 }; 5705 5706 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5707 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5708 5709 // Drop information about expressions based on loop-header PHIs. 5710 SmallVector<Instruction *, 16> Worklist; 5711 PushLoopPHIs(L, Worklist); 5712 5713 SmallPtrSet<Instruction *, 8> Visited; 5714 while (!Worklist.empty()) { 5715 Instruction *I = Worklist.pop_back_val(); 5716 if (!Visited.insert(I).second) 5717 continue; 5718 5719 ValueExprMapType::iterator It = 5720 ValueExprMap.find_as(static_cast<Value *>(I)); 5721 if (It != ValueExprMap.end()) { 5722 eraseValueFromMap(It->first); 5723 forgetMemoizedResults(It->second); 5724 if (PHINode *PN = dyn_cast<PHINode>(I)) 5725 ConstantEvolutionLoopExitValue.erase(PN); 5726 } 5727 5728 PushDefUseChildren(I, Worklist); 5729 } 5730 5731 // Forget all contained loops too, to avoid dangling entries in the 5732 // ValuesAtScopes map. 5733 for (Loop *I : *L) 5734 forgetLoop(I); 5735 5736 LoopPropertiesCache.erase(L); 5737 } 5738 5739 void ScalarEvolution::forgetValue(Value *V) { 5740 Instruction *I = dyn_cast<Instruction>(V); 5741 if (!I) return; 5742 5743 // Drop information about expressions based on loop-header PHIs. 5744 SmallVector<Instruction *, 16> Worklist; 5745 Worklist.push_back(I); 5746 5747 SmallPtrSet<Instruction *, 8> Visited; 5748 while (!Worklist.empty()) { 5749 I = Worklist.pop_back_val(); 5750 if (!Visited.insert(I).second) 5751 continue; 5752 5753 ValueExprMapType::iterator It = 5754 ValueExprMap.find_as(static_cast<Value *>(I)); 5755 if (It != ValueExprMap.end()) { 5756 eraseValueFromMap(It->first); 5757 forgetMemoizedResults(It->second); 5758 if (PHINode *PN = dyn_cast<PHINode>(I)) 5759 ConstantEvolutionLoopExitValue.erase(PN); 5760 } 5761 5762 PushDefUseChildren(I, Worklist); 5763 } 5764 } 5765 5766 /// Get the exact loop backedge taken count considering all loop exits. A 5767 /// computable result can only be returned for loops with a single exit. 5768 /// Returning the minimum taken count among all exits is incorrect because one 5769 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5770 /// the limit of each loop test is never skipped. This is a valid assumption as 5771 /// long as the loop exits via that test. For precise results, it is the 5772 /// caller's responsibility to specify the relevant loop exit using 5773 /// getExact(ExitingBlock, SE). 5774 const SCEV * 5775 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5776 SCEVUnionPredicate *Preds) const { 5777 // If any exits were not computable, the loop is not computable. 5778 if (!isComplete() || ExitNotTaken.empty()) 5779 return SE->getCouldNotCompute(); 5780 5781 const SCEV *BECount = nullptr; 5782 for (auto &ENT : ExitNotTaken) { 5783 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5784 5785 if (!BECount) 5786 BECount = ENT.ExactNotTaken; 5787 else if (BECount != ENT.ExactNotTaken) 5788 return SE->getCouldNotCompute(); 5789 if (Preds && !ENT.hasAlwaysTruePredicate()) 5790 Preds->add(ENT.Predicate.get()); 5791 5792 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5793 "Predicate should be always true!"); 5794 } 5795 5796 assert(BECount && "Invalid not taken count for loop exit"); 5797 return BECount; 5798 } 5799 5800 /// Get the exact not taken count for this loop exit. 5801 const SCEV * 5802 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5803 ScalarEvolution *SE) const { 5804 for (auto &ENT : ExitNotTaken) 5805 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5806 return ENT.ExactNotTaken; 5807 5808 return SE->getCouldNotCompute(); 5809 } 5810 5811 /// getMax - Get the max backedge taken count for the loop. 5812 const SCEV * 5813 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5814 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5815 return !ENT.hasAlwaysTruePredicate(); 5816 }; 5817 5818 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5819 return SE->getCouldNotCompute(); 5820 5821 return getMax(); 5822 } 5823 5824 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5825 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5826 return !ENT.hasAlwaysTruePredicate(); 5827 }; 5828 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5829 } 5830 5831 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5832 ScalarEvolution *SE) const { 5833 if (getMax() && getMax() != SE->getCouldNotCompute() && 5834 SE->hasOperand(getMax(), S)) 5835 return true; 5836 5837 for (auto &ENT : ExitNotTaken) 5838 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5839 SE->hasOperand(ENT.ExactNotTaken, S)) 5840 return true; 5841 5842 return false; 5843 } 5844 5845 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5846 /// computable exit into a persistent ExitNotTakenInfo array. 5847 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5848 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5849 &&ExitCounts, 5850 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5851 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5852 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5853 ExitNotTaken.reserve(ExitCounts.size()); 5854 std::transform( 5855 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5856 [&](const EdgeExitInfo &EEI) { 5857 BasicBlock *ExitBB = EEI.first; 5858 const ExitLimit &EL = EEI.second; 5859 if (EL.Predicates.empty()) 5860 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5861 5862 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5863 for (auto *Pred : EL.Predicates) 5864 Predicate->add(Pred); 5865 5866 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5867 }); 5868 } 5869 5870 /// Invalidate this result and free the ExitNotTakenInfo array. 5871 void ScalarEvolution::BackedgeTakenInfo::clear() { 5872 ExitNotTaken.clear(); 5873 } 5874 5875 /// Compute the number of times the backedge of the specified loop will execute. 5876 ScalarEvolution::BackedgeTakenInfo 5877 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5878 bool AllowPredicates) { 5879 SmallVector<BasicBlock *, 8> ExitingBlocks; 5880 L->getExitingBlocks(ExitingBlocks); 5881 5882 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5883 5884 SmallVector<EdgeExitInfo, 4> ExitCounts; 5885 bool CouldComputeBECount = true; 5886 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5887 const SCEV *MustExitMaxBECount = nullptr; 5888 const SCEV *MayExitMaxBECount = nullptr; 5889 bool MustExitMaxOrZero = false; 5890 5891 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5892 // and compute maxBECount. 5893 // Do a union of all the predicates here. 5894 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5895 BasicBlock *ExitBB = ExitingBlocks[i]; 5896 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5897 5898 assert((AllowPredicates || EL.Predicates.empty()) && 5899 "Predicated exit limit when predicates are not allowed!"); 5900 5901 // 1. For each exit that can be computed, add an entry to ExitCounts. 5902 // CouldComputeBECount is true only if all exits can be computed. 5903 if (EL.ExactNotTaken == getCouldNotCompute()) 5904 // We couldn't compute an exact value for this exit, so 5905 // we won't be able to compute an exact value for the loop. 5906 CouldComputeBECount = false; 5907 else 5908 ExitCounts.emplace_back(ExitBB, EL); 5909 5910 // 2. Derive the loop's MaxBECount from each exit's max number of 5911 // non-exiting iterations. Partition the loop exits into two kinds: 5912 // LoopMustExits and LoopMayExits. 5913 // 5914 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5915 // is a LoopMayExit. If any computable LoopMustExit is found, then 5916 // MaxBECount is the minimum EL.MaxNotTaken of computable 5917 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5918 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5919 // computable EL.MaxNotTaken. 5920 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5921 DT.dominates(ExitBB, Latch)) { 5922 if (!MustExitMaxBECount) { 5923 MustExitMaxBECount = EL.MaxNotTaken; 5924 MustExitMaxOrZero = EL.MaxOrZero; 5925 } else { 5926 MustExitMaxBECount = 5927 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5928 } 5929 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5930 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5931 MayExitMaxBECount = EL.MaxNotTaken; 5932 else { 5933 MayExitMaxBECount = 5934 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5935 } 5936 } 5937 } 5938 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5939 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5940 // The loop backedge will be taken the maximum or zero times if there's 5941 // a single exit that must be taken the maximum or zero times. 5942 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5943 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5944 MaxBECount, MaxOrZero); 5945 } 5946 5947 ScalarEvolution::ExitLimit 5948 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5949 bool AllowPredicates) { 5950 5951 // Okay, we've chosen an exiting block. See what condition causes us to exit 5952 // at this block and remember the exit block and whether all other targets 5953 // lead to the loop header. 5954 bool MustExecuteLoopHeader = true; 5955 BasicBlock *Exit = nullptr; 5956 for (auto *SBB : successors(ExitingBlock)) 5957 if (!L->contains(SBB)) { 5958 if (Exit) // Multiple exit successors. 5959 return getCouldNotCompute(); 5960 Exit = SBB; 5961 } else if (SBB != L->getHeader()) { 5962 MustExecuteLoopHeader = false; 5963 } 5964 5965 // At this point, we know we have a conditional branch that determines whether 5966 // the loop is exited. However, we don't know if the branch is executed each 5967 // time through the loop. If not, then the execution count of the branch will 5968 // not be equal to the trip count of the loop. 5969 // 5970 // Currently we check for this by checking to see if the Exit branch goes to 5971 // the loop header. If so, we know it will always execute the same number of 5972 // times as the loop. We also handle the case where the exit block *is* the 5973 // loop header. This is common for un-rotated loops. 5974 // 5975 // If both of those tests fail, walk up the unique predecessor chain to the 5976 // header, stopping if there is an edge that doesn't exit the loop. If the 5977 // header is reached, the execution count of the branch will be equal to the 5978 // trip count of the loop. 5979 // 5980 // More extensive analysis could be done to handle more cases here. 5981 // 5982 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5983 // The simple checks failed, try climbing the unique predecessor chain 5984 // up to the header. 5985 bool Ok = false; 5986 for (BasicBlock *BB = ExitingBlock; BB; ) { 5987 BasicBlock *Pred = BB->getUniquePredecessor(); 5988 if (!Pred) 5989 return getCouldNotCompute(); 5990 TerminatorInst *PredTerm = Pred->getTerminator(); 5991 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5992 if (PredSucc == BB) 5993 continue; 5994 // If the predecessor has a successor that isn't BB and isn't 5995 // outside the loop, assume the worst. 5996 if (L->contains(PredSucc)) 5997 return getCouldNotCompute(); 5998 } 5999 if (Pred == L->getHeader()) { 6000 Ok = true; 6001 break; 6002 } 6003 BB = Pred; 6004 } 6005 if (!Ok) 6006 return getCouldNotCompute(); 6007 } 6008 6009 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6010 TerminatorInst *Term = ExitingBlock->getTerminator(); 6011 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6012 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6013 // Proceed to the next level to examine the exit condition expression. 6014 return computeExitLimitFromCond( 6015 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6016 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6017 } 6018 6019 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6020 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6021 /*ControlsExit=*/IsOnlyExit); 6022 6023 return getCouldNotCompute(); 6024 } 6025 6026 ScalarEvolution::ExitLimit 6027 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 6028 Value *ExitCond, 6029 BasicBlock *TBB, 6030 BasicBlock *FBB, 6031 bool ControlsExit, 6032 bool AllowPredicates) { 6033 // Check if the controlling expression for this loop is an And or Or. 6034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6035 if (BO->getOpcode() == Instruction::And) { 6036 // Recurse on the operands of the and. 6037 bool EitherMayExit = L->contains(TBB); 6038 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 6039 ControlsExit && !EitherMayExit, 6040 AllowPredicates); 6041 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 6042 ControlsExit && !EitherMayExit, 6043 AllowPredicates); 6044 const SCEV *BECount = getCouldNotCompute(); 6045 const SCEV *MaxBECount = getCouldNotCompute(); 6046 if (EitherMayExit) { 6047 // Both conditions must be true for the loop to continue executing. 6048 // Choose the less conservative count. 6049 if (EL0.ExactNotTaken == getCouldNotCompute() || 6050 EL1.ExactNotTaken == getCouldNotCompute()) 6051 BECount = getCouldNotCompute(); 6052 else 6053 BECount = 6054 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6055 if (EL0.MaxNotTaken == getCouldNotCompute()) 6056 MaxBECount = EL1.MaxNotTaken; 6057 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6058 MaxBECount = EL0.MaxNotTaken; 6059 else 6060 MaxBECount = 6061 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6062 } else { 6063 // Both conditions must be true at the same time for the loop to exit. 6064 // For now, be conservative. 6065 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 6066 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6067 MaxBECount = EL0.MaxNotTaken; 6068 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6069 BECount = EL0.ExactNotTaken; 6070 } 6071 6072 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 6073 // to be more aggressive when computing BECount than when computing 6074 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 6075 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 6076 // to not. 6077 if (isa<SCEVCouldNotCompute>(MaxBECount) && 6078 !isa<SCEVCouldNotCompute>(BECount)) 6079 MaxBECount = BECount; 6080 6081 return ExitLimit(BECount, MaxBECount, false, 6082 {&EL0.Predicates, &EL1.Predicates}); 6083 } 6084 if (BO->getOpcode() == Instruction::Or) { 6085 // Recurse on the operands of the or. 6086 bool EitherMayExit = L->contains(FBB); 6087 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 6088 ControlsExit && !EitherMayExit, 6089 AllowPredicates); 6090 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 6091 ControlsExit && !EitherMayExit, 6092 AllowPredicates); 6093 const SCEV *BECount = getCouldNotCompute(); 6094 const SCEV *MaxBECount = getCouldNotCompute(); 6095 if (EitherMayExit) { 6096 // Both conditions must be false for the loop to continue executing. 6097 // Choose the less conservative count. 6098 if (EL0.ExactNotTaken == getCouldNotCompute() || 6099 EL1.ExactNotTaken == getCouldNotCompute()) 6100 BECount = getCouldNotCompute(); 6101 else 6102 BECount = 6103 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6104 if (EL0.MaxNotTaken == getCouldNotCompute()) 6105 MaxBECount = EL1.MaxNotTaken; 6106 else if (EL1.MaxNotTaken == getCouldNotCompute()) 6107 MaxBECount = EL0.MaxNotTaken; 6108 else 6109 MaxBECount = 6110 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 6111 } else { 6112 // Both conditions must be false at the same time for the loop to exit. 6113 // For now, be conservative. 6114 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 6115 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 6116 MaxBECount = EL0.MaxNotTaken; 6117 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 6118 BECount = EL0.ExactNotTaken; 6119 } 6120 6121 return ExitLimit(BECount, MaxBECount, false, 6122 {&EL0.Predicates, &EL1.Predicates}); 6123 } 6124 } 6125 6126 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6127 // Proceed to the next level to examine the icmp. 6128 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6129 ExitLimit EL = 6130 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6131 if (EL.hasFullInfo() || !AllowPredicates) 6132 return EL; 6133 6134 // Try again, but use SCEV predicates this time. 6135 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6136 /*AllowPredicates=*/true); 6137 } 6138 6139 // Check for a constant condition. These are normally stripped out by 6140 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6141 // preserve the CFG and is temporarily leaving constant conditions 6142 // in place. 6143 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6144 if (L->contains(FBB) == !CI->getZExtValue()) 6145 // The backedge is always taken. 6146 return getCouldNotCompute(); 6147 else 6148 // The backedge is never taken. 6149 return getZero(CI->getType()); 6150 } 6151 6152 // If it's not an integer or pointer comparison then compute it the hard way. 6153 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6154 } 6155 6156 ScalarEvolution::ExitLimit 6157 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6158 ICmpInst *ExitCond, 6159 BasicBlock *TBB, 6160 BasicBlock *FBB, 6161 bool ControlsExit, 6162 bool AllowPredicates) { 6163 6164 // If the condition was exit on true, convert the condition to exit on false 6165 ICmpInst::Predicate Cond; 6166 if (!L->contains(FBB)) 6167 Cond = ExitCond->getPredicate(); 6168 else 6169 Cond = ExitCond->getInversePredicate(); 6170 6171 // Handle common loops like: for (X = "string"; *X; ++X) 6172 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6173 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6174 ExitLimit ItCnt = 6175 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6176 if (ItCnt.hasAnyInfo()) 6177 return ItCnt; 6178 } 6179 6180 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6181 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6182 6183 // Try to evaluate any dependencies out of the loop. 6184 LHS = getSCEVAtScope(LHS, L); 6185 RHS = getSCEVAtScope(RHS, L); 6186 6187 // At this point, we would like to compute how many iterations of the 6188 // loop the predicate will return true for these inputs. 6189 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6190 // If there is a loop-invariant, force it into the RHS. 6191 std::swap(LHS, RHS); 6192 Cond = ICmpInst::getSwappedPredicate(Cond); 6193 } 6194 6195 // Simplify the operands before analyzing them. 6196 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6197 6198 // If we have a comparison of a chrec against a constant, try to use value 6199 // ranges to answer this query. 6200 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6201 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6202 if (AddRec->getLoop() == L) { 6203 // Form the constant range. 6204 ConstantRange CompRange = 6205 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6206 6207 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6208 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6209 } 6210 6211 switch (Cond) { 6212 case ICmpInst::ICMP_NE: { // while (X != Y) 6213 // Convert to: while (X-Y != 0) 6214 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6215 AllowPredicates); 6216 if (EL.hasAnyInfo()) return EL; 6217 break; 6218 } 6219 case ICmpInst::ICMP_EQ: { // while (X == Y) 6220 // Convert to: while (X-Y == 0) 6221 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6222 if (EL.hasAnyInfo()) return EL; 6223 break; 6224 } 6225 case ICmpInst::ICMP_SLT: 6226 case ICmpInst::ICMP_ULT: { // while (X < Y) 6227 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6228 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6229 AllowPredicates); 6230 if (EL.hasAnyInfo()) return EL; 6231 break; 6232 } 6233 case ICmpInst::ICMP_SGT: 6234 case ICmpInst::ICMP_UGT: { // while (X > Y) 6235 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6236 ExitLimit EL = 6237 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6238 AllowPredicates); 6239 if (EL.hasAnyInfo()) return EL; 6240 break; 6241 } 6242 default: 6243 break; 6244 } 6245 6246 auto *ExhaustiveCount = 6247 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6248 6249 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6250 return ExhaustiveCount; 6251 6252 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6253 ExitCond->getOperand(1), L, Cond); 6254 } 6255 6256 ScalarEvolution::ExitLimit 6257 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6258 SwitchInst *Switch, 6259 BasicBlock *ExitingBlock, 6260 bool ControlsExit) { 6261 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6262 6263 // Give up if the exit is the default dest of a switch. 6264 if (Switch->getDefaultDest() == ExitingBlock) 6265 return getCouldNotCompute(); 6266 6267 assert(L->contains(Switch->getDefaultDest()) && 6268 "Default case must not exit the loop!"); 6269 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6270 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6271 6272 // while (X != Y) --> while (X-Y != 0) 6273 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6274 if (EL.hasAnyInfo()) 6275 return EL; 6276 6277 return getCouldNotCompute(); 6278 } 6279 6280 static ConstantInt * 6281 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6282 ScalarEvolution &SE) { 6283 const SCEV *InVal = SE.getConstant(C); 6284 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6285 assert(isa<SCEVConstant>(Val) && 6286 "Evaluation of SCEV at constant didn't fold correctly?"); 6287 return cast<SCEVConstant>(Val)->getValue(); 6288 } 6289 6290 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6291 /// compute the backedge execution count. 6292 ScalarEvolution::ExitLimit 6293 ScalarEvolution::computeLoadConstantCompareExitLimit( 6294 LoadInst *LI, 6295 Constant *RHS, 6296 const Loop *L, 6297 ICmpInst::Predicate predicate) { 6298 6299 if (LI->isVolatile()) return getCouldNotCompute(); 6300 6301 // Check to see if the loaded pointer is a getelementptr of a global. 6302 // TODO: Use SCEV instead of manually grubbing with GEPs. 6303 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6304 if (!GEP) return getCouldNotCompute(); 6305 6306 // Make sure that it is really a constant global we are gepping, with an 6307 // initializer, and make sure the first IDX is really 0. 6308 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6309 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6310 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6311 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6312 return getCouldNotCompute(); 6313 6314 // Okay, we allow one non-constant index into the GEP instruction. 6315 Value *VarIdx = nullptr; 6316 std::vector<Constant*> Indexes; 6317 unsigned VarIdxNum = 0; 6318 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6319 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6320 Indexes.push_back(CI); 6321 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6322 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6323 VarIdx = GEP->getOperand(i); 6324 VarIdxNum = i-2; 6325 Indexes.push_back(nullptr); 6326 } 6327 6328 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6329 if (!VarIdx) 6330 return getCouldNotCompute(); 6331 6332 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6333 // Check to see if X is a loop variant variable value now. 6334 const SCEV *Idx = getSCEV(VarIdx); 6335 Idx = getSCEVAtScope(Idx, L); 6336 6337 // We can only recognize very limited forms of loop index expressions, in 6338 // particular, only affine AddRec's like {C1,+,C2}. 6339 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6340 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6341 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6342 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6343 return getCouldNotCompute(); 6344 6345 unsigned MaxSteps = MaxBruteForceIterations; 6346 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6347 ConstantInt *ItCst = ConstantInt::get( 6348 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6349 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6350 6351 // Form the GEP offset. 6352 Indexes[VarIdxNum] = Val; 6353 6354 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6355 Indexes); 6356 if (!Result) break; // Cannot compute! 6357 6358 // Evaluate the condition for this iteration. 6359 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6360 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6361 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6362 ++NumArrayLenItCounts; 6363 return getConstant(ItCst); // Found terminating iteration! 6364 } 6365 } 6366 return getCouldNotCompute(); 6367 } 6368 6369 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6370 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6371 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6372 if (!RHS) 6373 return getCouldNotCompute(); 6374 6375 const BasicBlock *Latch = L->getLoopLatch(); 6376 if (!Latch) 6377 return getCouldNotCompute(); 6378 6379 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6380 if (!Predecessor) 6381 return getCouldNotCompute(); 6382 6383 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6384 // Return LHS in OutLHS and shift_opt in OutOpCode. 6385 auto MatchPositiveShift = 6386 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6387 6388 using namespace PatternMatch; 6389 6390 ConstantInt *ShiftAmt; 6391 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6392 OutOpCode = Instruction::LShr; 6393 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6394 OutOpCode = Instruction::AShr; 6395 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6396 OutOpCode = Instruction::Shl; 6397 else 6398 return false; 6399 6400 return ShiftAmt->getValue().isStrictlyPositive(); 6401 }; 6402 6403 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6404 // 6405 // loop: 6406 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6407 // %iv.shifted = lshr i32 %iv, <positive constant> 6408 // 6409 // Return true on a successful match. Return the corresponding PHI node (%iv 6410 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6411 auto MatchShiftRecurrence = 6412 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6413 Optional<Instruction::BinaryOps> PostShiftOpCode; 6414 6415 { 6416 Instruction::BinaryOps OpC; 6417 Value *V; 6418 6419 // If we encounter a shift instruction, "peel off" the shift operation, 6420 // and remember that we did so. Later when we inspect %iv's backedge 6421 // value, we will make sure that the backedge value uses the same 6422 // operation. 6423 // 6424 // Note: the peeled shift operation does not have to be the same 6425 // instruction as the one feeding into the PHI's backedge value. We only 6426 // really care about it being the same *kind* of shift instruction -- 6427 // that's all that is required for our later inferences to hold. 6428 if (MatchPositiveShift(LHS, V, OpC)) { 6429 PostShiftOpCode = OpC; 6430 LHS = V; 6431 } 6432 } 6433 6434 PNOut = dyn_cast<PHINode>(LHS); 6435 if (!PNOut || PNOut->getParent() != L->getHeader()) 6436 return false; 6437 6438 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6439 Value *OpLHS; 6440 6441 return 6442 // The backedge value for the PHI node must be a shift by a positive 6443 // amount 6444 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6445 6446 // of the PHI node itself 6447 OpLHS == PNOut && 6448 6449 // and the kind of shift should be match the kind of shift we peeled 6450 // off, if any. 6451 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6452 }; 6453 6454 PHINode *PN; 6455 Instruction::BinaryOps OpCode; 6456 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6457 return getCouldNotCompute(); 6458 6459 const DataLayout &DL = getDataLayout(); 6460 6461 // The key rationale for this optimization is that for some kinds of shift 6462 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6463 // within a finite number of iterations. If the condition guarding the 6464 // backedge (in the sense that the backedge is taken if the condition is true) 6465 // is false for the value the shift recurrence stabilizes to, then we know 6466 // that the backedge is taken only a finite number of times. 6467 6468 ConstantInt *StableValue = nullptr; 6469 switch (OpCode) { 6470 default: 6471 llvm_unreachable("Impossible case!"); 6472 6473 case Instruction::AShr: { 6474 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6475 // bitwidth(K) iterations. 6476 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6477 bool KnownZero, KnownOne; 6478 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6479 Predecessor->getTerminator(), &DT); 6480 auto *Ty = cast<IntegerType>(RHS->getType()); 6481 if (KnownZero) 6482 StableValue = ConstantInt::get(Ty, 0); 6483 else if (KnownOne) 6484 StableValue = ConstantInt::get(Ty, -1, true); 6485 else 6486 return getCouldNotCompute(); 6487 6488 break; 6489 } 6490 case Instruction::LShr: 6491 case Instruction::Shl: 6492 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6493 // stabilize to 0 in at most bitwidth(K) iterations. 6494 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6495 break; 6496 } 6497 6498 auto *Result = 6499 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6500 assert(Result->getType()->isIntegerTy(1) && 6501 "Otherwise cannot be an operand to a branch instruction"); 6502 6503 if (Result->isZeroValue()) { 6504 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6505 const SCEV *UpperBound = 6506 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6507 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6508 } 6509 6510 return getCouldNotCompute(); 6511 } 6512 6513 /// Return true if we can constant fold an instruction of the specified type, 6514 /// assuming that all operands were constants. 6515 static bool CanConstantFold(const Instruction *I) { 6516 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6517 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6518 isa<LoadInst>(I)) 6519 return true; 6520 6521 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6522 if (const Function *F = CI->getCalledFunction()) 6523 return canConstantFoldCallTo(F); 6524 return false; 6525 } 6526 6527 /// Determine whether this instruction can constant evolve within this loop 6528 /// assuming its operands can all constant evolve. 6529 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6530 // An instruction outside of the loop can't be derived from a loop PHI. 6531 if (!L->contains(I)) return false; 6532 6533 if (isa<PHINode>(I)) { 6534 // We don't currently keep track of the control flow needed to evaluate 6535 // PHIs, so we cannot handle PHIs inside of loops. 6536 return L->getHeader() == I->getParent(); 6537 } 6538 6539 // If we won't be able to constant fold this expression even if the operands 6540 // are constants, bail early. 6541 return CanConstantFold(I); 6542 } 6543 6544 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6545 /// recursing through each instruction operand until reaching a loop header phi. 6546 static PHINode * 6547 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6548 DenseMap<Instruction *, PHINode *> &PHIMap, 6549 unsigned Depth) { 6550 if (Depth > MaxConstantEvolvingDepth) 6551 return nullptr; 6552 6553 // Otherwise, we can evaluate this instruction if all of its operands are 6554 // constant or derived from a PHI node themselves. 6555 PHINode *PHI = nullptr; 6556 for (Value *Op : UseInst->operands()) { 6557 if (isa<Constant>(Op)) continue; 6558 6559 Instruction *OpInst = dyn_cast<Instruction>(Op); 6560 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6561 6562 PHINode *P = dyn_cast<PHINode>(OpInst); 6563 if (!P) 6564 // If this operand is already visited, reuse the prior result. 6565 // We may have P != PHI if this is the deepest point at which the 6566 // inconsistent paths meet. 6567 P = PHIMap.lookup(OpInst); 6568 if (!P) { 6569 // Recurse and memoize the results, whether a phi is found or not. 6570 // This recursive call invalidates pointers into PHIMap. 6571 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 6572 PHIMap[OpInst] = P; 6573 } 6574 if (!P) 6575 return nullptr; // Not evolving from PHI 6576 if (PHI && PHI != P) 6577 return nullptr; // Evolving from multiple different PHIs. 6578 PHI = P; 6579 } 6580 // This is a expression evolving from a constant PHI! 6581 return PHI; 6582 } 6583 6584 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6585 /// in the loop that V is derived from. We allow arbitrary operations along the 6586 /// way, but the operands of an operation must either be constants or a value 6587 /// derived from a constant PHI. If this expression does not fit with these 6588 /// constraints, return null. 6589 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6590 Instruction *I = dyn_cast<Instruction>(V); 6591 if (!I || !canConstantEvolve(I, L)) return nullptr; 6592 6593 if (PHINode *PN = dyn_cast<PHINode>(I)) 6594 return PN; 6595 6596 // Record non-constant instructions contained by the loop. 6597 DenseMap<Instruction *, PHINode *> PHIMap; 6598 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 6599 } 6600 6601 /// EvaluateExpression - Given an expression that passes the 6602 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6603 /// in the loop has the value PHIVal. If we can't fold this expression for some 6604 /// reason, return null. 6605 static Constant *EvaluateExpression(Value *V, const Loop *L, 6606 DenseMap<Instruction *, Constant *> &Vals, 6607 const DataLayout &DL, 6608 const TargetLibraryInfo *TLI) { 6609 // Convenient constant check, but redundant for recursive calls. 6610 if (Constant *C = dyn_cast<Constant>(V)) return C; 6611 Instruction *I = dyn_cast<Instruction>(V); 6612 if (!I) return nullptr; 6613 6614 if (Constant *C = Vals.lookup(I)) return C; 6615 6616 // An instruction inside the loop depends on a value outside the loop that we 6617 // weren't given a mapping for, or a value such as a call inside the loop. 6618 if (!canConstantEvolve(I, L)) return nullptr; 6619 6620 // An unmapped PHI can be due to a branch or another loop inside this loop, 6621 // or due to this not being the initial iteration through a loop where we 6622 // couldn't compute the evolution of this particular PHI last time. 6623 if (isa<PHINode>(I)) return nullptr; 6624 6625 std::vector<Constant*> Operands(I->getNumOperands()); 6626 6627 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6628 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6629 if (!Operand) { 6630 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6631 if (!Operands[i]) return nullptr; 6632 continue; 6633 } 6634 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6635 Vals[Operand] = C; 6636 if (!C) return nullptr; 6637 Operands[i] = C; 6638 } 6639 6640 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6641 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6642 Operands[1], DL, TLI); 6643 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6644 if (!LI->isVolatile()) 6645 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6646 } 6647 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6648 } 6649 6650 6651 // If every incoming value to PN except the one for BB is a specific Constant, 6652 // return that, else return nullptr. 6653 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6654 Constant *IncomingVal = nullptr; 6655 6656 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6657 if (PN->getIncomingBlock(i) == BB) 6658 continue; 6659 6660 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6661 if (!CurrentVal) 6662 return nullptr; 6663 6664 if (IncomingVal != CurrentVal) { 6665 if (IncomingVal) 6666 return nullptr; 6667 IncomingVal = CurrentVal; 6668 } 6669 } 6670 6671 return IncomingVal; 6672 } 6673 6674 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6675 /// in the header of its containing loop, we know the loop executes a 6676 /// constant number of times, and the PHI node is just a recurrence 6677 /// involving constants, fold it. 6678 Constant * 6679 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6680 const APInt &BEs, 6681 const Loop *L) { 6682 auto I = ConstantEvolutionLoopExitValue.find(PN); 6683 if (I != ConstantEvolutionLoopExitValue.end()) 6684 return I->second; 6685 6686 if (BEs.ugt(MaxBruteForceIterations)) 6687 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6688 6689 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6690 6691 DenseMap<Instruction *, Constant *> CurrentIterVals; 6692 BasicBlock *Header = L->getHeader(); 6693 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6694 6695 BasicBlock *Latch = L->getLoopLatch(); 6696 if (!Latch) 6697 return nullptr; 6698 6699 for (auto &I : *Header) { 6700 PHINode *PHI = dyn_cast<PHINode>(&I); 6701 if (!PHI) break; 6702 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6703 if (!StartCST) continue; 6704 CurrentIterVals[PHI] = StartCST; 6705 } 6706 if (!CurrentIterVals.count(PN)) 6707 return RetVal = nullptr; 6708 6709 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6710 6711 // Execute the loop symbolically to determine the exit value. 6712 if (BEs.getActiveBits() >= 32) 6713 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6714 6715 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6716 unsigned IterationNum = 0; 6717 const DataLayout &DL = getDataLayout(); 6718 for (; ; ++IterationNum) { 6719 if (IterationNum == NumIterations) 6720 return RetVal = CurrentIterVals[PN]; // Got exit value! 6721 6722 // Compute the value of the PHIs for the next iteration. 6723 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6724 DenseMap<Instruction *, Constant *> NextIterVals; 6725 Constant *NextPHI = 6726 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6727 if (!NextPHI) 6728 return nullptr; // Couldn't evaluate! 6729 NextIterVals[PN] = NextPHI; 6730 6731 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6732 6733 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6734 // cease to be able to evaluate one of them or if they stop evolving, 6735 // because that doesn't necessarily prevent us from computing PN. 6736 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6737 for (const auto &I : CurrentIterVals) { 6738 PHINode *PHI = dyn_cast<PHINode>(I.first); 6739 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6740 PHIsToCompute.emplace_back(PHI, I.second); 6741 } 6742 // We use two distinct loops because EvaluateExpression may invalidate any 6743 // iterators into CurrentIterVals. 6744 for (const auto &I : PHIsToCompute) { 6745 PHINode *PHI = I.first; 6746 Constant *&NextPHI = NextIterVals[PHI]; 6747 if (!NextPHI) { // Not already computed. 6748 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6749 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6750 } 6751 if (NextPHI != I.second) 6752 StoppedEvolving = false; 6753 } 6754 6755 // If all entries in CurrentIterVals == NextIterVals then we can stop 6756 // iterating, the loop can't continue to change. 6757 if (StoppedEvolving) 6758 return RetVal = CurrentIterVals[PN]; 6759 6760 CurrentIterVals.swap(NextIterVals); 6761 } 6762 } 6763 6764 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6765 Value *Cond, 6766 bool ExitWhen) { 6767 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6768 if (!PN) return getCouldNotCompute(); 6769 6770 // If the loop is canonicalized, the PHI will have exactly two entries. 6771 // That's the only form we support here. 6772 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6773 6774 DenseMap<Instruction *, Constant *> CurrentIterVals; 6775 BasicBlock *Header = L->getHeader(); 6776 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6777 6778 BasicBlock *Latch = L->getLoopLatch(); 6779 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6780 6781 for (auto &I : *Header) { 6782 PHINode *PHI = dyn_cast<PHINode>(&I); 6783 if (!PHI) 6784 break; 6785 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6786 if (!StartCST) continue; 6787 CurrentIterVals[PHI] = StartCST; 6788 } 6789 if (!CurrentIterVals.count(PN)) 6790 return getCouldNotCompute(); 6791 6792 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6793 // the loop symbolically to determine when the condition gets a value of 6794 // "ExitWhen". 6795 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6796 const DataLayout &DL = getDataLayout(); 6797 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6798 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6799 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6800 6801 // Couldn't symbolically evaluate. 6802 if (!CondVal) return getCouldNotCompute(); 6803 6804 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6805 ++NumBruteForceTripCountsComputed; 6806 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6807 } 6808 6809 // Update all the PHI nodes for the next iteration. 6810 DenseMap<Instruction *, Constant *> NextIterVals; 6811 6812 // Create a list of which PHIs we need to compute. We want to do this before 6813 // calling EvaluateExpression on them because that may invalidate iterators 6814 // into CurrentIterVals. 6815 SmallVector<PHINode *, 8> PHIsToCompute; 6816 for (const auto &I : CurrentIterVals) { 6817 PHINode *PHI = dyn_cast<PHINode>(I.first); 6818 if (!PHI || PHI->getParent() != Header) continue; 6819 PHIsToCompute.push_back(PHI); 6820 } 6821 for (PHINode *PHI : PHIsToCompute) { 6822 Constant *&NextPHI = NextIterVals[PHI]; 6823 if (NextPHI) continue; // Already computed! 6824 6825 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6826 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6827 } 6828 CurrentIterVals.swap(NextIterVals); 6829 } 6830 6831 // Too many iterations were needed to evaluate. 6832 return getCouldNotCompute(); 6833 } 6834 6835 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6836 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6837 ValuesAtScopes[V]; 6838 // Check to see if we've folded this expression at this loop before. 6839 for (auto &LS : Values) 6840 if (LS.first == L) 6841 return LS.second ? LS.second : V; 6842 6843 Values.emplace_back(L, nullptr); 6844 6845 // Otherwise compute it. 6846 const SCEV *C = computeSCEVAtScope(V, L); 6847 for (auto &LS : reverse(ValuesAtScopes[V])) 6848 if (LS.first == L) { 6849 LS.second = C; 6850 break; 6851 } 6852 return C; 6853 } 6854 6855 /// This builds up a Constant using the ConstantExpr interface. That way, we 6856 /// will return Constants for objects which aren't represented by a 6857 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6858 /// Returns NULL if the SCEV isn't representable as a Constant. 6859 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6860 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6861 case scCouldNotCompute: 6862 case scAddRecExpr: 6863 break; 6864 case scConstant: 6865 return cast<SCEVConstant>(V)->getValue(); 6866 case scUnknown: 6867 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6868 case scSignExtend: { 6869 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6870 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6871 return ConstantExpr::getSExt(CastOp, SS->getType()); 6872 break; 6873 } 6874 case scZeroExtend: { 6875 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6876 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6877 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6878 break; 6879 } 6880 case scTruncate: { 6881 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6882 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6883 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6884 break; 6885 } 6886 case scAddExpr: { 6887 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6888 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6889 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6890 unsigned AS = PTy->getAddressSpace(); 6891 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6892 C = ConstantExpr::getBitCast(C, DestPtrTy); 6893 } 6894 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6895 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6896 if (!C2) return nullptr; 6897 6898 // First pointer! 6899 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6900 unsigned AS = C2->getType()->getPointerAddressSpace(); 6901 std::swap(C, C2); 6902 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6903 // The offsets have been converted to bytes. We can add bytes to an 6904 // i8* by GEP with the byte count in the first index. 6905 C = ConstantExpr::getBitCast(C, DestPtrTy); 6906 } 6907 6908 // Don't bother trying to sum two pointers. We probably can't 6909 // statically compute a load that results from it anyway. 6910 if (C2->getType()->isPointerTy()) 6911 return nullptr; 6912 6913 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6914 if (PTy->getElementType()->isStructTy()) 6915 C2 = ConstantExpr::getIntegerCast( 6916 C2, Type::getInt32Ty(C->getContext()), true); 6917 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6918 } else 6919 C = ConstantExpr::getAdd(C, C2); 6920 } 6921 return C; 6922 } 6923 break; 6924 } 6925 case scMulExpr: { 6926 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6927 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6928 // Don't bother with pointers at all. 6929 if (C->getType()->isPointerTy()) return nullptr; 6930 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6931 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6932 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6933 C = ConstantExpr::getMul(C, C2); 6934 } 6935 return C; 6936 } 6937 break; 6938 } 6939 case scUDivExpr: { 6940 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6941 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6942 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6943 if (LHS->getType() == RHS->getType()) 6944 return ConstantExpr::getUDiv(LHS, RHS); 6945 break; 6946 } 6947 case scSMaxExpr: 6948 case scUMaxExpr: 6949 break; // TODO: smax, umax. 6950 } 6951 return nullptr; 6952 } 6953 6954 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6955 if (isa<SCEVConstant>(V)) return V; 6956 6957 // If this instruction is evolved from a constant-evolving PHI, compute the 6958 // exit value from the loop without using SCEVs. 6959 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6960 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6961 const Loop *LI = this->LI[I->getParent()]; 6962 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6963 if (PHINode *PN = dyn_cast<PHINode>(I)) 6964 if (PN->getParent() == LI->getHeader()) { 6965 // Okay, there is no closed form solution for the PHI node. Check 6966 // to see if the loop that contains it has a known backedge-taken 6967 // count. If so, we may be able to force computation of the exit 6968 // value. 6969 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6970 if (const SCEVConstant *BTCC = 6971 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6972 // Okay, we know how many times the containing loop executes. If 6973 // this is a constant evolving PHI node, get the final value at 6974 // the specified iteration number. 6975 Constant *RV = 6976 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6977 if (RV) return getSCEV(RV); 6978 } 6979 } 6980 6981 // Okay, this is an expression that we cannot symbolically evaluate 6982 // into a SCEV. Check to see if it's possible to symbolically evaluate 6983 // the arguments into constants, and if so, try to constant propagate the 6984 // result. This is particularly useful for computing loop exit values. 6985 if (CanConstantFold(I)) { 6986 SmallVector<Constant *, 4> Operands; 6987 bool MadeImprovement = false; 6988 for (Value *Op : I->operands()) { 6989 if (Constant *C = dyn_cast<Constant>(Op)) { 6990 Operands.push_back(C); 6991 continue; 6992 } 6993 6994 // If any of the operands is non-constant and if they are 6995 // non-integer and non-pointer, don't even try to analyze them 6996 // with scev techniques. 6997 if (!isSCEVable(Op->getType())) 6998 return V; 6999 7000 const SCEV *OrigV = getSCEV(Op); 7001 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7002 MadeImprovement |= OrigV != OpV; 7003 7004 Constant *C = BuildConstantFromSCEV(OpV); 7005 if (!C) return V; 7006 if (C->getType() != Op->getType()) 7007 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7008 Op->getType(), 7009 false), 7010 C, Op->getType()); 7011 Operands.push_back(C); 7012 } 7013 7014 // Check to see if getSCEVAtScope actually made an improvement. 7015 if (MadeImprovement) { 7016 Constant *C = nullptr; 7017 const DataLayout &DL = getDataLayout(); 7018 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7019 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7020 Operands[1], DL, &TLI); 7021 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7022 if (!LI->isVolatile()) 7023 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7024 } else 7025 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7026 if (!C) return V; 7027 return getSCEV(C); 7028 } 7029 } 7030 } 7031 7032 // This is some other type of SCEVUnknown, just return it. 7033 return V; 7034 } 7035 7036 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7037 // Avoid performing the look-up in the common case where the specified 7038 // expression has no loop-variant portions. 7039 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7040 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7041 if (OpAtScope != Comm->getOperand(i)) { 7042 // Okay, at least one of these operands is loop variant but might be 7043 // foldable. Build a new instance of the folded commutative expression. 7044 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7045 Comm->op_begin()+i); 7046 NewOps.push_back(OpAtScope); 7047 7048 for (++i; i != e; ++i) { 7049 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7050 NewOps.push_back(OpAtScope); 7051 } 7052 if (isa<SCEVAddExpr>(Comm)) 7053 return getAddExpr(NewOps); 7054 if (isa<SCEVMulExpr>(Comm)) 7055 return getMulExpr(NewOps); 7056 if (isa<SCEVSMaxExpr>(Comm)) 7057 return getSMaxExpr(NewOps); 7058 if (isa<SCEVUMaxExpr>(Comm)) 7059 return getUMaxExpr(NewOps); 7060 llvm_unreachable("Unknown commutative SCEV type!"); 7061 } 7062 } 7063 // If we got here, all operands are loop invariant. 7064 return Comm; 7065 } 7066 7067 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 7068 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 7069 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 7070 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 7071 return Div; // must be loop invariant 7072 return getUDivExpr(LHS, RHS); 7073 } 7074 7075 // If this is a loop recurrence for a loop that does not contain L, then we 7076 // are dealing with the final value computed by the loop. 7077 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 7078 // First, attempt to evaluate each operand. 7079 // Avoid performing the look-up in the common case where the specified 7080 // expression has no loop-variant portions. 7081 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 7082 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 7083 if (OpAtScope == AddRec->getOperand(i)) 7084 continue; 7085 7086 // Okay, at least one of these operands is loop variant but might be 7087 // foldable. Build a new instance of the folded commutative expression. 7088 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 7089 AddRec->op_begin()+i); 7090 NewOps.push_back(OpAtScope); 7091 for (++i; i != e; ++i) 7092 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 7093 7094 const SCEV *FoldedRec = 7095 getAddRecExpr(NewOps, AddRec->getLoop(), 7096 AddRec->getNoWrapFlags(SCEV::FlagNW)); 7097 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 7098 // The addrec may be folded to a nonrecurrence, for example, if the 7099 // induction variable is multiplied by zero after constant folding. Go 7100 // ahead and return the folded value. 7101 if (!AddRec) 7102 return FoldedRec; 7103 break; 7104 } 7105 7106 // If the scope is outside the addrec's loop, evaluate it by using the 7107 // loop exit value of the addrec. 7108 if (!AddRec->getLoop()->contains(L)) { 7109 // To evaluate this recurrence, we need to know how many times the AddRec 7110 // loop iterates. Compute this now. 7111 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 7112 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 7113 7114 // Then, evaluate the AddRec. 7115 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 7116 } 7117 7118 return AddRec; 7119 } 7120 7121 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 7122 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7123 if (Op == Cast->getOperand()) 7124 return Cast; // must be loop invariant 7125 return getZeroExtendExpr(Op, Cast->getType()); 7126 } 7127 7128 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7129 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7130 if (Op == Cast->getOperand()) 7131 return Cast; // must be loop invariant 7132 return getSignExtendExpr(Op, Cast->getType()); 7133 } 7134 7135 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7136 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7137 if (Op == Cast->getOperand()) 7138 return Cast; // must be loop invariant 7139 return getTruncateExpr(Op, Cast->getType()); 7140 } 7141 7142 llvm_unreachable("Unknown SCEV type!"); 7143 } 7144 7145 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7146 return getSCEVAtScope(getSCEV(V), L); 7147 } 7148 7149 /// Finds the minimum unsigned root of the following equation: 7150 /// 7151 /// A * X = B (mod N) 7152 /// 7153 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7154 /// A and B isn't important. 7155 /// 7156 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7157 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 7158 ScalarEvolution &SE) { 7159 uint32_t BW = A.getBitWidth(); 7160 assert(BW == SE.getTypeSizeInBits(B->getType())); 7161 assert(A != 0 && "A must be non-zero."); 7162 7163 // 1. D = gcd(A, N) 7164 // 7165 // The gcd of A and N may have only one prime factor: 2. The number of 7166 // trailing zeros in A is its multiplicity 7167 uint32_t Mult2 = A.countTrailingZeros(); 7168 // D = 2^Mult2 7169 7170 // 2. Check if B is divisible by D. 7171 // 7172 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7173 // is not less than multiplicity of this prime factor for D. 7174 if (SE.GetMinTrailingZeros(B) < Mult2) 7175 return SE.getCouldNotCompute(); 7176 7177 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7178 // modulo (N / D). 7179 // 7180 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 7181 // (N / D) in general. The inverse itself always fits into BW bits, though, 7182 // so we immediately truncate it. 7183 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7184 APInt Mod(BW + 1, 0); 7185 Mod.setBit(BW - Mult2); // Mod = N / D 7186 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 7187 7188 // 4. Compute the minimum unsigned root of the equation: 7189 // I * (B / D) mod (N / D) 7190 // To simplify the computation, we factor out the divide by D: 7191 // (I * B mod N) / D 7192 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 7193 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 7194 } 7195 7196 /// Find the roots of the quadratic equation for the given quadratic chrec 7197 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7198 /// two SCEVCouldNotCompute objects. 7199 /// 7200 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7201 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7202 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7203 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7204 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7205 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7206 7207 // We currently can only solve this if the coefficients are constants. 7208 if (!LC || !MC || !NC) 7209 return None; 7210 7211 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7212 const APInt &L = LC->getAPInt(); 7213 const APInt &M = MC->getAPInt(); 7214 const APInt &N = NC->getAPInt(); 7215 APInt Two(BitWidth, 2); 7216 APInt Four(BitWidth, 4); 7217 7218 { 7219 using namespace APIntOps; 7220 const APInt& C = L; 7221 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7222 // The B coefficient is M-N/2 7223 APInt B(M); 7224 B -= N.sdiv(Two); 7225 7226 // The A coefficient is N/2 7227 APInt A(N.sdiv(Two)); 7228 7229 // Compute the B^2-4ac term. 7230 APInt SqrtTerm(B); 7231 SqrtTerm *= B; 7232 SqrtTerm -= Four * (A * C); 7233 7234 if (SqrtTerm.isNegative()) { 7235 // The loop is provably infinite. 7236 return None; 7237 } 7238 7239 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7240 // integer value or else APInt::sqrt() will assert. 7241 APInt SqrtVal(SqrtTerm.sqrt()); 7242 7243 // Compute the two solutions for the quadratic formula. 7244 // The divisions must be performed as signed divisions. 7245 APInt NegB(-B); 7246 APInt TwoA(A << 1); 7247 if (TwoA.isMinValue()) 7248 return None; 7249 7250 LLVMContext &Context = SE.getContext(); 7251 7252 ConstantInt *Solution1 = 7253 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7254 ConstantInt *Solution2 = 7255 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7256 7257 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7258 cast<SCEVConstant>(SE.getConstant(Solution2))); 7259 } // end APIntOps namespace 7260 } 7261 7262 ScalarEvolution::ExitLimit 7263 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7264 bool AllowPredicates) { 7265 7266 // This is only used for loops with a "x != y" exit test. The exit condition 7267 // is now expressed as a single expression, V = x-y. So the exit test is 7268 // effectively V != 0. We know and take advantage of the fact that this 7269 // expression only being used in a comparison by zero context. 7270 7271 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7272 // If the value is a constant 7273 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7274 // If the value is already zero, the branch will execute zero times. 7275 if (C->getValue()->isZero()) return C; 7276 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7277 } 7278 7279 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7280 if (!AddRec && AllowPredicates) 7281 // Try to make this an AddRec using runtime tests, in the first X 7282 // iterations of this loop, where X is the SCEV expression found by the 7283 // algorithm below. 7284 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7285 7286 if (!AddRec || AddRec->getLoop() != L) 7287 return getCouldNotCompute(); 7288 7289 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7290 // the quadratic equation to solve it. 7291 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7292 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7293 const SCEVConstant *R1 = Roots->first; 7294 const SCEVConstant *R2 = Roots->second; 7295 // Pick the smallest positive root value. 7296 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7297 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7298 if (!CB->getZExtValue()) 7299 std::swap(R1, R2); // R1 is the minimum root now. 7300 7301 // We can only use this value if the chrec ends up with an exact zero 7302 // value at this index. When solving for "X*X != 5", for example, we 7303 // should not accept a root of 2. 7304 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7305 if (Val->isZero()) 7306 // We found a quadratic root! 7307 return ExitLimit(R1, R1, false, Predicates); 7308 } 7309 } 7310 return getCouldNotCompute(); 7311 } 7312 7313 // Otherwise we can only handle this if it is affine. 7314 if (!AddRec->isAffine()) 7315 return getCouldNotCompute(); 7316 7317 // If this is an affine expression, the execution count of this branch is 7318 // the minimum unsigned root of the following equation: 7319 // 7320 // Start + Step*N = 0 (mod 2^BW) 7321 // 7322 // equivalent to: 7323 // 7324 // Step*N = -Start (mod 2^BW) 7325 // 7326 // where BW is the common bit width of Start and Step. 7327 7328 // Get the initial value for the loop. 7329 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7330 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7331 7332 // For now we handle only constant steps. 7333 // 7334 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7335 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7336 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7337 // We have not yet seen any such cases. 7338 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7339 if (!StepC || StepC->getValue()->equalsInt(0)) 7340 return getCouldNotCompute(); 7341 7342 // For positive steps (counting up until unsigned overflow): 7343 // N = -Start/Step (as unsigned) 7344 // For negative steps (counting down to zero): 7345 // N = Start/-Step 7346 // First compute the unsigned distance from zero in the direction of Step. 7347 bool CountDown = StepC->getAPInt().isNegative(); 7348 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7349 7350 // Handle unitary steps, which cannot wraparound. 7351 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7352 // N = Distance (as unsigned) 7353 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7354 APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); 7355 7356 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 7357 // we end up with a loop whose backedge-taken count is n - 1. Detect this 7358 // case, and see if we can improve the bound. 7359 // 7360 // Explicitly handling this here is necessary because getUnsignedRange 7361 // isn't context-sensitive; it doesn't know that we only care about the 7362 // range inside the loop. 7363 const SCEV *Zero = getZero(Distance->getType()); 7364 const SCEV *One = getOne(Distance->getType()); 7365 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 7366 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 7367 // If Distance + 1 doesn't overflow, we can compute the maximum distance 7368 // as "unsigned_max(Distance + 1) - 1". 7369 ConstantRange CR = getUnsignedRange(DistancePlusOne); 7370 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 7371 } 7372 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 7373 } 7374 7375 // If the condition controls loop exit (the loop exits only if the expression 7376 // is true) and the addition is no-wrap we can use unsigned divide to 7377 // compute the backedge count. In this case, the step may not divide the 7378 // distance, but we don't care because if the condition is "missed" the loop 7379 // will have undefined behavior due to wrapping. 7380 if (ControlsExit && AddRec->hasNoSelfWrap() && 7381 loopHasNoAbnormalExits(AddRec->getLoop())) { 7382 const SCEV *Exact = 7383 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7384 return ExitLimit(Exact, Exact, false, Predicates); 7385 } 7386 7387 // Solve the general equation. 7388 const SCEV *E = SolveLinEquationWithOverflow( 7389 StepC->getAPInt(), getNegativeSCEV(Start), *this); 7390 return ExitLimit(E, E, false, Predicates); 7391 } 7392 7393 ScalarEvolution::ExitLimit 7394 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7395 // Loops that look like: while (X == 0) are very strange indeed. We don't 7396 // handle them yet except for the trivial case. This could be expanded in the 7397 // future as needed. 7398 7399 // If the value is a constant, check to see if it is known to be non-zero 7400 // already. If so, the backedge will execute zero times. 7401 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7402 if (!C->getValue()->isNullValue()) 7403 return getZero(C->getType()); 7404 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7405 } 7406 7407 // We could implement others, but I really doubt anyone writes loops like 7408 // this, and if they did, they would already be constant folded. 7409 return getCouldNotCompute(); 7410 } 7411 7412 std::pair<BasicBlock *, BasicBlock *> 7413 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7414 // If the block has a unique predecessor, then there is no path from the 7415 // predecessor to the block that does not go through the direct edge 7416 // from the predecessor to the block. 7417 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7418 return {Pred, BB}; 7419 7420 // A loop's header is defined to be a block that dominates the loop. 7421 // If the header has a unique predecessor outside the loop, it must be 7422 // a block that has exactly one successor that can reach the loop. 7423 if (Loop *L = LI.getLoopFor(BB)) 7424 return {L->getLoopPredecessor(), L->getHeader()}; 7425 7426 return {nullptr, nullptr}; 7427 } 7428 7429 /// SCEV structural equivalence is usually sufficient for testing whether two 7430 /// expressions are equal, however for the purposes of looking for a condition 7431 /// guarding a loop, it can be useful to be a little more general, since a 7432 /// front-end may have replicated the controlling expression. 7433 /// 7434 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7435 // Quick check to see if they are the same SCEV. 7436 if (A == B) return true; 7437 7438 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7439 // Not all instructions that are "identical" compute the same value. For 7440 // instance, two distinct alloca instructions allocating the same type are 7441 // identical and do not read memory; but compute distinct values. 7442 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7443 }; 7444 7445 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7446 // two different instructions with the same value. Check for this case. 7447 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7448 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7449 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7450 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7451 if (ComputesEqualValues(AI, BI)) 7452 return true; 7453 7454 // Otherwise assume they may have a different value. 7455 return false; 7456 } 7457 7458 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7459 const SCEV *&LHS, const SCEV *&RHS, 7460 unsigned Depth) { 7461 bool Changed = false; 7462 7463 // If we hit the max recursion limit bail out. 7464 if (Depth >= 3) 7465 return false; 7466 7467 // Canonicalize a constant to the right side. 7468 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7469 // Check for both operands constant. 7470 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7471 if (ConstantExpr::getICmp(Pred, 7472 LHSC->getValue(), 7473 RHSC->getValue())->isNullValue()) 7474 goto trivially_false; 7475 else 7476 goto trivially_true; 7477 } 7478 // Otherwise swap the operands to put the constant on the right. 7479 std::swap(LHS, RHS); 7480 Pred = ICmpInst::getSwappedPredicate(Pred); 7481 Changed = true; 7482 } 7483 7484 // If we're comparing an addrec with a value which is loop-invariant in the 7485 // addrec's loop, put the addrec on the left. Also make a dominance check, 7486 // as both operands could be addrecs loop-invariant in each other's loop. 7487 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7488 const Loop *L = AR->getLoop(); 7489 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7490 std::swap(LHS, RHS); 7491 Pred = ICmpInst::getSwappedPredicate(Pred); 7492 Changed = true; 7493 } 7494 } 7495 7496 // If there's a constant operand, canonicalize comparisons with boundary 7497 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7498 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7499 const APInt &RA = RC->getAPInt(); 7500 7501 bool SimplifiedByConstantRange = false; 7502 7503 if (!ICmpInst::isEquality(Pred)) { 7504 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7505 if (ExactCR.isFullSet()) 7506 goto trivially_true; 7507 else if (ExactCR.isEmptySet()) 7508 goto trivially_false; 7509 7510 APInt NewRHS; 7511 CmpInst::Predicate NewPred; 7512 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7513 ICmpInst::isEquality(NewPred)) { 7514 // We were able to convert an inequality to an equality. 7515 Pred = NewPred; 7516 RHS = getConstant(NewRHS); 7517 Changed = SimplifiedByConstantRange = true; 7518 } 7519 } 7520 7521 if (!SimplifiedByConstantRange) { 7522 switch (Pred) { 7523 default: 7524 break; 7525 case ICmpInst::ICMP_EQ: 7526 case ICmpInst::ICMP_NE: 7527 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7528 if (!RA) 7529 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7530 if (const SCEVMulExpr *ME = 7531 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7532 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7533 ME->getOperand(0)->isAllOnesValue()) { 7534 RHS = AE->getOperand(1); 7535 LHS = ME->getOperand(1); 7536 Changed = true; 7537 } 7538 break; 7539 7540 7541 // The "Should have been caught earlier!" messages refer to the fact 7542 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7543 // should have fired on the corresponding cases, and canonicalized the 7544 // check to trivially_true or trivially_false. 7545 7546 case ICmpInst::ICMP_UGE: 7547 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7548 Pred = ICmpInst::ICMP_UGT; 7549 RHS = getConstant(RA - 1); 7550 Changed = true; 7551 break; 7552 case ICmpInst::ICMP_ULE: 7553 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7554 Pred = ICmpInst::ICMP_ULT; 7555 RHS = getConstant(RA + 1); 7556 Changed = true; 7557 break; 7558 case ICmpInst::ICMP_SGE: 7559 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7560 Pred = ICmpInst::ICMP_SGT; 7561 RHS = getConstant(RA - 1); 7562 Changed = true; 7563 break; 7564 case ICmpInst::ICMP_SLE: 7565 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7566 Pred = ICmpInst::ICMP_SLT; 7567 RHS = getConstant(RA + 1); 7568 Changed = true; 7569 break; 7570 } 7571 } 7572 } 7573 7574 // Check for obvious equality. 7575 if (HasSameValue(LHS, RHS)) { 7576 if (ICmpInst::isTrueWhenEqual(Pred)) 7577 goto trivially_true; 7578 if (ICmpInst::isFalseWhenEqual(Pred)) 7579 goto trivially_false; 7580 } 7581 7582 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7583 // adding or subtracting 1 from one of the operands. 7584 switch (Pred) { 7585 case ICmpInst::ICMP_SLE: 7586 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7587 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7588 SCEV::FlagNSW); 7589 Pred = ICmpInst::ICMP_SLT; 7590 Changed = true; 7591 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7592 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7593 SCEV::FlagNSW); 7594 Pred = ICmpInst::ICMP_SLT; 7595 Changed = true; 7596 } 7597 break; 7598 case ICmpInst::ICMP_SGE: 7599 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7600 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7601 SCEV::FlagNSW); 7602 Pred = ICmpInst::ICMP_SGT; 7603 Changed = true; 7604 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7605 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7606 SCEV::FlagNSW); 7607 Pred = ICmpInst::ICMP_SGT; 7608 Changed = true; 7609 } 7610 break; 7611 case ICmpInst::ICMP_ULE: 7612 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7613 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7614 SCEV::FlagNUW); 7615 Pred = ICmpInst::ICMP_ULT; 7616 Changed = true; 7617 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7618 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7619 Pred = ICmpInst::ICMP_ULT; 7620 Changed = true; 7621 } 7622 break; 7623 case ICmpInst::ICMP_UGE: 7624 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7625 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7626 Pred = ICmpInst::ICMP_UGT; 7627 Changed = true; 7628 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7629 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7630 SCEV::FlagNUW); 7631 Pred = ICmpInst::ICMP_UGT; 7632 Changed = true; 7633 } 7634 break; 7635 default: 7636 break; 7637 } 7638 7639 // TODO: More simplifications are possible here. 7640 7641 // Recursively simplify until we either hit a recursion limit or nothing 7642 // changes. 7643 if (Changed) 7644 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7645 7646 return Changed; 7647 7648 trivially_true: 7649 // Return 0 == 0. 7650 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7651 Pred = ICmpInst::ICMP_EQ; 7652 return true; 7653 7654 trivially_false: 7655 // Return 0 != 0. 7656 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7657 Pred = ICmpInst::ICMP_NE; 7658 return true; 7659 } 7660 7661 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7662 return getSignedRange(S).getSignedMax().isNegative(); 7663 } 7664 7665 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7666 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7667 } 7668 7669 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7670 return !getSignedRange(S).getSignedMin().isNegative(); 7671 } 7672 7673 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7674 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7675 } 7676 7677 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7678 return isKnownNegative(S) || isKnownPositive(S); 7679 } 7680 7681 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7682 const SCEV *LHS, const SCEV *RHS) { 7683 // Canonicalize the inputs first. 7684 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7685 7686 // If LHS or RHS is an addrec, check to see if the condition is true in 7687 // every iteration of the loop. 7688 // If LHS and RHS are both addrec, both conditions must be true in 7689 // every iteration of the loop. 7690 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7691 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7692 bool LeftGuarded = false; 7693 bool RightGuarded = false; 7694 if (LAR) { 7695 const Loop *L = LAR->getLoop(); 7696 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7697 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7698 if (!RAR) return true; 7699 LeftGuarded = true; 7700 } 7701 } 7702 if (RAR) { 7703 const Loop *L = RAR->getLoop(); 7704 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7705 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7706 if (!LAR) return true; 7707 RightGuarded = true; 7708 } 7709 } 7710 if (LeftGuarded && RightGuarded) 7711 return true; 7712 7713 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7714 return true; 7715 7716 // Otherwise see what can be done with known constant ranges. 7717 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7718 } 7719 7720 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7721 ICmpInst::Predicate Pred, 7722 bool &Increasing) { 7723 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7724 7725 #ifndef NDEBUG 7726 // Verify an invariant: inverting the predicate should turn a monotonically 7727 // increasing change to a monotonically decreasing one, and vice versa. 7728 bool IncreasingSwapped; 7729 bool ResultSwapped = isMonotonicPredicateImpl( 7730 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7731 7732 assert(Result == ResultSwapped && "should be able to analyze both!"); 7733 if (ResultSwapped) 7734 assert(Increasing == !IncreasingSwapped && 7735 "monotonicity should flip as we flip the predicate"); 7736 #endif 7737 7738 return Result; 7739 } 7740 7741 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7742 ICmpInst::Predicate Pred, 7743 bool &Increasing) { 7744 7745 // A zero step value for LHS means the induction variable is essentially a 7746 // loop invariant value. We don't really depend on the predicate actually 7747 // flipping from false to true (for increasing predicates, and the other way 7748 // around for decreasing predicates), all we care about is that *if* the 7749 // predicate changes then it only changes from false to true. 7750 // 7751 // A zero step value in itself is not very useful, but there may be places 7752 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7753 // as general as possible. 7754 7755 switch (Pred) { 7756 default: 7757 return false; // Conservative answer 7758 7759 case ICmpInst::ICMP_UGT: 7760 case ICmpInst::ICMP_UGE: 7761 case ICmpInst::ICMP_ULT: 7762 case ICmpInst::ICMP_ULE: 7763 if (!LHS->hasNoUnsignedWrap()) 7764 return false; 7765 7766 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7767 return true; 7768 7769 case ICmpInst::ICMP_SGT: 7770 case ICmpInst::ICMP_SGE: 7771 case ICmpInst::ICMP_SLT: 7772 case ICmpInst::ICMP_SLE: { 7773 if (!LHS->hasNoSignedWrap()) 7774 return false; 7775 7776 const SCEV *Step = LHS->getStepRecurrence(*this); 7777 7778 if (isKnownNonNegative(Step)) { 7779 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7780 return true; 7781 } 7782 7783 if (isKnownNonPositive(Step)) { 7784 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7785 return true; 7786 } 7787 7788 return false; 7789 } 7790 7791 } 7792 7793 llvm_unreachable("switch has default clause!"); 7794 } 7795 7796 bool ScalarEvolution::isLoopInvariantPredicate( 7797 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7798 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7799 const SCEV *&InvariantRHS) { 7800 7801 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7802 if (!isLoopInvariant(RHS, L)) { 7803 if (!isLoopInvariant(LHS, L)) 7804 return false; 7805 7806 std::swap(LHS, RHS); 7807 Pred = ICmpInst::getSwappedPredicate(Pred); 7808 } 7809 7810 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7811 if (!ArLHS || ArLHS->getLoop() != L) 7812 return false; 7813 7814 bool Increasing; 7815 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7816 return false; 7817 7818 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7819 // true as the loop iterates, and the backedge is control dependent on 7820 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7821 // 7822 // * if the predicate was false in the first iteration then the predicate 7823 // is never evaluated again, since the loop exits without taking the 7824 // backedge. 7825 // * if the predicate was true in the first iteration then it will 7826 // continue to be true for all future iterations since it is 7827 // monotonically increasing. 7828 // 7829 // For both the above possibilities, we can replace the loop varying 7830 // predicate with its value on the first iteration of the loop (which is 7831 // loop invariant). 7832 // 7833 // A similar reasoning applies for a monotonically decreasing predicate, by 7834 // replacing true with false and false with true in the above two bullets. 7835 7836 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7837 7838 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7839 return false; 7840 7841 InvariantPred = Pred; 7842 InvariantLHS = ArLHS->getStart(); 7843 InvariantRHS = RHS; 7844 return true; 7845 } 7846 7847 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7848 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7849 if (HasSameValue(LHS, RHS)) 7850 return ICmpInst::isTrueWhenEqual(Pred); 7851 7852 // This code is split out from isKnownPredicate because it is called from 7853 // within isLoopEntryGuardedByCond. 7854 7855 auto CheckRanges = 7856 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7857 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7858 .contains(RangeLHS); 7859 }; 7860 7861 // The check at the top of the function catches the case where the values are 7862 // known to be equal. 7863 if (Pred == CmpInst::ICMP_EQ) 7864 return false; 7865 7866 if (Pred == CmpInst::ICMP_NE) 7867 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7868 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7869 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7870 7871 if (CmpInst::isSigned(Pred)) 7872 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7873 7874 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7875 } 7876 7877 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7878 const SCEV *LHS, 7879 const SCEV *RHS) { 7880 7881 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7882 // Return Y via OutY. 7883 auto MatchBinaryAddToConst = 7884 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7885 SCEV::NoWrapFlags ExpectedFlags) { 7886 const SCEV *NonConstOp, *ConstOp; 7887 SCEV::NoWrapFlags FlagsPresent; 7888 7889 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7890 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7891 return false; 7892 7893 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7894 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7895 }; 7896 7897 APInt C; 7898 7899 switch (Pred) { 7900 default: 7901 break; 7902 7903 case ICmpInst::ICMP_SGE: 7904 std::swap(LHS, RHS); 7905 case ICmpInst::ICMP_SLE: 7906 // X s<= (X + C)<nsw> if C >= 0 7907 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7908 return true; 7909 7910 // (X + C)<nsw> s<= X if C <= 0 7911 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7912 !C.isStrictlyPositive()) 7913 return true; 7914 break; 7915 7916 case ICmpInst::ICMP_SGT: 7917 std::swap(LHS, RHS); 7918 case ICmpInst::ICMP_SLT: 7919 // X s< (X + C)<nsw> if C > 0 7920 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7921 C.isStrictlyPositive()) 7922 return true; 7923 7924 // (X + C)<nsw> s< X if C < 0 7925 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7926 return true; 7927 break; 7928 } 7929 7930 return false; 7931 } 7932 7933 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7934 const SCEV *LHS, 7935 const SCEV *RHS) { 7936 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7937 return false; 7938 7939 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7940 // the stack can result in exponential time complexity. 7941 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7942 7943 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7944 // 7945 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7946 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7947 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7948 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7949 // use isKnownPredicate later if needed. 7950 return isKnownNonNegative(RHS) && 7951 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7952 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7953 } 7954 7955 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7956 ICmpInst::Predicate Pred, 7957 const SCEV *LHS, const SCEV *RHS) { 7958 // No need to even try if we know the module has no guards. 7959 if (!HasGuards) 7960 return false; 7961 7962 return any_of(*BB, [&](Instruction &I) { 7963 using namespace llvm::PatternMatch; 7964 7965 Value *Condition; 7966 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7967 m_Value(Condition))) && 7968 isImpliedCond(Pred, LHS, RHS, Condition, false); 7969 }); 7970 } 7971 7972 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7973 /// protected by a conditional between LHS and RHS. This is used to 7974 /// to eliminate casts. 7975 bool 7976 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7977 ICmpInst::Predicate Pred, 7978 const SCEV *LHS, const SCEV *RHS) { 7979 // Interpret a null as meaning no loop, where there is obviously no guard 7980 // (interprocedural conditions notwithstanding). 7981 if (!L) return true; 7982 7983 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7984 return true; 7985 7986 BasicBlock *Latch = L->getLoopLatch(); 7987 if (!Latch) 7988 return false; 7989 7990 BranchInst *LoopContinuePredicate = 7991 dyn_cast<BranchInst>(Latch->getTerminator()); 7992 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7993 isImpliedCond(Pred, LHS, RHS, 7994 LoopContinuePredicate->getCondition(), 7995 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7996 return true; 7997 7998 // We don't want more than one activation of the following loops on the stack 7999 // -- that can lead to O(n!) time complexity. 8000 if (WalkingBEDominatingConds) 8001 return false; 8002 8003 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8004 8005 // See if we can exploit a trip count to prove the predicate. 8006 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8007 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8008 if (LatchBECount != getCouldNotCompute()) { 8009 // We know that Latch branches back to the loop header exactly 8010 // LatchBECount times. This means the backdege condition at Latch is 8011 // equivalent to "{0,+,1} u< LatchBECount". 8012 Type *Ty = LatchBECount->getType(); 8013 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8014 const SCEV *LoopCounter = 8015 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8016 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8017 LatchBECount)) 8018 return true; 8019 } 8020 8021 // Check conditions due to any @llvm.assume intrinsics. 8022 for (auto &AssumeVH : AC.assumptions()) { 8023 if (!AssumeVH) 8024 continue; 8025 auto *CI = cast<CallInst>(AssumeVH); 8026 if (!DT.dominates(CI, Latch->getTerminator())) 8027 continue; 8028 8029 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8030 return true; 8031 } 8032 8033 // If the loop is not reachable from the entry block, we risk running into an 8034 // infinite loop as we walk up into the dom tree. These loops do not matter 8035 // anyway, so we just return a conservative answer when we see them. 8036 if (!DT.isReachableFromEntry(L->getHeader())) 8037 return false; 8038 8039 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8040 return true; 8041 8042 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8043 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8044 8045 assert(DTN && "should reach the loop header before reaching the root!"); 8046 8047 BasicBlock *BB = DTN->getBlock(); 8048 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8049 return true; 8050 8051 BasicBlock *PBB = BB->getSinglePredecessor(); 8052 if (!PBB) 8053 continue; 8054 8055 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8056 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8057 continue; 8058 8059 Value *Condition = ContinuePredicate->getCondition(); 8060 8061 // If we have an edge `E` within the loop body that dominates the only 8062 // latch, the condition guarding `E` also guards the backedge. This 8063 // reasoning works only for loops with a single latch. 8064 8065 BasicBlockEdge DominatingEdge(PBB, BB); 8066 if (DominatingEdge.isSingleEdge()) { 8067 // We're constructively (and conservatively) enumerating edges within the 8068 // loop body that dominate the latch. The dominator tree better agree 8069 // with us on this: 8070 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8071 8072 if (isImpliedCond(Pred, LHS, RHS, Condition, 8073 BB != ContinuePredicate->getSuccessor(0))) 8074 return true; 8075 } 8076 } 8077 8078 return false; 8079 } 8080 8081 bool 8082 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8083 ICmpInst::Predicate Pred, 8084 const SCEV *LHS, const SCEV *RHS) { 8085 // Interpret a null as meaning no loop, where there is obviously no guard 8086 // (interprocedural conditions notwithstanding). 8087 if (!L) return false; 8088 8089 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8090 return true; 8091 8092 // Starting at the loop predecessor, climb up the predecessor chain, as long 8093 // as there are predecessors that can be found that have unique successors 8094 // leading to the original header. 8095 for (std::pair<BasicBlock *, BasicBlock *> 8096 Pair(L->getLoopPredecessor(), L->getHeader()); 8097 Pair.first; 8098 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8099 8100 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8101 return true; 8102 8103 BranchInst *LoopEntryPredicate = 8104 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8105 if (!LoopEntryPredicate || 8106 LoopEntryPredicate->isUnconditional()) 8107 continue; 8108 8109 if (isImpliedCond(Pred, LHS, RHS, 8110 LoopEntryPredicate->getCondition(), 8111 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8112 return true; 8113 } 8114 8115 // Check conditions due to any @llvm.assume intrinsics. 8116 for (auto &AssumeVH : AC.assumptions()) { 8117 if (!AssumeVH) 8118 continue; 8119 auto *CI = cast<CallInst>(AssumeVH); 8120 if (!DT.dominates(CI, L->getHeader())) 8121 continue; 8122 8123 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8124 return true; 8125 } 8126 8127 return false; 8128 } 8129 8130 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8131 const SCEV *LHS, const SCEV *RHS, 8132 Value *FoundCondValue, 8133 bool Inverse) { 8134 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8135 return false; 8136 8137 auto ClearOnExit = 8138 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8139 8140 // Recursively handle And and Or conditions. 8141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8142 if (BO->getOpcode() == Instruction::And) { 8143 if (!Inverse) 8144 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8145 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8146 } else if (BO->getOpcode() == Instruction::Or) { 8147 if (Inverse) 8148 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8149 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8150 } 8151 } 8152 8153 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8154 if (!ICI) return false; 8155 8156 // Now that we found a conditional branch that dominates the loop or controls 8157 // the loop latch. Check to see if it is the comparison we are looking for. 8158 ICmpInst::Predicate FoundPred; 8159 if (Inverse) 8160 FoundPred = ICI->getInversePredicate(); 8161 else 8162 FoundPred = ICI->getPredicate(); 8163 8164 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8165 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8166 8167 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8168 } 8169 8170 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8171 const SCEV *RHS, 8172 ICmpInst::Predicate FoundPred, 8173 const SCEV *FoundLHS, 8174 const SCEV *FoundRHS) { 8175 // Balance the types. 8176 if (getTypeSizeInBits(LHS->getType()) < 8177 getTypeSizeInBits(FoundLHS->getType())) { 8178 if (CmpInst::isSigned(Pred)) { 8179 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8180 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8181 } else { 8182 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8183 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8184 } 8185 } else if (getTypeSizeInBits(LHS->getType()) > 8186 getTypeSizeInBits(FoundLHS->getType())) { 8187 if (CmpInst::isSigned(FoundPred)) { 8188 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8189 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8190 } else { 8191 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8192 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8193 } 8194 } 8195 8196 // Canonicalize the query to match the way instcombine will have 8197 // canonicalized the comparison. 8198 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8199 if (LHS == RHS) 8200 return CmpInst::isTrueWhenEqual(Pred); 8201 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8202 if (FoundLHS == FoundRHS) 8203 return CmpInst::isFalseWhenEqual(FoundPred); 8204 8205 // Check to see if we can make the LHS or RHS match. 8206 if (LHS == FoundRHS || RHS == FoundLHS) { 8207 if (isa<SCEVConstant>(RHS)) { 8208 std::swap(FoundLHS, FoundRHS); 8209 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8210 } else { 8211 std::swap(LHS, RHS); 8212 Pred = ICmpInst::getSwappedPredicate(Pred); 8213 } 8214 } 8215 8216 // Check whether the found predicate is the same as the desired predicate. 8217 if (FoundPred == Pred) 8218 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8219 8220 // Check whether swapping the found predicate makes it the same as the 8221 // desired predicate. 8222 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8223 if (isa<SCEVConstant>(RHS)) 8224 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8225 else 8226 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8227 RHS, LHS, FoundLHS, FoundRHS); 8228 } 8229 8230 // Unsigned comparison is the same as signed comparison when both the operands 8231 // are non-negative. 8232 if (CmpInst::isUnsigned(FoundPred) && 8233 CmpInst::getSignedPredicate(FoundPred) == Pred && 8234 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8235 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8236 8237 // Check if we can make progress by sharpening ranges. 8238 if (FoundPred == ICmpInst::ICMP_NE && 8239 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8240 8241 const SCEVConstant *C = nullptr; 8242 const SCEV *V = nullptr; 8243 8244 if (isa<SCEVConstant>(FoundLHS)) { 8245 C = cast<SCEVConstant>(FoundLHS); 8246 V = FoundRHS; 8247 } else { 8248 C = cast<SCEVConstant>(FoundRHS); 8249 V = FoundLHS; 8250 } 8251 8252 // The guarding predicate tells us that C != V. If the known range 8253 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8254 // range we consider has to correspond to same signedness as the 8255 // predicate we're interested in folding. 8256 8257 APInt Min = ICmpInst::isSigned(Pred) ? 8258 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8259 8260 if (Min == C->getAPInt()) { 8261 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8262 // This is true even if (Min + 1) wraps around -- in case of 8263 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8264 8265 APInt SharperMin = Min + 1; 8266 8267 switch (Pred) { 8268 case ICmpInst::ICMP_SGE: 8269 case ICmpInst::ICMP_UGE: 8270 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8271 // RHS, we're done. 8272 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8273 getConstant(SharperMin))) 8274 return true; 8275 8276 case ICmpInst::ICMP_SGT: 8277 case ICmpInst::ICMP_UGT: 8278 // We know from the range information that (V `Pred` Min || 8279 // V == Min). We know from the guarding condition that !(V 8280 // == Min). This gives us 8281 // 8282 // V `Pred` Min || V == Min && !(V == Min) 8283 // => V `Pred` Min 8284 // 8285 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8286 8287 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8288 return true; 8289 8290 default: 8291 // No change 8292 break; 8293 } 8294 } 8295 } 8296 8297 // Check whether the actual condition is beyond sufficient. 8298 if (FoundPred == ICmpInst::ICMP_EQ) 8299 if (ICmpInst::isTrueWhenEqual(Pred)) 8300 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8301 return true; 8302 if (Pred == ICmpInst::ICMP_NE) 8303 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8304 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8305 return true; 8306 8307 // Otherwise assume the worst. 8308 return false; 8309 } 8310 8311 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8312 const SCEV *&L, const SCEV *&R, 8313 SCEV::NoWrapFlags &Flags) { 8314 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8315 if (!AE || AE->getNumOperands() != 2) 8316 return false; 8317 8318 L = AE->getOperand(0); 8319 R = AE->getOperand(1); 8320 Flags = AE->getNoWrapFlags(); 8321 return true; 8322 } 8323 8324 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8325 const SCEV *Less) { 8326 // We avoid subtracting expressions here because this function is usually 8327 // fairly deep in the call stack (i.e. is called many times). 8328 8329 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8330 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8331 const auto *MAR = cast<SCEVAddRecExpr>(More); 8332 8333 if (LAR->getLoop() != MAR->getLoop()) 8334 return None; 8335 8336 // We look at affine expressions only; not for correctness but to keep 8337 // getStepRecurrence cheap. 8338 if (!LAR->isAffine() || !MAR->isAffine()) 8339 return None; 8340 8341 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8342 return None; 8343 8344 Less = LAR->getStart(); 8345 More = MAR->getStart(); 8346 8347 // fall through 8348 } 8349 8350 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8351 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8352 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8353 return M - L; 8354 } 8355 8356 const SCEV *L, *R; 8357 SCEV::NoWrapFlags Flags; 8358 if (splitBinaryAdd(Less, L, R, Flags)) 8359 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8360 if (R == More) 8361 return -(LC->getAPInt()); 8362 8363 if (splitBinaryAdd(More, L, R, Flags)) 8364 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8365 if (R == Less) 8366 return LC->getAPInt(); 8367 8368 return None; 8369 } 8370 8371 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8372 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8373 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8374 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8375 return false; 8376 8377 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8378 if (!AddRecLHS) 8379 return false; 8380 8381 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8382 if (!AddRecFoundLHS) 8383 return false; 8384 8385 // We'd like to let SCEV reason about control dependencies, so we constrain 8386 // both the inequalities to be about add recurrences on the same loop. This 8387 // way we can use isLoopEntryGuardedByCond later. 8388 8389 const Loop *L = AddRecFoundLHS->getLoop(); 8390 if (L != AddRecLHS->getLoop()) 8391 return false; 8392 8393 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8394 // 8395 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8396 // ... (2) 8397 // 8398 // Informal proof for (2), assuming (1) [*]: 8399 // 8400 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8401 // 8402 // Then 8403 // 8404 // FoundLHS s< FoundRHS s< INT_MIN - C 8405 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8406 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8407 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8408 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8409 // <=> FoundLHS + C s< FoundRHS + C 8410 // 8411 // [*]: (1) can be proved by ruling out overflow. 8412 // 8413 // [**]: This can be proved by analyzing all the four possibilities: 8414 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8415 // (A s>= 0, B s>= 0). 8416 // 8417 // Note: 8418 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8419 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8420 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8421 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8422 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8423 // C)". 8424 8425 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8426 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8427 if (!LDiff || !RDiff || *LDiff != *RDiff) 8428 return false; 8429 8430 if (LDiff->isMinValue()) 8431 return true; 8432 8433 APInt FoundRHSLimit; 8434 8435 if (Pred == CmpInst::ICMP_ULT) { 8436 FoundRHSLimit = -(*RDiff); 8437 } else { 8438 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8439 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8440 } 8441 8442 // Try to prove (1) or (2), as needed. 8443 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8444 getConstant(FoundRHSLimit)); 8445 } 8446 8447 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8448 const SCEV *LHS, const SCEV *RHS, 8449 const SCEV *FoundLHS, 8450 const SCEV *FoundRHS) { 8451 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8452 return true; 8453 8454 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8455 return true; 8456 8457 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8458 FoundLHS, FoundRHS) || 8459 // ~x < ~y --> x > y 8460 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8461 getNotSCEV(FoundRHS), 8462 getNotSCEV(FoundLHS)); 8463 } 8464 8465 8466 /// If Expr computes ~A, return A else return nullptr 8467 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8468 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8469 if (!Add || Add->getNumOperands() != 2 || 8470 !Add->getOperand(0)->isAllOnesValue()) 8471 return nullptr; 8472 8473 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8474 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8475 !AddRHS->getOperand(0)->isAllOnesValue()) 8476 return nullptr; 8477 8478 return AddRHS->getOperand(1); 8479 } 8480 8481 8482 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8483 template<typename MaxExprType> 8484 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8485 const SCEV *Candidate) { 8486 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8487 if (!MaxExpr) return false; 8488 8489 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8490 } 8491 8492 8493 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8494 template<typename MaxExprType> 8495 static bool IsMinConsistingOf(ScalarEvolution &SE, 8496 const SCEV *MaybeMinExpr, 8497 const SCEV *Candidate) { 8498 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8499 if (!MaybeMaxExpr) 8500 return false; 8501 8502 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8503 } 8504 8505 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8506 ICmpInst::Predicate Pred, 8507 const SCEV *LHS, const SCEV *RHS) { 8508 8509 // If both sides are affine addrecs for the same loop, with equal 8510 // steps, and we know the recurrences don't wrap, then we only 8511 // need to check the predicate on the starting values. 8512 8513 if (!ICmpInst::isRelational(Pred)) 8514 return false; 8515 8516 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8517 if (!LAR) 8518 return false; 8519 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8520 if (!RAR) 8521 return false; 8522 if (LAR->getLoop() != RAR->getLoop()) 8523 return false; 8524 if (!LAR->isAffine() || !RAR->isAffine()) 8525 return false; 8526 8527 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8528 return false; 8529 8530 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8531 SCEV::FlagNSW : SCEV::FlagNUW; 8532 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8533 return false; 8534 8535 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8536 } 8537 8538 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8539 /// expression? 8540 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8541 ICmpInst::Predicate Pred, 8542 const SCEV *LHS, const SCEV *RHS) { 8543 switch (Pred) { 8544 default: 8545 return false; 8546 8547 case ICmpInst::ICMP_SGE: 8548 std::swap(LHS, RHS); 8549 LLVM_FALLTHROUGH; 8550 case ICmpInst::ICMP_SLE: 8551 return 8552 // min(A, ...) <= A 8553 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8554 // A <= max(A, ...) 8555 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8556 8557 case ICmpInst::ICMP_UGE: 8558 std::swap(LHS, RHS); 8559 LLVM_FALLTHROUGH; 8560 case ICmpInst::ICMP_ULE: 8561 return 8562 // min(A, ...) <= A 8563 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8564 // A <= max(A, ...) 8565 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8566 } 8567 8568 llvm_unreachable("covered switch fell through?!"); 8569 } 8570 8571 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 8572 const SCEV *LHS, const SCEV *RHS, 8573 const SCEV *FoundLHS, 8574 const SCEV *FoundRHS, 8575 unsigned Depth) { 8576 assert(getTypeSizeInBits(LHS->getType()) == 8577 getTypeSizeInBits(RHS->getType()) && 8578 "LHS and RHS have different sizes?"); 8579 assert(getTypeSizeInBits(FoundLHS->getType()) == 8580 getTypeSizeInBits(FoundRHS->getType()) && 8581 "FoundLHS and FoundRHS have different sizes?"); 8582 // We want to avoid hurting the compile time with analysis of too big trees. 8583 if (Depth > MaxSCEVOperationsImplicationDepth) 8584 return false; 8585 // We only want to work with ICMP_SGT comparison so far. 8586 // TODO: Extend to ICMP_UGT? 8587 if (Pred == ICmpInst::ICMP_SLT) { 8588 Pred = ICmpInst::ICMP_SGT; 8589 std::swap(LHS, RHS); 8590 std::swap(FoundLHS, FoundRHS); 8591 } 8592 if (Pred != ICmpInst::ICMP_SGT) 8593 return false; 8594 8595 auto GetOpFromSExt = [&](const SCEV *S) { 8596 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 8597 return Ext->getOperand(); 8598 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 8599 // the constant in some cases. 8600 return S; 8601 }; 8602 8603 // Acquire values from extensions. 8604 auto *OrigFoundLHS = FoundLHS; 8605 LHS = GetOpFromSExt(LHS); 8606 FoundLHS = GetOpFromSExt(FoundLHS); 8607 8608 // Is the SGT predicate can be proved trivially or using the found context. 8609 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 8610 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 8611 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 8612 FoundRHS, Depth + 1); 8613 }; 8614 8615 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 8616 // We want to avoid creation of any new non-constant SCEV. Since we are 8617 // going to compare the operands to RHS, we should be certain that we don't 8618 // need any size extensions for this. So let's decline all cases when the 8619 // sizes of types of LHS and RHS do not match. 8620 // TODO: Maybe try to get RHS from sext to catch more cases? 8621 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 8622 return false; 8623 8624 // Should not overflow. 8625 if (!LHSAddExpr->hasNoSignedWrap()) 8626 return false; 8627 8628 auto *LL = LHSAddExpr->getOperand(0); 8629 auto *LR = LHSAddExpr->getOperand(1); 8630 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 8631 8632 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 8633 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 8634 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 8635 }; 8636 // Try to prove the following rule: 8637 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 8638 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 8639 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 8640 return true; 8641 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 8642 Value *LL, *LR; 8643 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 8644 using namespace llvm::PatternMatch; 8645 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 8646 // Rules for division. 8647 // We are going to perform some comparisons with Denominator and its 8648 // derivative expressions. In general case, creating a SCEV for it may 8649 // lead to a complex analysis of the entire graph, and in particular it 8650 // can request trip count recalculation for the same loop. This would 8651 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 8652 // this, we only want to create SCEVs that are constants in this section. 8653 // So we bail if Denominator is not a constant. 8654 if (!isa<ConstantInt>(LR)) 8655 return false; 8656 8657 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 8658 8659 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 8660 // then a SCEV for the numerator already exists and matches with FoundLHS. 8661 auto *Numerator = getExistingSCEV(LL); 8662 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 8663 return false; 8664 8665 // Make sure that the numerator matches with FoundLHS and the denominator 8666 // is positive. 8667 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 8668 return false; 8669 8670 auto *DTy = Denominator->getType(); 8671 auto *FRHSTy = FoundRHS->getType(); 8672 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 8673 // One of types is a pointer and another one is not. We cannot extend 8674 // them properly to a wider type, so let us just reject this case. 8675 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 8676 // to avoid this check. 8677 return false; 8678 8679 // Given that: 8680 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 8681 auto *WTy = getWiderType(DTy, FRHSTy); 8682 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 8683 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 8684 8685 // Try to prove the following rule: 8686 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 8687 // For example, given that FoundLHS > 2. It means that FoundLHS is at 8688 // least 3. If we divide it by Denominator < 4, we will have at least 1. 8689 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 8690 if (isKnownNonPositive(RHS) && 8691 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 8692 return true; 8693 8694 // Try to prove the following rule: 8695 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 8696 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 8697 // If we divide it by Denominator > 2, then: 8698 // 1. If FoundLHS is negative, then the result is 0. 8699 // 2. If FoundLHS is non-negative, then the result is non-negative. 8700 // Anyways, the result is non-negative. 8701 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 8702 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 8703 if (isKnownNegative(RHS) && 8704 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 8705 return true; 8706 } 8707 } 8708 8709 return false; 8710 } 8711 8712 bool 8713 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 8714 const SCEV *LHS, const SCEV *RHS) { 8715 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8716 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8717 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8718 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8719 } 8720 8721 bool 8722 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8723 const SCEV *LHS, const SCEV *RHS, 8724 const SCEV *FoundLHS, 8725 const SCEV *FoundRHS) { 8726 switch (Pred) { 8727 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8728 case ICmpInst::ICMP_EQ: 8729 case ICmpInst::ICMP_NE: 8730 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8731 return true; 8732 break; 8733 case ICmpInst::ICMP_SLT: 8734 case ICmpInst::ICMP_SLE: 8735 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8736 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8737 return true; 8738 break; 8739 case ICmpInst::ICMP_SGT: 8740 case ICmpInst::ICMP_SGE: 8741 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8742 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8743 return true; 8744 break; 8745 case ICmpInst::ICMP_ULT: 8746 case ICmpInst::ICMP_ULE: 8747 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8748 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8749 return true; 8750 break; 8751 case ICmpInst::ICMP_UGT: 8752 case ICmpInst::ICMP_UGE: 8753 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8754 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8755 return true; 8756 break; 8757 } 8758 8759 // Maybe it can be proved via operations? 8760 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8761 return true; 8762 8763 return false; 8764 } 8765 8766 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8767 const SCEV *LHS, 8768 const SCEV *RHS, 8769 const SCEV *FoundLHS, 8770 const SCEV *FoundRHS) { 8771 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8772 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8773 // reduce the compile time impact of this optimization. 8774 return false; 8775 8776 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8777 if (!Addend) 8778 return false; 8779 8780 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8781 8782 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8783 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8784 ConstantRange FoundLHSRange = 8785 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8786 8787 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8788 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8789 8790 // We can also compute the range of values for `LHS` that satisfy the 8791 // consequent, "`LHS` `Pred` `RHS`": 8792 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8793 ConstantRange SatisfyingLHSRange = 8794 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8795 8796 // The antecedent implies the consequent if every value of `LHS` that 8797 // satisfies the antecedent also satisfies the consequent. 8798 return SatisfyingLHSRange.contains(LHSRange); 8799 } 8800 8801 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8802 bool IsSigned, bool NoWrap) { 8803 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8804 8805 if (NoWrap) return false; 8806 8807 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8808 const SCEV *One = getOne(Stride->getType()); 8809 8810 if (IsSigned) { 8811 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8812 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8813 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8814 .getSignedMax(); 8815 8816 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8817 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8818 } 8819 8820 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8821 APInt MaxValue = APInt::getMaxValue(BitWidth); 8822 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8823 .getUnsignedMax(); 8824 8825 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8826 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8827 } 8828 8829 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8830 bool IsSigned, bool NoWrap) { 8831 if (NoWrap) return false; 8832 8833 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8834 const SCEV *One = getOne(Stride->getType()); 8835 8836 if (IsSigned) { 8837 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8838 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8839 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8840 .getSignedMax(); 8841 8842 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8843 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8844 } 8845 8846 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8847 APInt MinValue = APInt::getMinValue(BitWidth); 8848 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8849 .getUnsignedMax(); 8850 8851 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8852 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8853 } 8854 8855 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8856 bool Equality) { 8857 const SCEV *One = getOne(Step->getType()); 8858 Delta = Equality ? getAddExpr(Delta, Step) 8859 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8860 return getUDivExpr(Delta, Step); 8861 } 8862 8863 ScalarEvolution::ExitLimit 8864 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8865 const Loop *L, bool IsSigned, 8866 bool ControlsExit, bool AllowPredicates) { 8867 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8868 // We handle only IV < Invariant 8869 if (!isLoopInvariant(RHS, L)) 8870 return getCouldNotCompute(); 8871 8872 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8873 bool PredicatedIV = false; 8874 8875 if (!IV && AllowPredicates) { 8876 // Try to make this an AddRec using runtime tests, in the first X 8877 // iterations of this loop, where X is the SCEV expression found by the 8878 // algorithm below. 8879 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8880 PredicatedIV = true; 8881 } 8882 8883 // Avoid weird loops 8884 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8885 return getCouldNotCompute(); 8886 8887 bool NoWrap = ControlsExit && 8888 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8889 8890 const SCEV *Stride = IV->getStepRecurrence(*this); 8891 8892 bool PositiveStride = isKnownPositive(Stride); 8893 8894 // Avoid negative or zero stride values. 8895 if (!PositiveStride) { 8896 // We can compute the correct backedge taken count for loops with unknown 8897 // strides if we can prove that the loop is not an infinite loop with side 8898 // effects. Here's the loop structure we are trying to handle - 8899 // 8900 // i = start 8901 // do { 8902 // A[i] = i; 8903 // i += s; 8904 // } while (i < end); 8905 // 8906 // The backedge taken count for such loops is evaluated as - 8907 // (max(end, start + stride) - start - 1) /u stride 8908 // 8909 // The additional preconditions that we need to check to prove correctness 8910 // of the above formula is as follows - 8911 // 8912 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8913 // NoWrap flag). 8914 // b) loop is single exit with no side effects. 8915 // 8916 // 8917 // Precondition a) implies that if the stride is negative, this is a single 8918 // trip loop. The backedge taken count formula reduces to zero in this case. 8919 // 8920 // Precondition b) implies that the unknown stride cannot be zero otherwise 8921 // we have UB. 8922 // 8923 // The positive stride case is the same as isKnownPositive(Stride) returning 8924 // true (original behavior of the function). 8925 // 8926 // We want to make sure that the stride is truly unknown as there are edge 8927 // cases where ScalarEvolution propagates no wrap flags to the 8928 // post-increment/decrement IV even though the increment/decrement operation 8929 // itself is wrapping. The computed backedge taken count may be wrong in 8930 // such cases. This is prevented by checking that the stride is not known to 8931 // be either positive or non-positive. For example, no wrap flags are 8932 // propagated to the post-increment IV of this loop with a trip count of 2 - 8933 // 8934 // unsigned char i; 8935 // for(i=127; i<128; i+=129) 8936 // A[i] = i; 8937 // 8938 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8939 !loopHasNoSideEffects(L)) 8940 return getCouldNotCompute(); 8941 8942 } else if (!Stride->isOne() && 8943 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8944 // Avoid proven overflow cases: this will ensure that the backedge taken 8945 // count will not generate any unsigned overflow. Relaxed no-overflow 8946 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8947 // undefined behaviors like the case of C language. 8948 return getCouldNotCompute(); 8949 8950 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8951 : ICmpInst::ICMP_ULT; 8952 const SCEV *Start = IV->getStart(); 8953 const SCEV *End = RHS; 8954 // If the backedge is taken at least once, then it will be taken 8955 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8956 // is the LHS value of the less-than comparison the first time it is evaluated 8957 // and End is the RHS. 8958 const SCEV *BECountIfBackedgeTaken = 8959 computeBECount(getMinusSCEV(End, Start), Stride, false); 8960 // If the loop entry is guarded by the result of the backedge test of the 8961 // first loop iteration, then we know the backedge will be taken at least 8962 // once and so the backedge taken count is as above. If not then we use the 8963 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8964 // as if the backedge is taken at least once max(End,Start) is End and so the 8965 // result is as above, and if not max(End,Start) is Start so we get a backedge 8966 // count of zero. 8967 const SCEV *BECount; 8968 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8969 BECount = BECountIfBackedgeTaken; 8970 else { 8971 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8972 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8973 } 8974 8975 const SCEV *MaxBECount; 8976 bool MaxOrZero = false; 8977 if (isa<SCEVConstant>(BECount)) 8978 MaxBECount = BECount; 8979 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8980 // If we know exactly how many times the backedge will be taken if it's 8981 // taken at least once, then the backedge count will either be that or 8982 // zero. 8983 MaxBECount = BECountIfBackedgeTaken; 8984 MaxOrZero = true; 8985 } else { 8986 // Calculate the maximum backedge count based on the range of values 8987 // permitted by Start, End, and Stride. 8988 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8989 : getUnsignedRange(Start).getUnsignedMin(); 8990 8991 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8992 8993 APInt StrideForMaxBECount; 8994 8995 if (PositiveStride) 8996 StrideForMaxBECount = 8997 IsSigned ? getSignedRange(Stride).getSignedMin() 8998 : getUnsignedRange(Stride).getUnsignedMin(); 8999 else 9000 // Using a stride of 1 is safe when computing max backedge taken count for 9001 // a loop with unknown stride. 9002 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 9003 9004 APInt Limit = 9005 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 9006 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 9007 9008 // Although End can be a MAX expression we estimate MaxEnd considering only 9009 // the case End = RHS. This is safe because in the other case (End - Start) 9010 // is zero, leading to a zero maximum backedge taken count. 9011 APInt MaxEnd = 9012 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 9013 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 9014 9015 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 9016 getConstant(StrideForMaxBECount), false); 9017 } 9018 9019 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9020 MaxBECount = BECount; 9021 9022 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9023 } 9024 9025 ScalarEvolution::ExitLimit 9026 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 9027 const Loop *L, bool IsSigned, 9028 bool ControlsExit, bool AllowPredicates) { 9029 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9030 // We handle only IV > Invariant 9031 if (!isLoopInvariant(RHS, L)) 9032 return getCouldNotCompute(); 9033 9034 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9035 if (!IV && AllowPredicates) 9036 // Try to make this an AddRec using runtime tests, in the first X 9037 // iterations of this loop, where X is the SCEV expression found by the 9038 // algorithm below. 9039 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9040 9041 // Avoid weird loops 9042 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9043 return getCouldNotCompute(); 9044 9045 bool NoWrap = ControlsExit && 9046 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9047 9048 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 9049 9050 // Avoid negative or zero stride values 9051 if (!isKnownPositive(Stride)) 9052 return getCouldNotCompute(); 9053 9054 // Avoid proven overflow cases: this will ensure that the backedge taken count 9055 // will not generate any unsigned overflow. Relaxed no-overflow conditions 9056 // exploit NoWrapFlags, allowing to optimize in presence of undefined 9057 // behaviors like the case of C language. 9058 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 9059 return getCouldNotCompute(); 9060 9061 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 9062 : ICmpInst::ICMP_UGT; 9063 9064 const SCEV *Start = IV->getStart(); 9065 const SCEV *End = RHS; 9066 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 9067 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 9068 9069 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 9070 9071 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 9072 : getUnsignedRange(Start).getUnsignedMax(); 9073 9074 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 9075 : getUnsignedRange(Stride).getUnsignedMin(); 9076 9077 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 9078 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 9079 : APInt::getMinValue(BitWidth) + (MinStride - 1); 9080 9081 // Although End can be a MIN expression we estimate MinEnd considering only 9082 // the case End = RHS. This is safe because in the other case (Start - End) 9083 // is zero, leading to a zero maximum backedge taken count. 9084 APInt MinEnd = 9085 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 9086 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 9087 9088 9089 const SCEV *MaxBECount = getCouldNotCompute(); 9090 if (isa<SCEVConstant>(BECount)) 9091 MaxBECount = BECount; 9092 else 9093 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 9094 getConstant(MinStride), false); 9095 9096 if (isa<SCEVCouldNotCompute>(MaxBECount)) 9097 MaxBECount = BECount; 9098 9099 return ExitLimit(BECount, MaxBECount, false, Predicates); 9100 } 9101 9102 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 9103 ScalarEvolution &SE) const { 9104 if (Range.isFullSet()) // Infinite loop. 9105 return SE.getCouldNotCompute(); 9106 9107 // If the start is a non-zero constant, shift the range to simplify things. 9108 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 9109 if (!SC->getValue()->isZero()) { 9110 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 9111 Operands[0] = SE.getZero(SC->getType()); 9112 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 9113 getNoWrapFlags(FlagNW)); 9114 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 9115 return ShiftedAddRec->getNumIterationsInRange( 9116 Range.subtract(SC->getAPInt()), SE); 9117 // This is strange and shouldn't happen. 9118 return SE.getCouldNotCompute(); 9119 } 9120 9121 // The only time we can solve this is when we have all constant indices. 9122 // Otherwise, we cannot determine the overflow conditions. 9123 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 9124 return SE.getCouldNotCompute(); 9125 9126 // Okay at this point we know that all elements of the chrec are constants and 9127 // that the start element is zero. 9128 9129 // First check to see if the range contains zero. If not, the first 9130 // iteration exits. 9131 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 9132 if (!Range.contains(APInt(BitWidth, 0))) 9133 return SE.getZero(getType()); 9134 9135 if (isAffine()) { 9136 // If this is an affine expression then we have this situation: 9137 // Solve {0,+,A} in Range === Ax in Range 9138 9139 // We know that zero is in the range. If A is positive then we know that 9140 // the upper value of the range must be the first possible exit value. 9141 // If A is negative then the lower of the range is the last possible loop 9142 // value. Also note that we already checked for a full range. 9143 APInt One(BitWidth,1); 9144 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 9145 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 9146 9147 // The exit value should be (End+A)/A. 9148 APInt ExitVal = (End + A).udiv(A); 9149 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 9150 9151 // Evaluate at the exit value. If we really did fall out of the valid 9152 // range, then we computed our trip count, otherwise wrap around or other 9153 // things must have happened. 9154 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 9155 if (Range.contains(Val->getValue())) 9156 return SE.getCouldNotCompute(); // Something strange happened 9157 9158 // Ensure that the previous value is in the range. This is a sanity check. 9159 assert(Range.contains( 9160 EvaluateConstantChrecAtConstant(this, 9161 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 9162 "Linear scev computation is off in a bad way!"); 9163 return SE.getConstant(ExitValue); 9164 } else if (isQuadratic()) { 9165 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 9166 // quadratic equation to solve it. To do this, we must frame our problem in 9167 // terms of figuring out when zero is crossed, instead of when 9168 // Range.getUpper() is crossed. 9169 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 9170 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 9171 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 9172 9173 // Next, solve the constructed addrec 9174 if (auto Roots = 9175 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 9176 const SCEVConstant *R1 = Roots->first; 9177 const SCEVConstant *R2 = Roots->second; 9178 // Pick the smallest positive root value. 9179 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 9180 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 9181 if (!CB->getZExtValue()) 9182 std::swap(R1, R2); // R1 is the minimum root now. 9183 9184 // Make sure the root is not off by one. The returned iteration should 9185 // not be in the range, but the previous one should be. When solving 9186 // for "X*X < 5", for example, we should not return a root of 2. 9187 ConstantInt *R1Val = 9188 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9189 if (Range.contains(R1Val->getValue())) { 9190 // The next iteration must be out of the range... 9191 ConstantInt *NextVal = 9192 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9193 9194 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9195 if (!Range.contains(R1Val->getValue())) 9196 return SE.getConstant(NextVal); 9197 return SE.getCouldNotCompute(); // Something strange happened 9198 } 9199 9200 // If R1 was not in the range, then it is a good return value. Make 9201 // sure that R1-1 WAS in the range though, just in case. 9202 ConstantInt *NextVal = 9203 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9204 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9205 if (Range.contains(R1Val->getValue())) 9206 return R1; 9207 return SE.getCouldNotCompute(); // Something strange happened 9208 } 9209 } 9210 } 9211 9212 return SE.getCouldNotCompute(); 9213 } 9214 9215 // Return true when S contains at least an undef value. 9216 static inline bool containsUndefs(const SCEV *S) { 9217 return SCEVExprContains(S, [](const SCEV *S) { 9218 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 9219 return isa<UndefValue>(SU->getValue()); 9220 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 9221 return isa<UndefValue>(SC->getValue()); 9222 return false; 9223 }); 9224 } 9225 9226 namespace { 9227 // Collect all steps of SCEV expressions. 9228 struct SCEVCollectStrides { 9229 ScalarEvolution &SE; 9230 SmallVectorImpl<const SCEV *> &Strides; 9231 9232 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9233 : SE(SE), Strides(S) {} 9234 9235 bool follow(const SCEV *S) { 9236 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9237 Strides.push_back(AR->getStepRecurrence(SE)); 9238 return true; 9239 } 9240 bool isDone() const { return false; } 9241 }; 9242 9243 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9244 struct SCEVCollectTerms { 9245 SmallVectorImpl<const SCEV *> &Terms; 9246 9247 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9248 : Terms(T) {} 9249 9250 bool follow(const SCEV *S) { 9251 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9252 isa<SCEVSignExtendExpr>(S)) { 9253 if (!containsUndefs(S)) 9254 Terms.push_back(S); 9255 9256 // Stop recursion: once we collected a term, do not walk its operands. 9257 return false; 9258 } 9259 9260 // Keep looking. 9261 return true; 9262 } 9263 bool isDone() const { return false; } 9264 }; 9265 9266 // Check if a SCEV contains an AddRecExpr. 9267 struct SCEVHasAddRec { 9268 bool &ContainsAddRec; 9269 9270 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9271 ContainsAddRec = false; 9272 } 9273 9274 bool follow(const SCEV *S) { 9275 if (isa<SCEVAddRecExpr>(S)) { 9276 ContainsAddRec = true; 9277 9278 // Stop recursion: once we collected a term, do not walk its operands. 9279 return false; 9280 } 9281 9282 // Keep looking. 9283 return true; 9284 } 9285 bool isDone() const { return false; } 9286 }; 9287 9288 // Find factors that are multiplied with an expression that (possibly as a 9289 // subexpression) contains an AddRecExpr. In the expression: 9290 // 9291 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9292 // 9293 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9294 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9295 // parameters as they form a product with an induction variable. 9296 // 9297 // This collector expects all array size parameters to be in the same MulExpr. 9298 // It might be necessary to later add support for collecting parameters that are 9299 // spread over different nested MulExpr. 9300 struct SCEVCollectAddRecMultiplies { 9301 SmallVectorImpl<const SCEV *> &Terms; 9302 ScalarEvolution &SE; 9303 9304 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9305 : Terms(T), SE(SE) {} 9306 9307 bool follow(const SCEV *S) { 9308 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9309 bool HasAddRec = false; 9310 SmallVector<const SCEV *, 0> Operands; 9311 for (auto Op : Mul->operands()) { 9312 if (isa<SCEVUnknown>(Op)) { 9313 Operands.push_back(Op); 9314 } else { 9315 bool ContainsAddRec; 9316 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9317 visitAll(Op, ContiansAddRec); 9318 HasAddRec |= ContainsAddRec; 9319 } 9320 } 9321 if (Operands.size() == 0) 9322 return true; 9323 9324 if (!HasAddRec) 9325 return false; 9326 9327 Terms.push_back(SE.getMulExpr(Operands)); 9328 // Stop recursion: once we collected a term, do not walk its operands. 9329 return false; 9330 } 9331 9332 // Keep looking. 9333 return true; 9334 } 9335 bool isDone() const { return false; } 9336 }; 9337 } 9338 9339 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9340 /// two places: 9341 /// 1) The strides of AddRec expressions. 9342 /// 2) Unknowns that are multiplied with AddRec expressions. 9343 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9344 SmallVectorImpl<const SCEV *> &Terms) { 9345 SmallVector<const SCEV *, 4> Strides; 9346 SCEVCollectStrides StrideCollector(*this, Strides); 9347 visitAll(Expr, StrideCollector); 9348 9349 DEBUG({ 9350 dbgs() << "Strides:\n"; 9351 for (const SCEV *S : Strides) 9352 dbgs() << *S << "\n"; 9353 }); 9354 9355 for (const SCEV *S : Strides) { 9356 SCEVCollectTerms TermCollector(Terms); 9357 visitAll(S, TermCollector); 9358 } 9359 9360 DEBUG({ 9361 dbgs() << "Terms:\n"; 9362 for (const SCEV *T : Terms) 9363 dbgs() << *T << "\n"; 9364 }); 9365 9366 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9367 visitAll(Expr, MulCollector); 9368 } 9369 9370 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9371 SmallVectorImpl<const SCEV *> &Terms, 9372 SmallVectorImpl<const SCEV *> &Sizes) { 9373 int Last = Terms.size() - 1; 9374 const SCEV *Step = Terms[Last]; 9375 9376 // End of recursion. 9377 if (Last == 0) { 9378 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9379 SmallVector<const SCEV *, 2> Qs; 9380 for (const SCEV *Op : M->operands()) 9381 if (!isa<SCEVConstant>(Op)) 9382 Qs.push_back(Op); 9383 9384 Step = SE.getMulExpr(Qs); 9385 } 9386 9387 Sizes.push_back(Step); 9388 return true; 9389 } 9390 9391 for (const SCEV *&Term : Terms) { 9392 // Normalize the terms before the next call to findArrayDimensionsRec. 9393 const SCEV *Q, *R; 9394 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9395 9396 // Bail out when GCD does not evenly divide one of the terms. 9397 if (!R->isZero()) 9398 return false; 9399 9400 Term = Q; 9401 } 9402 9403 // Remove all SCEVConstants. 9404 Terms.erase( 9405 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9406 Terms.end()); 9407 9408 if (Terms.size() > 0) 9409 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9410 return false; 9411 9412 Sizes.push_back(Step); 9413 return true; 9414 } 9415 9416 9417 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9418 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9419 for (const SCEV *T : Terms) 9420 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9421 return true; 9422 return false; 9423 } 9424 9425 // Return the number of product terms in S. 9426 static inline int numberOfTerms(const SCEV *S) { 9427 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9428 return Expr->getNumOperands(); 9429 return 1; 9430 } 9431 9432 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9433 if (isa<SCEVConstant>(T)) 9434 return nullptr; 9435 9436 if (isa<SCEVUnknown>(T)) 9437 return T; 9438 9439 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9440 SmallVector<const SCEV *, 2> Factors; 9441 for (const SCEV *Op : M->operands()) 9442 if (!isa<SCEVConstant>(Op)) 9443 Factors.push_back(Op); 9444 9445 return SE.getMulExpr(Factors); 9446 } 9447 9448 return T; 9449 } 9450 9451 /// Return the size of an element read or written by Inst. 9452 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9453 Type *Ty; 9454 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9455 Ty = Store->getValueOperand()->getType(); 9456 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9457 Ty = Load->getType(); 9458 else 9459 return nullptr; 9460 9461 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9462 return getSizeOfExpr(ETy, Ty); 9463 } 9464 9465 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9466 SmallVectorImpl<const SCEV *> &Sizes, 9467 const SCEV *ElementSize) const { 9468 if (Terms.size() < 1 || !ElementSize) 9469 return; 9470 9471 // Early return when Terms do not contain parameters: we do not delinearize 9472 // non parametric SCEVs. 9473 if (!containsParameters(Terms)) 9474 return; 9475 9476 DEBUG({ 9477 dbgs() << "Terms:\n"; 9478 for (const SCEV *T : Terms) 9479 dbgs() << *T << "\n"; 9480 }); 9481 9482 // Remove duplicates. 9483 std::sort(Terms.begin(), Terms.end()); 9484 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9485 9486 // Put larger terms first. 9487 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9488 return numberOfTerms(LHS) > numberOfTerms(RHS); 9489 }); 9490 9491 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9492 9493 // Try to divide all terms by the element size. If term is not divisible by 9494 // element size, proceed with the original term. 9495 for (const SCEV *&Term : Terms) { 9496 const SCEV *Q, *R; 9497 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9498 if (!Q->isZero()) 9499 Term = Q; 9500 } 9501 9502 SmallVector<const SCEV *, 4> NewTerms; 9503 9504 // Remove constant factors. 9505 for (const SCEV *T : Terms) 9506 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9507 NewTerms.push_back(NewT); 9508 9509 DEBUG({ 9510 dbgs() << "Terms after sorting:\n"; 9511 for (const SCEV *T : NewTerms) 9512 dbgs() << *T << "\n"; 9513 }); 9514 9515 if (NewTerms.empty() || 9516 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9517 Sizes.clear(); 9518 return; 9519 } 9520 9521 // The last element to be pushed into Sizes is the size of an element. 9522 Sizes.push_back(ElementSize); 9523 9524 DEBUG({ 9525 dbgs() << "Sizes:\n"; 9526 for (const SCEV *S : Sizes) 9527 dbgs() << *S << "\n"; 9528 }); 9529 } 9530 9531 void ScalarEvolution::computeAccessFunctions( 9532 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9533 SmallVectorImpl<const SCEV *> &Sizes) { 9534 9535 // Early exit in case this SCEV is not an affine multivariate function. 9536 if (Sizes.empty()) 9537 return; 9538 9539 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9540 if (!AR->isAffine()) 9541 return; 9542 9543 const SCEV *Res = Expr; 9544 int Last = Sizes.size() - 1; 9545 for (int i = Last; i >= 0; i--) { 9546 const SCEV *Q, *R; 9547 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9548 9549 DEBUG({ 9550 dbgs() << "Res: " << *Res << "\n"; 9551 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9552 dbgs() << "Res divided by Sizes[i]:\n"; 9553 dbgs() << "Quotient: " << *Q << "\n"; 9554 dbgs() << "Remainder: " << *R << "\n"; 9555 }); 9556 9557 Res = Q; 9558 9559 // Do not record the last subscript corresponding to the size of elements in 9560 // the array. 9561 if (i == Last) { 9562 9563 // Bail out if the remainder is too complex. 9564 if (isa<SCEVAddRecExpr>(R)) { 9565 Subscripts.clear(); 9566 Sizes.clear(); 9567 return; 9568 } 9569 9570 continue; 9571 } 9572 9573 // Record the access function for the current subscript. 9574 Subscripts.push_back(R); 9575 } 9576 9577 // Also push in last position the remainder of the last division: it will be 9578 // the access function of the innermost dimension. 9579 Subscripts.push_back(Res); 9580 9581 std::reverse(Subscripts.begin(), Subscripts.end()); 9582 9583 DEBUG({ 9584 dbgs() << "Subscripts:\n"; 9585 for (const SCEV *S : Subscripts) 9586 dbgs() << *S << "\n"; 9587 }); 9588 } 9589 9590 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9591 /// sizes of an array access. Returns the remainder of the delinearization that 9592 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9593 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9594 /// expressions in the stride and base of a SCEV corresponding to the 9595 /// computation of a GCD (greatest common divisor) of base and stride. When 9596 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9597 /// 9598 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9599 /// 9600 /// void foo(long n, long m, long o, double A[n][m][o]) { 9601 /// 9602 /// for (long i = 0; i < n; i++) 9603 /// for (long j = 0; j < m; j++) 9604 /// for (long k = 0; k < o; k++) 9605 /// A[i][j][k] = 1.0; 9606 /// } 9607 /// 9608 /// the delinearization input is the following AddRec SCEV: 9609 /// 9610 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9611 /// 9612 /// From this SCEV, we are able to say that the base offset of the access is %A 9613 /// because it appears as an offset that does not divide any of the strides in 9614 /// the loops: 9615 /// 9616 /// CHECK: Base offset: %A 9617 /// 9618 /// and then SCEV->delinearize determines the size of some of the dimensions of 9619 /// the array as these are the multiples by which the strides are happening: 9620 /// 9621 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9622 /// 9623 /// Note that the outermost dimension remains of UnknownSize because there are 9624 /// no strides that would help identifying the size of the last dimension: when 9625 /// the array has been statically allocated, one could compute the size of that 9626 /// dimension by dividing the overall size of the array by the size of the known 9627 /// dimensions: %m * %o * 8. 9628 /// 9629 /// Finally delinearize provides the access functions for the array reference 9630 /// that does correspond to A[i][j][k] of the above C testcase: 9631 /// 9632 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9633 /// 9634 /// The testcases are checking the output of a function pass: 9635 /// DelinearizationPass that walks through all loads and stores of a function 9636 /// asking for the SCEV of the memory access with respect to all enclosing 9637 /// loops, calling SCEV->delinearize on that and printing the results. 9638 9639 void ScalarEvolution::delinearize(const SCEV *Expr, 9640 SmallVectorImpl<const SCEV *> &Subscripts, 9641 SmallVectorImpl<const SCEV *> &Sizes, 9642 const SCEV *ElementSize) { 9643 // First step: collect parametric terms. 9644 SmallVector<const SCEV *, 4> Terms; 9645 collectParametricTerms(Expr, Terms); 9646 9647 if (Terms.empty()) 9648 return; 9649 9650 // Second step: find subscript sizes. 9651 findArrayDimensions(Terms, Sizes, ElementSize); 9652 9653 if (Sizes.empty()) 9654 return; 9655 9656 // Third step: compute the access functions for each subscript. 9657 computeAccessFunctions(Expr, Subscripts, Sizes); 9658 9659 if (Subscripts.empty()) 9660 return; 9661 9662 DEBUG({ 9663 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9664 dbgs() << "ArrayDecl[UnknownSize]"; 9665 for (const SCEV *S : Sizes) 9666 dbgs() << "[" << *S << "]"; 9667 9668 dbgs() << "\nArrayRef"; 9669 for (const SCEV *S : Subscripts) 9670 dbgs() << "[" << *S << "]"; 9671 dbgs() << "\n"; 9672 }); 9673 } 9674 9675 //===----------------------------------------------------------------------===// 9676 // SCEVCallbackVH Class Implementation 9677 //===----------------------------------------------------------------------===// 9678 9679 void ScalarEvolution::SCEVCallbackVH::deleted() { 9680 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9681 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9682 SE->ConstantEvolutionLoopExitValue.erase(PN); 9683 SE->eraseValueFromMap(getValPtr()); 9684 // this now dangles! 9685 } 9686 9687 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9688 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9689 9690 // Forget all the expressions associated with users of the old value, 9691 // so that future queries will recompute the expressions using the new 9692 // value. 9693 Value *Old = getValPtr(); 9694 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9695 SmallPtrSet<User *, 8> Visited; 9696 while (!Worklist.empty()) { 9697 User *U = Worklist.pop_back_val(); 9698 // Deleting the Old value will cause this to dangle. Postpone 9699 // that until everything else is done. 9700 if (U == Old) 9701 continue; 9702 if (!Visited.insert(U).second) 9703 continue; 9704 if (PHINode *PN = dyn_cast<PHINode>(U)) 9705 SE->ConstantEvolutionLoopExitValue.erase(PN); 9706 SE->eraseValueFromMap(U); 9707 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9708 } 9709 // Delete the Old value. 9710 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9711 SE->ConstantEvolutionLoopExitValue.erase(PN); 9712 SE->eraseValueFromMap(Old); 9713 // this now dangles! 9714 } 9715 9716 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9717 : CallbackVH(V), SE(se) {} 9718 9719 //===----------------------------------------------------------------------===// 9720 // ScalarEvolution Class Implementation 9721 //===----------------------------------------------------------------------===// 9722 9723 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9724 AssumptionCache &AC, DominatorTree &DT, 9725 LoopInfo &LI) 9726 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9727 CouldNotCompute(new SCEVCouldNotCompute()), 9728 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9729 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9730 FirstUnknown(nullptr) { 9731 9732 // To use guards for proving predicates, we need to scan every instruction in 9733 // relevant basic blocks, and not just terminators. Doing this is a waste of 9734 // time if the IR does not actually contain any calls to 9735 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9736 // 9737 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9738 // to _add_ guards to the module when there weren't any before, and wants 9739 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9740 // efficient in lieu of being smart in that rather obscure case. 9741 9742 auto *GuardDecl = F.getParent()->getFunction( 9743 Intrinsic::getName(Intrinsic::experimental_guard)); 9744 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9745 } 9746 9747 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9748 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9749 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9750 ValueExprMap(std::move(Arg.ValueExprMap)), 9751 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9752 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9753 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 9754 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9755 PredicatedBackedgeTakenCounts( 9756 std::move(Arg.PredicatedBackedgeTakenCounts)), 9757 ConstantEvolutionLoopExitValue( 9758 std::move(Arg.ConstantEvolutionLoopExitValue)), 9759 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9760 LoopDispositions(std::move(Arg.LoopDispositions)), 9761 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9762 BlockDispositions(std::move(Arg.BlockDispositions)), 9763 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9764 SignedRanges(std::move(Arg.SignedRanges)), 9765 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9766 UniquePreds(std::move(Arg.UniquePreds)), 9767 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9768 FirstUnknown(Arg.FirstUnknown) { 9769 Arg.FirstUnknown = nullptr; 9770 } 9771 9772 ScalarEvolution::~ScalarEvolution() { 9773 // Iterate through all the SCEVUnknown instances and call their 9774 // destructors, so that they release their references to their values. 9775 for (SCEVUnknown *U = FirstUnknown; U;) { 9776 SCEVUnknown *Tmp = U; 9777 U = U->Next; 9778 Tmp->~SCEVUnknown(); 9779 } 9780 FirstUnknown = nullptr; 9781 9782 ExprValueMap.clear(); 9783 ValueExprMap.clear(); 9784 HasRecMap.clear(); 9785 9786 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9787 // that a loop had multiple computable exits. 9788 for (auto &BTCI : BackedgeTakenCounts) 9789 BTCI.second.clear(); 9790 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9791 BTCI.second.clear(); 9792 9793 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9794 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9795 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9796 } 9797 9798 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9799 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9800 } 9801 9802 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9803 const Loop *L) { 9804 // Print all inner loops first 9805 for (Loop *I : *L) 9806 PrintLoopInfo(OS, SE, I); 9807 9808 OS << "Loop "; 9809 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9810 OS << ": "; 9811 9812 SmallVector<BasicBlock *, 8> ExitBlocks; 9813 L->getExitBlocks(ExitBlocks); 9814 if (ExitBlocks.size() != 1) 9815 OS << "<multiple exits> "; 9816 9817 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9818 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9819 } else { 9820 OS << "Unpredictable backedge-taken count. "; 9821 } 9822 9823 OS << "\n" 9824 "Loop "; 9825 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9826 OS << ": "; 9827 9828 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9829 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9830 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9831 OS << ", actual taken count either this or zero."; 9832 } else { 9833 OS << "Unpredictable max backedge-taken count. "; 9834 } 9835 9836 OS << "\n" 9837 "Loop "; 9838 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9839 OS << ": "; 9840 9841 SCEVUnionPredicate Pred; 9842 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9843 if (!isa<SCEVCouldNotCompute>(PBT)) { 9844 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9845 OS << " Predicates:\n"; 9846 Pred.print(OS, 4); 9847 } else { 9848 OS << "Unpredictable predicated backedge-taken count. "; 9849 } 9850 OS << "\n"; 9851 9852 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9853 OS << "Loop "; 9854 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9855 OS << ": "; 9856 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 9857 } 9858 } 9859 9860 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9861 switch (LD) { 9862 case ScalarEvolution::LoopVariant: 9863 return "Variant"; 9864 case ScalarEvolution::LoopInvariant: 9865 return "Invariant"; 9866 case ScalarEvolution::LoopComputable: 9867 return "Computable"; 9868 } 9869 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9870 } 9871 9872 void ScalarEvolution::print(raw_ostream &OS) const { 9873 // ScalarEvolution's implementation of the print method is to print 9874 // out SCEV values of all instructions that are interesting. Doing 9875 // this potentially causes it to create new SCEV objects though, 9876 // which technically conflicts with the const qualifier. This isn't 9877 // observable from outside the class though, so casting away the 9878 // const isn't dangerous. 9879 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9880 9881 OS << "Classifying expressions for: "; 9882 F.printAsOperand(OS, /*PrintType=*/false); 9883 OS << "\n"; 9884 for (Instruction &I : instructions(F)) 9885 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9886 OS << I << '\n'; 9887 OS << " --> "; 9888 const SCEV *SV = SE.getSCEV(&I); 9889 SV->print(OS); 9890 if (!isa<SCEVCouldNotCompute>(SV)) { 9891 OS << " U: "; 9892 SE.getUnsignedRange(SV).print(OS); 9893 OS << " S: "; 9894 SE.getSignedRange(SV).print(OS); 9895 } 9896 9897 const Loop *L = LI.getLoopFor(I.getParent()); 9898 9899 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9900 if (AtUse != SV) { 9901 OS << " --> "; 9902 AtUse->print(OS); 9903 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9904 OS << " U: "; 9905 SE.getUnsignedRange(AtUse).print(OS); 9906 OS << " S: "; 9907 SE.getSignedRange(AtUse).print(OS); 9908 } 9909 } 9910 9911 if (L) { 9912 OS << "\t\t" "Exits: "; 9913 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9914 if (!SE.isLoopInvariant(ExitValue, L)) { 9915 OS << "<<Unknown>>"; 9916 } else { 9917 OS << *ExitValue; 9918 } 9919 9920 bool First = true; 9921 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9922 if (First) { 9923 OS << "\t\t" "LoopDispositions: { "; 9924 First = false; 9925 } else { 9926 OS << ", "; 9927 } 9928 9929 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9930 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9931 } 9932 9933 for (auto *InnerL : depth_first(L)) { 9934 if (InnerL == L) 9935 continue; 9936 if (First) { 9937 OS << "\t\t" "LoopDispositions: { "; 9938 First = false; 9939 } else { 9940 OS << ", "; 9941 } 9942 9943 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9944 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9945 } 9946 9947 OS << " }"; 9948 } 9949 9950 OS << "\n"; 9951 } 9952 9953 OS << "Determining loop execution counts for: "; 9954 F.printAsOperand(OS, /*PrintType=*/false); 9955 OS << "\n"; 9956 for (Loop *I : LI) 9957 PrintLoopInfo(OS, &SE, I); 9958 } 9959 9960 ScalarEvolution::LoopDisposition 9961 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9962 auto &Values = LoopDispositions[S]; 9963 for (auto &V : Values) { 9964 if (V.getPointer() == L) 9965 return V.getInt(); 9966 } 9967 Values.emplace_back(L, LoopVariant); 9968 LoopDisposition D = computeLoopDisposition(S, L); 9969 auto &Values2 = LoopDispositions[S]; 9970 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9971 if (V.getPointer() == L) { 9972 V.setInt(D); 9973 break; 9974 } 9975 } 9976 return D; 9977 } 9978 9979 ScalarEvolution::LoopDisposition 9980 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9981 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9982 case scConstant: 9983 return LoopInvariant; 9984 case scTruncate: 9985 case scZeroExtend: 9986 case scSignExtend: 9987 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9988 case scAddRecExpr: { 9989 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9990 9991 // If L is the addrec's loop, it's computable. 9992 if (AR->getLoop() == L) 9993 return LoopComputable; 9994 9995 // Add recurrences are never invariant in the function-body (null loop). 9996 if (!L) 9997 return LoopVariant; 9998 9999 // This recurrence is variant w.r.t. L if L contains AR's loop. 10000 if (L->contains(AR->getLoop())) 10001 return LoopVariant; 10002 10003 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10004 if (AR->getLoop()->contains(L)) 10005 return LoopInvariant; 10006 10007 // This recurrence is variant w.r.t. L if any of its operands 10008 // are variant. 10009 for (auto *Op : AR->operands()) 10010 if (!isLoopInvariant(Op, L)) 10011 return LoopVariant; 10012 10013 // Otherwise it's loop-invariant. 10014 return LoopInvariant; 10015 } 10016 case scAddExpr: 10017 case scMulExpr: 10018 case scUMaxExpr: 10019 case scSMaxExpr: { 10020 bool HasVarying = false; 10021 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10022 LoopDisposition D = getLoopDisposition(Op, L); 10023 if (D == LoopVariant) 10024 return LoopVariant; 10025 if (D == LoopComputable) 10026 HasVarying = true; 10027 } 10028 return HasVarying ? LoopComputable : LoopInvariant; 10029 } 10030 case scUDivExpr: { 10031 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10032 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 10033 if (LD == LoopVariant) 10034 return LoopVariant; 10035 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 10036 if (RD == LoopVariant) 10037 return LoopVariant; 10038 return (LD == LoopInvariant && RD == LoopInvariant) ? 10039 LoopInvariant : LoopComputable; 10040 } 10041 case scUnknown: 10042 // All non-instruction values are loop invariant. All instructions are loop 10043 // invariant if they are not contained in the specified loop. 10044 // Instructions are never considered invariant in the function body 10045 // (null loop) because they are defined within the "loop". 10046 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 10047 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 10048 return LoopInvariant; 10049 case scCouldNotCompute: 10050 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10051 } 10052 llvm_unreachable("Unknown SCEV kind!"); 10053 } 10054 10055 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 10056 return getLoopDisposition(S, L) == LoopInvariant; 10057 } 10058 10059 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 10060 return getLoopDisposition(S, L) == LoopComputable; 10061 } 10062 10063 ScalarEvolution::BlockDisposition 10064 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10065 auto &Values = BlockDispositions[S]; 10066 for (auto &V : Values) { 10067 if (V.getPointer() == BB) 10068 return V.getInt(); 10069 } 10070 Values.emplace_back(BB, DoesNotDominateBlock); 10071 BlockDisposition D = computeBlockDisposition(S, BB); 10072 auto &Values2 = BlockDispositions[S]; 10073 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10074 if (V.getPointer() == BB) { 10075 V.setInt(D); 10076 break; 10077 } 10078 } 10079 return D; 10080 } 10081 10082 ScalarEvolution::BlockDisposition 10083 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 10084 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10085 case scConstant: 10086 return ProperlyDominatesBlock; 10087 case scTruncate: 10088 case scZeroExtend: 10089 case scSignExtend: 10090 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 10091 case scAddRecExpr: { 10092 // This uses a "dominates" query instead of "properly dominates" query 10093 // to test for proper dominance too, because the instruction which 10094 // produces the addrec's value is a PHI, and a PHI effectively properly 10095 // dominates its entire containing block. 10096 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10097 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 10098 return DoesNotDominateBlock; 10099 10100 // Fall through into SCEVNAryExpr handling. 10101 LLVM_FALLTHROUGH; 10102 } 10103 case scAddExpr: 10104 case scMulExpr: 10105 case scUMaxExpr: 10106 case scSMaxExpr: { 10107 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 10108 bool Proper = true; 10109 for (const SCEV *NAryOp : NAry->operands()) { 10110 BlockDisposition D = getBlockDisposition(NAryOp, BB); 10111 if (D == DoesNotDominateBlock) 10112 return DoesNotDominateBlock; 10113 if (D == DominatesBlock) 10114 Proper = false; 10115 } 10116 return Proper ? ProperlyDominatesBlock : DominatesBlock; 10117 } 10118 case scUDivExpr: { 10119 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 10120 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 10121 BlockDisposition LD = getBlockDisposition(LHS, BB); 10122 if (LD == DoesNotDominateBlock) 10123 return DoesNotDominateBlock; 10124 BlockDisposition RD = getBlockDisposition(RHS, BB); 10125 if (RD == DoesNotDominateBlock) 10126 return DoesNotDominateBlock; 10127 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 10128 ProperlyDominatesBlock : DominatesBlock; 10129 } 10130 case scUnknown: 10131 if (Instruction *I = 10132 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 10133 if (I->getParent() == BB) 10134 return DominatesBlock; 10135 if (DT.properlyDominates(I->getParent(), BB)) 10136 return ProperlyDominatesBlock; 10137 return DoesNotDominateBlock; 10138 } 10139 return ProperlyDominatesBlock; 10140 case scCouldNotCompute: 10141 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 10142 } 10143 llvm_unreachable("Unknown SCEV kind!"); 10144 } 10145 10146 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 10147 return getBlockDisposition(S, BB) >= DominatesBlock; 10148 } 10149 10150 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10151 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10152 } 10153 10154 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10155 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 10156 } 10157 10158 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10159 ValuesAtScopes.erase(S); 10160 LoopDispositions.erase(S); 10161 BlockDispositions.erase(S); 10162 UnsignedRanges.erase(S); 10163 SignedRanges.erase(S); 10164 ExprValueMap.erase(S); 10165 HasRecMap.erase(S); 10166 MinTrailingZerosCache.erase(S); 10167 10168 auto RemoveSCEVFromBackedgeMap = 10169 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10170 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10171 BackedgeTakenInfo &BEInfo = I->second; 10172 if (BEInfo.hasOperand(S, this)) { 10173 BEInfo.clear(); 10174 Map.erase(I++); 10175 } else 10176 ++I; 10177 } 10178 }; 10179 10180 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10181 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10182 } 10183 10184 typedef DenseMap<const Loop *, std::string> VerifyMap; 10185 10186 /// replaceSubString - Replaces all occurrences of From in Str with To. 10187 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 10188 size_t Pos = 0; 10189 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 10190 Str.replace(Pos, From.size(), To.data(), To.size()); 10191 Pos += To.size(); 10192 } 10193 } 10194 10195 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 10196 static void 10197 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 10198 std::string &S = Map[L]; 10199 if (S.empty()) { 10200 raw_string_ostream OS(S); 10201 SE.getBackedgeTakenCount(L)->print(OS); 10202 10203 // false and 0 are semantically equivalent. This can happen in dead loops. 10204 replaceSubString(OS.str(), "false", "0"); 10205 // Remove wrap flags, their use in SCEV is highly fragile. 10206 // FIXME: Remove this when SCEV gets smarter about them. 10207 replaceSubString(OS.str(), "<nw>", ""); 10208 replaceSubString(OS.str(), "<nsw>", ""); 10209 replaceSubString(OS.str(), "<nuw>", ""); 10210 } 10211 10212 for (auto *R : reverse(*L)) 10213 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 10214 } 10215 10216 void ScalarEvolution::verify() const { 10217 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10218 10219 // Gather stringified backedge taken counts for all loops using SCEV's caches. 10220 // FIXME: It would be much better to store actual values instead of strings, 10221 // but SCEV pointers will change if we drop the caches. 10222 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 10223 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10224 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 10225 10226 // Gather stringified backedge taken counts for all loops using a fresh 10227 // ScalarEvolution object. 10228 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10229 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10230 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 10231 10232 // Now compare whether they're the same with and without caches. This allows 10233 // verifying that no pass changed the cache. 10234 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 10235 "New loops suddenly appeared!"); 10236 10237 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 10238 OldE = BackedgeDumpsOld.end(), 10239 NewI = BackedgeDumpsNew.begin(); 10240 OldI != OldE; ++OldI, ++NewI) { 10241 assert(OldI->first == NewI->first && "Loop order changed!"); 10242 10243 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10244 // changes. 10245 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10246 // means that a pass is buggy or SCEV has to learn a new pattern but is 10247 // usually not harmful. 10248 if (OldI->second != NewI->second && 10249 OldI->second.find("undef") == std::string::npos && 10250 NewI->second.find("undef") == std::string::npos && 10251 OldI->second != "***COULDNOTCOMPUTE***" && 10252 NewI->second != "***COULDNOTCOMPUTE***") { 10253 dbgs() << "SCEVValidator: SCEV for loop '" 10254 << OldI->first->getHeader()->getName() 10255 << "' changed from '" << OldI->second 10256 << "' to '" << NewI->second << "'!\n"; 10257 std::abort(); 10258 } 10259 } 10260 10261 // TODO: Verify more things. 10262 } 10263 10264 bool ScalarEvolution::invalidate( 10265 Function &F, const PreservedAnalyses &PA, 10266 FunctionAnalysisManager::Invalidator &Inv) { 10267 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 10268 // of its dependencies is invalidated. 10269 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 10270 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 10271 Inv.invalidate<AssumptionAnalysis>(F, PA) || 10272 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 10273 Inv.invalidate<LoopAnalysis>(F, PA); 10274 } 10275 10276 AnalysisKey ScalarEvolutionAnalysis::Key; 10277 10278 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10279 FunctionAnalysisManager &AM) { 10280 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10281 AM.getResult<AssumptionAnalysis>(F), 10282 AM.getResult<DominatorTreeAnalysis>(F), 10283 AM.getResult<LoopAnalysis>(F)); 10284 } 10285 10286 PreservedAnalyses 10287 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10288 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10289 return PreservedAnalyses::all(); 10290 } 10291 10292 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10293 "Scalar Evolution Analysis", false, true) 10294 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10295 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10296 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10297 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10298 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10299 "Scalar Evolution Analysis", false, true) 10300 char ScalarEvolutionWrapperPass::ID = 0; 10301 10302 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10303 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10304 } 10305 10306 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10307 SE.reset(new ScalarEvolution( 10308 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10309 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10310 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10311 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10312 return false; 10313 } 10314 10315 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10316 10317 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10318 SE->print(OS); 10319 } 10320 10321 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10322 if (!VerifySCEV) 10323 return; 10324 10325 SE->verify(); 10326 } 10327 10328 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10329 AU.setPreservesAll(); 10330 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10331 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10332 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10333 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10334 } 10335 10336 const SCEVPredicate * 10337 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10338 const SCEVConstant *RHS) { 10339 FoldingSetNodeID ID; 10340 // Unique this node based on the arguments 10341 ID.AddInteger(SCEVPredicate::P_Equal); 10342 ID.AddPointer(LHS); 10343 ID.AddPointer(RHS); 10344 void *IP = nullptr; 10345 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10346 return S; 10347 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10348 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10349 UniquePreds.InsertNode(Eq, IP); 10350 return Eq; 10351 } 10352 10353 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10354 const SCEVAddRecExpr *AR, 10355 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10356 FoldingSetNodeID ID; 10357 // Unique this node based on the arguments 10358 ID.AddInteger(SCEVPredicate::P_Wrap); 10359 ID.AddPointer(AR); 10360 ID.AddInteger(AddedFlags); 10361 void *IP = nullptr; 10362 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10363 return S; 10364 auto *OF = new (SCEVAllocator) 10365 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10366 UniquePreds.InsertNode(OF, IP); 10367 return OF; 10368 } 10369 10370 namespace { 10371 10372 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10373 public: 10374 /// Rewrites \p S in the context of a loop L and the SCEV predication 10375 /// infrastructure. 10376 /// 10377 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10378 /// equivalences present in \p Pred. 10379 /// 10380 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10381 /// \p NewPreds such that the result will be an AddRecExpr. 10382 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10383 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10384 SCEVUnionPredicate *Pred) { 10385 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10386 return Rewriter.visit(S); 10387 } 10388 10389 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10390 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10391 SCEVUnionPredicate *Pred) 10392 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10393 10394 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10395 if (Pred) { 10396 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10397 for (auto *Pred : ExprPreds) 10398 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10399 if (IPred->getLHS() == Expr) 10400 return IPred->getRHS(); 10401 } 10402 10403 return Expr; 10404 } 10405 10406 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10407 const SCEV *Operand = visit(Expr->getOperand()); 10408 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10409 if (AR && AR->getLoop() == L && AR->isAffine()) { 10410 // This couldn't be folded because the operand didn't have the nuw 10411 // flag. Add the nusw flag as an assumption that we could make. 10412 const SCEV *Step = AR->getStepRecurrence(SE); 10413 Type *Ty = Expr->getType(); 10414 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10415 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10416 SE.getSignExtendExpr(Step, Ty), L, 10417 AR->getNoWrapFlags()); 10418 } 10419 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10420 } 10421 10422 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10423 const SCEV *Operand = visit(Expr->getOperand()); 10424 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10425 if (AR && AR->getLoop() == L && AR->isAffine()) { 10426 // This couldn't be folded because the operand didn't have the nsw 10427 // flag. Add the nssw flag as an assumption that we could make. 10428 const SCEV *Step = AR->getStepRecurrence(SE); 10429 Type *Ty = Expr->getType(); 10430 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10431 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10432 SE.getSignExtendExpr(Step, Ty), L, 10433 AR->getNoWrapFlags()); 10434 } 10435 return SE.getSignExtendExpr(Operand, Expr->getType()); 10436 } 10437 10438 private: 10439 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10440 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10441 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10442 if (!NewPreds) { 10443 // Check if we've already made this assumption. 10444 return Pred && Pred->implies(A); 10445 } 10446 NewPreds->insert(A); 10447 return true; 10448 } 10449 10450 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10451 SCEVUnionPredicate *Pred; 10452 const Loop *L; 10453 }; 10454 } // end anonymous namespace 10455 10456 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10457 SCEVUnionPredicate &Preds) { 10458 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10459 } 10460 10461 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10462 const SCEV *S, const Loop *L, 10463 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10464 10465 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10466 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10467 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10468 10469 if (!AddRec) 10470 return nullptr; 10471 10472 // Since the transformation was successful, we can now transfer the SCEV 10473 // predicates. 10474 for (auto *P : TransformPreds) 10475 Preds.insert(P); 10476 10477 return AddRec; 10478 } 10479 10480 /// SCEV predicates 10481 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10482 SCEVPredicateKind Kind) 10483 : FastID(ID), Kind(Kind) {} 10484 10485 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10486 const SCEVUnknown *LHS, 10487 const SCEVConstant *RHS) 10488 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10489 10490 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10491 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10492 10493 if (!Op) 10494 return false; 10495 10496 return Op->LHS == LHS && Op->RHS == RHS; 10497 } 10498 10499 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10500 10501 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10502 10503 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10504 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10505 } 10506 10507 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10508 const SCEVAddRecExpr *AR, 10509 IncrementWrapFlags Flags) 10510 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10511 10512 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10513 10514 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10515 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10516 10517 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10518 } 10519 10520 bool SCEVWrapPredicate::isAlwaysTrue() const { 10521 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10522 IncrementWrapFlags IFlags = Flags; 10523 10524 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10525 IFlags = clearFlags(IFlags, IncrementNSSW); 10526 10527 return IFlags == IncrementAnyWrap; 10528 } 10529 10530 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10531 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10532 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10533 OS << "<nusw>"; 10534 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10535 OS << "<nssw>"; 10536 OS << "\n"; 10537 } 10538 10539 SCEVWrapPredicate::IncrementWrapFlags 10540 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10541 ScalarEvolution &SE) { 10542 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10543 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10544 10545 // We can safely transfer the NSW flag as NSSW. 10546 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10547 ImpliedFlags = IncrementNSSW; 10548 10549 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10550 // If the increment is positive, the SCEV NUW flag will also imply the 10551 // WrapPredicate NUSW flag. 10552 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10553 if (Step->getValue()->getValue().isNonNegative()) 10554 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10555 } 10556 10557 return ImpliedFlags; 10558 } 10559 10560 /// Union predicates don't get cached so create a dummy set ID for it. 10561 SCEVUnionPredicate::SCEVUnionPredicate() 10562 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10563 10564 bool SCEVUnionPredicate::isAlwaysTrue() const { 10565 return all_of(Preds, 10566 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10567 } 10568 10569 ArrayRef<const SCEVPredicate *> 10570 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10571 auto I = SCEVToPreds.find(Expr); 10572 if (I == SCEVToPreds.end()) 10573 return ArrayRef<const SCEVPredicate *>(); 10574 return I->second; 10575 } 10576 10577 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10578 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10579 return all_of(Set->Preds, 10580 [this](const SCEVPredicate *I) { return this->implies(I); }); 10581 10582 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10583 if (ScevPredsIt == SCEVToPreds.end()) 10584 return false; 10585 auto &SCEVPreds = ScevPredsIt->second; 10586 10587 return any_of(SCEVPreds, 10588 [N](const SCEVPredicate *I) { return I->implies(N); }); 10589 } 10590 10591 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10592 10593 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10594 for (auto Pred : Preds) 10595 Pred->print(OS, Depth); 10596 } 10597 10598 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10599 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10600 for (auto Pred : Set->Preds) 10601 add(Pred); 10602 return; 10603 } 10604 10605 if (implies(N)) 10606 return; 10607 10608 const SCEV *Key = N->getExpr(); 10609 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10610 " associated expression!"); 10611 10612 SCEVToPreds[Key].push_back(N); 10613 Preds.push_back(N); 10614 } 10615 10616 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10617 Loop &L) 10618 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10619 10620 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10621 const SCEV *Expr = SE.getSCEV(V); 10622 RewriteEntry &Entry = RewriteMap[Expr]; 10623 10624 // If we already have an entry and the version matches, return it. 10625 if (Entry.second && Generation == Entry.first) 10626 return Entry.second; 10627 10628 // We found an entry but it's stale. Rewrite the stale entry 10629 // according to the current predicate. 10630 if (Entry.second) 10631 Expr = Entry.second; 10632 10633 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10634 Entry = {Generation, NewSCEV}; 10635 10636 return NewSCEV; 10637 } 10638 10639 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10640 if (!BackedgeCount) { 10641 SCEVUnionPredicate BackedgePred; 10642 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10643 addPredicate(BackedgePred); 10644 } 10645 return BackedgeCount; 10646 } 10647 10648 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10649 if (Preds.implies(&Pred)) 10650 return; 10651 Preds.add(&Pred); 10652 updateGeneration(); 10653 } 10654 10655 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10656 return Preds; 10657 } 10658 10659 void PredicatedScalarEvolution::updateGeneration() { 10660 // If the generation number wrapped recompute everything. 10661 if (++Generation == 0) { 10662 for (auto &II : RewriteMap) { 10663 const SCEV *Rewritten = II.second.second; 10664 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10665 } 10666 } 10667 } 10668 10669 void PredicatedScalarEvolution::setNoOverflow( 10670 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10671 const SCEV *Expr = getSCEV(V); 10672 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10673 10674 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10675 10676 // Clear the statically implied flags. 10677 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10678 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10679 10680 auto II = FlagsMap.insert({V, Flags}); 10681 if (!II.second) 10682 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10683 } 10684 10685 bool PredicatedScalarEvolution::hasNoOverflow( 10686 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10687 const SCEV *Expr = getSCEV(V); 10688 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10689 10690 Flags = SCEVWrapPredicate::clearFlags( 10691 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10692 10693 auto II = FlagsMap.find(V); 10694 10695 if (II != FlagsMap.end()) 10696 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10697 10698 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10699 } 10700 10701 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10702 const SCEV *Expr = this->getSCEV(V); 10703 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10704 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10705 10706 if (!New) 10707 return nullptr; 10708 10709 for (auto *P : NewPreds) 10710 Preds.add(P); 10711 10712 updateGeneration(); 10713 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10714 return New; 10715 } 10716 10717 PredicatedScalarEvolution::PredicatedScalarEvolution( 10718 const PredicatedScalarEvolution &Init) 10719 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10720 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10721 for (const auto &I : Init.FlagsMap) 10722 FlagsMap.insert(I); 10723 } 10724 10725 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10726 // For each block. 10727 for (auto *BB : L.getBlocks()) 10728 for (auto &I : *BB) { 10729 if (!SE.isSCEVable(I.getType())) 10730 continue; 10731 10732 auto *Expr = SE.getSCEV(&I); 10733 auto II = RewriteMap.find(Expr); 10734 10735 if (II == RewriteMap.end()) 10736 continue; 10737 10738 // Don't print things that are not interesting. 10739 if (II->second.second == Expr) 10740 continue; 10741 10742 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10743 OS.indent(Depth + 2) << *Expr << "\n"; 10744 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10745 } 10746 } 10747