1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/APInt.h" 63 #include "llvm/ADT/ArrayRef.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/DepthFirstIterator.h" 66 #include "llvm/ADT/EquivalenceClasses.h" 67 #include "llvm/ADT/FoldingSet.h" 68 #include "llvm/ADT/None.h" 69 #include "llvm/ADT/Optional.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/ADT/ScopeExit.h" 72 #include "llvm/ADT/Sequence.h" 73 #include "llvm/ADT/SetVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallSet.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/Statistic.h" 78 #include "llvm/ADT/StringRef.h" 79 #include "llvm/Analysis/AssumptionCache.h" 80 #include "llvm/Analysis/ConstantFolding.h" 81 #include "llvm/Analysis/InstructionSimplify.h" 82 #include "llvm/Analysis/LoopInfo.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/CallSite.h" 91 #include "llvm/IR/Constant.h" 92 #include "llvm/IR/ConstantRange.h" 93 #include "llvm/IR/Constants.h" 94 #include "llvm/IR/DataLayout.h" 95 #include "llvm/IR/DerivedTypes.h" 96 #include "llvm/IR/Dominators.h" 97 #include "llvm/IR/Function.h" 98 #include "llvm/IR/GlobalAlias.h" 99 #include "llvm/IR/GlobalValue.h" 100 #include "llvm/IR/GlobalVariable.h" 101 #include "llvm/IR/InstIterator.h" 102 #include "llvm/IR/InstrTypes.h" 103 #include "llvm/IR/Instruction.h" 104 #include "llvm/IR/Instructions.h" 105 #include "llvm/IR/IntrinsicInst.h" 106 #include "llvm/IR/Intrinsics.h" 107 #include "llvm/IR/LLVMContext.h" 108 #include "llvm/IR/Metadata.h" 109 #include "llvm/IR/Operator.h" 110 #include "llvm/IR/PatternMatch.h" 111 #include "llvm/IR/Type.h" 112 #include "llvm/IR/Use.h" 113 #include "llvm/IR/User.h" 114 #include "llvm/IR/Value.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<unsigned> MulOpsInlineThreshold( 166 "scev-mulops-inline-threshold", cl::Hidden, 167 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 168 cl::init(32)); 169 170 static cl::opt<unsigned> AddOpsInlineThreshold( 171 "scev-addops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining addition operands into a SCEV"), 173 cl::init(500)); 174 175 static cl::opt<unsigned> MaxSCEVCompareDepth( 176 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 177 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 181 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 183 cl::init(2)); 184 185 static cl::opt<unsigned> MaxValueCompareDepth( 186 "scalar-evolution-max-value-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive value complexity comparisons"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> 191 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive arithmetics"), 193 cl::init(32)); 194 195 static cl::opt<unsigned> MaxConstantEvolvingDepth( 196 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 198 199 static cl::opt<unsigned> 200 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive SExt/ZExt"), 202 cl::init(8)); 203 204 static cl::opt<unsigned> 205 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 206 cl::desc("Max coefficients in AddRec during evolving"), 207 cl::init(16)); 208 209 //===----------------------------------------------------------------------===// 210 // SCEV class definitions 211 //===----------------------------------------------------------------------===// 212 213 //===----------------------------------------------------------------------===// 214 // Implementation of the SCEV class. 215 // 216 217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 218 LLVM_DUMP_METHOD void SCEV::dump() const { 219 print(dbgs()); 220 dbgs() << '\n'; 221 } 222 #endif 223 224 void SCEV::print(raw_ostream &OS) const { 225 switch (static_cast<SCEVTypes>(getSCEVType())) { 226 case scConstant: 227 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 228 return; 229 case scTruncate: { 230 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 231 const SCEV *Op = Trunc->getOperand(); 232 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 233 << *Trunc->getType() << ")"; 234 return; 235 } 236 case scZeroExtend: { 237 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 238 const SCEV *Op = ZExt->getOperand(); 239 OS << "(zext " << *Op->getType() << " " << *Op << " to " 240 << *ZExt->getType() << ")"; 241 return; 242 } 243 case scSignExtend: { 244 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 245 const SCEV *Op = SExt->getOperand(); 246 OS << "(sext " << *Op->getType() << " " << *Op << " to " 247 << *SExt->getType() << ")"; 248 return; 249 } 250 case scAddRecExpr: { 251 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 252 OS << "{" << *AR->getOperand(0); 253 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 254 OS << ",+," << *AR->getOperand(i); 255 OS << "}<"; 256 if (AR->hasNoUnsignedWrap()) 257 OS << "nuw><"; 258 if (AR->hasNoSignedWrap()) 259 OS << "nsw><"; 260 if (AR->hasNoSelfWrap() && 261 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 262 OS << "nw><"; 263 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 264 OS << ">"; 265 return; 266 } 267 case scAddExpr: 268 case scMulExpr: 269 case scUMaxExpr: 270 case scSMaxExpr: { 271 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 272 const char *OpStr = nullptr; 273 switch (NAry->getSCEVType()) { 274 case scAddExpr: OpStr = " + "; break; 275 case scMulExpr: OpStr = " * "; break; 276 case scUMaxExpr: OpStr = " umax "; break; 277 case scSMaxExpr: OpStr = " smax "; break; 278 } 279 OS << "("; 280 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 281 I != E; ++I) { 282 OS << **I; 283 if (std::next(I) != E) 284 OS << OpStr; 285 } 286 OS << ")"; 287 switch (NAry->getSCEVType()) { 288 case scAddExpr: 289 case scMulExpr: 290 if (NAry->hasNoUnsignedWrap()) 291 OS << "<nuw>"; 292 if (NAry->hasNoSignedWrap()) 293 OS << "<nsw>"; 294 } 295 return; 296 } 297 case scUDivExpr: { 298 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 299 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 300 return; 301 } 302 case scUnknown: { 303 const SCEVUnknown *U = cast<SCEVUnknown>(this); 304 Type *AllocTy; 305 if (U->isSizeOf(AllocTy)) { 306 OS << "sizeof(" << *AllocTy << ")"; 307 return; 308 } 309 if (U->isAlignOf(AllocTy)) { 310 OS << "alignof(" << *AllocTy << ")"; 311 return; 312 } 313 314 Type *CTy; 315 Constant *FieldNo; 316 if (U->isOffsetOf(CTy, FieldNo)) { 317 OS << "offsetof(" << *CTy << ", "; 318 FieldNo->printAsOperand(OS, false); 319 OS << ")"; 320 return; 321 } 322 323 // Otherwise just print it normally. 324 U->getValue()->printAsOperand(OS, false); 325 return; 326 } 327 case scCouldNotCompute: 328 OS << "***COULDNOTCOMPUTE***"; 329 return; 330 } 331 llvm_unreachable("Unknown SCEV kind!"); 332 } 333 334 Type *SCEV::getType() const { 335 switch (static_cast<SCEVTypes>(getSCEVType())) { 336 case scConstant: 337 return cast<SCEVConstant>(this)->getType(); 338 case scTruncate: 339 case scZeroExtend: 340 case scSignExtend: 341 return cast<SCEVCastExpr>(this)->getType(); 342 case scAddRecExpr: 343 case scMulExpr: 344 case scUMaxExpr: 345 case scSMaxExpr: 346 return cast<SCEVNAryExpr>(this)->getType(); 347 case scAddExpr: 348 return cast<SCEVAddExpr>(this)->getType(); 349 case scUDivExpr: 350 return cast<SCEVUDivExpr>(this)->getType(); 351 case scUnknown: 352 return cast<SCEVUnknown>(this)->getType(); 353 case scCouldNotCompute: 354 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 355 } 356 llvm_unreachable("Unknown SCEV kind!"); 357 } 358 359 bool SCEV::isZero() const { 360 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 361 return SC->getValue()->isZero(); 362 return false; 363 } 364 365 bool SCEV::isOne() const { 366 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 367 return SC->getValue()->isOne(); 368 return false; 369 } 370 371 bool SCEV::isAllOnesValue() const { 372 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 373 return SC->getValue()->isMinusOne(); 374 return false; 375 } 376 377 bool SCEV::isNonConstantNegative() const { 378 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 379 if (!Mul) return false; 380 381 // If there is a constant factor, it will be first. 382 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 383 if (!SC) return false; 384 385 // Return true if the value is negative, this matches things like (-42 * V). 386 return SC->getAPInt().isNegative(); 387 } 388 389 SCEVCouldNotCompute::SCEVCouldNotCompute() : 390 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 391 392 bool SCEVCouldNotCompute::classof(const SCEV *S) { 393 return S->getSCEVType() == scCouldNotCompute; 394 } 395 396 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 397 FoldingSetNodeID ID; 398 ID.AddInteger(scConstant); 399 ID.AddPointer(V); 400 void *IP = nullptr; 401 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 402 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 403 UniqueSCEVs.InsertNode(S, IP); 404 return S; 405 } 406 407 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 408 return getConstant(ConstantInt::get(getContext(), Val)); 409 } 410 411 const SCEV * 412 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 413 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 414 return getConstant(ConstantInt::get(ITy, V, isSigned)); 415 } 416 417 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 418 unsigned SCEVTy, const SCEV *op, Type *ty) 419 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 420 421 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 422 const SCEV *op, Type *ty) 423 : SCEVCastExpr(ID, scTruncate, op, ty) { 424 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 425 "Cannot truncate non-integer value!"); 426 } 427 428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 429 const SCEV *op, Type *ty) 430 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 431 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 432 "Cannot zero extend non-integer value!"); 433 } 434 435 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 436 const SCEV *op, Type *ty) 437 : SCEVCastExpr(ID, scSignExtend, op, ty) { 438 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 439 "Cannot sign extend non-integer value!"); 440 } 441 442 void SCEVUnknown::deleted() { 443 // Clear this SCEVUnknown from various maps. 444 SE->forgetMemoizedResults(this); 445 446 // Remove this SCEVUnknown from the uniquing map. 447 SE->UniqueSCEVs.RemoveNode(this); 448 449 // Release the value. 450 setValPtr(nullptr); 451 } 452 453 void SCEVUnknown::allUsesReplacedWith(Value *New) { 454 // Remove this SCEVUnknown from the uniquing map. 455 SE->UniqueSCEVs.RemoveNode(this); 456 457 // Update this SCEVUnknown to point to the new value. This is needed 458 // because there may still be outstanding SCEVs which still point to 459 // this SCEVUnknown. 460 setValPtr(New); 461 } 462 463 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 464 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 465 if (VCE->getOpcode() == Instruction::PtrToInt) 466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 467 if (CE->getOpcode() == Instruction::GetElementPtr && 468 CE->getOperand(0)->isNullValue() && 469 CE->getNumOperands() == 2) 470 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 471 if (CI->isOne()) { 472 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 473 ->getElementType(); 474 return true; 475 } 476 477 return false; 478 } 479 480 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 481 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 482 if (VCE->getOpcode() == Instruction::PtrToInt) 483 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 484 if (CE->getOpcode() == Instruction::GetElementPtr && 485 CE->getOperand(0)->isNullValue()) { 486 Type *Ty = 487 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 488 if (StructType *STy = dyn_cast<StructType>(Ty)) 489 if (!STy->isPacked() && 490 CE->getNumOperands() == 3 && 491 CE->getOperand(1)->isNullValue()) { 492 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 493 if (CI->isOne() && 494 STy->getNumElements() == 2 && 495 STy->getElementType(0)->isIntegerTy(1)) { 496 AllocTy = STy->getElementType(1); 497 return true; 498 } 499 } 500 } 501 502 return false; 503 } 504 505 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 506 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 507 if (VCE->getOpcode() == Instruction::PtrToInt) 508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 509 if (CE->getOpcode() == Instruction::GetElementPtr && 510 CE->getNumOperands() == 3 && 511 CE->getOperand(0)->isNullValue() && 512 CE->getOperand(1)->isNullValue()) { 513 Type *Ty = 514 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 515 // Ignore vector types here so that ScalarEvolutionExpander doesn't 516 // emit getelementptrs that index into vectors. 517 if (Ty->isStructTy() || Ty->isArrayTy()) { 518 CTy = Ty; 519 FieldNo = CE->getOperand(2); 520 return true; 521 } 522 } 523 524 return false; 525 } 526 527 //===----------------------------------------------------------------------===// 528 // SCEV Utilities 529 //===----------------------------------------------------------------------===// 530 531 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 532 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 533 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 534 /// have been previously deemed to be "equally complex" by this routine. It is 535 /// intended to avoid exponential time complexity in cases like: 536 /// 537 /// %a = f(%x, %y) 538 /// %b = f(%a, %a) 539 /// %c = f(%b, %b) 540 /// 541 /// %d = f(%x, %y) 542 /// %e = f(%d, %d) 543 /// %f = f(%e, %e) 544 /// 545 /// CompareValueComplexity(%f, %c) 546 /// 547 /// Since we do not continue running this routine on expression trees once we 548 /// have seen unequal values, there is no need to track them in the cache. 549 static int 550 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 551 const LoopInfo *const LI, Value *LV, Value *RV, 552 unsigned Depth) { 553 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 554 return 0; 555 556 // Order pointer values after integer values. This helps SCEVExpander form 557 // GEPs. 558 bool LIsPointer = LV->getType()->isPointerTy(), 559 RIsPointer = RV->getType()->isPointerTy(); 560 if (LIsPointer != RIsPointer) 561 return (int)LIsPointer - (int)RIsPointer; 562 563 // Compare getValueID values. 564 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 565 if (LID != RID) 566 return (int)LID - (int)RID; 567 568 // Sort arguments by their position. 569 if (const auto *LA = dyn_cast<Argument>(LV)) { 570 const auto *RA = cast<Argument>(RV); 571 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 572 return (int)LArgNo - (int)RArgNo; 573 } 574 575 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 576 const auto *RGV = cast<GlobalValue>(RV); 577 578 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 579 auto LT = GV->getLinkage(); 580 return !(GlobalValue::isPrivateLinkage(LT) || 581 GlobalValue::isInternalLinkage(LT)); 582 }; 583 584 // Use the names to distinguish the two values, but only if the 585 // names are semantically important. 586 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 587 return LGV->getName().compare(RGV->getName()); 588 } 589 590 // For instructions, compare their loop depth, and their operand count. This 591 // is pretty loose. 592 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 593 const auto *RInst = cast<Instruction>(RV); 594 595 // Compare loop depths. 596 const BasicBlock *LParent = LInst->getParent(), 597 *RParent = RInst->getParent(); 598 if (LParent != RParent) { 599 unsigned LDepth = LI->getLoopDepth(LParent), 600 RDepth = LI->getLoopDepth(RParent); 601 if (LDepth != RDepth) 602 return (int)LDepth - (int)RDepth; 603 } 604 605 // Compare the number of operands. 606 unsigned LNumOps = LInst->getNumOperands(), 607 RNumOps = RInst->getNumOperands(); 608 if (LNumOps != RNumOps) 609 return (int)LNumOps - (int)RNumOps; 610 611 for (unsigned Idx : seq(0u, LNumOps)) { 612 int Result = 613 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 614 RInst->getOperand(Idx), Depth + 1); 615 if (Result != 0) 616 return Result; 617 } 618 } 619 620 EqCacheValue.unionSets(LV, RV); 621 return 0; 622 } 623 624 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 625 // than RHS, respectively. A three-way result allows recursive comparisons to be 626 // more efficient. 627 static int CompareSCEVComplexity( 628 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 629 EquivalenceClasses<const Value *> &EqCacheValue, 630 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 631 DominatorTree &DT, unsigned Depth = 0) { 632 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 633 if (LHS == RHS) 634 return 0; 635 636 // Primarily, sort the SCEVs by their getSCEVType(). 637 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 638 if (LType != RType) 639 return (int)LType - (int)RType; 640 641 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 642 return 0; 643 // Aside from the getSCEVType() ordering, the particular ordering 644 // isn't very important except that it's beneficial to be consistent, 645 // so that (a + b) and (b + a) don't end up as different expressions. 646 switch (static_cast<SCEVTypes>(LType)) { 647 case scUnknown: { 648 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 649 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 650 651 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 652 RU->getValue(), Depth + 1); 653 if (X == 0) 654 EqCacheSCEV.unionSets(LHS, RHS); 655 return X; 656 } 657 658 case scConstant: { 659 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 660 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 661 662 // Compare constant values. 663 const APInt &LA = LC->getAPInt(); 664 const APInt &RA = RC->getAPInt(); 665 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 666 if (LBitWidth != RBitWidth) 667 return (int)LBitWidth - (int)RBitWidth; 668 return LA.ult(RA) ? -1 : 1; 669 } 670 671 case scAddRecExpr: { 672 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 673 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 674 675 // There is always a dominance between two recs that are used by one SCEV, 676 // so we can safely sort recs by loop header dominance. We require such 677 // order in getAddExpr. 678 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 679 if (LLoop != RLoop) { 680 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 681 assert(LHead != RHead && "Two loops share the same header?"); 682 if (DT.dominates(LHead, RHead)) 683 return 1; 684 else 685 assert(DT.dominates(RHead, LHead) && 686 "No dominance between recurrences used by one SCEV?"); 687 return -1; 688 } 689 690 // Addrec complexity grows with operand count. 691 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 692 if (LNumOps != RNumOps) 693 return (int)LNumOps - (int)RNumOps; 694 695 // Compare NoWrap flags. 696 if (LA->getNoWrapFlags() != RA->getNoWrapFlags()) 697 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags(); 698 699 // Lexicographically compare. 700 for (unsigned i = 0; i != LNumOps; ++i) { 701 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 702 LA->getOperand(i), RA->getOperand(i), DT, 703 Depth + 1); 704 if (X != 0) 705 return X; 706 } 707 EqCacheSCEV.unionSets(LHS, RHS); 708 return 0; 709 } 710 711 case scAddExpr: 712 case scMulExpr: 713 case scSMaxExpr: 714 case scUMaxExpr: { 715 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 716 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 717 718 // Lexicographically compare n-ary expressions. 719 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 720 if (LNumOps != RNumOps) 721 return (int)LNumOps - (int)RNumOps; 722 723 // Compare NoWrap flags. 724 if (LC->getNoWrapFlags() != RC->getNoWrapFlags()) 725 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags(); 726 727 for (unsigned i = 0; i != LNumOps; ++i) { 728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 729 LC->getOperand(i), RC->getOperand(i), DT, 730 Depth + 1); 731 if (X != 0) 732 return X; 733 } 734 EqCacheSCEV.unionSets(LHS, RHS); 735 return 0; 736 } 737 738 case scUDivExpr: { 739 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 740 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 741 742 // Lexicographically compare udiv expressions. 743 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 744 RC->getLHS(), DT, Depth + 1); 745 if (X != 0) 746 return X; 747 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 748 RC->getRHS(), DT, Depth + 1); 749 if (X == 0) 750 EqCacheSCEV.unionSets(LHS, RHS); 751 return X; 752 } 753 754 case scTruncate: 755 case scZeroExtend: 756 case scSignExtend: { 757 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 758 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 759 760 // Compare cast expressions by operand. 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 762 LC->getOperand(), RC->getOperand(), DT, 763 Depth + 1); 764 if (X == 0) 765 EqCacheSCEV.unionSets(LHS, RHS); 766 return X; 767 } 768 769 case scCouldNotCompute: 770 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 771 } 772 llvm_unreachable("Unknown SCEV kind!"); 773 } 774 775 /// Given a list of SCEV objects, order them by their complexity, and group 776 /// objects of the same complexity together by value. When this routine is 777 /// finished, we know that any duplicates in the vector are consecutive and that 778 /// complexity is monotonically increasing. 779 /// 780 /// Note that we go take special precautions to ensure that we get deterministic 781 /// results from this routine. In other words, we don't want the results of 782 /// this to depend on where the addresses of various SCEV objects happened to 783 /// land in memory. 784 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 785 LoopInfo *LI, DominatorTree &DT) { 786 if (Ops.size() < 2) return; // Noop 787 788 EquivalenceClasses<const SCEV *> EqCacheSCEV; 789 EquivalenceClasses<const Value *> EqCacheValue; 790 if (Ops.size() == 2) { 791 // This is the common case, which also happens to be trivially simple. 792 // Special case it. 793 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 794 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 795 std::swap(LHS, RHS); 796 return; 797 } 798 799 // Do the rough sort by complexity. 800 std::stable_sort(Ops.begin(), Ops.end(), 801 [&](const SCEV *LHS, const SCEV *RHS) { 802 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 803 LHS, RHS, DT) < 0; 804 }); 805 806 // Now that we are sorted by complexity, group elements of the same 807 // complexity. Note that this is, at worst, N^2, but the vector is likely to 808 // be extremely short in practice. Note that we take this approach because we 809 // do not want to depend on the addresses of the objects we are grouping. 810 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 811 const SCEV *S = Ops[i]; 812 unsigned Complexity = S->getSCEVType(); 813 814 // If there are any objects of the same complexity and same value as this 815 // one, group them. 816 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 817 if (Ops[j] == S) { // Found a duplicate. 818 // Move it to immediately after i'th element. 819 std::swap(Ops[i+1], Ops[j]); 820 ++i; // no need to rescan it. 821 if (i == e-2) return; // Done! 822 } 823 } 824 } 825 } 826 827 // Returns the size of the SCEV S. 828 static inline int sizeOfSCEV(const SCEV *S) { 829 struct FindSCEVSize { 830 int Size = 0; 831 832 FindSCEVSize() = default; 833 834 bool follow(const SCEV *S) { 835 ++Size; 836 // Keep looking at all operands of S. 837 return true; 838 } 839 840 bool isDone() const { 841 return false; 842 } 843 }; 844 845 FindSCEVSize F; 846 SCEVTraversal<FindSCEVSize> ST(F); 847 ST.visitAll(S); 848 return F.Size; 849 } 850 851 namespace { 852 853 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 854 public: 855 // Computes the Quotient and Remainder of the division of Numerator by 856 // Denominator. 857 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 858 const SCEV *Denominator, const SCEV **Quotient, 859 const SCEV **Remainder) { 860 assert(Numerator && Denominator && "Uninitialized SCEV"); 861 862 SCEVDivision D(SE, Numerator, Denominator); 863 864 // Check for the trivial case here to avoid having to check for it in the 865 // rest of the code. 866 if (Numerator == Denominator) { 867 *Quotient = D.One; 868 *Remainder = D.Zero; 869 return; 870 } 871 872 if (Numerator->isZero()) { 873 *Quotient = D.Zero; 874 *Remainder = D.Zero; 875 return; 876 } 877 878 // A simple case when N/1. The quotient is N. 879 if (Denominator->isOne()) { 880 *Quotient = Numerator; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 // Split the Denominator when it is a product. 886 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 887 const SCEV *Q, *R; 888 *Quotient = Numerator; 889 for (const SCEV *Op : T->operands()) { 890 divide(SE, *Quotient, Op, &Q, &R); 891 *Quotient = Q; 892 893 // Bail out when the Numerator is not divisible by one of the terms of 894 // the Denominator. 895 if (!R->isZero()) { 896 *Quotient = D.Zero; 897 *Remainder = Numerator; 898 return; 899 } 900 } 901 *Remainder = D.Zero; 902 return; 903 } 904 905 D.visit(Numerator); 906 *Quotient = D.Quotient; 907 *Remainder = D.Remainder; 908 } 909 910 // Except in the trivial case described above, we do not know how to divide 911 // Expr by Denominator for the following functions with empty implementation. 912 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 913 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 914 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 915 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 916 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 917 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 918 void visitUnknown(const SCEVUnknown *Numerator) {} 919 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 920 921 void visitConstant(const SCEVConstant *Numerator) { 922 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 923 APInt NumeratorVal = Numerator->getAPInt(); 924 APInt DenominatorVal = D->getAPInt(); 925 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 926 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 927 928 if (NumeratorBW > DenominatorBW) 929 DenominatorVal = DenominatorVal.sext(NumeratorBW); 930 else if (NumeratorBW < DenominatorBW) 931 NumeratorVal = NumeratorVal.sext(DenominatorBW); 932 933 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 934 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 935 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 936 Quotient = SE.getConstant(QuotientVal); 937 Remainder = SE.getConstant(RemainderVal); 938 return; 939 } 940 } 941 942 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 943 const SCEV *StartQ, *StartR, *StepQ, *StepR; 944 if (!Numerator->isAffine()) 945 return cannotDivide(Numerator); 946 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 947 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 948 // Bail out if the types do not match. 949 Type *Ty = Denominator->getType(); 950 if (Ty != StartQ->getType() || Ty != StartR->getType() || 951 Ty != StepQ->getType() || Ty != StepR->getType()) 952 return cannotDivide(Numerator); 953 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 954 Numerator->getNoWrapFlags()); 955 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 956 Numerator->getNoWrapFlags()); 957 } 958 959 void visitAddExpr(const SCEVAddExpr *Numerator) { 960 SmallVector<const SCEV *, 2> Qs, Rs; 961 Type *Ty = Denominator->getType(); 962 963 for (const SCEV *Op : Numerator->operands()) { 964 const SCEV *Q, *R; 965 divide(SE, Op, Denominator, &Q, &R); 966 967 // Bail out if types do not match. 968 if (Ty != Q->getType() || Ty != R->getType()) 969 return cannotDivide(Numerator); 970 971 Qs.push_back(Q); 972 Rs.push_back(R); 973 } 974 975 if (Qs.size() == 1) { 976 Quotient = Qs[0]; 977 Remainder = Rs[0]; 978 return; 979 } 980 981 Quotient = SE.getAddExpr(Qs); 982 Remainder = SE.getAddExpr(Rs); 983 } 984 985 void visitMulExpr(const SCEVMulExpr *Numerator) { 986 SmallVector<const SCEV *, 2> Qs; 987 Type *Ty = Denominator->getType(); 988 989 bool FoundDenominatorTerm = false; 990 for (const SCEV *Op : Numerator->operands()) { 991 // Bail out if types do not match. 992 if (Ty != Op->getType()) 993 return cannotDivide(Numerator); 994 995 if (FoundDenominatorTerm) { 996 Qs.push_back(Op); 997 continue; 998 } 999 1000 // Check whether Denominator divides one of the product operands. 1001 const SCEV *Q, *R; 1002 divide(SE, Op, Denominator, &Q, &R); 1003 if (!R->isZero()) { 1004 Qs.push_back(Op); 1005 continue; 1006 } 1007 1008 // Bail out if types do not match. 1009 if (Ty != Q->getType()) 1010 return cannotDivide(Numerator); 1011 1012 FoundDenominatorTerm = true; 1013 Qs.push_back(Q); 1014 } 1015 1016 if (FoundDenominatorTerm) { 1017 Remainder = Zero; 1018 if (Qs.size() == 1) 1019 Quotient = Qs[0]; 1020 else 1021 Quotient = SE.getMulExpr(Qs); 1022 return; 1023 } 1024 1025 if (!isa<SCEVUnknown>(Denominator)) 1026 return cannotDivide(Numerator); 1027 1028 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1029 ValueToValueMap RewriteMap; 1030 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1031 cast<SCEVConstant>(Zero)->getValue(); 1032 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1033 1034 if (Remainder->isZero()) { 1035 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1036 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1037 cast<SCEVConstant>(One)->getValue(); 1038 Quotient = 1039 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1040 return; 1041 } 1042 1043 // Quotient is (Numerator - Remainder) divided by Denominator. 1044 const SCEV *Q, *R; 1045 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1046 // This SCEV does not seem to simplify: fail the division here. 1047 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1048 return cannotDivide(Numerator); 1049 divide(SE, Diff, Denominator, &Q, &R); 1050 if (R != Zero) 1051 return cannotDivide(Numerator); 1052 Quotient = Q; 1053 } 1054 1055 private: 1056 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1057 const SCEV *Denominator) 1058 : SE(S), Denominator(Denominator) { 1059 Zero = SE.getZero(Denominator->getType()); 1060 One = SE.getOne(Denominator->getType()); 1061 1062 // We generally do not know how to divide Expr by Denominator. We 1063 // initialize the division to a "cannot divide" state to simplify the rest 1064 // of the code. 1065 cannotDivide(Numerator); 1066 } 1067 1068 // Convenience function for giving up on the division. We set the quotient to 1069 // be equal to zero and the remainder to be equal to the numerator. 1070 void cannotDivide(const SCEV *Numerator) { 1071 Quotient = Zero; 1072 Remainder = Numerator; 1073 } 1074 1075 ScalarEvolution &SE; 1076 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1077 }; 1078 1079 } // end anonymous namespace 1080 1081 //===----------------------------------------------------------------------===// 1082 // Simple SCEV method implementations 1083 //===----------------------------------------------------------------------===// 1084 1085 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1086 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1087 ScalarEvolution &SE, 1088 Type *ResultTy) { 1089 // Handle the simplest case efficiently. 1090 if (K == 1) 1091 return SE.getTruncateOrZeroExtend(It, ResultTy); 1092 1093 // We are using the following formula for BC(It, K): 1094 // 1095 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1096 // 1097 // Suppose, W is the bitwidth of the return value. We must be prepared for 1098 // overflow. Hence, we must assure that the result of our computation is 1099 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1100 // safe in modular arithmetic. 1101 // 1102 // However, this code doesn't use exactly that formula; the formula it uses 1103 // is something like the following, where T is the number of factors of 2 in 1104 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1105 // exponentiation: 1106 // 1107 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1108 // 1109 // This formula is trivially equivalent to the previous formula. However, 1110 // this formula can be implemented much more efficiently. The trick is that 1111 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1112 // arithmetic. To do exact division in modular arithmetic, all we have 1113 // to do is multiply by the inverse. Therefore, this step can be done at 1114 // width W. 1115 // 1116 // The next issue is how to safely do the division by 2^T. The way this 1117 // is done is by doing the multiplication step at a width of at least W + T 1118 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1119 // when we perform the division by 2^T (which is equivalent to a right shift 1120 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1121 // truncated out after the division by 2^T. 1122 // 1123 // In comparison to just directly using the first formula, this technique 1124 // is much more efficient; using the first formula requires W * K bits, 1125 // but this formula less than W + K bits. Also, the first formula requires 1126 // a division step, whereas this formula only requires multiplies and shifts. 1127 // 1128 // It doesn't matter whether the subtraction step is done in the calculation 1129 // width or the input iteration count's width; if the subtraction overflows, 1130 // the result must be zero anyway. We prefer here to do it in the width of 1131 // the induction variable because it helps a lot for certain cases; CodeGen 1132 // isn't smart enough to ignore the overflow, which leads to much less 1133 // efficient code if the width of the subtraction is wider than the native 1134 // register width. 1135 // 1136 // (It's possible to not widen at all by pulling out factors of 2 before 1137 // the multiplication; for example, K=2 can be calculated as 1138 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1139 // extra arithmetic, so it's not an obvious win, and it gets 1140 // much more complicated for K > 3.) 1141 1142 // Protection from insane SCEVs; this bound is conservative, 1143 // but it probably doesn't matter. 1144 if (K > 1000) 1145 return SE.getCouldNotCompute(); 1146 1147 unsigned W = SE.getTypeSizeInBits(ResultTy); 1148 1149 // Calculate K! / 2^T and T; we divide out the factors of two before 1150 // multiplying for calculating K! / 2^T to avoid overflow. 1151 // Other overflow doesn't matter because we only care about the bottom 1152 // W bits of the result. 1153 APInt OddFactorial(W, 1); 1154 unsigned T = 1; 1155 for (unsigned i = 3; i <= K; ++i) { 1156 APInt Mult(W, i); 1157 unsigned TwoFactors = Mult.countTrailingZeros(); 1158 T += TwoFactors; 1159 Mult.lshrInPlace(TwoFactors); 1160 OddFactorial *= Mult; 1161 } 1162 1163 // We need at least W + T bits for the multiplication step 1164 unsigned CalculationBits = W + T; 1165 1166 // Calculate 2^T, at width T+W. 1167 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1168 1169 // Calculate the multiplicative inverse of K! / 2^T; 1170 // this multiplication factor will perform the exact division by 1171 // K! / 2^T. 1172 APInt Mod = APInt::getSignedMinValue(W+1); 1173 APInt MultiplyFactor = OddFactorial.zext(W+1); 1174 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1175 MultiplyFactor = MultiplyFactor.trunc(W); 1176 1177 // Calculate the product, at width T+W 1178 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1179 CalculationBits); 1180 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1181 for (unsigned i = 1; i != K; ++i) { 1182 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1183 Dividend = SE.getMulExpr(Dividend, 1184 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1185 } 1186 1187 // Divide by 2^T 1188 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1189 1190 // Truncate the result, and divide by K! / 2^T. 1191 1192 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1193 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1194 } 1195 1196 /// Return the value of this chain of recurrences at the specified iteration 1197 /// number. We can evaluate this recurrence by multiplying each element in the 1198 /// chain by the binomial coefficient corresponding to it. In other words, we 1199 /// can evaluate {A,+,B,+,C,+,D} as: 1200 /// 1201 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1202 /// 1203 /// where BC(It, k) stands for binomial coefficient. 1204 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1205 ScalarEvolution &SE) const { 1206 const SCEV *Result = getStart(); 1207 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1208 // The computation is correct in the face of overflow provided that the 1209 // multiplication is performed _after_ the evaluation of the binomial 1210 // coefficient. 1211 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1212 if (isa<SCEVCouldNotCompute>(Coeff)) 1213 return Coeff; 1214 1215 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1216 } 1217 return Result; 1218 } 1219 1220 //===----------------------------------------------------------------------===// 1221 // SCEV Expression folder implementations 1222 //===----------------------------------------------------------------------===// 1223 1224 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1225 Type *Ty) { 1226 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1227 "This is not a truncating conversion!"); 1228 assert(isSCEVable(Ty) && 1229 "This is not a conversion to a SCEVable type!"); 1230 Ty = getEffectiveSCEVType(Ty); 1231 1232 FoldingSetNodeID ID; 1233 ID.AddInteger(scTruncate); 1234 ID.AddPointer(Op); 1235 ID.AddPointer(Ty); 1236 void *IP = nullptr; 1237 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1238 1239 // Fold if the operand is constant. 1240 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1241 return getConstant( 1242 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1243 1244 // trunc(trunc(x)) --> trunc(x) 1245 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1246 return getTruncateExpr(ST->getOperand(), Ty); 1247 1248 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1249 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1250 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1251 1252 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1253 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1254 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1255 1256 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1257 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1258 // if after transforming we have at most one truncate, not counting truncates 1259 // that replace other casts. 1260 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1261 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1262 SmallVector<const SCEV *, 4> Operands; 1263 unsigned numTruncs = 0; 1264 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1265 ++i) { 1266 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty); 1267 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1268 numTruncs++; 1269 Operands.push_back(S); 1270 } 1271 if (numTruncs < 2) { 1272 if (isa<SCEVAddExpr>(Op)) 1273 return getAddExpr(Operands); 1274 else if (isa<SCEVMulExpr>(Op)) 1275 return getMulExpr(Operands); 1276 else 1277 llvm_unreachable("Unexpected SCEV type for Op."); 1278 } 1279 // Although we checked in the beginning that ID is not in the cache, it is 1280 // possible that during recursion and different modification ID was inserted 1281 // into the cache. So if we find it, just return it. 1282 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1283 return S; 1284 } 1285 1286 // If the input value is a chrec scev, truncate the chrec's operands. 1287 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1288 SmallVector<const SCEV *, 4> Operands; 1289 for (const SCEV *Op : AddRec->operands()) 1290 Operands.push_back(getTruncateExpr(Op, Ty)); 1291 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1292 } 1293 1294 // The cast wasn't folded; create an explicit cast node. We can reuse 1295 // the existing insert position since if we get here, we won't have 1296 // made any changes which would invalidate it. 1297 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1298 Op, Ty); 1299 UniqueSCEVs.InsertNode(S, IP); 1300 addToLoopUseLists(S); 1301 return S; 1302 } 1303 1304 // Get the limit of a recurrence such that incrementing by Step cannot cause 1305 // signed overflow as long as the value of the recurrence within the 1306 // loop does not exceed this limit before incrementing. 1307 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1308 ICmpInst::Predicate *Pred, 1309 ScalarEvolution *SE) { 1310 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1311 if (SE->isKnownPositive(Step)) { 1312 *Pred = ICmpInst::ICMP_SLT; 1313 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1314 SE->getSignedRangeMax(Step)); 1315 } 1316 if (SE->isKnownNegative(Step)) { 1317 *Pred = ICmpInst::ICMP_SGT; 1318 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1319 SE->getSignedRangeMin(Step)); 1320 } 1321 return nullptr; 1322 } 1323 1324 // Get the limit of a recurrence such that incrementing by Step cannot cause 1325 // unsigned overflow as long as the value of the recurrence within the loop does 1326 // not exceed this limit before incrementing. 1327 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1328 ICmpInst::Predicate *Pred, 1329 ScalarEvolution *SE) { 1330 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1331 *Pred = ICmpInst::ICMP_ULT; 1332 1333 return SE->getConstant(APInt::getMinValue(BitWidth) - 1334 SE->getUnsignedRangeMax(Step)); 1335 } 1336 1337 namespace { 1338 1339 struct ExtendOpTraitsBase { 1340 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1341 unsigned); 1342 }; 1343 1344 // Used to make code generic over signed and unsigned overflow. 1345 template <typename ExtendOp> struct ExtendOpTraits { 1346 // Members present: 1347 // 1348 // static const SCEV::NoWrapFlags WrapType; 1349 // 1350 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1351 // 1352 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1353 // ICmpInst::Predicate *Pred, 1354 // ScalarEvolution *SE); 1355 }; 1356 1357 template <> 1358 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1359 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1360 1361 static const GetExtendExprTy GetExtendExpr; 1362 1363 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1364 ICmpInst::Predicate *Pred, 1365 ScalarEvolution *SE) { 1366 return getSignedOverflowLimitForStep(Step, Pred, SE); 1367 } 1368 }; 1369 1370 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1371 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1372 1373 template <> 1374 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1375 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1376 1377 static const GetExtendExprTy GetExtendExpr; 1378 1379 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1380 ICmpInst::Predicate *Pred, 1381 ScalarEvolution *SE) { 1382 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1383 } 1384 }; 1385 1386 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1387 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1388 1389 } // end anonymous namespace 1390 1391 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1392 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1393 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1394 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1395 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1396 // expression "Step + sext/zext(PreIncAR)" is congruent with 1397 // "sext/zext(PostIncAR)" 1398 template <typename ExtendOpTy> 1399 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1400 ScalarEvolution *SE, unsigned Depth) { 1401 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1402 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1403 1404 const Loop *L = AR->getLoop(); 1405 const SCEV *Start = AR->getStart(); 1406 const SCEV *Step = AR->getStepRecurrence(*SE); 1407 1408 // Check for a simple looking step prior to loop entry. 1409 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1410 if (!SA) 1411 return nullptr; 1412 1413 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1414 // subtraction is expensive. For this purpose, perform a quick and dirty 1415 // difference, by checking for Step in the operand list. 1416 SmallVector<const SCEV *, 4> DiffOps; 1417 for (const SCEV *Op : SA->operands()) 1418 if (Op != Step) 1419 DiffOps.push_back(Op); 1420 1421 if (DiffOps.size() == SA->getNumOperands()) 1422 return nullptr; 1423 1424 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1425 // `Step`: 1426 1427 // 1. NSW/NUW flags on the step increment. 1428 auto PreStartFlags = 1429 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1430 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1431 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1432 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1433 1434 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1435 // "S+X does not sign/unsign-overflow". 1436 // 1437 1438 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1439 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1440 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1441 return PreStart; 1442 1443 // 2. Direct overflow check on the step operation's expression. 1444 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1445 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1446 const SCEV *OperandExtendedStart = 1447 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1448 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1449 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1450 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1451 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1452 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1453 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1454 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1455 } 1456 return PreStart; 1457 } 1458 1459 // 3. Loop precondition. 1460 ICmpInst::Predicate Pred; 1461 const SCEV *OverflowLimit = 1462 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1463 1464 if (OverflowLimit && 1465 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1466 return PreStart; 1467 1468 return nullptr; 1469 } 1470 1471 // Get the normalized zero or sign extended expression for this AddRec's Start. 1472 template <typename ExtendOpTy> 1473 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1474 ScalarEvolution *SE, 1475 unsigned Depth) { 1476 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1477 1478 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1479 if (!PreStart) 1480 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1481 1482 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1483 Depth), 1484 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1485 } 1486 1487 // Try to prove away overflow by looking at "nearby" add recurrences. A 1488 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1489 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1490 // 1491 // Formally: 1492 // 1493 // {S,+,X} == {S-T,+,X} + T 1494 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1495 // 1496 // If ({S-T,+,X} + T) does not overflow ... (1) 1497 // 1498 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1499 // 1500 // If {S-T,+,X} does not overflow ... (2) 1501 // 1502 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1503 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1504 // 1505 // If (S-T)+T does not overflow ... (3) 1506 // 1507 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1508 // == {Ext(S),+,Ext(X)} == LHS 1509 // 1510 // Thus, if (1), (2) and (3) are true for some T, then 1511 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1512 // 1513 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1514 // does not overflow" restricted to the 0th iteration. Therefore we only need 1515 // to check for (1) and (2). 1516 // 1517 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1518 // is `Delta` (defined below). 1519 template <typename ExtendOpTy> 1520 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1521 const SCEV *Step, 1522 const Loop *L) { 1523 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1524 1525 // We restrict `Start` to a constant to prevent SCEV from spending too much 1526 // time here. It is correct (but more expensive) to continue with a 1527 // non-constant `Start` and do a general SCEV subtraction to compute 1528 // `PreStart` below. 1529 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1530 if (!StartC) 1531 return false; 1532 1533 APInt StartAI = StartC->getAPInt(); 1534 1535 for (unsigned Delta : {-2, -1, 1, 2}) { 1536 const SCEV *PreStart = getConstant(StartAI - Delta); 1537 1538 FoldingSetNodeID ID; 1539 ID.AddInteger(scAddRecExpr); 1540 ID.AddPointer(PreStart); 1541 ID.AddPointer(Step); 1542 ID.AddPointer(L); 1543 void *IP = nullptr; 1544 const auto *PreAR = 1545 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1546 1547 // Give up if we don't already have the add recurrence we need because 1548 // actually constructing an add recurrence is relatively expensive. 1549 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1550 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1551 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1552 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1553 DeltaS, &Pred, this); 1554 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1555 return true; 1556 } 1557 } 1558 1559 return false; 1560 } 1561 1562 const SCEV * 1563 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1564 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1565 "This is not an extending conversion!"); 1566 assert(isSCEVable(Ty) && 1567 "This is not a conversion to a SCEVable type!"); 1568 Ty = getEffectiveSCEVType(Ty); 1569 1570 // Fold if the operand is constant. 1571 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1572 return getConstant( 1573 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1574 1575 // zext(zext(x)) --> zext(x) 1576 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1577 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1578 1579 // Before doing any expensive analysis, check to see if we've already 1580 // computed a SCEV for this Op and Ty. 1581 FoldingSetNodeID ID; 1582 ID.AddInteger(scZeroExtend); 1583 ID.AddPointer(Op); 1584 ID.AddPointer(Ty); 1585 void *IP = nullptr; 1586 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1587 if (Depth > MaxExtDepth) { 1588 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1589 Op, Ty); 1590 UniqueSCEVs.InsertNode(S, IP); 1591 addToLoopUseLists(S); 1592 return S; 1593 } 1594 1595 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1596 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1597 // It's possible the bits taken off by the truncate were all zero bits. If 1598 // so, we should be able to simplify this further. 1599 const SCEV *X = ST->getOperand(); 1600 ConstantRange CR = getUnsignedRange(X); 1601 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1602 unsigned NewBits = getTypeSizeInBits(Ty); 1603 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1604 CR.zextOrTrunc(NewBits))) 1605 return getTruncateOrZeroExtend(X, Ty); 1606 } 1607 1608 // If the input value is a chrec scev, and we can prove that the value 1609 // did not overflow the old, smaller, value, we can zero extend all of the 1610 // operands (often constants). This allows analysis of something like 1611 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1612 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1613 if (AR->isAffine()) { 1614 const SCEV *Start = AR->getStart(); 1615 const SCEV *Step = AR->getStepRecurrence(*this); 1616 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1617 const Loop *L = AR->getLoop(); 1618 1619 if (!AR->hasNoUnsignedWrap()) { 1620 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1621 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1622 } 1623 1624 // If we have special knowledge that this addrec won't overflow, 1625 // we don't need to do any further analysis. 1626 if (AR->hasNoUnsignedWrap()) 1627 return getAddRecExpr( 1628 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1629 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1630 1631 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1632 // Note that this serves two purposes: It filters out loops that are 1633 // simply not analyzable, and it covers the case where this code is 1634 // being called from within backedge-taken count analysis, such that 1635 // attempting to ask for the backedge-taken count would likely result 1636 // in infinite recursion. In the later case, the analysis code will 1637 // cope with a conservative value, and it will take care to purge 1638 // that value once it has finished. 1639 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1640 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1641 // Manually compute the final value for AR, checking for 1642 // overflow. 1643 1644 // Check whether the backedge-taken count can be losslessly casted to 1645 // the addrec's type. The count is always unsigned. 1646 const SCEV *CastedMaxBECount = 1647 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1648 const SCEV *RecastedMaxBECount = 1649 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1650 if (MaxBECount == RecastedMaxBECount) { 1651 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1652 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1653 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1654 SCEV::FlagAnyWrap, Depth + 1); 1655 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1656 SCEV::FlagAnyWrap, 1657 Depth + 1), 1658 WideTy, Depth + 1); 1659 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1660 const SCEV *WideMaxBECount = 1661 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1662 const SCEV *OperandExtendedAdd = 1663 getAddExpr(WideStart, 1664 getMulExpr(WideMaxBECount, 1665 getZeroExtendExpr(Step, WideTy, Depth + 1), 1666 SCEV::FlagAnyWrap, Depth + 1), 1667 SCEV::FlagAnyWrap, Depth + 1); 1668 if (ZAdd == OperandExtendedAdd) { 1669 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1670 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1671 // Return the expression with the addrec on the outside. 1672 return getAddRecExpr( 1673 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1674 Depth + 1), 1675 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1676 AR->getNoWrapFlags()); 1677 } 1678 // Similar to above, only this time treat the step value as signed. 1679 // This covers loops that count down. 1680 OperandExtendedAdd = 1681 getAddExpr(WideStart, 1682 getMulExpr(WideMaxBECount, 1683 getSignExtendExpr(Step, WideTy, Depth + 1), 1684 SCEV::FlagAnyWrap, Depth + 1), 1685 SCEV::FlagAnyWrap, Depth + 1); 1686 if (ZAdd == OperandExtendedAdd) { 1687 // Cache knowledge of AR NW, which is propagated to this AddRec. 1688 // Negative step causes unsigned wrap, but it still can't self-wrap. 1689 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1690 // Return the expression with the addrec on the outside. 1691 return getAddRecExpr( 1692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1693 Depth + 1), 1694 getSignExtendExpr(Step, Ty, Depth + 1), L, 1695 AR->getNoWrapFlags()); 1696 } 1697 } 1698 } 1699 1700 // Normally, in the cases we can prove no-overflow via a 1701 // backedge guarding condition, we can also compute a backedge 1702 // taken count for the loop. The exceptions are assumptions and 1703 // guards present in the loop -- SCEV is not great at exploiting 1704 // these to compute max backedge taken counts, but can still use 1705 // these to prove lack of overflow. Use this fact to avoid 1706 // doing extra work that may not pay off. 1707 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1708 !AC.assumptions().empty()) { 1709 // If the backedge is guarded by a comparison with the pre-inc 1710 // value the addrec is safe. Also, if the entry is guarded by 1711 // a comparison with the start value and the backedge is 1712 // guarded by a comparison with the post-inc value, the addrec 1713 // is safe. 1714 if (isKnownPositive(Step)) { 1715 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1716 getUnsignedRangeMax(Step)); 1717 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1718 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1719 // Cache knowledge of AR NUW, which is propagated to this 1720 // AddRec. 1721 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1722 // Return the expression with the addrec on the outside. 1723 return getAddRecExpr( 1724 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1725 Depth + 1), 1726 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1727 AR->getNoWrapFlags()); 1728 } 1729 } else if (isKnownNegative(Step)) { 1730 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1731 getSignedRangeMin(Step)); 1732 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1733 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1734 // Cache knowledge of AR NW, which is propagated to this 1735 // AddRec. Negative step causes unsigned wrap, but it 1736 // still can't self-wrap. 1737 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1738 // Return the expression with the addrec on the outside. 1739 return getAddRecExpr( 1740 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1741 Depth + 1), 1742 getSignExtendExpr(Step, Ty, Depth + 1), L, 1743 AR->getNoWrapFlags()); 1744 } 1745 } 1746 } 1747 1748 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1752 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1753 } 1754 } 1755 1756 // zext(A % B) --> zext(A) % zext(B) 1757 { 1758 const SCEV *LHS; 1759 const SCEV *RHS; 1760 if (matchURem(Op, LHS, RHS)) 1761 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1762 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1763 } 1764 1765 // zext(A / B) --> zext(A) / zext(B). 1766 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1767 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1768 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1769 1770 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1771 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1772 if (SA->hasNoUnsignedWrap()) { 1773 // If the addition does not unsign overflow then we can, by definition, 1774 // commute the zero extension with the addition operation. 1775 SmallVector<const SCEV *, 4> Ops; 1776 for (const auto *Op : SA->operands()) 1777 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1778 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1779 } 1780 } 1781 1782 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1783 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1784 if (SM->hasNoUnsignedWrap()) { 1785 // If the multiply does not unsign overflow then we can, by definition, 1786 // commute the zero extension with the multiply operation. 1787 SmallVector<const SCEV *, 4> Ops; 1788 for (const auto *Op : SM->operands()) 1789 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1790 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1791 } 1792 1793 // zext(2^K * (trunc X to iN)) to iM -> 1794 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1795 // 1796 // Proof: 1797 // 1798 // zext(2^K * (trunc X to iN)) to iM 1799 // = zext((trunc X to iN) << K) to iM 1800 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1801 // (because shl removes the top K bits) 1802 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1803 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1804 // 1805 if (SM->getNumOperands() == 2) 1806 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1807 if (MulLHS->getAPInt().isPowerOf2()) 1808 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1809 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1810 MulLHS->getAPInt().logBase2(); 1811 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1812 return getMulExpr( 1813 getZeroExtendExpr(MulLHS, Ty), 1814 getZeroExtendExpr( 1815 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1816 SCEV::FlagNUW, Depth + 1); 1817 } 1818 } 1819 1820 // The cast wasn't folded; create an explicit cast node. 1821 // Recompute the insert position, as it may have been invalidated. 1822 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1823 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1824 Op, Ty); 1825 UniqueSCEVs.InsertNode(S, IP); 1826 addToLoopUseLists(S); 1827 return S; 1828 } 1829 1830 const SCEV * 1831 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1832 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1833 "This is not an extending conversion!"); 1834 assert(isSCEVable(Ty) && 1835 "This is not a conversion to a SCEVable type!"); 1836 Ty = getEffectiveSCEVType(Ty); 1837 1838 // Fold if the operand is constant. 1839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1840 return getConstant( 1841 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1842 1843 // sext(sext(x)) --> sext(x) 1844 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1845 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1846 1847 // sext(zext(x)) --> zext(x) 1848 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1849 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1850 1851 // Before doing any expensive analysis, check to see if we've already 1852 // computed a SCEV for this Op and Ty. 1853 FoldingSetNodeID ID; 1854 ID.AddInteger(scSignExtend); 1855 ID.AddPointer(Op); 1856 ID.AddPointer(Ty); 1857 void *IP = nullptr; 1858 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1859 // Limit recursion depth. 1860 if (Depth > MaxExtDepth) { 1861 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1862 Op, Ty); 1863 UniqueSCEVs.InsertNode(S, IP); 1864 addToLoopUseLists(S); 1865 return S; 1866 } 1867 1868 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1869 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1870 // It's possible the bits taken off by the truncate were all sign bits. If 1871 // so, we should be able to simplify this further. 1872 const SCEV *X = ST->getOperand(); 1873 ConstantRange CR = getSignedRange(X); 1874 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1875 unsigned NewBits = getTypeSizeInBits(Ty); 1876 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1877 CR.sextOrTrunc(NewBits))) 1878 return getTruncateOrSignExtend(X, Ty); 1879 } 1880 1881 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1882 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1883 if (SA->getNumOperands() == 2) { 1884 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1885 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1886 if (SMul && SC1) { 1887 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1888 const APInt &C1 = SC1->getAPInt(); 1889 const APInt &C2 = SC2->getAPInt(); 1890 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1891 C2.ugt(C1) && C2.isPowerOf2()) 1892 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1893 getSignExtendExpr(SMul, Ty, Depth + 1), 1894 SCEV::FlagAnyWrap, Depth + 1); 1895 } 1896 } 1897 } 1898 1899 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1900 if (SA->hasNoSignedWrap()) { 1901 // If the addition does not sign overflow then we can, by definition, 1902 // commute the sign extension with the addition operation. 1903 SmallVector<const SCEV *, 4> Ops; 1904 for (const auto *Op : SA->operands()) 1905 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1906 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1907 } 1908 } 1909 // If the input value is a chrec scev, and we can prove that the value 1910 // did not overflow the old, smaller, value, we can sign extend all of the 1911 // operands (often constants). This allows analysis of something like 1912 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1914 if (AR->isAffine()) { 1915 const SCEV *Start = AR->getStart(); 1916 const SCEV *Step = AR->getStepRecurrence(*this); 1917 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1918 const Loop *L = AR->getLoop(); 1919 1920 if (!AR->hasNoSignedWrap()) { 1921 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1922 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1923 } 1924 1925 // If we have special knowledge that this addrec won't overflow, 1926 // we don't need to do any further analysis. 1927 if (AR->hasNoSignedWrap()) 1928 return getAddRecExpr( 1929 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1930 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1931 1932 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1933 // Note that this serves two purposes: It filters out loops that are 1934 // simply not analyzable, and it covers the case where this code is 1935 // being called from within backedge-taken count analysis, such that 1936 // attempting to ask for the backedge-taken count would likely result 1937 // in infinite recursion. In the later case, the analysis code will 1938 // cope with a conservative value, and it will take care to purge 1939 // that value once it has finished. 1940 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1941 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1942 // Manually compute the final value for AR, checking for 1943 // overflow. 1944 1945 // Check whether the backedge-taken count can be losslessly casted to 1946 // the addrec's type. The count is always unsigned. 1947 const SCEV *CastedMaxBECount = 1948 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1949 const SCEV *RecastedMaxBECount = 1950 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1951 if (MaxBECount == RecastedMaxBECount) { 1952 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1953 // Check whether Start+Step*MaxBECount has no signed overflow. 1954 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1955 SCEV::FlagAnyWrap, Depth + 1); 1956 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1957 SCEV::FlagAnyWrap, 1958 Depth + 1), 1959 WideTy, Depth + 1); 1960 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1961 const SCEV *WideMaxBECount = 1962 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1963 const SCEV *OperandExtendedAdd = 1964 getAddExpr(WideStart, 1965 getMulExpr(WideMaxBECount, 1966 getSignExtendExpr(Step, WideTy, Depth + 1), 1967 SCEV::FlagAnyWrap, Depth + 1), 1968 SCEV::FlagAnyWrap, Depth + 1); 1969 if (SAdd == OperandExtendedAdd) { 1970 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1971 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1972 // Return the expression with the addrec on the outside. 1973 return getAddRecExpr( 1974 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1975 Depth + 1), 1976 getSignExtendExpr(Step, Ty, Depth + 1), L, 1977 AR->getNoWrapFlags()); 1978 } 1979 // Similar to above, only this time treat the step value as unsigned. 1980 // This covers loops that count up with an unsigned step. 1981 OperandExtendedAdd = 1982 getAddExpr(WideStart, 1983 getMulExpr(WideMaxBECount, 1984 getZeroExtendExpr(Step, WideTy, Depth + 1), 1985 SCEV::FlagAnyWrap, Depth + 1), 1986 SCEV::FlagAnyWrap, Depth + 1); 1987 if (SAdd == OperandExtendedAdd) { 1988 // If AR wraps around then 1989 // 1990 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1991 // => SAdd != OperandExtendedAdd 1992 // 1993 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1994 // (SAdd == OperandExtendedAdd => AR is NW) 1995 1996 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1997 1998 // Return the expression with the addrec on the outside. 1999 return getAddRecExpr( 2000 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2001 Depth + 1), 2002 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2003 AR->getNoWrapFlags()); 2004 } 2005 } 2006 } 2007 2008 // Normally, in the cases we can prove no-overflow via a 2009 // backedge guarding condition, we can also compute a backedge 2010 // taken count for the loop. The exceptions are assumptions and 2011 // guards present in the loop -- SCEV is not great at exploiting 2012 // these to compute max backedge taken counts, but can still use 2013 // these to prove lack of overflow. Use this fact to avoid 2014 // doing extra work that may not pay off. 2015 2016 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2017 !AC.assumptions().empty()) { 2018 // If the backedge is guarded by a comparison with the pre-inc 2019 // value the addrec is safe. Also, if the entry is guarded by 2020 // a comparison with the start value and the backedge is 2021 // guarded by a comparison with the post-inc value, the addrec 2022 // is safe. 2023 ICmpInst::Predicate Pred; 2024 const SCEV *OverflowLimit = 2025 getSignedOverflowLimitForStep(Step, &Pred, this); 2026 if (OverflowLimit && 2027 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2028 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2029 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2030 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2031 return getAddRecExpr( 2032 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2033 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2034 } 2035 } 2036 2037 // If Start and Step are constants, check if we can apply this 2038 // transformation: 2039 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2040 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2041 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2042 if (SC1 && SC2) { 2043 const APInt &C1 = SC1->getAPInt(); 2044 const APInt &C2 = SC2->getAPInt(); 2045 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2046 C2.isPowerOf2()) { 2047 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2048 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2049 AR->getNoWrapFlags()); 2050 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2051 SCEV::FlagAnyWrap, Depth + 1); 2052 } 2053 } 2054 2055 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2056 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2057 return getAddRecExpr( 2058 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2059 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2060 } 2061 } 2062 2063 // If the input value is provably positive and we could not simplify 2064 // away the sext build a zext instead. 2065 if (isKnownNonNegative(Op)) 2066 return getZeroExtendExpr(Op, Ty, Depth + 1); 2067 2068 // The cast wasn't folded; create an explicit cast node. 2069 // Recompute the insert position, as it may have been invalidated. 2070 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2071 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2072 Op, Ty); 2073 UniqueSCEVs.InsertNode(S, IP); 2074 addToLoopUseLists(S); 2075 return S; 2076 } 2077 2078 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2079 /// unspecified bits out to the given type. 2080 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2081 Type *Ty) { 2082 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2083 "This is not an extending conversion!"); 2084 assert(isSCEVable(Ty) && 2085 "This is not a conversion to a SCEVable type!"); 2086 Ty = getEffectiveSCEVType(Ty); 2087 2088 // Sign-extend negative constants. 2089 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2090 if (SC->getAPInt().isNegative()) 2091 return getSignExtendExpr(Op, Ty); 2092 2093 // Peel off a truncate cast. 2094 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2095 const SCEV *NewOp = T->getOperand(); 2096 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2097 return getAnyExtendExpr(NewOp, Ty); 2098 return getTruncateOrNoop(NewOp, Ty); 2099 } 2100 2101 // Next try a zext cast. If the cast is folded, use it. 2102 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2103 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2104 return ZExt; 2105 2106 // Next try a sext cast. If the cast is folded, use it. 2107 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2108 if (!isa<SCEVSignExtendExpr>(SExt)) 2109 return SExt; 2110 2111 // Force the cast to be folded into the operands of an addrec. 2112 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2113 SmallVector<const SCEV *, 4> Ops; 2114 for (const SCEV *Op : AR->operands()) 2115 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2116 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2117 } 2118 2119 // If the expression is obviously signed, use the sext cast value. 2120 if (isa<SCEVSMaxExpr>(Op)) 2121 return SExt; 2122 2123 // Absent any other information, use the zext cast value. 2124 return ZExt; 2125 } 2126 2127 /// Process the given Ops list, which is a list of operands to be added under 2128 /// the given scale, update the given map. This is a helper function for 2129 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2130 /// that would form an add expression like this: 2131 /// 2132 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2133 /// 2134 /// where A and B are constants, update the map with these values: 2135 /// 2136 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2137 /// 2138 /// and add 13 + A*B*29 to AccumulatedConstant. 2139 /// This will allow getAddRecExpr to produce this: 2140 /// 2141 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2142 /// 2143 /// This form often exposes folding opportunities that are hidden in 2144 /// the original operand list. 2145 /// 2146 /// Return true iff it appears that any interesting folding opportunities 2147 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2148 /// the common case where no interesting opportunities are present, and 2149 /// is also used as a check to avoid infinite recursion. 2150 static bool 2151 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2152 SmallVectorImpl<const SCEV *> &NewOps, 2153 APInt &AccumulatedConstant, 2154 const SCEV *const *Ops, size_t NumOperands, 2155 const APInt &Scale, 2156 ScalarEvolution &SE) { 2157 bool Interesting = false; 2158 2159 // Iterate over the add operands. They are sorted, with constants first. 2160 unsigned i = 0; 2161 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2162 ++i; 2163 // Pull a buried constant out to the outside. 2164 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2165 Interesting = true; 2166 AccumulatedConstant += Scale * C->getAPInt(); 2167 } 2168 2169 // Next comes everything else. We're especially interested in multiplies 2170 // here, but they're in the middle, so just visit the rest with one loop. 2171 for (; i != NumOperands; ++i) { 2172 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2173 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2174 APInt NewScale = 2175 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2176 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2177 // A multiplication of a constant with another add; recurse. 2178 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2179 Interesting |= 2180 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2181 Add->op_begin(), Add->getNumOperands(), 2182 NewScale, SE); 2183 } else { 2184 // A multiplication of a constant with some other value. Update 2185 // the map. 2186 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2187 const SCEV *Key = SE.getMulExpr(MulOps); 2188 auto Pair = M.insert({Key, NewScale}); 2189 if (Pair.second) { 2190 NewOps.push_back(Pair.first->first); 2191 } else { 2192 Pair.first->second += NewScale; 2193 // The map already had an entry for this value, which may indicate 2194 // a folding opportunity. 2195 Interesting = true; 2196 } 2197 } 2198 } else { 2199 // An ordinary operand. Update the map. 2200 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2201 M.insert({Ops[i], Scale}); 2202 if (Pair.second) { 2203 NewOps.push_back(Pair.first->first); 2204 } else { 2205 Pair.first->second += Scale; 2206 // The map already had an entry for this value, which may indicate 2207 // a folding opportunity. 2208 Interesting = true; 2209 } 2210 } 2211 } 2212 2213 return Interesting; 2214 } 2215 2216 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2217 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2218 // can't-overflow flags for the operation if possible. 2219 static SCEV::NoWrapFlags 2220 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2221 const SmallVectorImpl<const SCEV *> &Ops, 2222 SCEV::NoWrapFlags Flags) { 2223 using namespace std::placeholders; 2224 2225 using OBO = OverflowingBinaryOperator; 2226 2227 bool CanAnalyze = 2228 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2229 (void)CanAnalyze; 2230 assert(CanAnalyze && "don't call from other places!"); 2231 2232 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2233 SCEV::NoWrapFlags SignOrUnsignWrap = 2234 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2235 2236 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2237 auto IsKnownNonNegative = [&](const SCEV *S) { 2238 return SE->isKnownNonNegative(S); 2239 }; 2240 2241 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2242 Flags = 2243 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2244 2245 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2246 2247 if (SignOrUnsignWrap != SignOrUnsignMask && 2248 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2249 isa<SCEVConstant>(Ops[0])) { 2250 2251 auto Opcode = [&] { 2252 switch (Type) { 2253 case scAddExpr: 2254 return Instruction::Add; 2255 case scMulExpr: 2256 return Instruction::Mul; 2257 default: 2258 llvm_unreachable("Unexpected SCEV op."); 2259 } 2260 }(); 2261 2262 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2263 2264 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2265 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2266 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2267 Opcode, C, OBO::NoSignedWrap); 2268 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2269 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2270 } 2271 2272 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2273 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2274 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2275 Opcode, C, OBO::NoUnsignedWrap); 2276 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2277 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2278 } 2279 } 2280 2281 return Flags; 2282 } 2283 2284 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2285 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2286 } 2287 2288 /// Get a canonical add expression, or something simpler if possible. 2289 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2290 SCEV::NoWrapFlags Flags, 2291 unsigned Depth) { 2292 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2293 "only nuw or nsw allowed"); 2294 assert(!Ops.empty() && "Cannot get empty add!"); 2295 if (Ops.size() == 1) return Ops[0]; 2296 #ifndef NDEBUG 2297 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2298 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2299 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2300 "SCEVAddExpr operand types don't match!"); 2301 #endif 2302 2303 // Sort by complexity, this groups all similar expression types together. 2304 GroupByComplexity(Ops, &LI, DT); 2305 2306 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2307 2308 // If there are any constants, fold them together. 2309 unsigned Idx = 0; 2310 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2311 ++Idx; 2312 assert(Idx < Ops.size()); 2313 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2314 // We found two constants, fold them together! 2315 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2316 if (Ops.size() == 2) return Ops[0]; 2317 Ops.erase(Ops.begin()+1); // Erase the folded element 2318 LHSC = cast<SCEVConstant>(Ops[0]); 2319 } 2320 2321 // If we are left with a constant zero being added, strip it off. 2322 if (LHSC->getValue()->isZero()) { 2323 Ops.erase(Ops.begin()); 2324 --Idx; 2325 } 2326 2327 if (Ops.size() == 1) return Ops[0]; 2328 } 2329 2330 // Limit recursion calls depth. 2331 if (Depth > MaxArithDepth) 2332 return getOrCreateAddExpr(Ops, Flags); 2333 2334 // Okay, check to see if the same value occurs in the operand list more than 2335 // once. If so, merge them together into an multiply expression. Since we 2336 // sorted the list, these values are required to be adjacent. 2337 Type *Ty = Ops[0]->getType(); 2338 bool FoundMatch = false; 2339 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2340 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2341 // Scan ahead to count how many equal operands there are. 2342 unsigned Count = 2; 2343 while (i+Count != e && Ops[i+Count] == Ops[i]) 2344 ++Count; 2345 // Merge the values into a multiply. 2346 const SCEV *Scale = getConstant(Ty, Count); 2347 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2348 if (Ops.size() == Count) 2349 return Mul; 2350 Ops[i] = Mul; 2351 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2352 --i; e -= Count - 1; 2353 FoundMatch = true; 2354 } 2355 if (FoundMatch) 2356 return getAddExpr(Ops, Flags, Depth + 1); 2357 2358 // Check for truncates. If all the operands are truncated from the same 2359 // type, see if factoring out the truncate would permit the result to be 2360 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2361 // if the contents of the resulting outer trunc fold to something simple. 2362 auto FindTruncSrcType = [&]() -> Type * { 2363 // We're ultimately looking to fold an addrec of truncs and muls of only 2364 // constants and truncs, so if we find any other types of SCEV 2365 // as operands of the addrec then we bail and return nullptr here. 2366 // Otherwise, we return the type of the operand of a trunc that we find. 2367 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2368 return T->getOperand()->getType(); 2369 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2370 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2371 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2372 return T->getOperand()->getType(); 2373 } 2374 return nullptr; 2375 }; 2376 if (auto *SrcType = FindTruncSrcType()) { 2377 SmallVector<const SCEV *, 8> LargeOps; 2378 bool Ok = true; 2379 // Check all the operands to see if they can be represented in the 2380 // source type of the truncate. 2381 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2382 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2383 if (T->getOperand()->getType() != SrcType) { 2384 Ok = false; 2385 break; 2386 } 2387 LargeOps.push_back(T->getOperand()); 2388 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2389 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2390 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2391 SmallVector<const SCEV *, 8> LargeMulOps; 2392 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2393 if (const SCEVTruncateExpr *T = 2394 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2395 if (T->getOperand()->getType() != SrcType) { 2396 Ok = false; 2397 break; 2398 } 2399 LargeMulOps.push_back(T->getOperand()); 2400 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2401 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2402 } else { 2403 Ok = false; 2404 break; 2405 } 2406 } 2407 if (Ok) 2408 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2409 } else { 2410 Ok = false; 2411 break; 2412 } 2413 } 2414 if (Ok) { 2415 // Evaluate the expression in the larger type. 2416 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2417 // If it folds to something simple, use it. Otherwise, don't. 2418 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2419 return getTruncateExpr(Fold, Ty); 2420 } 2421 } 2422 2423 // Skip past any other cast SCEVs. 2424 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2425 ++Idx; 2426 2427 // If there are add operands they would be next. 2428 if (Idx < Ops.size()) { 2429 bool DeletedAdd = false; 2430 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2431 if (Ops.size() > AddOpsInlineThreshold || 2432 Add->getNumOperands() > AddOpsInlineThreshold) 2433 break; 2434 // If we have an add, expand the add operands onto the end of the operands 2435 // list. 2436 Ops.erase(Ops.begin()+Idx); 2437 Ops.append(Add->op_begin(), Add->op_end()); 2438 DeletedAdd = true; 2439 } 2440 2441 // If we deleted at least one add, we added operands to the end of the list, 2442 // and they are not necessarily sorted. Recurse to resort and resimplify 2443 // any operands we just acquired. 2444 if (DeletedAdd) 2445 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2446 } 2447 2448 // Skip over the add expression until we get to a multiply. 2449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2450 ++Idx; 2451 2452 // Check to see if there are any folding opportunities present with 2453 // operands multiplied by constant values. 2454 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2455 uint64_t BitWidth = getTypeSizeInBits(Ty); 2456 DenseMap<const SCEV *, APInt> M; 2457 SmallVector<const SCEV *, 8> NewOps; 2458 APInt AccumulatedConstant(BitWidth, 0); 2459 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2460 Ops.data(), Ops.size(), 2461 APInt(BitWidth, 1), *this)) { 2462 struct APIntCompare { 2463 bool operator()(const APInt &LHS, const APInt &RHS) const { 2464 return LHS.ult(RHS); 2465 } 2466 }; 2467 2468 // Some interesting folding opportunity is present, so its worthwhile to 2469 // re-generate the operands list. Group the operands by constant scale, 2470 // to avoid multiplying by the same constant scale multiple times. 2471 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2472 for (const SCEV *NewOp : NewOps) 2473 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2474 // Re-generate the operands list. 2475 Ops.clear(); 2476 if (AccumulatedConstant != 0) 2477 Ops.push_back(getConstant(AccumulatedConstant)); 2478 for (auto &MulOp : MulOpLists) 2479 if (MulOp.first != 0) 2480 Ops.push_back(getMulExpr( 2481 getConstant(MulOp.first), 2482 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2483 SCEV::FlagAnyWrap, Depth + 1)); 2484 if (Ops.empty()) 2485 return getZero(Ty); 2486 if (Ops.size() == 1) 2487 return Ops[0]; 2488 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2489 } 2490 } 2491 2492 // If we are adding something to a multiply expression, make sure the 2493 // something is not already an operand of the multiply. If so, merge it into 2494 // the multiply. 2495 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2496 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2497 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2498 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2499 if (isa<SCEVConstant>(MulOpSCEV)) 2500 continue; 2501 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2502 if (MulOpSCEV == Ops[AddOp]) { 2503 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2504 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2505 if (Mul->getNumOperands() != 2) { 2506 // If the multiply has more than two operands, we must get the 2507 // Y*Z term. 2508 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2509 Mul->op_begin()+MulOp); 2510 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2511 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2512 } 2513 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2514 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2515 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2516 SCEV::FlagAnyWrap, Depth + 1); 2517 if (Ops.size() == 2) return OuterMul; 2518 if (AddOp < Idx) { 2519 Ops.erase(Ops.begin()+AddOp); 2520 Ops.erase(Ops.begin()+Idx-1); 2521 } else { 2522 Ops.erase(Ops.begin()+Idx); 2523 Ops.erase(Ops.begin()+AddOp-1); 2524 } 2525 Ops.push_back(OuterMul); 2526 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2527 } 2528 2529 // Check this multiply against other multiplies being added together. 2530 for (unsigned OtherMulIdx = Idx+1; 2531 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2532 ++OtherMulIdx) { 2533 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2534 // If MulOp occurs in OtherMul, we can fold the two multiplies 2535 // together. 2536 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2537 OMulOp != e; ++OMulOp) 2538 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2539 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2540 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2541 if (Mul->getNumOperands() != 2) { 2542 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2543 Mul->op_begin()+MulOp); 2544 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2545 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2546 } 2547 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2548 if (OtherMul->getNumOperands() != 2) { 2549 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2550 OtherMul->op_begin()+OMulOp); 2551 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2552 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2553 } 2554 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2555 const SCEV *InnerMulSum = 2556 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2557 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2558 SCEV::FlagAnyWrap, Depth + 1); 2559 if (Ops.size() == 2) return OuterMul; 2560 Ops.erase(Ops.begin()+Idx); 2561 Ops.erase(Ops.begin()+OtherMulIdx-1); 2562 Ops.push_back(OuterMul); 2563 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2564 } 2565 } 2566 } 2567 } 2568 2569 // If there are any add recurrences in the operands list, see if any other 2570 // added values are loop invariant. If so, we can fold them into the 2571 // recurrence. 2572 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2573 ++Idx; 2574 2575 // Scan over all recurrences, trying to fold loop invariants into them. 2576 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2577 // Scan all of the other operands to this add and add them to the vector if 2578 // they are loop invariant w.r.t. the recurrence. 2579 SmallVector<const SCEV *, 8> LIOps; 2580 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2581 const Loop *AddRecLoop = AddRec->getLoop(); 2582 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2583 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2584 LIOps.push_back(Ops[i]); 2585 Ops.erase(Ops.begin()+i); 2586 --i; --e; 2587 } 2588 2589 // If we found some loop invariants, fold them into the recurrence. 2590 if (!LIOps.empty()) { 2591 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2592 LIOps.push_back(AddRec->getStart()); 2593 2594 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2595 AddRec->op_end()); 2596 // This follows from the fact that the no-wrap flags on the outer add 2597 // expression are applicable on the 0th iteration, when the add recurrence 2598 // will be equal to its start value. 2599 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2600 2601 // Build the new addrec. Propagate the NUW and NSW flags if both the 2602 // outer add and the inner addrec are guaranteed to have no overflow. 2603 // Always propagate NW. 2604 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2605 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2606 2607 // If all of the other operands were loop invariant, we are done. 2608 if (Ops.size() == 1) return NewRec; 2609 2610 // Otherwise, add the folded AddRec by the non-invariant parts. 2611 for (unsigned i = 0;; ++i) 2612 if (Ops[i] == AddRec) { 2613 Ops[i] = NewRec; 2614 break; 2615 } 2616 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2617 } 2618 2619 // Okay, if there weren't any loop invariants to be folded, check to see if 2620 // there are multiple AddRec's with the same loop induction variable being 2621 // added together. If so, we can fold them. 2622 for (unsigned OtherIdx = Idx+1; 2623 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2624 ++OtherIdx) { 2625 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2626 // so that the 1st found AddRecExpr is dominated by all others. 2627 assert(DT.dominates( 2628 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2629 AddRec->getLoop()->getHeader()) && 2630 "AddRecExprs are not sorted in reverse dominance order?"); 2631 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2632 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2633 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2634 AddRec->op_end()); 2635 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2636 ++OtherIdx) { 2637 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2638 if (OtherAddRec->getLoop() == AddRecLoop) { 2639 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2640 i != e; ++i) { 2641 if (i >= AddRecOps.size()) { 2642 AddRecOps.append(OtherAddRec->op_begin()+i, 2643 OtherAddRec->op_end()); 2644 break; 2645 } 2646 SmallVector<const SCEV *, 2> TwoOps = { 2647 AddRecOps[i], OtherAddRec->getOperand(i)}; 2648 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2649 } 2650 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2651 } 2652 } 2653 // Step size has changed, so we cannot guarantee no self-wraparound. 2654 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2655 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2656 } 2657 } 2658 2659 // Otherwise couldn't fold anything into this recurrence. Move onto the 2660 // next one. 2661 } 2662 2663 // Okay, it looks like we really DO need an add expr. Check to see if we 2664 // already have one, otherwise create a new one. 2665 return getOrCreateAddExpr(Ops, Flags); 2666 } 2667 2668 const SCEV * 2669 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2670 SCEV::NoWrapFlags Flags) { 2671 FoldingSetNodeID ID; 2672 ID.AddInteger(scAddExpr); 2673 for (const SCEV *Op : Ops) 2674 ID.AddPointer(Op); 2675 void *IP = nullptr; 2676 SCEVAddExpr *S = 2677 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2678 if (!S) { 2679 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2680 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2681 S = new (SCEVAllocator) 2682 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2683 UniqueSCEVs.InsertNode(S, IP); 2684 addToLoopUseLists(S); 2685 } 2686 S->setNoWrapFlags(Flags); 2687 return S; 2688 } 2689 2690 const SCEV * 2691 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2692 SCEV::NoWrapFlags Flags) { 2693 FoldingSetNodeID ID; 2694 ID.AddInteger(scMulExpr); 2695 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2696 ID.AddPointer(Ops[i]); 2697 void *IP = nullptr; 2698 SCEVMulExpr *S = 2699 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2700 if (!S) { 2701 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2702 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2703 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2704 O, Ops.size()); 2705 UniqueSCEVs.InsertNode(S, IP); 2706 addToLoopUseLists(S); 2707 } 2708 S->setNoWrapFlags(Flags); 2709 return S; 2710 } 2711 2712 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2713 uint64_t k = i*j; 2714 if (j > 1 && k / j != i) Overflow = true; 2715 return k; 2716 } 2717 2718 /// Compute the result of "n choose k", the binomial coefficient. If an 2719 /// intermediate computation overflows, Overflow will be set and the return will 2720 /// be garbage. Overflow is not cleared on absence of overflow. 2721 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2722 // We use the multiplicative formula: 2723 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2724 // At each iteration, we take the n-th term of the numeral and divide by the 2725 // (k-n)th term of the denominator. This division will always produce an 2726 // integral result, and helps reduce the chance of overflow in the 2727 // intermediate computations. However, we can still overflow even when the 2728 // final result would fit. 2729 2730 if (n == 0 || n == k) return 1; 2731 if (k > n) return 0; 2732 2733 if (k > n/2) 2734 k = n-k; 2735 2736 uint64_t r = 1; 2737 for (uint64_t i = 1; i <= k; ++i) { 2738 r = umul_ov(r, n-(i-1), Overflow); 2739 r /= i; 2740 } 2741 return r; 2742 } 2743 2744 /// Determine if any of the operands in this SCEV are a constant or if 2745 /// any of the add or multiply expressions in this SCEV contain a constant. 2746 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2747 struct FindConstantInAddMulChain { 2748 bool FoundConstant = false; 2749 2750 bool follow(const SCEV *S) { 2751 FoundConstant |= isa<SCEVConstant>(S); 2752 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2753 } 2754 2755 bool isDone() const { 2756 return FoundConstant; 2757 } 2758 }; 2759 2760 FindConstantInAddMulChain F; 2761 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2762 ST.visitAll(StartExpr); 2763 return F.FoundConstant; 2764 } 2765 2766 /// Get a canonical multiply expression, or something simpler if possible. 2767 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2768 SCEV::NoWrapFlags Flags, 2769 unsigned Depth) { 2770 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2771 "only nuw or nsw allowed"); 2772 assert(!Ops.empty() && "Cannot get empty mul!"); 2773 if (Ops.size() == 1) return Ops[0]; 2774 #ifndef NDEBUG 2775 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2776 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2777 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2778 "SCEVMulExpr operand types don't match!"); 2779 #endif 2780 2781 // Sort by complexity, this groups all similar expression types together. 2782 GroupByComplexity(Ops, &LI, DT); 2783 2784 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2785 2786 // Limit recursion calls depth. 2787 if (Depth > MaxArithDepth) 2788 return getOrCreateMulExpr(Ops, Flags); 2789 2790 // If there are any constants, fold them together. 2791 unsigned Idx = 0; 2792 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2793 2794 if (Ops.size() == 2) 2795 // C1*(C2+V) -> C1*C2 + C1*V 2796 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2797 // If any of Add's ops are Adds or Muls with a constant, apply this 2798 // transformation as well. 2799 // 2800 // TODO: There are some cases where this transformation is not 2801 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2802 // this transformation should be narrowed down. 2803 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2804 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2805 SCEV::FlagAnyWrap, Depth + 1), 2806 getMulExpr(LHSC, Add->getOperand(1), 2807 SCEV::FlagAnyWrap, Depth + 1), 2808 SCEV::FlagAnyWrap, Depth + 1); 2809 2810 ++Idx; 2811 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2812 // We found two constants, fold them together! 2813 ConstantInt *Fold = 2814 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2815 Ops[0] = getConstant(Fold); 2816 Ops.erase(Ops.begin()+1); // Erase the folded element 2817 if (Ops.size() == 1) return Ops[0]; 2818 LHSC = cast<SCEVConstant>(Ops[0]); 2819 } 2820 2821 // If we are left with a constant one being multiplied, strip it off. 2822 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2823 Ops.erase(Ops.begin()); 2824 --Idx; 2825 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2826 // If we have a multiply of zero, it will always be zero. 2827 return Ops[0]; 2828 } else if (Ops[0]->isAllOnesValue()) { 2829 // If we have a mul by -1 of an add, try distributing the -1 among the 2830 // add operands. 2831 if (Ops.size() == 2) { 2832 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2833 SmallVector<const SCEV *, 4> NewOps; 2834 bool AnyFolded = false; 2835 for (const SCEV *AddOp : Add->operands()) { 2836 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2837 Depth + 1); 2838 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2839 NewOps.push_back(Mul); 2840 } 2841 if (AnyFolded) 2842 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2843 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2844 // Negation preserves a recurrence's no self-wrap property. 2845 SmallVector<const SCEV *, 4> Operands; 2846 for (const SCEV *AddRecOp : AddRec->operands()) 2847 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2848 Depth + 1)); 2849 2850 return getAddRecExpr(Operands, AddRec->getLoop(), 2851 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2852 } 2853 } 2854 } 2855 2856 if (Ops.size() == 1) 2857 return Ops[0]; 2858 } 2859 2860 // Skip over the add expression until we get to a multiply. 2861 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2862 ++Idx; 2863 2864 // If there are mul operands inline them all into this expression. 2865 if (Idx < Ops.size()) { 2866 bool DeletedMul = false; 2867 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2868 if (Ops.size() > MulOpsInlineThreshold) 2869 break; 2870 // If we have an mul, expand the mul operands onto the end of the 2871 // operands list. 2872 Ops.erase(Ops.begin()+Idx); 2873 Ops.append(Mul->op_begin(), Mul->op_end()); 2874 DeletedMul = true; 2875 } 2876 2877 // If we deleted at least one mul, we added operands to the end of the 2878 // list, and they are not necessarily sorted. Recurse to resort and 2879 // resimplify any operands we just acquired. 2880 if (DeletedMul) 2881 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2882 } 2883 2884 // If there are any add recurrences in the operands list, see if any other 2885 // added values are loop invariant. If so, we can fold them into the 2886 // recurrence. 2887 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2888 ++Idx; 2889 2890 // Scan over all recurrences, trying to fold loop invariants into them. 2891 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2892 // Scan all of the other operands to this mul and add them to the vector 2893 // if they are loop invariant w.r.t. the recurrence. 2894 SmallVector<const SCEV *, 8> LIOps; 2895 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2896 const Loop *AddRecLoop = AddRec->getLoop(); 2897 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2898 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2899 LIOps.push_back(Ops[i]); 2900 Ops.erase(Ops.begin()+i); 2901 --i; --e; 2902 } 2903 2904 // If we found some loop invariants, fold them into the recurrence. 2905 if (!LIOps.empty()) { 2906 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2907 SmallVector<const SCEV *, 4> NewOps; 2908 NewOps.reserve(AddRec->getNumOperands()); 2909 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2910 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2911 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2912 SCEV::FlagAnyWrap, Depth + 1)); 2913 2914 // Build the new addrec. Propagate the NUW and NSW flags if both the 2915 // outer mul and the inner addrec are guaranteed to have no overflow. 2916 // 2917 // No self-wrap cannot be guaranteed after changing the step size, but 2918 // will be inferred if either NUW or NSW is true. 2919 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2920 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2921 2922 // If all of the other operands were loop invariant, we are done. 2923 if (Ops.size() == 1) return NewRec; 2924 2925 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2926 for (unsigned i = 0;; ++i) 2927 if (Ops[i] == AddRec) { 2928 Ops[i] = NewRec; 2929 break; 2930 } 2931 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2932 } 2933 2934 // Okay, if there weren't any loop invariants to be folded, check to see 2935 // if there are multiple AddRec's with the same loop induction variable 2936 // being multiplied together. If so, we can fold them. 2937 2938 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2939 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2940 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2941 // ]]],+,...up to x=2n}. 2942 // Note that the arguments to choose() are always integers with values 2943 // known at compile time, never SCEV objects. 2944 // 2945 // The implementation avoids pointless extra computations when the two 2946 // addrec's are of different length (mathematically, it's equivalent to 2947 // an infinite stream of zeros on the right). 2948 bool OpsModified = false; 2949 for (unsigned OtherIdx = Idx+1; 2950 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2951 ++OtherIdx) { 2952 const SCEVAddRecExpr *OtherAddRec = 2953 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2954 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2955 continue; 2956 2957 // Limit max number of arguments to avoid creation of unreasonably big 2958 // SCEVAddRecs with very complex operands. 2959 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2960 MaxAddRecSize) 2961 continue; 2962 2963 bool Overflow = false; 2964 Type *Ty = AddRec->getType(); 2965 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2966 SmallVector<const SCEV*, 7> AddRecOps; 2967 for (int x = 0, xe = AddRec->getNumOperands() + 2968 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2969 const SCEV *Term = getZero(Ty); 2970 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2971 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2972 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2973 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2974 z < ze && !Overflow; ++z) { 2975 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2976 uint64_t Coeff; 2977 if (LargerThan64Bits) 2978 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2979 else 2980 Coeff = Coeff1*Coeff2; 2981 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2982 const SCEV *Term1 = AddRec->getOperand(y-z); 2983 const SCEV *Term2 = OtherAddRec->getOperand(z); 2984 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2985 SCEV::FlagAnyWrap, Depth + 1), 2986 SCEV::FlagAnyWrap, Depth + 1); 2987 } 2988 } 2989 AddRecOps.push_back(Term); 2990 } 2991 if (!Overflow) { 2992 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2993 SCEV::FlagAnyWrap); 2994 if (Ops.size() == 2) return NewAddRec; 2995 Ops[Idx] = NewAddRec; 2996 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2997 OpsModified = true; 2998 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2999 if (!AddRec) 3000 break; 3001 } 3002 } 3003 if (OpsModified) 3004 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3005 3006 // Otherwise couldn't fold anything into this recurrence. Move onto the 3007 // next one. 3008 } 3009 3010 // Okay, it looks like we really DO need an mul expr. Check to see if we 3011 // already have one, otherwise create a new one. 3012 return getOrCreateMulExpr(Ops, Flags); 3013 } 3014 3015 /// Represents an unsigned remainder expression based on unsigned division. 3016 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3017 const SCEV *RHS) { 3018 assert(getEffectiveSCEVType(LHS->getType()) == 3019 getEffectiveSCEVType(RHS->getType()) && 3020 "SCEVURemExpr operand types don't match!"); 3021 3022 // Short-circuit easy cases 3023 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3024 // If constant is one, the result is trivial 3025 if (RHSC->getValue()->isOne()) 3026 return getZero(LHS->getType()); // X urem 1 --> 0 3027 3028 // If constant is a power of two, fold into a zext(trunc(LHS)). 3029 if (RHSC->getAPInt().isPowerOf2()) { 3030 Type *FullTy = LHS->getType(); 3031 Type *TruncTy = 3032 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3033 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3034 } 3035 } 3036 3037 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3038 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3039 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3040 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3041 } 3042 3043 /// Get a canonical unsigned division expression, or something simpler if 3044 /// possible. 3045 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3046 const SCEV *RHS) { 3047 assert(getEffectiveSCEVType(LHS->getType()) == 3048 getEffectiveSCEVType(RHS->getType()) && 3049 "SCEVUDivExpr operand types don't match!"); 3050 3051 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3052 if (RHSC->getValue()->isOne()) 3053 return LHS; // X udiv 1 --> x 3054 // If the denominator is zero, the result of the udiv is undefined. Don't 3055 // try to analyze it, because the resolution chosen here may differ from 3056 // the resolution chosen in other parts of the compiler. 3057 if (!RHSC->getValue()->isZero()) { 3058 // Determine if the division can be folded into the operands of 3059 // its operands. 3060 // TODO: Generalize this to non-constants by using known-bits information. 3061 Type *Ty = LHS->getType(); 3062 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3063 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3064 // For non-power-of-two values, effectively round the value up to the 3065 // nearest power of two. 3066 if (!RHSC->getAPInt().isPowerOf2()) 3067 ++MaxShiftAmt; 3068 IntegerType *ExtTy = 3069 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3070 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3071 if (const SCEVConstant *Step = 3072 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3073 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3074 const APInt &StepInt = Step->getAPInt(); 3075 const APInt &DivInt = RHSC->getAPInt(); 3076 if (!StepInt.urem(DivInt) && 3077 getZeroExtendExpr(AR, ExtTy) == 3078 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3079 getZeroExtendExpr(Step, ExtTy), 3080 AR->getLoop(), SCEV::FlagAnyWrap)) { 3081 SmallVector<const SCEV *, 4> Operands; 3082 for (const SCEV *Op : AR->operands()) 3083 Operands.push_back(getUDivExpr(Op, RHS)); 3084 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3085 } 3086 /// Get a canonical UDivExpr for a recurrence. 3087 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3088 // We can currently only fold X%N if X is constant. 3089 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3090 if (StartC && !DivInt.urem(StepInt) && 3091 getZeroExtendExpr(AR, ExtTy) == 3092 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3093 getZeroExtendExpr(Step, ExtTy), 3094 AR->getLoop(), SCEV::FlagAnyWrap)) { 3095 const APInt &StartInt = StartC->getAPInt(); 3096 const APInt &StartRem = StartInt.urem(StepInt); 3097 if (StartRem != 0) 3098 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3099 AR->getLoop(), SCEV::FlagNW); 3100 } 3101 } 3102 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3103 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3104 SmallVector<const SCEV *, 4> Operands; 3105 for (const SCEV *Op : M->operands()) 3106 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3107 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3108 // Find an operand that's safely divisible. 3109 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3110 const SCEV *Op = M->getOperand(i); 3111 const SCEV *Div = getUDivExpr(Op, RHSC); 3112 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3113 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3114 M->op_end()); 3115 Operands[i] = Div; 3116 return getMulExpr(Operands); 3117 } 3118 } 3119 } 3120 3121 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3122 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3123 if (auto *DivisorConstant = 3124 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3125 bool Overflow = false; 3126 APInt NewRHS = 3127 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3128 if (Overflow) { 3129 return getConstant(RHSC->getType(), 0, false); 3130 } 3131 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3132 } 3133 } 3134 3135 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3136 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3137 SmallVector<const SCEV *, 4> Operands; 3138 for (const SCEV *Op : A->operands()) 3139 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3140 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3141 Operands.clear(); 3142 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3143 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3144 if (isa<SCEVUDivExpr>(Op) || 3145 getMulExpr(Op, RHS) != A->getOperand(i)) 3146 break; 3147 Operands.push_back(Op); 3148 } 3149 if (Operands.size() == A->getNumOperands()) 3150 return getAddExpr(Operands); 3151 } 3152 } 3153 3154 // Fold if both operands are constant. 3155 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3156 Constant *LHSCV = LHSC->getValue(); 3157 Constant *RHSCV = RHSC->getValue(); 3158 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3159 RHSCV))); 3160 } 3161 } 3162 } 3163 3164 FoldingSetNodeID ID; 3165 ID.AddInteger(scUDivExpr); 3166 ID.AddPointer(LHS); 3167 ID.AddPointer(RHS); 3168 void *IP = nullptr; 3169 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3170 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3171 LHS, RHS); 3172 UniqueSCEVs.InsertNode(S, IP); 3173 addToLoopUseLists(S); 3174 return S; 3175 } 3176 3177 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3178 APInt A = C1->getAPInt().abs(); 3179 APInt B = C2->getAPInt().abs(); 3180 uint32_t ABW = A.getBitWidth(); 3181 uint32_t BBW = B.getBitWidth(); 3182 3183 if (ABW > BBW) 3184 B = B.zext(ABW); 3185 else if (ABW < BBW) 3186 A = A.zext(BBW); 3187 3188 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3189 } 3190 3191 /// Get a canonical unsigned division expression, or something simpler if 3192 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3193 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3194 /// it's not exact because the udiv may be clearing bits. 3195 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3196 const SCEV *RHS) { 3197 // TODO: we could try to find factors in all sorts of things, but for now we 3198 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3199 // end of this file for inspiration. 3200 3201 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3202 if (!Mul || !Mul->hasNoUnsignedWrap()) 3203 return getUDivExpr(LHS, RHS); 3204 3205 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3206 // If the mulexpr multiplies by a constant, then that constant must be the 3207 // first element of the mulexpr. 3208 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3209 if (LHSCst == RHSCst) { 3210 SmallVector<const SCEV *, 2> Operands; 3211 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3212 return getMulExpr(Operands); 3213 } 3214 3215 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3216 // that there's a factor provided by one of the other terms. We need to 3217 // check. 3218 APInt Factor = gcd(LHSCst, RHSCst); 3219 if (!Factor.isIntN(1)) { 3220 LHSCst = 3221 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3222 RHSCst = 3223 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3224 SmallVector<const SCEV *, 2> Operands; 3225 Operands.push_back(LHSCst); 3226 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3227 LHS = getMulExpr(Operands); 3228 RHS = RHSCst; 3229 Mul = dyn_cast<SCEVMulExpr>(LHS); 3230 if (!Mul) 3231 return getUDivExactExpr(LHS, RHS); 3232 } 3233 } 3234 } 3235 3236 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3237 if (Mul->getOperand(i) == RHS) { 3238 SmallVector<const SCEV *, 2> Operands; 3239 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3240 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3241 return getMulExpr(Operands); 3242 } 3243 } 3244 3245 return getUDivExpr(LHS, RHS); 3246 } 3247 3248 /// Get an add recurrence expression for the specified loop. Simplify the 3249 /// expression as much as possible. 3250 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3251 const Loop *L, 3252 SCEV::NoWrapFlags Flags) { 3253 SmallVector<const SCEV *, 4> Operands; 3254 Operands.push_back(Start); 3255 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3256 if (StepChrec->getLoop() == L) { 3257 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3258 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3259 } 3260 3261 Operands.push_back(Step); 3262 return getAddRecExpr(Operands, L, Flags); 3263 } 3264 3265 /// Get an add recurrence expression for the specified loop. Simplify the 3266 /// expression as much as possible. 3267 const SCEV * 3268 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3269 const Loop *L, SCEV::NoWrapFlags Flags) { 3270 if (Operands.size() == 1) return Operands[0]; 3271 #ifndef NDEBUG 3272 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3273 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3274 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3275 "SCEVAddRecExpr operand types don't match!"); 3276 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3277 assert(isLoopInvariant(Operands[i], L) && 3278 "SCEVAddRecExpr operand is not loop-invariant!"); 3279 #endif 3280 3281 if (Operands.back()->isZero()) { 3282 Operands.pop_back(); 3283 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3284 } 3285 3286 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3287 // use that information to infer NUW and NSW flags. However, computing a 3288 // BE count requires calling getAddRecExpr, so we may not yet have a 3289 // meaningful BE count at this point (and if we don't, we'd be stuck 3290 // with a SCEVCouldNotCompute as the cached BE count). 3291 3292 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3293 3294 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3295 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3296 const Loop *NestedLoop = NestedAR->getLoop(); 3297 if (L->contains(NestedLoop) 3298 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3299 : (!NestedLoop->contains(L) && 3300 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3301 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3302 NestedAR->op_end()); 3303 Operands[0] = NestedAR->getStart(); 3304 // AddRecs require their operands be loop-invariant with respect to their 3305 // loops. Don't perform this transformation if it would break this 3306 // requirement. 3307 bool AllInvariant = all_of( 3308 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3309 3310 if (AllInvariant) { 3311 // Create a recurrence for the outer loop with the same step size. 3312 // 3313 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3314 // inner recurrence has the same property. 3315 SCEV::NoWrapFlags OuterFlags = 3316 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3317 3318 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3319 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3320 return isLoopInvariant(Op, NestedLoop); 3321 }); 3322 3323 if (AllInvariant) { 3324 // Ok, both add recurrences are valid after the transformation. 3325 // 3326 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3327 // the outer recurrence has the same property. 3328 SCEV::NoWrapFlags InnerFlags = 3329 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3330 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3331 } 3332 } 3333 // Reset Operands to its original state. 3334 Operands[0] = NestedAR; 3335 } 3336 } 3337 3338 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3339 // already have one, otherwise create a new one. 3340 FoldingSetNodeID ID; 3341 ID.AddInteger(scAddRecExpr); 3342 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3343 ID.AddPointer(Operands[i]); 3344 ID.AddPointer(L); 3345 void *IP = nullptr; 3346 SCEVAddRecExpr *S = 3347 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3348 if (!S) { 3349 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3350 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3351 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3352 O, Operands.size(), L); 3353 UniqueSCEVs.InsertNode(S, IP); 3354 addToLoopUseLists(S); 3355 } 3356 S->setNoWrapFlags(Flags); 3357 return S; 3358 } 3359 3360 const SCEV * 3361 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3362 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3363 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3364 // getSCEV(Base)->getType() has the same address space as Base->getType() 3365 // because SCEV::getType() preserves the address space. 3366 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3367 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3368 // instruction to its SCEV, because the Instruction may be guarded by control 3369 // flow and the no-overflow bits may not be valid for the expression in any 3370 // context. This can be fixed similarly to how these flags are handled for 3371 // adds. 3372 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3373 : SCEV::FlagAnyWrap; 3374 3375 const SCEV *TotalOffset = getZero(IntPtrTy); 3376 // The array size is unimportant. The first thing we do on CurTy is getting 3377 // its element type. 3378 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3379 for (const SCEV *IndexExpr : IndexExprs) { 3380 // Compute the (potentially symbolic) offset in bytes for this index. 3381 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3382 // For a struct, add the member offset. 3383 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3384 unsigned FieldNo = Index->getZExtValue(); 3385 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3386 3387 // Add the field offset to the running total offset. 3388 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3389 3390 // Update CurTy to the type of the field at Index. 3391 CurTy = STy->getTypeAtIndex(Index); 3392 } else { 3393 // Update CurTy to its element type. 3394 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3395 // For an array, add the element offset, explicitly scaled. 3396 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3397 // Getelementptr indices are signed. 3398 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3399 3400 // Multiply the index by the element size to compute the element offset. 3401 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3402 3403 // Add the element offset to the running total offset. 3404 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3405 } 3406 } 3407 3408 // Add the total offset from all the GEP indices to the base. 3409 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3410 } 3411 3412 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3413 const SCEV *RHS) { 3414 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3415 return getSMaxExpr(Ops); 3416 } 3417 3418 const SCEV * 3419 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3420 assert(!Ops.empty() && "Cannot get empty smax!"); 3421 if (Ops.size() == 1) return Ops[0]; 3422 #ifndef NDEBUG 3423 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3424 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3425 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3426 "SCEVSMaxExpr operand types don't match!"); 3427 #endif 3428 3429 // Sort by complexity, this groups all similar expression types together. 3430 GroupByComplexity(Ops, &LI, DT); 3431 3432 // If there are any constants, fold them together. 3433 unsigned Idx = 0; 3434 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3435 ++Idx; 3436 assert(Idx < Ops.size()); 3437 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3438 // We found two constants, fold them together! 3439 ConstantInt *Fold = ConstantInt::get( 3440 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3441 Ops[0] = getConstant(Fold); 3442 Ops.erase(Ops.begin()+1); // Erase the folded element 3443 if (Ops.size() == 1) return Ops[0]; 3444 LHSC = cast<SCEVConstant>(Ops[0]); 3445 } 3446 3447 // If we are left with a constant minimum-int, strip it off. 3448 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3449 Ops.erase(Ops.begin()); 3450 --Idx; 3451 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3452 // If we have an smax with a constant maximum-int, it will always be 3453 // maximum-int. 3454 return Ops[0]; 3455 } 3456 3457 if (Ops.size() == 1) return Ops[0]; 3458 } 3459 3460 // Find the first SMax 3461 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3462 ++Idx; 3463 3464 // Check to see if one of the operands is an SMax. If so, expand its operands 3465 // onto our operand list, and recurse to simplify. 3466 if (Idx < Ops.size()) { 3467 bool DeletedSMax = false; 3468 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3469 Ops.erase(Ops.begin()+Idx); 3470 Ops.append(SMax->op_begin(), SMax->op_end()); 3471 DeletedSMax = true; 3472 } 3473 3474 if (DeletedSMax) 3475 return getSMaxExpr(Ops); 3476 } 3477 3478 // Okay, check to see if the same value occurs in the operand list twice. If 3479 // so, delete one. Since we sorted the list, these values are required to 3480 // be adjacent. 3481 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3482 // X smax Y smax Y --> X smax Y 3483 // X smax Y --> X, if X is always greater than Y 3484 if (Ops[i] == Ops[i+1] || 3485 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3486 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3487 --i; --e; 3488 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3489 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3490 --i; --e; 3491 } 3492 3493 if (Ops.size() == 1) return Ops[0]; 3494 3495 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3496 3497 // Okay, it looks like we really DO need an smax expr. Check to see if we 3498 // already have one, otherwise create a new one. 3499 FoldingSetNodeID ID; 3500 ID.AddInteger(scSMaxExpr); 3501 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3502 ID.AddPointer(Ops[i]); 3503 void *IP = nullptr; 3504 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3505 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3506 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3507 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3508 O, Ops.size()); 3509 UniqueSCEVs.InsertNode(S, IP); 3510 addToLoopUseLists(S); 3511 return S; 3512 } 3513 3514 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3515 const SCEV *RHS) { 3516 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3517 return getUMaxExpr(Ops); 3518 } 3519 3520 const SCEV * 3521 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3522 assert(!Ops.empty() && "Cannot get empty umax!"); 3523 if (Ops.size() == 1) return Ops[0]; 3524 #ifndef NDEBUG 3525 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3526 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3527 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3528 "SCEVUMaxExpr operand types don't match!"); 3529 #endif 3530 3531 // Sort by complexity, this groups all similar expression types together. 3532 GroupByComplexity(Ops, &LI, DT); 3533 3534 // If there are any constants, fold them together. 3535 unsigned Idx = 0; 3536 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3537 ++Idx; 3538 assert(Idx < Ops.size()); 3539 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3540 // We found two constants, fold them together! 3541 ConstantInt *Fold = ConstantInt::get( 3542 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3543 Ops[0] = getConstant(Fold); 3544 Ops.erase(Ops.begin()+1); // Erase the folded element 3545 if (Ops.size() == 1) return Ops[0]; 3546 LHSC = cast<SCEVConstant>(Ops[0]); 3547 } 3548 3549 // If we are left with a constant minimum-int, strip it off. 3550 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3551 Ops.erase(Ops.begin()); 3552 --Idx; 3553 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3554 // If we have an umax with a constant maximum-int, it will always be 3555 // maximum-int. 3556 return Ops[0]; 3557 } 3558 3559 if (Ops.size() == 1) return Ops[0]; 3560 } 3561 3562 // Find the first UMax 3563 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3564 ++Idx; 3565 3566 // Check to see if one of the operands is a UMax. If so, expand its operands 3567 // onto our operand list, and recurse to simplify. 3568 if (Idx < Ops.size()) { 3569 bool DeletedUMax = false; 3570 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3571 Ops.erase(Ops.begin()+Idx); 3572 Ops.append(UMax->op_begin(), UMax->op_end()); 3573 DeletedUMax = true; 3574 } 3575 3576 if (DeletedUMax) 3577 return getUMaxExpr(Ops); 3578 } 3579 3580 // Okay, check to see if the same value occurs in the operand list twice. If 3581 // so, delete one. Since we sorted the list, these values are required to 3582 // be adjacent. 3583 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3584 // X umax Y umax Y --> X umax Y 3585 // X umax Y --> X, if X is always greater than Y 3586 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3587 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3588 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3589 --i; --e; 3590 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3591 Ops[i + 1])) { 3592 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3593 --i; --e; 3594 } 3595 3596 if (Ops.size() == 1) return Ops[0]; 3597 3598 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3599 3600 // Okay, it looks like we really DO need a umax expr. Check to see if we 3601 // already have one, otherwise create a new one. 3602 FoldingSetNodeID ID; 3603 ID.AddInteger(scUMaxExpr); 3604 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3605 ID.AddPointer(Ops[i]); 3606 void *IP = nullptr; 3607 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3608 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3609 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3610 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3611 O, Ops.size()); 3612 UniqueSCEVs.InsertNode(S, IP); 3613 addToLoopUseLists(S); 3614 return S; 3615 } 3616 3617 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3618 const SCEV *RHS) { 3619 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3620 return getSMinExpr(Ops); 3621 } 3622 3623 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3624 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3625 SmallVector<const SCEV *, 2> NotOps; 3626 for (auto *S : Ops) 3627 NotOps.push_back(getNotSCEV(S)); 3628 return getNotSCEV(getSMaxExpr(NotOps)); 3629 } 3630 3631 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3632 const SCEV *RHS) { 3633 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3634 return getUMinExpr(Ops); 3635 } 3636 3637 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3638 assert(!Ops.empty() && "At least one operand must be!"); 3639 // Trivial case. 3640 if (Ops.size() == 1) 3641 return Ops[0]; 3642 3643 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3644 SmallVector<const SCEV *, 2> NotOps; 3645 for (auto *S : Ops) 3646 NotOps.push_back(getNotSCEV(S)); 3647 return getNotSCEV(getUMaxExpr(NotOps)); 3648 } 3649 3650 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3651 // We can bypass creating a target-independent 3652 // constant expression and then folding it back into a ConstantInt. 3653 // This is just a compile-time optimization. 3654 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3655 } 3656 3657 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3658 StructType *STy, 3659 unsigned FieldNo) { 3660 // We can bypass creating a target-independent 3661 // constant expression and then folding it back into a ConstantInt. 3662 // This is just a compile-time optimization. 3663 return getConstant( 3664 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3665 } 3666 3667 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3668 // Don't attempt to do anything other than create a SCEVUnknown object 3669 // here. createSCEV only calls getUnknown after checking for all other 3670 // interesting possibilities, and any other code that calls getUnknown 3671 // is doing so in order to hide a value from SCEV canonicalization. 3672 3673 FoldingSetNodeID ID; 3674 ID.AddInteger(scUnknown); 3675 ID.AddPointer(V); 3676 void *IP = nullptr; 3677 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3678 assert(cast<SCEVUnknown>(S)->getValue() == V && 3679 "Stale SCEVUnknown in uniquing map!"); 3680 return S; 3681 } 3682 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3683 FirstUnknown); 3684 FirstUnknown = cast<SCEVUnknown>(S); 3685 UniqueSCEVs.InsertNode(S, IP); 3686 return S; 3687 } 3688 3689 //===----------------------------------------------------------------------===// 3690 // Basic SCEV Analysis and PHI Idiom Recognition Code 3691 // 3692 3693 /// Test if values of the given type are analyzable within the SCEV 3694 /// framework. This primarily includes integer types, and it can optionally 3695 /// include pointer types if the ScalarEvolution class has access to 3696 /// target-specific information. 3697 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3698 // Integers and pointers are always SCEVable. 3699 return Ty->isIntOrPtrTy(); 3700 } 3701 3702 /// Return the size in bits of the specified type, for which isSCEVable must 3703 /// return true. 3704 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3705 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3706 if (Ty->isPointerTy()) 3707 return getDataLayout().getIndexTypeSizeInBits(Ty); 3708 return getDataLayout().getTypeSizeInBits(Ty); 3709 } 3710 3711 /// Return a type with the same bitwidth as the given type and which represents 3712 /// how SCEV will treat the given type, for which isSCEVable must return 3713 /// true. For pointer types, this is the pointer-sized integer type. 3714 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3715 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3716 3717 if (Ty->isIntegerTy()) 3718 return Ty; 3719 3720 // The only other support type is pointer. 3721 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3722 return getDataLayout().getIntPtrType(Ty); 3723 } 3724 3725 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3726 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3727 } 3728 3729 const SCEV *ScalarEvolution::getCouldNotCompute() { 3730 return CouldNotCompute.get(); 3731 } 3732 3733 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3734 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3735 auto *SU = dyn_cast<SCEVUnknown>(S); 3736 return SU && SU->getValue() == nullptr; 3737 }); 3738 3739 return !ContainsNulls; 3740 } 3741 3742 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3743 HasRecMapType::iterator I = HasRecMap.find(S); 3744 if (I != HasRecMap.end()) 3745 return I->second; 3746 3747 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3748 HasRecMap.insert({S, FoundAddRec}); 3749 return FoundAddRec; 3750 } 3751 3752 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3753 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3754 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3755 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3756 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3757 if (!Add) 3758 return {S, nullptr}; 3759 3760 if (Add->getNumOperands() != 2) 3761 return {S, nullptr}; 3762 3763 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3764 if (!ConstOp) 3765 return {S, nullptr}; 3766 3767 return {Add->getOperand(1), ConstOp->getValue()}; 3768 } 3769 3770 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3771 /// by the value and offset from any ValueOffsetPair in the set. 3772 SetVector<ScalarEvolution::ValueOffsetPair> * 3773 ScalarEvolution::getSCEVValues(const SCEV *S) { 3774 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3775 if (SI == ExprValueMap.end()) 3776 return nullptr; 3777 #ifndef NDEBUG 3778 if (VerifySCEVMap) { 3779 // Check there is no dangling Value in the set returned. 3780 for (const auto &VE : SI->second) 3781 assert(ValueExprMap.count(VE.first)); 3782 } 3783 #endif 3784 return &SI->second; 3785 } 3786 3787 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3788 /// cannot be used separately. eraseValueFromMap should be used to remove 3789 /// V from ValueExprMap and ExprValueMap at the same time. 3790 void ScalarEvolution::eraseValueFromMap(Value *V) { 3791 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3792 if (I != ValueExprMap.end()) { 3793 const SCEV *S = I->second; 3794 // Remove {V, 0} from the set of ExprValueMap[S] 3795 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3796 SV->remove({V, nullptr}); 3797 3798 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3799 const SCEV *Stripped; 3800 ConstantInt *Offset; 3801 std::tie(Stripped, Offset) = splitAddExpr(S); 3802 if (Offset != nullptr) { 3803 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3804 SV->remove({V, Offset}); 3805 } 3806 ValueExprMap.erase(V); 3807 } 3808 } 3809 3810 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3811 /// TODO: In reality it is better to check the poison recursevely 3812 /// but this is better than nothing. 3813 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3814 if (auto *I = dyn_cast<Instruction>(V)) { 3815 if (isa<OverflowingBinaryOperator>(I)) { 3816 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3817 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3818 return true; 3819 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3820 return true; 3821 } 3822 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3823 return true; 3824 } 3825 return false; 3826 } 3827 3828 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3829 /// create a new one. 3830 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3831 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3832 3833 const SCEV *S = getExistingSCEV(V); 3834 if (S == nullptr) { 3835 S = createSCEV(V); 3836 // During PHI resolution, it is possible to create two SCEVs for the same 3837 // V, so it is needed to double check whether V->S is inserted into 3838 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3839 std::pair<ValueExprMapType::iterator, bool> Pair = 3840 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3841 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3842 ExprValueMap[S].insert({V, nullptr}); 3843 3844 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3845 // ExprValueMap. 3846 const SCEV *Stripped = S; 3847 ConstantInt *Offset = nullptr; 3848 std::tie(Stripped, Offset) = splitAddExpr(S); 3849 // If stripped is SCEVUnknown, don't bother to save 3850 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3851 // increase the complexity of the expansion code. 3852 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3853 // because it may generate add/sub instead of GEP in SCEV expansion. 3854 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3855 !isa<GetElementPtrInst>(V)) 3856 ExprValueMap[Stripped].insert({V, Offset}); 3857 } 3858 } 3859 return S; 3860 } 3861 3862 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3863 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3864 3865 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3866 if (I != ValueExprMap.end()) { 3867 const SCEV *S = I->second; 3868 if (checkValidity(S)) 3869 return S; 3870 eraseValueFromMap(V); 3871 forgetMemoizedResults(S); 3872 } 3873 return nullptr; 3874 } 3875 3876 /// Return a SCEV corresponding to -V = -1*V 3877 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3878 SCEV::NoWrapFlags Flags) { 3879 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3880 return getConstant( 3881 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3882 3883 Type *Ty = V->getType(); 3884 Ty = getEffectiveSCEVType(Ty); 3885 return getMulExpr( 3886 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3887 } 3888 3889 /// Return a SCEV corresponding to ~V = -1-V 3890 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3891 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3892 return getConstant( 3893 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3894 3895 Type *Ty = V->getType(); 3896 Ty = getEffectiveSCEVType(Ty); 3897 const SCEV *AllOnes = 3898 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3899 return getMinusSCEV(AllOnes, V); 3900 } 3901 3902 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3903 SCEV::NoWrapFlags Flags, 3904 unsigned Depth) { 3905 // Fast path: X - X --> 0. 3906 if (LHS == RHS) 3907 return getZero(LHS->getType()); 3908 3909 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3910 // makes it so that we cannot make much use of NUW. 3911 auto AddFlags = SCEV::FlagAnyWrap; 3912 const bool RHSIsNotMinSigned = 3913 !getSignedRangeMin(RHS).isMinSignedValue(); 3914 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3915 // Let M be the minimum representable signed value. Then (-1)*RHS 3916 // signed-wraps if and only if RHS is M. That can happen even for 3917 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3918 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3919 // (-1)*RHS, we need to prove that RHS != M. 3920 // 3921 // If LHS is non-negative and we know that LHS - RHS does not 3922 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3923 // either by proving that RHS > M or that LHS >= 0. 3924 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3925 AddFlags = SCEV::FlagNSW; 3926 } 3927 } 3928 3929 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3930 // RHS is NSW and LHS >= 0. 3931 // 3932 // The difficulty here is that the NSW flag may have been proven 3933 // relative to a loop that is to be found in a recurrence in LHS and 3934 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3935 // larger scope than intended. 3936 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3937 3938 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3939 } 3940 3941 const SCEV * 3942 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3943 Type *SrcTy = V->getType(); 3944 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3945 "Cannot truncate or zero extend with non-integer arguments!"); 3946 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3947 return V; // No conversion 3948 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3949 return getTruncateExpr(V, Ty); 3950 return getZeroExtendExpr(V, Ty); 3951 } 3952 3953 const SCEV * 3954 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3955 Type *Ty) { 3956 Type *SrcTy = V->getType(); 3957 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3958 "Cannot truncate or zero extend with non-integer arguments!"); 3959 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3960 return V; // No conversion 3961 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3962 return getTruncateExpr(V, Ty); 3963 return getSignExtendExpr(V, Ty); 3964 } 3965 3966 const SCEV * 3967 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3968 Type *SrcTy = V->getType(); 3969 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3970 "Cannot noop or zero extend with non-integer arguments!"); 3971 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3972 "getNoopOrZeroExtend cannot truncate!"); 3973 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3974 return V; // No conversion 3975 return getZeroExtendExpr(V, Ty); 3976 } 3977 3978 const SCEV * 3979 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3980 Type *SrcTy = V->getType(); 3981 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3982 "Cannot noop or sign extend with non-integer arguments!"); 3983 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3984 "getNoopOrSignExtend cannot truncate!"); 3985 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3986 return V; // No conversion 3987 return getSignExtendExpr(V, Ty); 3988 } 3989 3990 const SCEV * 3991 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3992 Type *SrcTy = V->getType(); 3993 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3994 "Cannot noop or any extend with non-integer arguments!"); 3995 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3996 "getNoopOrAnyExtend cannot truncate!"); 3997 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3998 return V; // No conversion 3999 return getAnyExtendExpr(V, Ty); 4000 } 4001 4002 const SCEV * 4003 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4004 Type *SrcTy = V->getType(); 4005 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4006 "Cannot truncate or noop with non-integer arguments!"); 4007 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4008 "getTruncateOrNoop cannot extend!"); 4009 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4010 return V; // No conversion 4011 return getTruncateExpr(V, Ty); 4012 } 4013 4014 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4015 const SCEV *RHS) { 4016 const SCEV *PromotedLHS = LHS; 4017 const SCEV *PromotedRHS = RHS; 4018 4019 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4020 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4021 else 4022 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4023 4024 return getUMaxExpr(PromotedLHS, PromotedRHS); 4025 } 4026 4027 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4028 const SCEV *RHS) { 4029 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4030 return getUMinFromMismatchedTypes(Ops); 4031 } 4032 4033 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4034 SmallVectorImpl<const SCEV *> &Ops) { 4035 assert(!Ops.empty() && "At least one operand must be!"); 4036 // Trivial case. 4037 if (Ops.size() == 1) 4038 return Ops[0]; 4039 4040 // Find the max type first. 4041 Type *MaxType = nullptr; 4042 for (auto *S : Ops) 4043 if (MaxType) 4044 MaxType = getWiderType(MaxType, S->getType()); 4045 else 4046 MaxType = S->getType(); 4047 4048 // Extend all ops to max type. 4049 SmallVector<const SCEV *, 2> PromotedOps; 4050 for (auto *S : Ops) 4051 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4052 4053 // Generate umin. 4054 return getUMinExpr(PromotedOps); 4055 } 4056 4057 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4058 // A pointer operand may evaluate to a nonpointer expression, such as null. 4059 if (!V->getType()->isPointerTy()) 4060 return V; 4061 4062 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4063 return getPointerBase(Cast->getOperand()); 4064 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4065 const SCEV *PtrOp = nullptr; 4066 for (const SCEV *NAryOp : NAry->operands()) { 4067 if (NAryOp->getType()->isPointerTy()) { 4068 // Cannot find the base of an expression with multiple pointer operands. 4069 if (PtrOp) 4070 return V; 4071 PtrOp = NAryOp; 4072 } 4073 } 4074 if (!PtrOp) 4075 return V; 4076 return getPointerBase(PtrOp); 4077 } 4078 return V; 4079 } 4080 4081 /// Push users of the given Instruction onto the given Worklist. 4082 static void 4083 PushDefUseChildren(Instruction *I, 4084 SmallVectorImpl<Instruction *> &Worklist) { 4085 // Push the def-use children onto the Worklist stack. 4086 for (User *U : I->users()) 4087 Worklist.push_back(cast<Instruction>(U)); 4088 } 4089 4090 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4091 SmallVector<Instruction *, 16> Worklist; 4092 PushDefUseChildren(PN, Worklist); 4093 4094 SmallPtrSet<Instruction *, 8> Visited; 4095 Visited.insert(PN); 4096 while (!Worklist.empty()) { 4097 Instruction *I = Worklist.pop_back_val(); 4098 if (!Visited.insert(I).second) 4099 continue; 4100 4101 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4102 if (It != ValueExprMap.end()) { 4103 const SCEV *Old = It->second; 4104 4105 // Short-circuit the def-use traversal if the symbolic name 4106 // ceases to appear in expressions. 4107 if (Old != SymName && !hasOperand(Old, SymName)) 4108 continue; 4109 4110 // SCEVUnknown for a PHI either means that it has an unrecognized 4111 // structure, it's a PHI that's in the progress of being computed 4112 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4113 // additional loop trip count information isn't going to change anything. 4114 // In the second case, createNodeForPHI will perform the necessary 4115 // updates on its own when it gets to that point. In the third, we do 4116 // want to forget the SCEVUnknown. 4117 if (!isa<PHINode>(I) || 4118 !isa<SCEVUnknown>(Old) || 4119 (I != PN && Old == SymName)) { 4120 eraseValueFromMap(It->first); 4121 forgetMemoizedResults(Old); 4122 } 4123 } 4124 4125 PushDefUseChildren(I, Worklist); 4126 } 4127 } 4128 4129 namespace { 4130 4131 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4132 /// expression in case its Loop is L. If it is not L then 4133 /// if IgnoreOtherLoops is true then use AddRec itself 4134 /// otherwise rewrite cannot be done. 4135 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4136 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4137 public: 4138 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4139 bool IgnoreOtherLoops = true) { 4140 SCEVInitRewriter Rewriter(L, SE); 4141 const SCEV *Result = Rewriter.visit(S); 4142 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4143 return SE.getCouldNotCompute(); 4144 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4145 ? SE.getCouldNotCompute() 4146 : Result; 4147 } 4148 4149 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4150 if (!SE.isLoopInvariant(Expr, L)) 4151 SeenLoopVariantSCEVUnknown = true; 4152 return Expr; 4153 } 4154 4155 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4156 // Only re-write AddRecExprs for this loop. 4157 if (Expr->getLoop() == L) 4158 return Expr->getStart(); 4159 SeenOtherLoops = true; 4160 return Expr; 4161 } 4162 4163 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4164 4165 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4166 4167 private: 4168 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4169 : SCEVRewriteVisitor(SE), L(L) {} 4170 4171 const Loop *L; 4172 bool SeenLoopVariantSCEVUnknown = false; 4173 bool SeenOtherLoops = false; 4174 }; 4175 4176 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4177 /// increment expression in case its Loop is L. If it is not L then 4178 /// use AddRec itself. 4179 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4180 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4181 public: 4182 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4183 SCEVPostIncRewriter Rewriter(L, SE); 4184 const SCEV *Result = Rewriter.visit(S); 4185 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4186 ? SE.getCouldNotCompute() 4187 : Result; 4188 } 4189 4190 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4191 if (!SE.isLoopInvariant(Expr, L)) 4192 SeenLoopVariantSCEVUnknown = true; 4193 return Expr; 4194 } 4195 4196 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4197 // Only re-write AddRecExprs for this loop. 4198 if (Expr->getLoop() == L) 4199 return Expr->getPostIncExpr(SE); 4200 SeenOtherLoops = true; 4201 return Expr; 4202 } 4203 4204 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4205 4206 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4207 4208 private: 4209 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4210 : SCEVRewriteVisitor(SE), L(L) {} 4211 4212 const Loop *L; 4213 bool SeenLoopVariantSCEVUnknown = false; 4214 bool SeenOtherLoops = false; 4215 }; 4216 4217 /// This class evaluates the compare condition by matching it against the 4218 /// condition of loop latch. If there is a match we assume a true value 4219 /// for the condition while building SCEV nodes. 4220 class SCEVBackedgeConditionFolder 4221 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4222 public: 4223 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4224 ScalarEvolution &SE) { 4225 bool IsPosBECond = false; 4226 Value *BECond = nullptr; 4227 if (BasicBlock *Latch = L->getLoopLatch()) { 4228 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4229 if (BI && BI->isConditional()) { 4230 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4231 "Both outgoing branches should not target same header!"); 4232 BECond = BI->getCondition(); 4233 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4234 } else { 4235 return S; 4236 } 4237 } 4238 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4239 return Rewriter.visit(S); 4240 } 4241 4242 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4243 const SCEV *Result = Expr; 4244 bool InvariantF = SE.isLoopInvariant(Expr, L); 4245 4246 if (!InvariantF) { 4247 Instruction *I = cast<Instruction>(Expr->getValue()); 4248 switch (I->getOpcode()) { 4249 case Instruction::Select: { 4250 SelectInst *SI = cast<SelectInst>(I); 4251 Optional<const SCEV *> Res = 4252 compareWithBackedgeCondition(SI->getCondition()); 4253 if (Res.hasValue()) { 4254 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4255 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4256 } 4257 break; 4258 } 4259 default: { 4260 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4261 if (Res.hasValue()) 4262 Result = Res.getValue(); 4263 break; 4264 } 4265 } 4266 } 4267 return Result; 4268 } 4269 4270 private: 4271 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4272 bool IsPosBECond, ScalarEvolution &SE) 4273 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4274 IsPositiveBECond(IsPosBECond) {} 4275 4276 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4277 4278 const Loop *L; 4279 /// Loop back condition. 4280 Value *BackedgeCond = nullptr; 4281 /// Set to true if loop back is on positive branch condition. 4282 bool IsPositiveBECond; 4283 }; 4284 4285 Optional<const SCEV *> 4286 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4287 4288 // If value matches the backedge condition for loop latch, 4289 // then return a constant evolution node based on loopback 4290 // branch taken. 4291 if (BackedgeCond == IC) 4292 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4293 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4294 return None; 4295 } 4296 4297 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4298 public: 4299 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4300 ScalarEvolution &SE) { 4301 SCEVShiftRewriter Rewriter(L, SE); 4302 const SCEV *Result = Rewriter.visit(S); 4303 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4304 } 4305 4306 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4307 // Only allow AddRecExprs for this loop. 4308 if (!SE.isLoopInvariant(Expr, L)) 4309 Valid = false; 4310 return Expr; 4311 } 4312 4313 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4314 if (Expr->getLoop() == L && Expr->isAffine()) 4315 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4316 Valid = false; 4317 return Expr; 4318 } 4319 4320 bool isValid() { return Valid; } 4321 4322 private: 4323 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4324 : SCEVRewriteVisitor(SE), L(L) {} 4325 4326 const Loop *L; 4327 bool Valid = true; 4328 }; 4329 4330 } // end anonymous namespace 4331 4332 SCEV::NoWrapFlags 4333 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4334 if (!AR->isAffine()) 4335 return SCEV::FlagAnyWrap; 4336 4337 using OBO = OverflowingBinaryOperator; 4338 4339 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4340 4341 if (!AR->hasNoSignedWrap()) { 4342 ConstantRange AddRecRange = getSignedRange(AR); 4343 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4344 4345 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4346 Instruction::Add, IncRange, OBO::NoSignedWrap); 4347 if (NSWRegion.contains(AddRecRange)) 4348 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4349 } 4350 4351 if (!AR->hasNoUnsignedWrap()) { 4352 ConstantRange AddRecRange = getUnsignedRange(AR); 4353 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4354 4355 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4356 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4357 if (NUWRegion.contains(AddRecRange)) 4358 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4359 } 4360 4361 return Result; 4362 } 4363 4364 namespace { 4365 4366 /// Represents an abstract binary operation. This may exist as a 4367 /// normal instruction or constant expression, or may have been 4368 /// derived from an expression tree. 4369 struct BinaryOp { 4370 unsigned Opcode; 4371 Value *LHS; 4372 Value *RHS; 4373 bool IsNSW = false; 4374 bool IsNUW = false; 4375 4376 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4377 /// constant expression. 4378 Operator *Op = nullptr; 4379 4380 explicit BinaryOp(Operator *Op) 4381 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4382 Op(Op) { 4383 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4384 IsNSW = OBO->hasNoSignedWrap(); 4385 IsNUW = OBO->hasNoUnsignedWrap(); 4386 } 4387 } 4388 4389 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4390 bool IsNUW = false) 4391 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4392 }; 4393 4394 } // end anonymous namespace 4395 4396 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4397 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4398 auto *Op = dyn_cast<Operator>(V); 4399 if (!Op) 4400 return None; 4401 4402 // Implementation detail: all the cleverness here should happen without 4403 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4404 // SCEV expressions when possible, and we should not break that. 4405 4406 switch (Op->getOpcode()) { 4407 case Instruction::Add: 4408 case Instruction::Sub: 4409 case Instruction::Mul: 4410 case Instruction::UDiv: 4411 case Instruction::URem: 4412 case Instruction::And: 4413 case Instruction::Or: 4414 case Instruction::AShr: 4415 case Instruction::Shl: 4416 return BinaryOp(Op); 4417 4418 case Instruction::Xor: 4419 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4420 // If the RHS of the xor is a signmask, then this is just an add. 4421 // Instcombine turns add of signmask into xor as a strength reduction step. 4422 if (RHSC->getValue().isSignMask()) 4423 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4424 return BinaryOp(Op); 4425 4426 case Instruction::LShr: 4427 // Turn logical shift right of a constant into a unsigned divide. 4428 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4429 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4430 4431 // If the shift count is not less than the bitwidth, the result of 4432 // the shift is undefined. Don't try to analyze it, because the 4433 // resolution chosen here may differ from the resolution chosen in 4434 // other parts of the compiler. 4435 if (SA->getValue().ult(BitWidth)) { 4436 Constant *X = 4437 ConstantInt::get(SA->getContext(), 4438 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4439 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4440 } 4441 } 4442 return BinaryOp(Op); 4443 4444 case Instruction::ExtractValue: { 4445 auto *EVI = cast<ExtractValueInst>(Op); 4446 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4447 break; 4448 4449 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4450 if (!CI) 4451 break; 4452 4453 if (auto *F = CI->getCalledFunction()) 4454 switch (F->getIntrinsicID()) { 4455 case Intrinsic::sadd_with_overflow: 4456 case Intrinsic::uadd_with_overflow: 4457 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4458 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4459 CI->getArgOperand(1)); 4460 4461 // Now that we know that all uses of the arithmetic-result component of 4462 // CI are guarded by the overflow check, we can go ahead and pretend 4463 // that the arithmetic is non-overflowing. 4464 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4465 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4466 CI->getArgOperand(1), /* IsNSW = */ true, 4467 /* IsNUW = */ false); 4468 else 4469 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4470 CI->getArgOperand(1), /* IsNSW = */ false, 4471 /* IsNUW*/ true); 4472 case Intrinsic::ssub_with_overflow: 4473 case Intrinsic::usub_with_overflow: 4474 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4475 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4476 CI->getArgOperand(1)); 4477 4478 // The same reasoning as sadd/uadd above. 4479 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4480 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4481 CI->getArgOperand(1), /* IsNSW = */ true, 4482 /* IsNUW = */ false); 4483 else 4484 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4485 CI->getArgOperand(1), /* IsNSW = */ false, 4486 /* IsNUW = */ true); 4487 case Intrinsic::smul_with_overflow: 4488 case Intrinsic::umul_with_overflow: 4489 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4490 CI->getArgOperand(1)); 4491 default: 4492 break; 4493 } 4494 break; 4495 } 4496 4497 default: 4498 break; 4499 } 4500 4501 return None; 4502 } 4503 4504 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4505 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4506 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4507 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4508 /// follows one of the following patterns: 4509 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4510 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4511 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4512 /// we return the type of the truncation operation, and indicate whether the 4513 /// truncated type should be treated as signed/unsigned by setting 4514 /// \p Signed to true/false, respectively. 4515 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4516 bool &Signed, ScalarEvolution &SE) { 4517 // The case where Op == SymbolicPHI (that is, with no type conversions on 4518 // the way) is handled by the regular add recurrence creating logic and 4519 // would have already been triggered in createAddRecForPHI. Reaching it here 4520 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4521 // because one of the other operands of the SCEVAddExpr updating this PHI is 4522 // not invariant). 4523 // 4524 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4525 // this case predicates that allow us to prove that Op == SymbolicPHI will 4526 // be added. 4527 if (Op == SymbolicPHI) 4528 return nullptr; 4529 4530 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4531 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4532 if (SourceBits != NewBits) 4533 return nullptr; 4534 4535 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4536 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4537 if (!SExt && !ZExt) 4538 return nullptr; 4539 const SCEVTruncateExpr *Trunc = 4540 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4541 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4542 if (!Trunc) 4543 return nullptr; 4544 const SCEV *X = Trunc->getOperand(); 4545 if (X != SymbolicPHI) 4546 return nullptr; 4547 Signed = SExt != nullptr; 4548 return Trunc->getType(); 4549 } 4550 4551 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4552 if (!PN->getType()->isIntegerTy()) 4553 return nullptr; 4554 const Loop *L = LI.getLoopFor(PN->getParent()); 4555 if (!L || L->getHeader() != PN->getParent()) 4556 return nullptr; 4557 return L; 4558 } 4559 4560 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4561 // computation that updates the phi follows the following pattern: 4562 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4563 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4564 // If so, try to see if it can be rewritten as an AddRecExpr under some 4565 // Predicates. If successful, return them as a pair. Also cache the results 4566 // of the analysis. 4567 // 4568 // Example usage scenario: 4569 // Say the Rewriter is called for the following SCEV: 4570 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4571 // where: 4572 // %X = phi i64 (%Start, %BEValue) 4573 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4574 // and call this function with %SymbolicPHI = %X. 4575 // 4576 // The analysis will find that the value coming around the backedge has 4577 // the following SCEV: 4578 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4579 // Upon concluding that this matches the desired pattern, the function 4580 // will return the pair {NewAddRec, SmallPredsVec} where: 4581 // NewAddRec = {%Start,+,%Step} 4582 // SmallPredsVec = {P1, P2, P3} as follows: 4583 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4584 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4585 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4586 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4587 // under the predicates {P1,P2,P3}. 4588 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4589 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4590 // 4591 // TODO's: 4592 // 4593 // 1) Extend the Induction descriptor to also support inductions that involve 4594 // casts: When needed (namely, when we are called in the context of the 4595 // vectorizer induction analysis), a Set of cast instructions will be 4596 // populated by this method, and provided back to isInductionPHI. This is 4597 // needed to allow the vectorizer to properly record them to be ignored by 4598 // the cost model and to avoid vectorizing them (otherwise these casts, 4599 // which are redundant under the runtime overflow checks, will be 4600 // vectorized, which can be costly). 4601 // 4602 // 2) Support additional induction/PHISCEV patterns: We also want to support 4603 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4604 // after the induction update operation (the induction increment): 4605 // 4606 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4607 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4608 // 4609 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4610 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4611 // 4612 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4613 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4614 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4615 SmallVector<const SCEVPredicate *, 3> Predicates; 4616 4617 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4618 // return an AddRec expression under some predicate. 4619 4620 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4621 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4622 assert(L && "Expecting an integer loop header phi"); 4623 4624 // The loop may have multiple entrances or multiple exits; we can analyze 4625 // this phi as an addrec if it has a unique entry value and a unique 4626 // backedge value. 4627 Value *BEValueV = nullptr, *StartValueV = nullptr; 4628 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4629 Value *V = PN->getIncomingValue(i); 4630 if (L->contains(PN->getIncomingBlock(i))) { 4631 if (!BEValueV) { 4632 BEValueV = V; 4633 } else if (BEValueV != V) { 4634 BEValueV = nullptr; 4635 break; 4636 } 4637 } else if (!StartValueV) { 4638 StartValueV = V; 4639 } else if (StartValueV != V) { 4640 StartValueV = nullptr; 4641 break; 4642 } 4643 } 4644 if (!BEValueV || !StartValueV) 4645 return None; 4646 4647 const SCEV *BEValue = getSCEV(BEValueV); 4648 4649 // If the value coming around the backedge is an add with the symbolic 4650 // value we just inserted, possibly with casts that we can ignore under 4651 // an appropriate runtime guard, then we found a simple induction variable! 4652 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4653 if (!Add) 4654 return None; 4655 4656 // If there is a single occurrence of the symbolic value, possibly 4657 // casted, replace it with a recurrence. 4658 unsigned FoundIndex = Add->getNumOperands(); 4659 Type *TruncTy = nullptr; 4660 bool Signed; 4661 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4662 if ((TruncTy = 4663 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4664 if (FoundIndex == e) { 4665 FoundIndex = i; 4666 break; 4667 } 4668 4669 if (FoundIndex == Add->getNumOperands()) 4670 return None; 4671 4672 // Create an add with everything but the specified operand. 4673 SmallVector<const SCEV *, 8> Ops; 4674 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4675 if (i != FoundIndex) 4676 Ops.push_back(Add->getOperand(i)); 4677 const SCEV *Accum = getAddExpr(Ops); 4678 4679 // The runtime checks will not be valid if the step amount is 4680 // varying inside the loop. 4681 if (!isLoopInvariant(Accum, L)) 4682 return None; 4683 4684 // *** Part2: Create the predicates 4685 4686 // Analysis was successful: we have a phi-with-cast pattern for which we 4687 // can return an AddRec expression under the following predicates: 4688 // 4689 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4690 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4691 // P2: An Equal predicate that guarantees that 4692 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4693 // P3: An Equal predicate that guarantees that 4694 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4695 // 4696 // As we next prove, the above predicates guarantee that: 4697 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4698 // 4699 // 4700 // More formally, we want to prove that: 4701 // Expr(i+1) = Start + (i+1) * Accum 4702 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4703 // 4704 // Given that: 4705 // 1) Expr(0) = Start 4706 // 2) Expr(1) = Start + Accum 4707 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4708 // 3) Induction hypothesis (step i): 4709 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4710 // 4711 // Proof: 4712 // Expr(i+1) = 4713 // = Start + (i+1)*Accum 4714 // = (Start + i*Accum) + Accum 4715 // = Expr(i) + Accum 4716 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4717 // :: from step i 4718 // 4719 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4720 // 4721 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4722 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4723 // + Accum :: from P3 4724 // 4725 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4726 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4727 // 4728 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4729 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4730 // 4731 // By induction, the same applies to all iterations 1<=i<n: 4732 // 4733 4734 // Create a truncated addrec for which we will add a no overflow check (P1). 4735 const SCEV *StartVal = getSCEV(StartValueV); 4736 const SCEV *PHISCEV = 4737 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4738 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4739 4740 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4741 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4742 // will be constant. 4743 // 4744 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4745 // add P1. 4746 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4747 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4748 Signed ? SCEVWrapPredicate::IncrementNSSW 4749 : SCEVWrapPredicate::IncrementNUSW; 4750 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4751 Predicates.push_back(AddRecPred); 4752 } 4753 4754 // Create the Equal Predicates P2,P3: 4755 4756 // It is possible that the predicates P2 and/or P3 are computable at 4757 // compile time due to StartVal and/or Accum being constants. 4758 // If either one is, then we can check that now and escape if either P2 4759 // or P3 is false. 4760 4761 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4762 // for each of StartVal and Accum 4763 auto getExtendedExpr = [&](const SCEV *Expr, 4764 bool CreateSignExtend) -> const SCEV * { 4765 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4766 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4767 const SCEV *ExtendedExpr = 4768 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4769 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4770 return ExtendedExpr; 4771 }; 4772 4773 // Given: 4774 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4775 // = getExtendedExpr(Expr) 4776 // Determine whether the predicate P: Expr == ExtendedExpr 4777 // is known to be false at compile time 4778 auto PredIsKnownFalse = [&](const SCEV *Expr, 4779 const SCEV *ExtendedExpr) -> bool { 4780 return Expr != ExtendedExpr && 4781 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4782 }; 4783 4784 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4785 if (PredIsKnownFalse(StartVal, StartExtended)) { 4786 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4787 return None; 4788 } 4789 4790 // The Step is always Signed (because the overflow checks are either 4791 // NSSW or NUSW) 4792 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4793 if (PredIsKnownFalse(Accum, AccumExtended)) { 4794 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4795 return None; 4796 } 4797 4798 auto AppendPredicate = [&](const SCEV *Expr, 4799 const SCEV *ExtendedExpr) -> void { 4800 if (Expr != ExtendedExpr && 4801 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4802 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4803 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4804 Predicates.push_back(Pred); 4805 } 4806 }; 4807 4808 AppendPredicate(StartVal, StartExtended); 4809 AppendPredicate(Accum, AccumExtended); 4810 4811 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4812 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4813 // into NewAR if it will also add the runtime overflow checks specified in 4814 // Predicates. 4815 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4816 4817 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4818 std::make_pair(NewAR, Predicates); 4819 // Remember the result of the analysis for this SCEV at this locayyytion. 4820 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4821 return PredRewrite; 4822 } 4823 4824 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4825 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4826 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4827 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4828 if (!L) 4829 return None; 4830 4831 // Check to see if we already analyzed this PHI. 4832 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4833 if (I != PredicatedSCEVRewrites.end()) { 4834 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4835 I->second; 4836 // Analysis was done before and failed to create an AddRec: 4837 if (Rewrite.first == SymbolicPHI) 4838 return None; 4839 // Analysis was done before and succeeded to create an AddRec under 4840 // a predicate: 4841 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4842 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4843 return Rewrite; 4844 } 4845 4846 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4847 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4848 4849 // Record in the cache that the analysis failed 4850 if (!Rewrite) { 4851 SmallVector<const SCEVPredicate *, 3> Predicates; 4852 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4853 return None; 4854 } 4855 4856 return Rewrite; 4857 } 4858 4859 // FIXME: This utility is currently required because the Rewriter currently 4860 // does not rewrite this expression: 4861 // {0, +, (sext ix (trunc iy to ix) to iy)} 4862 // into {0, +, %step}, 4863 // even when the following Equal predicate exists: 4864 // "%step == (sext ix (trunc iy to ix) to iy)". 4865 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4866 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4867 if (AR1 == AR2) 4868 return true; 4869 4870 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4871 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4872 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4873 return false; 4874 return true; 4875 }; 4876 4877 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4878 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4879 return false; 4880 return true; 4881 } 4882 4883 /// A helper function for createAddRecFromPHI to handle simple cases. 4884 /// 4885 /// This function tries to find an AddRec expression for the simplest (yet most 4886 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4887 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4888 /// technique for finding the AddRec expression. 4889 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4890 Value *BEValueV, 4891 Value *StartValueV) { 4892 const Loop *L = LI.getLoopFor(PN->getParent()); 4893 assert(L && L->getHeader() == PN->getParent()); 4894 assert(BEValueV && StartValueV); 4895 4896 auto BO = MatchBinaryOp(BEValueV, DT); 4897 if (!BO) 4898 return nullptr; 4899 4900 if (BO->Opcode != Instruction::Add) 4901 return nullptr; 4902 4903 const SCEV *Accum = nullptr; 4904 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4905 Accum = getSCEV(BO->RHS); 4906 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4907 Accum = getSCEV(BO->LHS); 4908 4909 if (!Accum) 4910 return nullptr; 4911 4912 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4913 if (BO->IsNUW) 4914 Flags = setFlags(Flags, SCEV::FlagNUW); 4915 if (BO->IsNSW) 4916 Flags = setFlags(Flags, SCEV::FlagNSW); 4917 4918 const SCEV *StartVal = getSCEV(StartValueV); 4919 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4920 4921 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4922 4923 // We can add Flags to the post-inc expression only if we 4924 // know that it is *undefined behavior* for BEValueV to 4925 // overflow. 4926 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4927 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4928 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4929 4930 return PHISCEV; 4931 } 4932 4933 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4934 const Loop *L = LI.getLoopFor(PN->getParent()); 4935 if (!L || L->getHeader() != PN->getParent()) 4936 return nullptr; 4937 4938 // The loop may have multiple entrances or multiple exits; we can analyze 4939 // this phi as an addrec if it has a unique entry value and a unique 4940 // backedge value. 4941 Value *BEValueV = nullptr, *StartValueV = nullptr; 4942 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4943 Value *V = PN->getIncomingValue(i); 4944 if (L->contains(PN->getIncomingBlock(i))) { 4945 if (!BEValueV) { 4946 BEValueV = V; 4947 } else if (BEValueV != V) { 4948 BEValueV = nullptr; 4949 break; 4950 } 4951 } else if (!StartValueV) { 4952 StartValueV = V; 4953 } else if (StartValueV != V) { 4954 StartValueV = nullptr; 4955 break; 4956 } 4957 } 4958 if (!BEValueV || !StartValueV) 4959 return nullptr; 4960 4961 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4962 "PHI node already processed?"); 4963 4964 // First, try to find AddRec expression without creating a fictituos symbolic 4965 // value for PN. 4966 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4967 return S; 4968 4969 // Handle PHI node value symbolically. 4970 const SCEV *SymbolicName = getUnknown(PN); 4971 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4972 4973 // Using this symbolic name for the PHI, analyze the value coming around 4974 // the back-edge. 4975 const SCEV *BEValue = getSCEV(BEValueV); 4976 4977 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4978 // has a special value for the first iteration of the loop. 4979 4980 // If the value coming around the backedge is an add with the symbolic 4981 // value we just inserted, then we found a simple induction variable! 4982 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4983 // If there is a single occurrence of the symbolic value, replace it 4984 // with a recurrence. 4985 unsigned FoundIndex = Add->getNumOperands(); 4986 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4987 if (Add->getOperand(i) == SymbolicName) 4988 if (FoundIndex == e) { 4989 FoundIndex = i; 4990 break; 4991 } 4992 4993 if (FoundIndex != Add->getNumOperands()) { 4994 // Create an add with everything but the specified operand. 4995 SmallVector<const SCEV *, 8> Ops; 4996 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4997 if (i != FoundIndex) 4998 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4999 L, *this)); 5000 const SCEV *Accum = getAddExpr(Ops); 5001 5002 // This is not a valid addrec if the step amount is varying each 5003 // loop iteration, but is not itself an addrec in this loop. 5004 if (isLoopInvariant(Accum, L) || 5005 (isa<SCEVAddRecExpr>(Accum) && 5006 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5007 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5008 5009 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5010 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5011 if (BO->IsNUW) 5012 Flags = setFlags(Flags, SCEV::FlagNUW); 5013 if (BO->IsNSW) 5014 Flags = setFlags(Flags, SCEV::FlagNSW); 5015 } 5016 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5017 // If the increment is an inbounds GEP, then we know the address 5018 // space cannot be wrapped around. We cannot make any guarantee 5019 // about signed or unsigned overflow because pointers are 5020 // unsigned but we may have a negative index from the base 5021 // pointer. We can guarantee that no unsigned wrap occurs if the 5022 // indices form a positive value. 5023 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5024 Flags = setFlags(Flags, SCEV::FlagNW); 5025 5026 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5027 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5028 Flags = setFlags(Flags, SCEV::FlagNUW); 5029 } 5030 5031 // We cannot transfer nuw and nsw flags from subtraction 5032 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5033 // for instance. 5034 } 5035 5036 const SCEV *StartVal = getSCEV(StartValueV); 5037 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5038 5039 // Okay, for the entire analysis of this edge we assumed the PHI 5040 // to be symbolic. We now need to go back and purge all of the 5041 // entries for the scalars that use the symbolic expression. 5042 forgetSymbolicName(PN, SymbolicName); 5043 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5044 5045 // We can add Flags to the post-inc expression only if we 5046 // know that it is *undefined behavior* for BEValueV to 5047 // overflow. 5048 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5049 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5050 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5051 5052 return PHISCEV; 5053 } 5054 } 5055 } else { 5056 // Otherwise, this could be a loop like this: 5057 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5058 // In this case, j = {1,+,1} and BEValue is j. 5059 // Because the other in-value of i (0) fits the evolution of BEValue 5060 // i really is an addrec evolution. 5061 // 5062 // We can generalize this saying that i is the shifted value of BEValue 5063 // by one iteration: 5064 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5065 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5066 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5067 if (Shifted != getCouldNotCompute() && 5068 Start != getCouldNotCompute()) { 5069 const SCEV *StartVal = getSCEV(StartValueV); 5070 if (Start == StartVal) { 5071 // Okay, for the entire analysis of this edge we assumed the PHI 5072 // to be symbolic. We now need to go back and purge all of the 5073 // entries for the scalars that use the symbolic expression. 5074 forgetSymbolicName(PN, SymbolicName); 5075 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5076 return Shifted; 5077 } 5078 } 5079 } 5080 5081 // Remove the temporary PHI node SCEV that has been inserted while intending 5082 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5083 // as it will prevent later (possibly simpler) SCEV expressions to be added 5084 // to the ValueExprMap. 5085 eraseValueFromMap(PN); 5086 5087 return nullptr; 5088 } 5089 5090 // Checks if the SCEV S is available at BB. S is considered available at BB 5091 // if S can be materialized at BB without introducing a fault. 5092 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5093 BasicBlock *BB) { 5094 struct CheckAvailable { 5095 bool TraversalDone = false; 5096 bool Available = true; 5097 5098 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5099 BasicBlock *BB = nullptr; 5100 DominatorTree &DT; 5101 5102 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5103 : L(L), BB(BB), DT(DT) {} 5104 5105 bool setUnavailable() { 5106 TraversalDone = true; 5107 Available = false; 5108 return false; 5109 } 5110 5111 bool follow(const SCEV *S) { 5112 switch (S->getSCEVType()) { 5113 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5114 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5115 // These expressions are available if their operand(s) is/are. 5116 return true; 5117 5118 case scAddRecExpr: { 5119 // We allow add recurrences that are on the loop BB is in, or some 5120 // outer loop. This guarantees availability because the value of the 5121 // add recurrence at BB is simply the "current" value of the induction 5122 // variable. We can relax this in the future; for instance an add 5123 // recurrence on a sibling dominating loop is also available at BB. 5124 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5125 if (L && (ARLoop == L || ARLoop->contains(L))) 5126 return true; 5127 5128 return setUnavailable(); 5129 } 5130 5131 case scUnknown: { 5132 // For SCEVUnknown, we check for simple dominance. 5133 const auto *SU = cast<SCEVUnknown>(S); 5134 Value *V = SU->getValue(); 5135 5136 if (isa<Argument>(V)) 5137 return false; 5138 5139 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5140 return false; 5141 5142 return setUnavailable(); 5143 } 5144 5145 case scUDivExpr: 5146 case scCouldNotCompute: 5147 // We do not try to smart about these at all. 5148 return setUnavailable(); 5149 } 5150 llvm_unreachable("switch should be fully covered!"); 5151 } 5152 5153 bool isDone() { return TraversalDone; } 5154 }; 5155 5156 CheckAvailable CA(L, BB, DT); 5157 SCEVTraversal<CheckAvailable> ST(CA); 5158 5159 ST.visitAll(S); 5160 return CA.Available; 5161 } 5162 5163 // Try to match a control flow sequence that branches out at BI and merges back 5164 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5165 // match. 5166 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5167 Value *&C, Value *&LHS, Value *&RHS) { 5168 C = BI->getCondition(); 5169 5170 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5171 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5172 5173 if (!LeftEdge.isSingleEdge()) 5174 return false; 5175 5176 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5177 5178 Use &LeftUse = Merge->getOperandUse(0); 5179 Use &RightUse = Merge->getOperandUse(1); 5180 5181 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5182 LHS = LeftUse; 5183 RHS = RightUse; 5184 return true; 5185 } 5186 5187 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5188 LHS = RightUse; 5189 RHS = LeftUse; 5190 return true; 5191 } 5192 5193 return false; 5194 } 5195 5196 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5197 auto IsReachable = 5198 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5199 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5200 const Loop *L = LI.getLoopFor(PN->getParent()); 5201 5202 // We don't want to break LCSSA, even in a SCEV expression tree. 5203 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5204 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5205 return nullptr; 5206 5207 // Try to match 5208 // 5209 // br %cond, label %left, label %right 5210 // left: 5211 // br label %merge 5212 // right: 5213 // br label %merge 5214 // merge: 5215 // V = phi [ %x, %left ], [ %y, %right ] 5216 // 5217 // as "select %cond, %x, %y" 5218 5219 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5220 assert(IDom && "At least the entry block should dominate PN"); 5221 5222 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5223 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5224 5225 if (BI && BI->isConditional() && 5226 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5227 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5228 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5229 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5230 } 5231 5232 return nullptr; 5233 } 5234 5235 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5236 if (const SCEV *S = createAddRecFromPHI(PN)) 5237 return S; 5238 5239 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5240 return S; 5241 5242 // If the PHI has a single incoming value, follow that value, unless the 5243 // PHI's incoming blocks are in a different loop, in which case doing so 5244 // risks breaking LCSSA form. Instcombine would normally zap these, but 5245 // it doesn't have DominatorTree information, so it may miss cases. 5246 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5247 if (LI.replacementPreservesLCSSAForm(PN, V)) 5248 return getSCEV(V); 5249 5250 // If it's not a loop phi, we can't handle it yet. 5251 return getUnknown(PN); 5252 } 5253 5254 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5255 Value *Cond, 5256 Value *TrueVal, 5257 Value *FalseVal) { 5258 // Handle "constant" branch or select. This can occur for instance when a 5259 // loop pass transforms an inner loop and moves on to process the outer loop. 5260 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5261 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5262 5263 // Try to match some simple smax or umax patterns. 5264 auto *ICI = dyn_cast<ICmpInst>(Cond); 5265 if (!ICI) 5266 return getUnknown(I); 5267 5268 Value *LHS = ICI->getOperand(0); 5269 Value *RHS = ICI->getOperand(1); 5270 5271 switch (ICI->getPredicate()) { 5272 case ICmpInst::ICMP_SLT: 5273 case ICmpInst::ICMP_SLE: 5274 std::swap(LHS, RHS); 5275 LLVM_FALLTHROUGH; 5276 case ICmpInst::ICMP_SGT: 5277 case ICmpInst::ICMP_SGE: 5278 // a >s b ? a+x : b+x -> smax(a, b)+x 5279 // a >s b ? b+x : a+x -> smin(a, b)+x 5280 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5281 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5282 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5283 const SCEV *LA = getSCEV(TrueVal); 5284 const SCEV *RA = getSCEV(FalseVal); 5285 const SCEV *LDiff = getMinusSCEV(LA, LS); 5286 const SCEV *RDiff = getMinusSCEV(RA, RS); 5287 if (LDiff == RDiff) 5288 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5289 LDiff = getMinusSCEV(LA, RS); 5290 RDiff = getMinusSCEV(RA, LS); 5291 if (LDiff == RDiff) 5292 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5293 } 5294 break; 5295 case ICmpInst::ICMP_ULT: 5296 case ICmpInst::ICMP_ULE: 5297 std::swap(LHS, RHS); 5298 LLVM_FALLTHROUGH; 5299 case ICmpInst::ICMP_UGT: 5300 case ICmpInst::ICMP_UGE: 5301 // a >u b ? a+x : b+x -> umax(a, b)+x 5302 // a >u b ? b+x : a+x -> umin(a, b)+x 5303 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5304 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5305 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5306 const SCEV *LA = getSCEV(TrueVal); 5307 const SCEV *RA = getSCEV(FalseVal); 5308 const SCEV *LDiff = getMinusSCEV(LA, LS); 5309 const SCEV *RDiff = getMinusSCEV(RA, RS); 5310 if (LDiff == RDiff) 5311 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5312 LDiff = getMinusSCEV(LA, RS); 5313 RDiff = getMinusSCEV(RA, LS); 5314 if (LDiff == RDiff) 5315 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5316 } 5317 break; 5318 case ICmpInst::ICMP_NE: 5319 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5320 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5321 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5322 const SCEV *One = getOne(I->getType()); 5323 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5324 const SCEV *LA = getSCEV(TrueVal); 5325 const SCEV *RA = getSCEV(FalseVal); 5326 const SCEV *LDiff = getMinusSCEV(LA, LS); 5327 const SCEV *RDiff = getMinusSCEV(RA, One); 5328 if (LDiff == RDiff) 5329 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5330 } 5331 break; 5332 case ICmpInst::ICMP_EQ: 5333 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5334 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5335 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5336 const SCEV *One = getOne(I->getType()); 5337 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5338 const SCEV *LA = getSCEV(TrueVal); 5339 const SCEV *RA = getSCEV(FalseVal); 5340 const SCEV *LDiff = getMinusSCEV(LA, One); 5341 const SCEV *RDiff = getMinusSCEV(RA, LS); 5342 if (LDiff == RDiff) 5343 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5344 } 5345 break; 5346 default: 5347 break; 5348 } 5349 5350 return getUnknown(I); 5351 } 5352 5353 /// Expand GEP instructions into add and multiply operations. This allows them 5354 /// to be analyzed by regular SCEV code. 5355 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5356 // Don't attempt to analyze GEPs over unsized objects. 5357 if (!GEP->getSourceElementType()->isSized()) 5358 return getUnknown(GEP); 5359 5360 SmallVector<const SCEV *, 4> IndexExprs; 5361 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5362 IndexExprs.push_back(getSCEV(*Index)); 5363 return getGEPExpr(GEP, IndexExprs); 5364 } 5365 5366 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5367 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5368 return C->getAPInt().countTrailingZeros(); 5369 5370 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5371 return std::min(GetMinTrailingZeros(T->getOperand()), 5372 (uint32_t)getTypeSizeInBits(T->getType())); 5373 5374 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5375 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5376 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5377 ? getTypeSizeInBits(E->getType()) 5378 : OpRes; 5379 } 5380 5381 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5382 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5383 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5384 ? getTypeSizeInBits(E->getType()) 5385 : OpRes; 5386 } 5387 5388 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5389 // The result is the min of all operands results. 5390 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5391 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5392 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5393 return MinOpRes; 5394 } 5395 5396 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5397 // The result is the sum of all operands results. 5398 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5399 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5400 for (unsigned i = 1, e = M->getNumOperands(); 5401 SumOpRes != BitWidth && i != e; ++i) 5402 SumOpRes = 5403 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5404 return SumOpRes; 5405 } 5406 5407 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5408 // The result is the min of all operands results. 5409 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5410 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5411 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5412 return MinOpRes; 5413 } 5414 5415 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5416 // The result is the min of all operands results. 5417 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5418 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5419 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5420 return MinOpRes; 5421 } 5422 5423 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5424 // The result is the min of all operands results. 5425 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5426 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5427 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5428 return MinOpRes; 5429 } 5430 5431 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5432 // For a SCEVUnknown, ask ValueTracking. 5433 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5434 return Known.countMinTrailingZeros(); 5435 } 5436 5437 // SCEVUDivExpr 5438 return 0; 5439 } 5440 5441 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5442 auto I = MinTrailingZerosCache.find(S); 5443 if (I != MinTrailingZerosCache.end()) 5444 return I->second; 5445 5446 uint32_t Result = GetMinTrailingZerosImpl(S); 5447 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5448 assert(InsertPair.second && "Should insert a new key"); 5449 return InsertPair.first->second; 5450 } 5451 5452 /// Helper method to assign a range to V from metadata present in the IR. 5453 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5454 if (Instruction *I = dyn_cast<Instruction>(V)) 5455 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5456 return getConstantRangeFromMetadata(*MD); 5457 5458 return None; 5459 } 5460 5461 /// Determine the range for a particular SCEV. If SignHint is 5462 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5463 /// with a "cleaner" unsigned (resp. signed) representation. 5464 const ConstantRange & 5465 ScalarEvolution::getRangeRef(const SCEV *S, 5466 ScalarEvolution::RangeSignHint SignHint) { 5467 DenseMap<const SCEV *, ConstantRange> &Cache = 5468 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5469 : SignedRanges; 5470 5471 // See if we've computed this range already. 5472 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5473 if (I != Cache.end()) 5474 return I->second; 5475 5476 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5477 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5478 5479 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5480 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5481 5482 // If the value has known zeros, the maximum value will have those known zeros 5483 // as well. 5484 uint32_t TZ = GetMinTrailingZeros(S); 5485 if (TZ != 0) { 5486 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5487 ConservativeResult = 5488 ConstantRange(APInt::getMinValue(BitWidth), 5489 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5490 else 5491 ConservativeResult = ConstantRange( 5492 APInt::getSignedMinValue(BitWidth), 5493 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5494 } 5495 5496 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5497 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5498 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5499 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5500 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5501 } 5502 5503 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5504 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5505 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5506 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5507 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5508 } 5509 5510 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5511 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5512 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5513 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5514 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5515 } 5516 5517 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5518 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5519 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5520 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5521 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5522 } 5523 5524 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5525 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5526 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5527 return setRange(UDiv, SignHint, 5528 ConservativeResult.intersectWith(X.udiv(Y))); 5529 } 5530 5531 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5532 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5533 return setRange(ZExt, SignHint, 5534 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5535 } 5536 5537 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5538 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5539 return setRange(SExt, SignHint, 5540 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5541 } 5542 5543 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5544 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5545 return setRange(Trunc, SignHint, 5546 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5547 } 5548 5549 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5550 // If there's no unsigned wrap, the value will never be less than its 5551 // initial value. 5552 if (AddRec->hasNoUnsignedWrap()) 5553 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5554 if (!C->getValue()->isZero()) 5555 ConservativeResult = ConservativeResult.intersectWith( 5556 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5557 5558 // If there's no signed wrap, and all the operands have the same sign or 5559 // zero, the value won't ever change sign. 5560 if (AddRec->hasNoSignedWrap()) { 5561 bool AllNonNeg = true; 5562 bool AllNonPos = true; 5563 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5564 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5565 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5566 } 5567 if (AllNonNeg) 5568 ConservativeResult = ConservativeResult.intersectWith( 5569 ConstantRange(APInt(BitWidth, 0), 5570 APInt::getSignedMinValue(BitWidth))); 5571 else if (AllNonPos) 5572 ConservativeResult = ConservativeResult.intersectWith( 5573 ConstantRange(APInt::getSignedMinValue(BitWidth), 5574 APInt(BitWidth, 1))); 5575 } 5576 5577 // TODO: non-affine addrec 5578 if (AddRec->isAffine()) { 5579 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5580 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5581 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5582 auto RangeFromAffine = getRangeForAffineAR( 5583 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5584 BitWidth); 5585 if (!RangeFromAffine.isFullSet()) 5586 ConservativeResult = 5587 ConservativeResult.intersectWith(RangeFromAffine); 5588 5589 auto RangeFromFactoring = getRangeViaFactoring( 5590 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5591 BitWidth); 5592 if (!RangeFromFactoring.isFullSet()) 5593 ConservativeResult = 5594 ConservativeResult.intersectWith(RangeFromFactoring); 5595 } 5596 } 5597 5598 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5599 } 5600 5601 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5602 // Check if the IR explicitly contains !range metadata. 5603 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5604 if (MDRange.hasValue()) 5605 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5606 5607 // Split here to avoid paying the compile-time cost of calling both 5608 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5609 // if needed. 5610 const DataLayout &DL = getDataLayout(); 5611 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5612 // For a SCEVUnknown, ask ValueTracking. 5613 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5614 if (Known.One != ~Known.Zero + 1) 5615 ConservativeResult = 5616 ConservativeResult.intersectWith(ConstantRange(Known.One, 5617 ~Known.Zero + 1)); 5618 } else { 5619 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5620 "generalize as needed!"); 5621 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5622 if (NS > 1) 5623 ConservativeResult = ConservativeResult.intersectWith( 5624 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5625 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5626 } 5627 5628 // A range of Phi is a subset of union of all ranges of its input. 5629 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5630 // Make sure that we do not run over cycled Phis. 5631 if (PendingPhiRanges.insert(Phi).second) { 5632 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5633 for (auto &Op : Phi->operands()) { 5634 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5635 RangeFromOps = RangeFromOps.unionWith(OpRange); 5636 // No point to continue if we already have a full set. 5637 if (RangeFromOps.isFullSet()) 5638 break; 5639 } 5640 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5641 bool Erased = PendingPhiRanges.erase(Phi); 5642 assert(Erased && "Failed to erase Phi properly?"); 5643 (void) Erased; 5644 } 5645 } 5646 5647 return setRange(U, SignHint, std::move(ConservativeResult)); 5648 } 5649 5650 return setRange(S, SignHint, std::move(ConservativeResult)); 5651 } 5652 5653 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5654 // values that the expression can take. Initially, the expression has a value 5655 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5656 // argument defines if we treat Step as signed or unsigned. 5657 static ConstantRange getRangeForAffineARHelper(APInt Step, 5658 const ConstantRange &StartRange, 5659 const APInt &MaxBECount, 5660 unsigned BitWidth, bool Signed) { 5661 // If either Step or MaxBECount is 0, then the expression won't change, and we 5662 // just need to return the initial range. 5663 if (Step == 0 || MaxBECount == 0) 5664 return StartRange; 5665 5666 // If we don't know anything about the initial value (i.e. StartRange is 5667 // FullRange), then we don't know anything about the final range either. 5668 // Return FullRange. 5669 if (StartRange.isFullSet()) 5670 return ConstantRange(BitWidth, /* isFullSet = */ true); 5671 5672 // If Step is signed and negative, then we use its absolute value, but we also 5673 // note that we're moving in the opposite direction. 5674 bool Descending = Signed && Step.isNegative(); 5675 5676 if (Signed) 5677 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5678 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5679 // This equations hold true due to the well-defined wrap-around behavior of 5680 // APInt. 5681 Step = Step.abs(); 5682 5683 // Check if Offset is more than full span of BitWidth. If it is, the 5684 // expression is guaranteed to overflow. 5685 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5686 return ConstantRange(BitWidth, /* isFullSet = */ true); 5687 5688 // Offset is by how much the expression can change. Checks above guarantee no 5689 // overflow here. 5690 APInt Offset = Step * MaxBECount; 5691 5692 // Minimum value of the final range will match the minimal value of StartRange 5693 // if the expression is increasing and will be decreased by Offset otherwise. 5694 // Maximum value of the final range will match the maximal value of StartRange 5695 // if the expression is decreasing and will be increased by Offset otherwise. 5696 APInt StartLower = StartRange.getLower(); 5697 APInt StartUpper = StartRange.getUpper() - 1; 5698 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5699 : (StartUpper + std::move(Offset)); 5700 5701 // It's possible that the new minimum/maximum value will fall into the initial 5702 // range (due to wrap around). This means that the expression can take any 5703 // value in this bitwidth, and we have to return full range. 5704 if (StartRange.contains(MovedBoundary)) 5705 return ConstantRange(BitWidth, /* isFullSet = */ true); 5706 5707 APInt NewLower = 5708 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5709 APInt NewUpper = 5710 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5711 NewUpper += 1; 5712 5713 // If we end up with full range, return a proper full range. 5714 if (NewLower == NewUpper) 5715 return ConstantRange(BitWidth, /* isFullSet = */ true); 5716 5717 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5718 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5719 } 5720 5721 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5722 const SCEV *Step, 5723 const SCEV *MaxBECount, 5724 unsigned BitWidth) { 5725 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5726 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5727 "Precondition!"); 5728 5729 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5730 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5731 5732 // First, consider step signed. 5733 ConstantRange StartSRange = getSignedRange(Start); 5734 ConstantRange StepSRange = getSignedRange(Step); 5735 5736 // If Step can be both positive and negative, we need to find ranges for the 5737 // maximum absolute step values in both directions and union them. 5738 ConstantRange SR = 5739 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5740 MaxBECountValue, BitWidth, /* Signed = */ true); 5741 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5742 StartSRange, MaxBECountValue, 5743 BitWidth, /* Signed = */ true)); 5744 5745 // Next, consider step unsigned. 5746 ConstantRange UR = getRangeForAffineARHelper( 5747 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5748 MaxBECountValue, BitWidth, /* Signed = */ false); 5749 5750 // Finally, intersect signed and unsigned ranges. 5751 return SR.intersectWith(UR); 5752 } 5753 5754 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5755 const SCEV *Step, 5756 const SCEV *MaxBECount, 5757 unsigned BitWidth) { 5758 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5759 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5760 5761 struct SelectPattern { 5762 Value *Condition = nullptr; 5763 APInt TrueValue; 5764 APInt FalseValue; 5765 5766 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5767 const SCEV *S) { 5768 Optional<unsigned> CastOp; 5769 APInt Offset(BitWidth, 0); 5770 5771 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5772 "Should be!"); 5773 5774 // Peel off a constant offset: 5775 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5776 // In the future we could consider being smarter here and handle 5777 // {Start+Step,+,Step} too. 5778 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5779 return; 5780 5781 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5782 S = SA->getOperand(1); 5783 } 5784 5785 // Peel off a cast operation 5786 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5787 CastOp = SCast->getSCEVType(); 5788 S = SCast->getOperand(); 5789 } 5790 5791 using namespace llvm::PatternMatch; 5792 5793 auto *SU = dyn_cast<SCEVUnknown>(S); 5794 const APInt *TrueVal, *FalseVal; 5795 if (!SU || 5796 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5797 m_APInt(FalseVal)))) { 5798 Condition = nullptr; 5799 return; 5800 } 5801 5802 TrueValue = *TrueVal; 5803 FalseValue = *FalseVal; 5804 5805 // Re-apply the cast we peeled off earlier 5806 if (CastOp.hasValue()) 5807 switch (*CastOp) { 5808 default: 5809 llvm_unreachable("Unknown SCEV cast type!"); 5810 5811 case scTruncate: 5812 TrueValue = TrueValue.trunc(BitWidth); 5813 FalseValue = FalseValue.trunc(BitWidth); 5814 break; 5815 case scZeroExtend: 5816 TrueValue = TrueValue.zext(BitWidth); 5817 FalseValue = FalseValue.zext(BitWidth); 5818 break; 5819 case scSignExtend: 5820 TrueValue = TrueValue.sext(BitWidth); 5821 FalseValue = FalseValue.sext(BitWidth); 5822 break; 5823 } 5824 5825 // Re-apply the constant offset we peeled off earlier 5826 TrueValue += Offset; 5827 FalseValue += Offset; 5828 } 5829 5830 bool isRecognized() { return Condition != nullptr; } 5831 }; 5832 5833 SelectPattern StartPattern(*this, BitWidth, Start); 5834 if (!StartPattern.isRecognized()) 5835 return ConstantRange(BitWidth, /* isFullSet = */ true); 5836 5837 SelectPattern StepPattern(*this, BitWidth, Step); 5838 if (!StepPattern.isRecognized()) 5839 return ConstantRange(BitWidth, /* isFullSet = */ true); 5840 5841 if (StartPattern.Condition != StepPattern.Condition) { 5842 // We don't handle this case today; but we could, by considering four 5843 // possibilities below instead of two. I'm not sure if there are cases where 5844 // that will help over what getRange already does, though. 5845 return ConstantRange(BitWidth, /* isFullSet = */ true); 5846 } 5847 5848 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5849 // construct arbitrary general SCEV expressions here. This function is called 5850 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5851 // say) can end up caching a suboptimal value. 5852 5853 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5854 // C2352 and C2512 (otherwise it isn't needed). 5855 5856 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5857 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5858 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5859 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5860 5861 ConstantRange TrueRange = 5862 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5863 ConstantRange FalseRange = 5864 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5865 5866 return TrueRange.unionWith(FalseRange); 5867 } 5868 5869 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5870 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5871 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5872 5873 // Return early if there are no flags to propagate to the SCEV. 5874 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5875 if (BinOp->hasNoUnsignedWrap()) 5876 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5877 if (BinOp->hasNoSignedWrap()) 5878 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5879 if (Flags == SCEV::FlagAnyWrap) 5880 return SCEV::FlagAnyWrap; 5881 5882 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5883 } 5884 5885 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5886 // Here we check that I is in the header of the innermost loop containing I, 5887 // since we only deal with instructions in the loop header. The actual loop we 5888 // need to check later will come from an add recurrence, but getting that 5889 // requires computing the SCEV of the operands, which can be expensive. This 5890 // check we can do cheaply to rule out some cases early. 5891 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5892 if (InnermostContainingLoop == nullptr || 5893 InnermostContainingLoop->getHeader() != I->getParent()) 5894 return false; 5895 5896 // Only proceed if we can prove that I does not yield poison. 5897 if (!programUndefinedIfFullPoison(I)) 5898 return false; 5899 5900 // At this point we know that if I is executed, then it does not wrap 5901 // according to at least one of NSW or NUW. If I is not executed, then we do 5902 // not know if the calculation that I represents would wrap. Multiple 5903 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5904 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5905 // derived from other instructions that map to the same SCEV. We cannot make 5906 // that guarantee for cases where I is not executed. So we need to find the 5907 // loop that I is considered in relation to and prove that I is executed for 5908 // every iteration of that loop. That implies that the value that I 5909 // calculates does not wrap anywhere in the loop, so then we can apply the 5910 // flags to the SCEV. 5911 // 5912 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5913 // from different loops, so that we know which loop to prove that I is 5914 // executed in. 5915 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5916 // I could be an extractvalue from a call to an overflow intrinsic. 5917 // TODO: We can do better here in some cases. 5918 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5919 return false; 5920 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5921 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5922 bool AllOtherOpsLoopInvariant = true; 5923 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5924 ++OtherOpIndex) { 5925 if (OtherOpIndex != OpIndex) { 5926 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5927 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5928 AllOtherOpsLoopInvariant = false; 5929 break; 5930 } 5931 } 5932 } 5933 if (AllOtherOpsLoopInvariant && 5934 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5935 return true; 5936 } 5937 } 5938 return false; 5939 } 5940 5941 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5942 // If we know that \c I can never be poison period, then that's enough. 5943 if (isSCEVExprNeverPoison(I)) 5944 return true; 5945 5946 // For an add recurrence specifically, we assume that infinite loops without 5947 // side effects are undefined behavior, and then reason as follows: 5948 // 5949 // If the add recurrence is poison in any iteration, it is poison on all 5950 // future iterations (since incrementing poison yields poison). If the result 5951 // of the add recurrence is fed into the loop latch condition and the loop 5952 // does not contain any throws or exiting blocks other than the latch, we now 5953 // have the ability to "choose" whether the backedge is taken or not (by 5954 // choosing a sufficiently evil value for the poison feeding into the branch) 5955 // for every iteration including and after the one in which \p I first became 5956 // poison. There are two possibilities (let's call the iteration in which \p 5957 // I first became poison as K): 5958 // 5959 // 1. In the set of iterations including and after K, the loop body executes 5960 // no side effects. In this case executing the backege an infinte number 5961 // of times will yield undefined behavior. 5962 // 5963 // 2. In the set of iterations including and after K, the loop body executes 5964 // at least one side effect. In this case, that specific instance of side 5965 // effect is control dependent on poison, which also yields undefined 5966 // behavior. 5967 5968 auto *ExitingBB = L->getExitingBlock(); 5969 auto *LatchBB = L->getLoopLatch(); 5970 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5971 return false; 5972 5973 SmallPtrSet<const Instruction *, 16> Pushed; 5974 SmallVector<const Instruction *, 8> PoisonStack; 5975 5976 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5977 // things that are known to be fully poison under that assumption go on the 5978 // PoisonStack. 5979 Pushed.insert(I); 5980 PoisonStack.push_back(I); 5981 5982 bool LatchControlDependentOnPoison = false; 5983 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5984 const Instruction *Poison = PoisonStack.pop_back_val(); 5985 5986 for (auto *PoisonUser : Poison->users()) { 5987 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5988 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5989 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5990 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5991 assert(BI->isConditional() && "Only possibility!"); 5992 if (BI->getParent() == LatchBB) { 5993 LatchControlDependentOnPoison = true; 5994 break; 5995 } 5996 } 5997 } 5998 } 5999 6000 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6001 } 6002 6003 ScalarEvolution::LoopProperties 6004 ScalarEvolution::getLoopProperties(const Loop *L) { 6005 using LoopProperties = ScalarEvolution::LoopProperties; 6006 6007 auto Itr = LoopPropertiesCache.find(L); 6008 if (Itr == LoopPropertiesCache.end()) { 6009 auto HasSideEffects = [](Instruction *I) { 6010 if (auto *SI = dyn_cast<StoreInst>(I)) 6011 return !SI->isSimple(); 6012 6013 return I->mayHaveSideEffects(); 6014 }; 6015 6016 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6017 /*HasNoSideEffects*/ true}; 6018 6019 for (auto *BB : L->getBlocks()) 6020 for (auto &I : *BB) { 6021 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6022 LP.HasNoAbnormalExits = false; 6023 if (HasSideEffects(&I)) 6024 LP.HasNoSideEffects = false; 6025 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6026 break; // We're already as pessimistic as we can get. 6027 } 6028 6029 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6030 assert(InsertPair.second && "We just checked!"); 6031 Itr = InsertPair.first; 6032 } 6033 6034 return Itr->second; 6035 } 6036 6037 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6038 if (!isSCEVable(V->getType())) 6039 return getUnknown(V); 6040 6041 if (Instruction *I = dyn_cast<Instruction>(V)) { 6042 // Don't attempt to analyze instructions in blocks that aren't 6043 // reachable. Such instructions don't matter, and they aren't required 6044 // to obey basic rules for definitions dominating uses which this 6045 // analysis depends on. 6046 if (!DT.isReachableFromEntry(I->getParent())) 6047 return getUnknown(V); 6048 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6049 return getConstant(CI); 6050 else if (isa<ConstantPointerNull>(V)) 6051 return getZero(V->getType()); 6052 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6053 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6054 else if (!isa<ConstantExpr>(V)) 6055 return getUnknown(V); 6056 6057 Operator *U = cast<Operator>(V); 6058 if (auto BO = MatchBinaryOp(U, DT)) { 6059 switch (BO->Opcode) { 6060 case Instruction::Add: { 6061 // The simple thing to do would be to just call getSCEV on both operands 6062 // and call getAddExpr with the result. However if we're looking at a 6063 // bunch of things all added together, this can be quite inefficient, 6064 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6065 // Instead, gather up all the operands and make a single getAddExpr call. 6066 // LLVM IR canonical form means we need only traverse the left operands. 6067 SmallVector<const SCEV *, 4> AddOps; 6068 do { 6069 if (BO->Op) { 6070 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6071 AddOps.push_back(OpSCEV); 6072 break; 6073 } 6074 6075 // If a NUW or NSW flag can be applied to the SCEV for this 6076 // addition, then compute the SCEV for this addition by itself 6077 // with a separate call to getAddExpr. We need to do that 6078 // instead of pushing the operands of the addition onto AddOps, 6079 // since the flags are only known to apply to this particular 6080 // addition - they may not apply to other additions that can be 6081 // formed with operands from AddOps. 6082 const SCEV *RHS = getSCEV(BO->RHS); 6083 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6084 if (Flags != SCEV::FlagAnyWrap) { 6085 const SCEV *LHS = getSCEV(BO->LHS); 6086 if (BO->Opcode == Instruction::Sub) 6087 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6088 else 6089 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6090 break; 6091 } 6092 } 6093 6094 if (BO->Opcode == Instruction::Sub) 6095 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6096 else 6097 AddOps.push_back(getSCEV(BO->RHS)); 6098 6099 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6100 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6101 NewBO->Opcode != Instruction::Sub)) { 6102 AddOps.push_back(getSCEV(BO->LHS)); 6103 break; 6104 } 6105 BO = NewBO; 6106 } while (true); 6107 6108 return getAddExpr(AddOps); 6109 } 6110 6111 case Instruction::Mul: { 6112 SmallVector<const SCEV *, 4> MulOps; 6113 do { 6114 if (BO->Op) { 6115 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6116 MulOps.push_back(OpSCEV); 6117 break; 6118 } 6119 6120 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6121 if (Flags != SCEV::FlagAnyWrap) { 6122 MulOps.push_back( 6123 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6124 break; 6125 } 6126 } 6127 6128 MulOps.push_back(getSCEV(BO->RHS)); 6129 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6130 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6131 MulOps.push_back(getSCEV(BO->LHS)); 6132 break; 6133 } 6134 BO = NewBO; 6135 } while (true); 6136 6137 return getMulExpr(MulOps); 6138 } 6139 case Instruction::UDiv: 6140 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6141 case Instruction::URem: 6142 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6143 case Instruction::Sub: { 6144 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6145 if (BO->Op) 6146 Flags = getNoWrapFlagsFromUB(BO->Op); 6147 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6148 } 6149 case Instruction::And: 6150 // For an expression like x&255 that merely masks off the high bits, 6151 // use zext(trunc(x)) as the SCEV expression. 6152 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6153 if (CI->isZero()) 6154 return getSCEV(BO->RHS); 6155 if (CI->isMinusOne()) 6156 return getSCEV(BO->LHS); 6157 const APInt &A = CI->getValue(); 6158 6159 // Instcombine's ShrinkDemandedConstant may strip bits out of 6160 // constants, obscuring what would otherwise be a low-bits mask. 6161 // Use computeKnownBits to compute what ShrinkDemandedConstant 6162 // knew about to reconstruct a low-bits mask value. 6163 unsigned LZ = A.countLeadingZeros(); 6164 unsigned TZ = A.countTrailingZeros(); 6165 unsigned BitWidth = A.getBitWidth(); 6166 KnownBits Known(BitWidth); 6167 computeKnownBits(BO->LHS, Known, getDataLayout(), 6168 0, &AC, nullptr, &DT); 6169 6170 APInt EffectiveMask = 6171 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6172 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6173 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6174 const SCEV *LHS = getSCEV(BO->LHS); 6175 const SCEV *ShiftedLHS = nullptr; 6176 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6177 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6178 // For an expression like (x * 8) & 8, simplify the multiply. 6179 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6180 unsigned GCD = std::min(MulZeros, TZ); 6181 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6182 SmallVector<const SCEV*, 4> MulOps; 6183 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6184 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6185 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6186 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6187 } 6188 } 6189 if (!ShiftedLHS) 6190 ShiftedLHS = getUDivExpr(LHS, MulCount); 6191 return getMulExpr( 6192 getZeroExtendExpr( 6193 getTruncateExpr(ShiftedLHS, 6194 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6195 BO->LHS->getType()), 6196 MulCount); 6197 } 6198 } 6199 break; 6200 6201 case Instruction::Or: 6202 // If the RHS of the Or is a constant, we may have something like: 6203 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6204 // optimizations will transparently handle this case. 6205 // 6206 // In order for this transformation to be safe, the LHS must be of the 6207 // form X*(2^n) and the Or constant must be less than 2^n. 6208 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6209 const SCEV *LHS = getSCEV(BO->LHS); 6210 const APInt &CIVal = CI->getValue(); 6211 if (GetMinTrailingZeros(LHS) >= 6212 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6213 // Build a plain add SCEV. 6214 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6215 // If the LHS of the add was an addrec and it has no-wrap flags, 6216 // transfer the no-wrap flags, since an or won't introduce a wrap. 6217 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6218 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6219 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6220 OldAR->getNoWrapFlags()); 6221 } 6222 return S; 6223 } 6224 } 6225 break; 6226 6227 case Instruction::Xor: 6228 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6229 // If the RHS of xor is -1, then this is a not operation. 6230 if (CI->isMinusOne()) 6231 return getNotSCEV(getSCEV(BO->LHS)); 6232 6233 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6234 // This is a variant of the check for xor with -1, and it handles 6235 // the case where instcombine has trimmed non-demanded bits out 6236 // of an xor with -1. 6237 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6238 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6239 if (LBO->getOpcode() == Instruction::And && 6240 LCI->getValue() == CI->getValue()) 6241 if (const SCEVZeroExtendExpr *Z = 6242 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6243 Type *UTy = BO->LHS->getType(); 6244 const SCEV *Z0 = Z->getOperand(); 6245 Type *Z0Ty = Z0->getType(); 6246 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6247 6248 // If C is a low-bits mask, the zero extend is serving to 6249 // mask off the high bits. Complement the operand and 6250 // re-apply the zext. 6251 if (CI->getValue().isMask(Z0TySize)) 6252 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6253 6254 // If C is a single bit, it may be in the sign-bit position 6255 // before the zero-extend. In this case, represent the xor 6256 // using an add, which is equivalent, and re-apply the zext. 6257 APInt Trunc = CI->getValue().trunc(Z0TySize); 6258 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6259 Trunc.isSignMask()) 6260 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6261 UTy); 6262 } 6263 } 6264 break; 6265 6266 case Instruction::Shl: 6267 // Turn shift left of a constant amount into a multiply. 6268 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6269 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6270 6271 // If the shift count is not less than the bitwidth, the result of 6272 // the shift is undefined. Don't try to analyze it, because the 6273 // resolution chosen here may differ from the resolution chosen in 6274 // other parts of the compiler. 6275 if (SA->getValue().uge(BitWidth)) 6276 break; 6277 6278 // It is currently not resolved how to interpret NSW for left 6279 // shift by BitWidth - 1, so we avoid applying flags in that 6280 // case. Remove this check (or this comment) once the situation 6281 // is resolved. See 6282 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6283 // and http://reviews.llvm.org/D8890 . 6284 auto Flags = SCEV::FlagAnyWrap; 6285 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6286 Flags = getNoWrapFlagsFromUB(BO->Op); 6287 6288 Constant *X = ConstantInt::get( 6289 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6290 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6291 } 6292 break; 6293 6294 case Instruction::AShr: { 6295 // AShr X, C, where C is a constant. 6296 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6297 if (!CI) 6298 break; 6299 6300 Type *OuterTy = BO->LHS->getType(); 6301 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6302 // If the shift count is not less than the bitwidth, the result of 6303 // the shift is undefined. Don't try to analyze it, because the 6304 // resolution chosen here may differ from the resolution chosen in 6305 // other parts of the compiler. 6306 if (CI->getValue().uge(BitWidth)) 6307 break; 6308 6309 if (CI->isZero()) 6310 return getSCEV(BO->LHS); // shift by zero --> noop 6311 6312 uint64_t AShrAmt = CI->getZExtValue(); 6313 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6314 6315 Operator *L = dyn_cast<Operator>(BO->LHS); 6316 if (L && L->getOpcode() == Instruction::Shl) { 6317 // X = Shl A, n 6318 // Y = AShr X, m 6319 // Both n and m are constant. 6320 6321 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6322 if (L->getOperand(1) == BO->RHS) 6323 // For a two-shift sext-inreg, i.e. n = m, 6324 // use sext(trunc(x)) as the SCEV expression. 6325 return getSignExtendExpr( 6326 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6327 6328 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6329 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6330 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6331 if (ShlAmt > AShrAmt) { 6332 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6333 // expression. We already checked that ShlAmt < BitWidth, so 6334 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6335 // ShlAmt - AShrAmt < Amt. 6336 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6337 ShlAmt - AShrAmt); 6338 return getSignExtendExpr( 6339 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6340 getConstant(Mul)), OuterTy); 6341 } 6342 } 6343 } 6344 break; 6345 } 6346 } 6347 } 6348 6349 switch (U->getOpcode()) { 6350 case Instruction::Trunc: 6351 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6352 6353 case Instruction::ZExt: 6354 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6355 6356 case Instruction::SExt: 6357 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6358 // The NSW flag of a subtract does not always survive the conversion to 6359 // A + (-1)*B. By pushing sign extension onto its operands we are much 6360 // more likely to preserve NSW and allow later AddRec optimisations. 6361 // 6362 // NOTE: This is effectively duplicating this logic from getSignExtend: 6363 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6364 // but by that point the NSW information has potentially been lost. 6365 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6366 Type *Ty = U->getType(); 6367 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6368 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6369 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6370 } 6371 } 6372 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6373 6374 case Instruction::BitCast: 6375 // BitCasts are no-op casts so we just eliminate the cast. 6376 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6377 return getSCEV(U->getOperand(0)); 6378 break; 6379 6380 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6381 // lead to pointer expressions which cannot safely be expanded to GEPs, 6382 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6383 // simplifying integer expressions. 6384 6385 case Instruction::GetElementPtr: 6386 return createNodeForGEP(cast<GEPOperator>(U)); 6387 6388 case Instruction::PHI: 6389 return createNodeForPHI(cast<PHINode>(U)); 6390 6391 case Instruction::Select: 6392 // U can also be a select constant expr, which let fall through. Since 6393 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6394 // constant expressions cannot have instructions as operands, we'd have 6395 // returned getUnknown for a select constant expressions anyway. 6396 if (isa<Instruction>(U)) 6397 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6398 U->getOperand(1), U->getOperand(2)); 6399 break; 6400 6401 case Instruction::Call: 6402 case Instruction::Invoke: 6403 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6404 return getSCEV(RV); 6405 break; 6406 } 6407 6408 return getUnknown(V); 6409 } 6410 6411 //===----------------------------------------------------------------------===// 6412 // Iteration Count Computation Code 6413 // 6414 6415 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6416 if (!ExitCount) 6417 return 0; 6418 6419 ConstantInt *ExitConst = ExitCount->getValue(); 6420 6421 // Guard against huge trip counts. 6422 if (ExitConst->getValue().getActiveBits() > 32) 6423 return 0; 6424 6425 // In case of integer overflow, this returns 0, which is correct. 6426 return ((unsigned)ExitConst->getZExtValue()) + 1; 6427 } 6428 6429 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6430 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6431 return getSmallConstantTripCount(L, ExitingBB); 6432 6433 // No trip count information for multiple exits. 6434 return 0; 6435 } 6436 6437 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6438 BasicBlock *ExitingBlock) { 6439 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6440 assert(L->isLoopExiting(ExitingBlock) && 6441 "Exiting block must actually branch out of the loop!"); 6442 const SCEVConstant *ExitCount = 6443 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6444 return getConstantTripCount(ExitCount); 6445 } 6446 6447 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6448 const auto *MaxExitCount = 6449 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6450 return getConstantTripCount(MaxExitCount); 6451 } 6452 6453 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6454 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6455 return getSmallConstantTripMultiple(L, ExitingBB); 6456 6457 // No trip multiple information for multiple exits. 6458 return 0; 6459 } 6460 6461 /// Returns the largest constant divisor of the trip count of this loop as a 6462 /// normal unsigned value, if possible. This means that the actual trip count is 6463 /// always a multiple of the returned value (don't forget the trip count could 6464 /// very well be zero as well!). 6465 /// 6466 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6467 /// multiple of a constant (which is also the case if the trip count is simply 6468 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6469 /// if the trip count is very large (>= 2^32). 6470 /// 6471 /// As explained in the comments for getSmallConstantTripCount, this assumes 6472 /// that control exits the loop via ExitingBlock. 6473 unsigned 6474 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6475 BasicBlock *ExitingBlock) { 6476 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6477 assert(L->isLoopExiting(ExitingBlock) && 6478 "Exiting block must actually branch out of the loop!"); 6479 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6480 if (ExitCount == getCouldNotCompute()) 6481 return 1; 6482 6483 // Get the trip count from the BE count by adding 1. 6484 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6485 6486 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6487 if (!TC) 6488 // Attempt to factor more general cases. Returns the greatest power of 6489 // two divisor. If overflow happens, the trip count expression is still 6490 // divisible by the greatest power of 2 divisor returned. 6491 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6492 6493 ConstantInt *Result = TC->getValue(); 6494 6495 // Guard against huge trip counts (this requires checking 6496 // for zero to handle the case where the trip count == -1 and the 6497 // addition wraps). 6498 if (!Result || Result->getValue().getActiveBits() > 32 || 6499 Result->getValue().getActiveBits() == 0) 6500 return 1; 6501 6502 return (unsigned)Result->getZExtValue(); 6503 } 6504 6505 /// Get the expression for the number of loop iterations for which this loop is 6506 /// guaranteed not to exit via ExitingBlock. Otherwise return 6507 /// SCEVCouldNotCompute. 6508 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6509 BasicBlock *ExitingBlock) { 6510 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6511 } 6512 6513 const SCEV * 6514 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6515 SCEVUnionPredicate &Preds) { 6516 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6517 } 6518 6519 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6520 return getBackedgeTakenInfo(L).getExact(L, this); 6521 } 6522 6523 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6524 /// known never to be less than the actual backedge taken count. 6525 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6526 return getBackedgeTakenInfo(L).getMax(this); 6527 } 6528 6529 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6530 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6531 } 6532 6533 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6534 static void 6535 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6536 BasicBlock *Header = L->getHeader(); 6537 6538 // Push all Loop-header PHIs onto the Worklist stack. 6539 for (PHINode &PN : Header->phis()) 6540 Worklist.push_back(&PN); 6541 } 6542 6543 const ScalarEvolution::BackedgeTakenInfo & 6544 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6545 auto &BTI = getBackedgeTakenInfo(L); 6546 if (BTI.hasFullInfo()) 6547 return BTI; 6548 6549 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6550 6551 if (!Pair.second) 6552 return Pair.first->second; 6553 6554 BackedgeTakenInfo Result = 6555 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6556 6557 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6558 } 6559 6560 const ScalarEvolution::BackedgeTakenInfo & 6561 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6562 // Initially insert an invalid entry for this loop. If the insertion 6563 // succeeds, proceed to actually compute a backedge-taken count and 6564 // update the value. The temporary CouldNotCompute value tells SCEV 6565 // code elsewhere that it shouldn't attempt to request a new 6566 // backedge-taken count, which could result in infinite recursion. 6567 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6568 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6569 if (!Pair.second) 6570 return Pair.first->second; 6571 6572 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6573 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6574 // must be cleared in this scope. 6575 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6576 6577 // In product build, there are no usage of statistic. 6578 (void)NumTripCountsComputed; 6579 (void)NumTripCountsNotComputed; 6580 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6581 const SCEV *BEExact = Result.getExact(L, this); 6582 if (BEExact != getCouldNotCompute()) { 6583 assert(isLoopInvariant(BEExact, L) && 6584 isLoopInvariant(Result.getMax(this), L) && 6585 "Computed backedge-taken count isn't loop invariant for loop!"); 6586 ++NumTripCountsComputed; 6587 } 6588 else if (Result.getMax(this) == getCouldNotCompute() && 6589 isa<PHINode>(L->getHeader()->begin())) { 6590 // Only count loops that have phi nodes as not being computable. 6591 ++NumTripCountsNotComputed; 6592 } 6593 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6594 6595 // Now that we know more about the trip count for this loop, forget any 6596 // existing SCEV values for PHI nodes in this loop since they are only 6597 // conservative estimates made without the benefit of trip count 6598 // information. This is similar to the code in forgetLoop, except that 6599 // it handles SCEVUnknown PHI nodes specially. 6600 if (Result.hasAnyInfo()) { 6601 SmallVector<Instruction *, 16> Worklist; 6602 PushLoopPHIs(L, Worklist); 6603 6604 SmallPtrSet<Instruction *, 8> Discovered; 6605 while (!Worklist.empty()) { 6606 Instruction *I = Worklist.pop_back_val(); 6607 6608 ValueExprMapType::iterator It = 6609 ValueExprMap.find_as(static_cast<Value *>(I)); 6610 if (It != ValueExprMap.end()) { 6611 const SCEV *Old = It->second; 6612 6613 // SCEVUnknown for a PHI either means that it has an unrecognized 6614 // structure, or it's a PHI that's in the progress of being computed 6615 // by createNodeForPHI. In the former case, additional loop trip 6616 // count information isn't going to change anything. In the later 6617 // case, createNodeForPHI will perform the necessary updates on its 6618 // own when it gets to that point. 6619 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6620 eraseValueFromMap(It->first); 6621 forgetMemoizedResults(Old); 6622 } 6623 if (PHINode *PN = dyn_cast<PHINode>(I)) 6624 ConstantEvolutionLoopExitValue.erase(PN); 6625 } 6626 6627 // Since we don't need to invalidate anything for correctness and we're 6628 // only invalidating to make SCEV's results more precise, we get to stop 6629 // early to avoid invalidating too much. This is especially important in 6630 // cases like: 6631 // 6632 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6633 // loop0: 6634 // %pn0 = phi 6635 // ... 6636 // loop1: 6637 // %pn1 = phi 6638 // ... 6639 // 6640 // where both loop0 and loop1's backedge taken count uses the SCEV 6641 // expression for %v. If we don't have the early stop below then in cases 6642 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6643 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6644 // count for loop1, effectively nullifying SCEV's trip count cache. 6645 for (auto *U : I->users()) 6646 if (auto *I = dyn_cast<Instruction>(U)) { 6647 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6648 if (LoopForUser && L->contains(LoopForUser) && 6649 Discovered.insert(I).second) 6650 Worklist.push_back(I); 6651 } 6652 } 6653 } 6654 6655 // Re-lookup the insert position, since the call to 6656 // computeBackedgeTakenCount above could result in a 6657 // recusive call to getBackedgeTakenInfo (on a different 6658 // loop), which would invalidate the iterator computed 6659 // earlier. 6660 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6661 } 6662 6663 void ScalarEvolution::forgetLoop(const Loop *L) { 6664 // Drop any stored trip count value. 6665 auto RemoveLoopFromBackedgeMap = 6666 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6667 auto BTCPos = Map.find(L); 6668 if (BTCPos != Map.end()) { 6669 BTCPos->second.clear(); 6670 Map.erase(BTCPos); 6671 } 6672 }; 6673 6674 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6675 SmallVector<Instruction *, 32> Worklist; 6676 SmallPtrSet<Instruction *, 16> Visited; 6677 6678 // Iterate over all the loops and sub-loops to drop SCEV information. 6679 while (!LoopWorklist.empty()) { 6680 auto *CurrL = LoopWorklist.pop_back_val(); 6681 6682 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6683 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6684 6685 // Drop information about predicated SCEV rewrites for this loop. 6686 for (auto I = PredicatedSCEVRewrites.begin(); 6687 I != PredicatedSCEVRewrites.end();) { 6688 std::pair<const SCEV *, const Loop *> Entry = I->first; 6689 if (Entry.second == CurrL) 6690 PredicatedSCEVRewrites.erase(I++); 6691 else 6692 ++I; 6693 } 6694 6695 auto LoopUsersItr = LoopUsers.find(CurrL); 6696 if (LoopUsersItr != LoopUsers.end()) { 6697 for (auto *S : LoopUsersItr->second) 6698 forgetMemoizedResults(S); 6699 LoopUsers.erase(LoopUsersItr); 6700 } 6701 6702 // Drop information about expressions based on loop-header PHIs. 6703 PushLoopPHIs(CurrL, Worklist); 6704 6705 while (!Worklist.empty()) { 6706 Instruction *I = Worklist.pop_back_val(); 6707 if (!Visited.insert(I).second) 6708 continue; 6709 6710 ValueExprMapType::iterator It = 6711 ValueExprMap.find_as(static_cast<Value *>(I)); 6712 if (It != ValueExprMap.end()) { 6713 eraseValueFromMap(It->first); 6714 forgetMemoizedResults(It->second); 6715 if (PHINode *PN = dyn_cast<PHINode>(I)) 6716 ConstantEvolutionLoopExitValue.erase(PN); 6717 } 6718 6719 PushDefUseChildren(I, Worklist); 6720 } 6721 6722 LoopPropertiesCache.erase(CurrL); 6723 // Forget all contained loops too, to avoid dangling entries in the 6724 // ValuesAtScopes map. 6725 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6726 } 6727 } 6728 6729 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6730 while (Loop *Parent = L->getParentLoop()) 6731 L = Parent; 6732 forgetLoop(L); 6733 } 6734 6735 void ScalarEvolution::forgetValue(Value *V) { 6736 Instruction *I = dyn_cast<Instruction>(V); 6737 if (!I) return; 6738 6739 // Drop information about expressions based on loop-header PHIs. 6740 SmallVector<Instruction *, 16> Worklist; 6741 Worklist.push_back(I); 6742 6743 SmallPtrSet<Instruction *, 8> Visited; 6744 while (!Worklist.empty()) { 6745 I = Worklist.pop_back_val(); 6746 if (!Visited.insert(I).second) 6747 continue; 6748 6749 ValueExprMapType::iterator It = 6750 ValueExprMap.find_as(static_cast<Value *>(I)); 6751 if (It != ValueExprMap.end()) { 6752 eraseValueFromMap(It->first); 6753 forgetMemoizedResults(It->second); 6754 if (PHINode *PN = dyn_cast<PHINode>(I)) 6755 ConstantEvolutionLoopExitValue.erase(PN); 6756 } 6757 6758 PushDefUseChildren(I, Worklist); 6759 } 6760 } 6761 6762 /// Get the exact loop backedge taken count considering all loop exits. A 6763 /// computable result can only be returned for loops with all exiting blocks 6764 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6765 /// is never skipped. This is a valid assumption as long as the loop exits via 6766 /// that test. For precise results, it is the caller's responsibility to specify 6767 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6768 const SCEV * 6769 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6770 SCEVUnionPredicate *Preds) const { 6771 // If any exits were not computable, the loop is not computable. 6772 if (!isComplete() || ExitNotTaken.empty()) 6773 return SE->getCouldNotCompute(); 6774 6775 const BasicBlock *Latch = L->getLoopLatch(); 6776 // All exiting blocks we have collected must dominate the only backedge. 6777 if (!Latch) 6778 return SE->getCouldNotCompute(); 6779 6780 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6781 // count is simply a minimum out of all these calculated exit counts. 6782 SmallVector<const SCEV *, 2> Ops; 6783 for (auto &ENT : ExitNotTaken) { 6784 const SCEV *BECount = ENT.ExactNotTaken; 6785 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6786 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6787 "We should only have known counts for exiting blocks that dominate " 6788 "latch!"); 6789 6790 Ops.push_back(BECount); 6791 6792 if (Preds && !ENT.hasAlwaysTruePredicate()) 6793 Preds->add(ENT.Predicate.get()); 6794 6795 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6796 "Predicate should be always true!"); 6797 } 6798 6799 return SE->getUMinFromMismatchedTypes(Ops); 6800 } 6801 6802 /// Get the exact not taken count for this loop exit. 6803 const SCEV * 6804 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6805 ScalarEvolution *SE) const { 6806 for (auto &ENT : ExitNotTaken) 6807 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6808 return ENT.ExactNotTaken; 6809 6810 return SE->getCouldNotCompute(); 6811 } 6812 6813 /// getMax - Get the max backedge taken count for the loop. 6814 const SCEV * 6815 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6816 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6817 return !ENT.hasAlwaysTruePredicate(); 6818 }; 6819 6820 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6821 return SE->getCouldNotCompute(); 6822 6823 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6824 "No point in having a non-constant max backedge taken count!"); 6825 return getMax(); 6826 } 6827 6828 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6829 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6830 return !ENT.hasAlwaysTruePredicate(); 6831 }; 6832 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6833 } 6834 6835 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6836 ScalarEvolution *SE) const { 6837 if (getMax() && getMax() != SE->getCouldNotCompute() && 6838 SE->hasOperand(getMax(), S)) 6839 return true; 6840 6841 for (auto &ENT : ExitNotTaken) 6842 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6843 SE->hasOperand(ENT.ExactNotTaken, S)) 6844 return true; 6845 6846 return false; 6847 } 6848 6849 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6850 : ExactNotTaken(E), MaxNotTaken(E) { 6851 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6852 isa<SCEVConstant>(MaxNotTaken)) && 6853 "No point in having a non-constant max backedge taken count!"); 6854 } 6855 6856 ScalarEvolution::ExitLimit::ExitLimit( 6857 const SCEV *E, const SCEV *M, bool MaxOrZero, 6858 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6859 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6860 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6861 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6862 "Exact is not allowed to be less precise than Max"); 6863 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6864 isa<SCEVConstant>(MaxNotTaken)) && 6865 "No point in having a non-constant max backedge taken count!"); 6866 for (auto *PredSet : PredSetList) 6867 for (auto *P : *PredSet) 6868 addPredicate(P); 6869 } 6870 6871 ScalarEvolution::ExitLimit::ExitLimit( 6872 const SCEV *E, const SCEV *M, bool MaxOrZero, 6873 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6874 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6875 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6876 isa<SCEVConstant>(MaxNotTaken)) && 6877 "No point in having a non-constant max backedge taken count!"); 6878 } 6879 6880 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6881 bool MaxOrZero) 6882 : ExitLimit(E, M, MaxOrZero, None) { 6883 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6884 isa<SCEVConstant>(MaxNotTaken)) && 6885 "No point in having a non-constant max backedge taken count!"); 6886 } 6887 6888 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6889 /// computable exit into a persistent ExitNotTakenInfo array. 6890 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6891 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6892 &&ExitCounts, 6893 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6894 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6895 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6896 6897 ExitNotTaken.reserve(ExitCounts.size()); 6898 std::transform( 6899 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6900 [&](const EdgeExitInfo &EEI) { 6901 BasicBlock *ExitBB = EEI.first; 6902 const ExitLimit &EL = EEI.second; 6903 if (EL.Predicates.empty()) 6904 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6905 6906 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6907 for (auto *Pred : EL.Predicates) 6908 Predicate->add(Pred); 6909 6910 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6911 }); 6912 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6913 "No point in having a non-constant max backedge taken count!"); 6914 } 6915 6916 /// Invalidate this result and free the ExitNotTakenInfo array. 6917 void ScalarEvolution::BackedgeTakenInfo::clear() { 6918 ExitNotTaken.clear(); 6919 } 6920 6921 /// Compute the number of times the backedge of the specified loop will execute. 6922 ScalarEvolution::BackedgeTakenInfo 6923 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6924 bool AllowPredicates) { 6925 SmallVector<BasicBlock *, 8> ExitingBlocks; 6926 L->getExitingBlocks(ExitingBlocks); 6927 6928 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6929 6930 SmallVector<EdgeExitInfo, 4> ExitCounts; 6931 bool CouldComputeBECount = true; 6932 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6933 const SCEV *MustExitMaxBECount = nullptr; 6934 const SCEV *MayExitMaxBECount = nullptr; 6935 bool MustExitMaxOrZero = false; 6936 6937 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6938 // and compute maxBECount. 6939 // Do a union of all the predicates here. 6940 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6941 BasicBlock *ExitBB = ExitingBlocks[i]; 6942 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6943 6944 assert((AllowPredicates || EL.Predicates.empty()) && 6945 "Predicated exit limit when predicates are not allowed!"); 6946 6947 // 1. For each exit that can be computed, add an entry to ExitCounts. 6948 // CouldComputeBECount is true only if all exits can be computed. 6949 if (EL.ExactNotTaken == getCouldNotCompute()) 6950 // We couldn't compute an exact value for this exit, so 6951 // we won't be able to compute an exact value for the loop. 6952 CouldComputeBECount = false; 6953 else 6954 ExitCounts.emplace_back(ExitBB, EL); 6955 6956 // 2. Derive the loop's MaxBECount from each exit's max number of 6957 // non-exiting iterations. Partition the loop exits into two kinds: 6958 // LoopMustExits and LoopMayExits. 6959 // 6960 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6961 // is a LoopMayExit. If any computable LoopMustExit is found, then 6962 // MaxBECount is the minimum EL.MaxNotTaken of computable 6963 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6964 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6965 // computable EL.MaxNotTaken. 6966 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6967 DT.dominates(ExitBB, Latch)) { 6968 if (!MustExitMaxBECount) { 6969 MustExitMaxBECount = EL.MaxNotTaken; 6970 MustExitMaxOrZero = EL.MaxOrZero; 6971 } else { 6972 MustExitMaxBECount = 6973 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6974 } 6975 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6976 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6977 MayExitMaxBECount = EL.MaxNotTaken; 6978 else { 6979 MayExitMaxBECount = 6980 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6981 } 6982 } 6983 } 6984 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6985 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6986 // The loop backedge will be taken the maximum or zero times if there's 6987 // a single exit that must be taken the maximum or zero times. 6988 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6989 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6990 MaxBECount, MaxOrZero); 6991 } 6992 6993 ScalarEvolution::ExitLimit 6994 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6995 bool AllowPredicates) { 6996 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 6997 // If our exiting block does not dominate the latch, then its connection with 6998 // loop's exit limit may be far from trivial. 6999 const BasicBlock *Latch = L->getLoopLatch(); 7000 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7001 return getCouldNotCompute(); 7002 7003 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7004 TerminatorInst *Term = ExitingBlock->getTerminator(); 7005 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7006 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7007 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7008 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7009 "It should have one successor in loop and one exit block!"); 7010 // Proceed to the next level to examine the exit condition expression. 7011 return computeExitLimitFromCond( 7012 L, BI->getCondition(), ExitIfTrue, 7013 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7014 } 7015 7016 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7017 // For switch, make sure that there is a single exit from the loop. 7018 BasicBlock *Exit = nullptr; 7019 for (auto *SBB : successors(ExitingBlock)) 7020 if (!L->contains(SBB)) { 7021 if (Exit) // Multiple exit successors. 7022 return getCouldNotCompute(); 7023 Exit = SBB; 7024 } 7025 assert(Exit && "Exiting block must have at least one exit"); 7026 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7027 /*ControlsExit=*/IsOnlyExit); 7028 } 7029 7030 return getCouldNotCompute(); 7031 } 7032 7033 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7034 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7035 bool ControlsExit, bool AllowPredicates) { 7036 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7037 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7038 ControlsExit, AllowPredicates); 7039 } 7040 7041 Optional<ScalarEvolution::ExitLimit> 7042 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7043 bool ExitIfTrue, bool ControlsExit, 7044 bool AllowPredicates) { 7045 (void)this->L; 7046 (void)this->ExitIfTrue; 7047 (void)this->AllowPredicates; 7048 7049 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7050 this->AllowPredicates == AllowPredicates && 7051 "Variance in assumed invariant key components!"); 7052 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7053 if (Itr == TripCountMap.end()) 7054 return None; 7055 return Itr->second; 7056 } 7057 7058 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7059 bool ExitIfTrue, 7060 bool ControlsExit, 7061 bool AllowPredicates, 7062 const ExitLimit &EL) { 7063 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7064 this->AllowPredicates == AllowPredicates && 7065 "Variance in assumed invariant key components!"); 7066 7067 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7068 assert(InsertResult.second && "Expected successful insertion!"); 7069 (void)InsertResult; 7070 (void)ExitIfTrue; 7071 } 7072 7073 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7074 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7075 bool ControlsExit, bool AllowPredicates) { 7076 7077 if (auto MaybeEL = 7078 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7079 return *MaybeEL; 7080 7081 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7082 ControlsExit, AllowPredicates); 7083 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7084 return EL; 7085 } 7086 7087 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7088 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7089 bool ControlsExit, bool AllowPredicates) { 7090 // Check if the controlling expression for this loop is an And or Or. 7091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7092 if (BO->getOpcode() == Instruction::And) { 7093 // Recurse on the operands of the and. 7094 bool EitherMayExit = !ExitIfTrue; 7095 ExitLimit EL0 = computeExitLimitFromCondCached( 7096 Cache, L, BO->getOperand(0), ExitIfTrue, 7097 ControlsExit && !EitherMayExit, AllowPredicates); 7098 ExitLimit EL1 = computeExitLimitFromCondCached( 7099 Cache, L, BO->getOperand(1), ExitIfTrue, 7100 ControlsExit && !EitherMayExit, AllowPredicates); 7101 const SCEV *BECount = getCouldNotCompute(); 7102 const SCEV *MaxBECount = getCouldNotCompute(); 7103 if (EitherMayExit) { 7104 // Both conditions must be true for the loop to continue executing. 7105 // Choose the less conservative count. 7106 if (EL0.ExactNotTaken == getCouldNotCompute() || 7107 EL1.ExactNotTaken == getCouldNotCompute()) 7108 BECount = getCouldNotCompute(); 7109 else 7110 BECount = 7111 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7112 if (EL0.MaxNotTaken == getCouldNotCompute()) 7113 MaxBECount = EL1.MaxNotTaken; 7114 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7115 MaxBECount = EL0.MaxNotTaken; 7116 else 7117 MaxBECount = 7118 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7119 } else { 7120 // Both conditions must be true at the same time for the loop to exit. 7121 // For now, be conservative. 7122 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7123 MaxBECount = EL0.MaxNotTaken; 7124 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7125 BECount = EL0.ExactNotTaken; 7126 } 7127 7128 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7129 // to be more aggressive when computing BECount than when computing 7130 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7131 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7132 // to not. 7133 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7134 !isa<SCEVCouldNotCompute>(BECount)) 7135 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7136 7137 return ExitLimit(BECount, MaxBECount, false, 7138 {&EL0.Predicates, &EL1.Predicates}); 7139 } 7140 if (BO->getOpcode() == Instruction::Or) { 7141 // Recurse on the operands of the or. 7142 bool EitherMayExit = ExitIfTrue; 7143 ExitLimit EL0 = computeExitLimitFromCondCached( 7144 Cache, L, BO->getOperand(0), ExitIfTrue, 7145 ControlsExit && !EitherMayExit, AllowPredicates); 7146 ExitLimit EL1 = computeExitLimitFromCondCached( 7147 Cache, L, BO->getOperand(1), ExitIfTrue, 7148 ControlsExit && !EitherMayExit, AllowPredicates); 7149 const SCEV *BECount = getCouldNotCompute(); 7150 const SCEV *MaxBECount = getCouldNotCompute(); 7151 if (EitherMayExit) { 7152 // Both conditions must be false for the loop to continue executing. 7153 // Choose the less conservative count. 7154 if (EL0.ExactNotTaken == getCouldNotCompute() || 7155 EL1.ExactNotTaken == getCouldNotCompute()) 7156 BECount = getCouldNotCompute(); 7157 else 7158 BECount = 7159 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7160 if (EL0.MaxNotTaken == getCouldNotCompute()) 7161 MaxBECount = EL1.MaxNotTaken; 7162 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7163 MaxBECount = EL0.MaxNotTaken; 7164 else 7165 MaxBECount = 7166 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7167 } else { 7168 // Both conditions must be false at the same time for the loop to exit. 7169 // For now, be conservative. 7170 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7171 MaxBECount = EL0.MaxNotTaken; 7172 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7173 BECount = EL0.ExactNotTaken; 7174 } 7175 7176 return ExitLimit(BECount, MaxBECount, false, 7177 {&EL0.Predicates, &EL1.Predicates}); 7178 } 7179 } 7180 7181 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7182 // Proceed to the next level to examine the icmp. 7183 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7184 ExitLimit EL = 7185 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7186 if (EL.hasFullInfo() || !AllowPredicates) 7187 return EL; 7188 7189 // Try again, but use SCEV predicates this time. 7190 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7191 /*AllowPredicates=*/true); 7192 } 7193 7194 // Check for a constant condition. These are normally stripped out by 7195 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7196 // preserve the CFG and is temporarily leaving constant conditions 7197 // in place. 7198 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7199 if (ExitIfTrue == !CI->getZExtValue()) 7200 // The backedge is always taken. 7201 return getCouldNotCompute(); 7202 else 7203 // The backedge is never taken. 7204 return getZero(CI->getType()); 7205 } 7206 7207 // If it's not an integer or pointer comparison then compute it the hard way. 7208 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7209 } 7210 7211 ScalarEvolution::ExitLimit 7212 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7213 ICmpInst *ExitCond, 7214 bool ExitIfTrue, 7215 bool ControlsExit, 7216 bool AllowPredicates) { 7217 // If the condition was exit on true, convert the condition to exit on false 7218 ICmpInst::Predicate Pred; 7219 if (!ExitIfTrue) 7220 Pred = ExitCond->getPredicate(); 7221 else 7222 Pred = ExitCond->getInversePredicate(); 7223 const ICmpInst::Predicate OriginalPred = Pred; 7224 7225 // Handle common loops like: for (X = "string"; *X; ++X) 7226 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7227 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7228 ExitLimit ItCnt = 7229 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7230 if (ItCnt.hasAnyInfo()) 7231 return ItCnt; 7232 } 7233 7234 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7235 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7236 7237 // Try to evaluate any dependencies out of the loop. 7238 LHS = getSCEVAtScope(LHS, L); 7239 RHS = getSCEVAtScope(RHS, L); 7240 7241 // At this point, we would like to compute how many iterations of the 7242 // loop the predicate will return true for these inputs. 7243 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7244 // If there is a loop-invariant, force it into the RHS. 7245 std::swap(LHS, RHS); 7246 Pred = ICmpInst::getSwappedPredicate(Pred); 7247 } 7248 7249 // Simplify the operands before analyzing them. 7250 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7251 7252 // If we have a comparison of a chrec against a constant, try to use value 7253 // ranges to answer this query. 7254 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7255 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7256 if (AddRec->getLoop() == L) { 7257 // Form the constant range. 7258 ConstantRange CompRange = 7259 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7260 7261 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7262 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7263 } 7264 7265 switch (Pred) { 7266 case ICmpInst::ICMP_NE: { // while (X != Y) 7267 // Convert to: while (X-Y != 0) 7268 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7269 AllowPredicates); 7270 if (EL.hasAnyInfo()) return EL; 7271 break; 7272 } 7273 case ICmpInst::ICMP_EQ: { // while (X == Y) 7274 // Convert to: while (X-Y == 0) 7275 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7276 if (EL.hasAnyInfo()) return EL; 7277 break; 7278 } 7279 case ICmpInst::ICMP_SLT: 7280 case ICmpInst::ICMP_ULT: { // while (X < Y) 7281 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7282 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7283 AllowPredicates); 7284 if (EL.hasAnyInfo()) return EL; 7285 break; 7286 } 7287 case ICmpInst::ICMP_SGT: 7288 case ICmpInst::ICMP_UGT: { // while (X > Y) 7289 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7290 ExitLimit EL = 7291 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7292 AllowPredicates); 7293 if (EL.hasAnyInfo()) return EL; 7294 break; 7295 } 7296 default: 7297 break; 7298 } 7299 7300 auto *ExhaustiveCount = 7301 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7302 7303 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7304 return ExhaustiveCount; 7305 7306 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7307 ExitCond->getOperand(1), L, OriginalPred); 7308 } 7309 7310 ScalarEvolution::ExitLimit 7311 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7312 SwitchInst *Switch, 7313 BasicBlock *ExitingBlock, 7314 bool ControlsExit) { 7315 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7316 7317 // Give up if the exit is the default dest of a switch. 7318 if (Switch->getDefaultDest() == ExitingBlock) 7319 return getCouldNotCompute(); 7320 7321 assert(L->contains(Switch->getDefaultDest()) && 7322 "Default case must not exit the loop!"); 7323 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7324 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7325 7326 // while (X != Y) --> while (X-Y != 0) 7327 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7328 if (EL.hasAnyInfo()) 7329 return EL; 7330 7331 return getCouldNotCompute(); 7332 } 7333 7334 static ConstantInt * 7335 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7336 ScalarEvolution &SE) { 7337 const SCEV *InVal = SE.getConstant(C); 7338 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7339 assert(isa<SCEVConstant>(Val) && 7340 "Evaluation of SCEV at constant didn't fold correctly?"); 7341 return cast<SCEVConstant>(Val)->getValue(); 7342 } 7343 7344 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7345 /// compute the backedge execution count. 7346 ScalarEvolution::ExitLimit 7347 ScalarEvolution::computeLoadConstantCompareExitLimit( 7348 LoadInst *LI, 7349 Constant *RHS, 7350 const Loop *L, 7351 ICmpInst::Predicate predicate) { 7352 if (LI->isVolatile()) return getCouldNotCompute(); 7353 7354 // Check to see if the loaded pointer is a getelementptr of a global. 7355 // TODO: Use SCEV instead of manually grubbing with GEPs. 7356 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7357 if (!GEP) return getCouldNotCompute(); 7358 7359 // Make sure that it is really a constant global we are gepping, with an 7360 // initializer, and make sure the first IDX is really 0. 7361 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7362 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7363 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7364 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7365 return getCouldNotCompute(); 7366 7367 // Okay, we allow one non-constant index into the GEP instruction. 7368 Value *VarIdx = nullptr; 7369 std::vector<Constant*> Indexes; 7370 unsigned VarIdxNum = 0; 7371 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7372 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7373 Indexes.push_back(CI); 7374 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7375 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7376 VarIdx = GEP->getOperand(i); 7377 VarIdxNum = i-2; 7378 Indexes.push_back(nullptr); 7379 } 7380 7381 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7382 if (!VarIdx) 7383 return getCouldNotCompute(); 7384 7385 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7386 // Check to see if X is a loop variant variable value now. 7387 const SCEV *Idx = getSCEV(VarIdx); 7388 Idx = getSCEVAtScope(Idx, L); 7389 7390 // We can only recognize very limited forms of loop index expressions, in 7391 // particular, only affine AddRec's like {C1,+,C2}. 7392 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7393 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7394 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7395 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7396 return getCouldNotCompute(); 7397 7398 unsigned MaxSteps = MaxBruteForceIterations; 7399 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7400 ConstantInt *ItCst = ConstantInt::get( 7401 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7402 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7403 7404 // Form the GEP offset. 7405 Indexes[VarIdxNum] = Val; 7406 7407 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7408 Indexes); 7409 if (!Result) break; // Cannot compute! 7410 7411 // Evaluate the condition for this iteration. 7412 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7413 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7414 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7415 ++NumArrayLenItCounts; 7416 return getConstant(ItCst); // Found terminating iteration! 7417 } 7418 } 7419 return getCouldNotCompute(); 7420 } 7421 7422 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7423 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7424 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7425 if (!RHS) 7426 return getCouldNotCompute(); 7427 7428 const BasicBlock *Latch = L->getLoopLatch(); 7429 if (!Latch) 7430 return getCouldNotCompute(); 7431 7432 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7433 if (!Predecessor) 7434 return getCouldNotCompute(); 7435 7436 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7437 // Return LHS in OutLHS and shift_opt in OutOpCode. 7438 auto MatchPositiveShift = 7439 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7440 7441 using namespace PatternMatch; 7442 7443 ConstantInt *ShiftAmt; 7444 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7445 OutOpCode = Instruction::LShr; 7446 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7447 OutOpCode = Instruction::AShr; 7448 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7449 OutOpCode = Instruction::Shl; 7450 else 7451 return false; 7452 7453 return ShiftAmt->getValue().isStrictlyPositive(); 7454 }; 7455 7456 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7457 // 7458 // loop: 7459 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7460 // %iv.shifted = lshr i32 %iv, <positive constant> 7461 // 7462 // Return true on a successful match. Return the corresponding PHI node (%iv 7463 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7464 auto MatchShiftRecurrence = 7465 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7466 Optional<Instruction::BinaryOps> PostShiftOpCode; 7467 7468 { 7469 Instruction::BinaryOps OpC; 7470 Value *V; 7471 7472 // If we encounter a shift instruction, "peel off" the shift operation, 7473 // and remember that we did so. Later when we inspect %iv's backedge 7474 // value, we will make sure that the backedge value uses the same 7475 // operation. 7476 // 7477 // Note: the peeled shift operation does not have to be the same 7478 // instruction as the one feeding into the PHI's backedge value. We only 7479 // really care about it being the same *kind* of shift instruction -- 7480 // that's all that is required for our later inferences to hold. 7481 if (MatchPositiveShift(LHS, V, OpC)) { 7482 PostShiftOpCode = OpC; 7483 LHS = V; 7484 } 7485 } 7486 7487 PNOut = dyn_cast<PHINode>(LHS); 7488 if (!PNOut || PNOut->getParent() != L->getHeader()) 7489 return false; 7490 7491 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7492 Value *OpLHS; 7493 7494 return 7495 // The backedge value for the PHI node must be a shift by a positive 7496 // amount 7497 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7498 7499 // of the PHI node itself 7500 OpLHS == PNOut && 7501 7502 // and the kind of shift should be match the kind of shift we peeled 7503 // off, if any. 7504 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7505 }; 7506 7507 PHINode *PN; 7508 Instruction::BinaryOps OpCode; 7509 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7510 return getCouldNotCompute(); 7511 7512 const DataLayout &DL = getDataLayout(); 7513 7514 // The key rationale for this optimization is that for some kinds of shift 7515 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7516 // within a finite number of iterations. If the condition guarding the 7517 // backedge (in the sense that the backedge is taken if the condition is true) 7518 // is false for the value the shift recurrence stabilizes to, then we know 7519 // that the backedge is taken only a finite number of times. 7520 7521 ConstantInt *StableValue = nullptr; 7522 switch (OpCode) { 7523 default: 7524 llvm_unreachable("Impossible case!"); 7525 7526 case Instruction::AShr: { 7527 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7528 // bitwidth(K) iterations. 7529 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7530 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7531 Predecessor->getTerminator(), &DT); 7532 auto *Ty = cast<IntegerType>(RHS->getType()); 7533 if (Known.isNonNegative()) 7534 StableValue = ConstantInt::get(Ty, 0); 7535 else if (Known.isNegative()) 7536 StableValue = ConstantInt::get(Ty, -1, true); 7537 else 7538 return getCouldNotCompute(); 7539 7540 break; 7541 } 7542 case Instruction::LShr: 7543 case Instruction::Shl: 7544 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7545 // stabilize to 0 in at most bitwidth(K) iterations. 7546 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7547 break; 7548 } 7549 7550 auto *Result = 7551 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7552 assert(Result->getType()->isIntegerTy(1) && 7553 "Otherwise cannot be an operand to a branch instruction"); 7554 7555 if (Result->isZeroValue()) { 7556 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7557 const SCEV *UpperBound = 7558 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7559 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7560 } 7561 7562 return getCouldNotCompute(); 7563 } 7564 7565 /// Return true if we can constant fold an instruction of the specified type, 7566 /// assuming that all operands were constants. 7567 static bool CanConstantFold(const Instruction *I) { 7568 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7569 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7570 isa<LoadInst>(I)) 7571 return true; 7572 7573 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7574 if (const Function *F = CI->getCalledFunction()) 7575 return canConstantFoldCallTo(CI, F); 7576 return false; 7577 } 7578 7579 /// Determine whether this instruction can constant evolve within this loop 7580 /// assuming its operands can all constant evolve. 7581 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7582 // An instruction outside of the loop can't be derived from a loop PHI. 7583 if (!L->contains(I)) return false; 7584 7585 if (isa<PHINode>(I)) { 7586 // We don't currently keep track of the control flow needed to evaluate 7587 // PHIs, so we cannot handle PHIs inside of loops. 7588 return L->getHeader() == I->getParent(); 7589 } 7590 7591 // If we won't be able to constant fold this expression even if the operands 7592 // are constants, bail early. 7593 return CanConstantFold(I); 7594 } 7595 7596 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7597 /// recursing through each instruction operand until reaching a loop header phi. 7598 static PHINode * 7599 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7600 DenseMap<Instruction *, PHINode *> &PHIMap, 7601 unsigned Depth) { 7602 if (Depth > MaxConstantEvolvingDepth) 7603 return nullptr; 7604 7605 // Otherwise, we can evaluate this instruction if all of its operands are 7606 // constant or derived from a PHI node themselves. 7607 PHINode *PHI = nullptr; 7608 for (Value *Op : UseInst->operands()) { 7609 if (isa<Constant>(Op)) continue; 7610 7611 Instruction *OpInst = dyn_cast<Instruction>(Op); 7612 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7613 7614 PHINode *P = dyn_cast<PHINode>(OpInst); 7615 if (!P) 7616 // If this operand is already visited, reuse the prior result. 7617 // We may have P != PHI if this is the deepest point at which the 7618 // inconsistent paths meet. 7619 P = PHIMap.lookup(OpInst); 7620 if (!P) { 7621 // Recurse and memoize the results, whether a phi is found or not. 7622 // This recursive call invalidates pointers into PHIMap. 7623 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7624 PHIMap[OpInst] = P; 7625 } 7626 if (!P) 7627 return nullptr; // Not evolving from PHI 7628 if (PHI && PHI != P) 7629 return nullptr; // Evolving from multiple different PHIs. 7630 PHI = P; 7631 } 7632 // This is a expression evolving from a constant PHI! 7633 return PHI; 7634 } 7635 7636 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7637 /// in the loop that V is derived from. We allow arbitrary operations along the 7638 /// way, but the operands of an operation must either be constants or a value 7639 /// derived from a constant PHI. If this expression does not fit with these 7640 /// constraints, return null. 7641 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7642 Instruction *I = dyn_cast<Instruction>(V); 7643 if (!I || !canConstantEvolve(I, L)) return nullptr; 7644 7645 if (PHINode *PN = dyn_cast<PHINode>(I)) 7646 return PN; 7647 7648 // Record non-constant instructions contained by the loop. 7649 DenseMap<Instruction *, PHINode *> PHIMap; 7650 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7651 } 7652 7653 /// EvaluateExpression - Given an expression that passes the 7654 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7655 /// in the loop has the value PHIVal. If we can't fold this expression for some 7656 /// reason, return null. 7657 static Constant *EvaluateExpression(Value *V, const Loop *L, 7658 DenseMap<Instruction *, Constant *> &Vals, 7659 const DataLayout &DL, 7660 const TargetLibraryInfo *TLI) { 7661 // Convenient constant check, but redundant for recursive calls. 7662 if (Constant *C = dyn_cast<Constant>(V)) return C; 7663 Instruction *I = dyn_cast<Instruction>(V); 7664 if (!I) return nullptr; 7665 7666 if (Constant *C = Vals.lookup(I)) return C; 7667 7668 // An instruction inside the loop depends on a value outside the loop that we 7669 // weren't given a mapping for, or a value such as a call inside the loop. 7670 if (!canConstantEvolve(I, L)) return nullptr; 7671 7672 // An unmapped PHI can be due to a branch or another loop inside this loop, 7673 // or due to this not being the initial iteration through a loop where we 7674 // couldn't compute the evolution of this particular PHI last time. 7675 if (isa<PHINode>(I)) return nullptr; 7676 7677 std::vector<Constant*> Operands(I->getNumOperands()); 7678 7679 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7680 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7681 if (!Operand) { 7682 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7683 if (!Operands[i]) return nullptr; 7684 continue; 7685 } 7686 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7687 Vals[Operand] = C; 7688 if (!C) return nullptr; 7689 Operands[i] = C; 7690 } 7691 7692 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7693 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7694 Operands[1], DL, TLI); 7695 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7696 if (!LI->isVolatile()) 7697 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7698 } 7699 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7700 } 7701 7702 7703 // If every incoming value to PN except the one for BB is a specific Constant, 7704 // return that, else return nullptr. 7705 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7706 Constant *IncomingVal = nullptr; 7707 7708 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7709 if (PN->getIncomingBlock(i) == BB) 7710 continue; 7711 7712 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7713 if (!CurrentVal) 7714 return nullptr; 7715 7716 if (IncomingVal != CurrentVal) { 7717 if (IncomingVal) 7718 return nullptr; 7719 IncomingVal = CurrentVal; 7720 } 7721 } 7722 7723 return IncomingVal; 7724 } 7725 7726 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7727 /// in the header of its containing loop, we know the loop executes a 7728 /// constant number of times, and the PHI node is just a recurrence 7729 /// involving constants, fold it. 7730 Constant * 7731 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7732 const APInt &BEs, 7733 const Loop *L) { 7734 auto I = ConstantEvolutionLoopExitValue.find(PN); 7735 if (I != ConstantEvolutionLoopExitValue.end()) 7736 return I->second; 7737 7738 if (BEs.ugt(MaxBruteForceIterations)) 7739 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7740 7741 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7742 7743 DenseMap<Instruction *, Constant *> CurrentIterVals; 7744 BasicBlock *Header = L->getHeader(); 7745 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7746 7747 BasicBlock *Latch = L->getLoopLatch(); 7748 if (!Latch) 7749 return nullptr; 7750 7751 for (PHINode &PHI : Header->phis()) { 7752 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7753 CurrentIterVals[&PHI] = StartCST; 7754 } 7755 if (!CurrentIterVals.count(PN)) 7756 return RetVal = nullptr; 7757 7758 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7759 7760 // Execute the loop symbolically to determine the exit value. 7761 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7762 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7763 7764 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7765 unsigned IterationNum = 0; 7766 const DataLayout &DL = getDataLayout(); 7767 for (; ; ++IterationNum) { 7768 if (IterationNum == NumIterations) 7769 return RetVal = CurrentIterVals[PN]; // Got exit value! 7770 7771 // Compute the value of the PHIs for the next iteration. 7772 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7773 DenseMap<Instruction *, Constant *> NextIterVals; 7774 Constant *NextPHI = 7775 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7776 if (!NextPHI) 7777 return nullptr; // Couldn't evaluate! 7778 NextIterVals[PN] = NextPHI; 7779 7780 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7781 7782 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7783 // cease to be able to evaluate one of them or if they stop evolving, 7784 // because that doesn't necessarily prevent us from computing PN. 7785 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7786 for (const auto &I : CurrentIterVals) { 7787 PHINode *PHI = dyn_cast<PHINode>(I.first); 7788 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7789 PHIsToCompute.emplace_back(PHI, I.second); 7790 } 7791 // We use two distinct loops because EvaluateExpression may invalidate any 7792 // iterators into CurrentIterVals. 7793 for (const auto &I : PHIsToCompute) { 7794 PHINode *PHI = I.first; 7795 Constant *&NextPHI = NextIterVals[PHI]; 7796 if (!NextPHI) { // Not already computed. 7797 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7798 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7799 } 7800 if (NextPHI != I.second) 7801 StoppedEvolving = false; 7802 } 7803 7804 // If all entries in CurrentIterVals == NextIterVals then we can stop 7805 // iterating, the loop can't continue to change. 7806 if (StoppedEvolving) 7807 return RetVal = CurrentIterVals[PN]; 7808 7809 CurrentIterVals.swap(NextIterVals); 7810 } 7811 } 7812 7813 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7814 Value *Cond, 7815 bool ExitWhen) { 7816 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7817 if (!PN) return getCouldNotCompute(); 7818 7819 // If the loop is canonicalized, the PHI will have exactly two entries. 7820 // That's the only form we support here. 7821 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7822 7823 DenseMap<Instruction *, Constant *> CurrentIterVals; 7824 BasicBlock *Header = L->getHeader(); 7825 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7826 7827 BasicBlock *Latch = L->getLoopLatch(); 7828 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7829 7830 for (PHINode &PHI : Header->phis()) { 7831 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7832 CurrentIterVals[&PHI] = StartCST; 7833 } 7834 if (!CurrentIterVals.count(PN)) 7835 return getCouldNotCompute(); 7836 7837 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7838 // the loop symbolically to determine when the condition gets a value of 7839 // "ExitWhen". 7840 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7841 const DataLayout &DL = getDataLayout(); 7842 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7843 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7844 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7845 7846 // Couldn't symbolically evaluate. 7847 if (!CondVal) return getCouldNotCompute(); 7848 7849 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7850 ++NumBruteForceTripCountsComputed; 7851 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7852 } 7853 7854 // Update all the PHI nodes for the next iteration. 7855 DenseMap<Instruction *, Constant *> NextIterVals; 7856 7857 // Create a list of which PHIs we need to compute. We want to do this before 7858 // calling EvaluateExpression on them because that may invalidate iterators 7859 // into CurrentIterVals. 7860 SmallVector<PHINode *, 8> PHIsToCompute; 7861 for (const auto &I : CurrentIterVals) { 7862 PHINode *PHI = dyn_cast<PHINode>(I.first); 7863 if (!PHI || PHI->getParent() != Header) continue; 7864 PHIsToCompute.push_back(PHI); 7865 } 7866 for (PHINode *PHI : PHIsToCompute) { 7867 Constant *&NextPHI = NextIterVals[PHI]; 7868 if (NextPHI) continue; // Already computed! 7869 7870 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7871 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7872 } 7873 CurrentIterVals.swap(NextIterVals); 7874 } 7875 7876 // Too many iterations were needed to evaluate. 7877 return getCouldNotCompute(); 7878 } 7879 7880 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7881 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7882 ValuesAtScopes[V]; 7883 // Check to see if we've folded this expression at this loop before. 7884 for (auto &LS : Values) 7885 if (LS.first == L) 7886 return LS.second ? LS.second : V; 7887 7888 Values.emplace_back(L, nullptr); 7889 7890 // Otherwise compute it. 7891 const SCEV *C = computeSCEVAtScope(V, L); 7892 for (auto &LS : reverse(ValuesAtScopes[V])) 7893 if (LS.first == L) { 7894 LS.second = C; 7895 break; 7896 } 7897 return C; 7898 } 7899 7900 /// This builds up a Constant using the ConstantExpr interface. That way, we 7901 /// will return Constants for objects which aren't represented by a 7902 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7903 /// Returns NULL if the SCEV isn't representable as a Constant. 7904 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7905 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7906 case scCouldNotCompute: 7907 case scAddRecExpr: 7908 break; 7909 case scConstant: 7910 return cast<SCEVConstant>(V)->getValue(); 7911 case scUnknown: 7912 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7913 case scSignExtend: { 7914 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7915 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7916 return ConstantExpr::getSExt(CastOp, SS->getType()); 7917 break; 7918 } 7919 case scZeroExtend: { 7920 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7921 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7922 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7923 break; 7924 } 7925 case scTruncate: { 7926 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7927 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7928 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7929 break; 7930 } 7931 case scAddExpr: { 7932 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7933 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7934 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7935 unsigned AS = PTy->getAddressSpace(); 7936 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7937 C = ConstantExpr::getBitCast(C, DestPtrTy); 7938 } 7939 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7940 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7941 if (!C2) return nullptr; 7942 7943 // First pointer! 7944 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7945 unsigned AS = C2->getType()->getPointerAddressSpace(); 7946 std::swap(C, C2); 7947 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7948 // The offsets have been converted to bytes. We can add bytes to an 7949 // i8* by GEP with the byte count in the first index. 7950 C = ConstantExpr::getBitCast(C, DestPtrTy); 7951 } 7952 7953 // Don't bother trying to sum two pointers. We probably can't 7954 // statically compute a load that results from it anyway. 7955 if (C2->getType()->isPointerTy()) 7956 return nullptr; 7957 7958 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7959 if (PTy->getElementType()->isStructTy()) 7960 C2 = ConstantExpr::getIntegerCast( 7961 C2, Type::getInt32Ty(C->getContext()), true); 7962 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7963 } else 7964 C = ConstantExpr::getAdd(C, C2); 7965 } 7966 return C; 7967 } 7968 break; 7969 } 7970 case scMulExpr: { 7971 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7972 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7973 // Don't bother with pointers at all. 7974 if (C->getType()->isPointerTy()) return nullptr; 7975 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7976 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7977 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7978 C = ConstantExpr::getMul(C, C2); 7979 } 7980 return C; 7981 } 7982 break; 7983 } 7984 case scUDivExpr: { 7985 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7986 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7987 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7988 if (LHS->getType() == RHS->getType()) 7989 return ConstantExpr::getUDiv(LHS, RHS); 7990 break; 7991 } 7992 case scSMaxExpr: 7993 case scUMaxExpr: 7994 break; // TODO: smax, umax. 7995 } 7996 return nullptr; 7997 } 7998 7999 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8000 if (isa<SCEVConstant>(V)) return V; 8001 8002 // If this instruction is evolved from a constant-evolving PHI, compute the 8003 // exit value from the loop without using SCEVs. 8004 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8005 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8006 const Loop *LI = this->LI[I->getParent()]; 8007 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 8008 if (PHINode *PN = dyn_cast<PHINode>(I)) 8009 if (PN->getParent() == LI->getHeader()) { 8010 // Okay, there is no closed form solution for the PHI node. Check 8011 // to see if the loop that contains it has a known backedge-taken 8012 // count. If so, we may be able to force computation of the exit 8013 // value. 8014 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8015 if (const SCEVConstant *BTCC = 8016 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8017 8018 // This trivial case can show up in some degenerate cases where 8019 // the incoming IR has not yet been fully simplified. 8020 if (BTCC->getValue()->isZero()) { 8021 Value *InitValue = nullptr; 8022 bool MultipleInitValues = false; 8023 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8024 if (!LI->contains(PN->getIncomingBlock(i))) { 8025 if (!InitValue) 8026 InitValue = PN->getIncomingValue(i); 8027 else if (InitValue != PN->getIncomingValue(i)) { 8028 MultipleInitValues = true; 8029 break; 8030 } 8031 } 8032 if (!MultipleInitValues && InitValue) 8033 return getSCEV(InitValue); 8034 } 8035 } 8036 // Okay, we know how many times the containing loop executes. If 8037 // this is a constant evolving PHI node, get the final value at 8038 // the specified iteration number. 8039 Constant *RV = 8040 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8041 if (RV) return getSCEV(RV); 8042 } 8043 } 8044 8045 // Okay, this is an expression that we cannot symbolically evaluate 8046 // into a SCEV. Check to see if it's possible to symbolically evaluate 8047 // the arguments into constants, and if so, try to constant propagate the 8048 // result. This is particularly useful for computing loop exit values. 8049 if (CanConstantFold(I)) { 8050 SmallVector<Constant *, 4> Operands; 8051 bool MadeImprovement = false; 8052 for (Value *Op : I->operands()) { 8053 if (Constant *C = dyn_cast<Constant>(Op)) { 8054 Operands.push_back(C); 8055 continue; 8056 } 8057 8058 // If any of the operands is non-constant and if they are 8059 // non-integer and non-pointer, don't even try to analyze them 8060 // with scev techniques. 8061 if (!isSCEVable(Op->getType())) 8062 return V; 8063 8064 const SCEV *OrigV = getSCEV(Op); 8065 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8066 MadeImprovement |= OrigV != OpV; 8067 8068 Constant *C = BuildConstantFromSCEV(OpV); 8069 if (!C) return V; 8070 if (C->getType() != Op->getType()) 8071 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8072 Op->getType(), 8073 false), 8074 C, Op->getType()); 8075 Operands.push_back(C); 8076 } 8077 8078 // Check to see if getSCEVAtScope actually made an improvement. 8079 if (MadeImprovement) { 8080 Constant *C = nullptr; 8081 const DataLayout &DL = getDataLayout(); 8082 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8083 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8084 Operands[1], DL, &TLI); 8085 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8086 if (!LI->isVolatile()) 8087 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8088 } else 8089 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8090 if (!C) return V; 8091 return getSCEV(C); 8092 } 8093 } 8094 } 8095 8096 // This is some other type of SCEVUnknown, just return it. 8097 return V; 8098 } 8099 8100 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8101 // Avoid performing the look-up in the common case where the specified 8102 // expression has no loop-variant portions. 8103 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8104 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8105 if (OpAtScope != Comm->getOperand(i)) { 8106 // Okay, at least one of these operands is loop variant but might be 8107 // foldable. Build a new instance of the folded commutative expression. 8108 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8109 Comm->op_begin()+i); 8110 NewOps.push_back(OpAtScope); 8111 8112 for (++i; i != e; ++i) { 8113 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8114 NewOps.push_back(OpAtScope); 8115 } 8116 if (isa<SCEVAddExpr>(Comm)) 8117 return getAddExpr(NewOps); 8118 if (isa<SCEVMulExpr>(Comm)) 8119 return getMulExpr(NewOps); 8120 if (isa<SCEVSMaxExpr>(Comm)) 8121 return getSMaxExpr(NewOps); 8122 if (isa<SCEVUMaxExpr>(Comm)) 8123 return getUMaxExpr(NewOps); 8124 llvm_unreachable("Unknown commutative SCEV type!"); 8125 } 8126 } 8127 // If we got here, all operands are loop invariant. 8128 return Comm; 8129 } 8130 8131 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8132 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8133 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8134 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8135 return Div; // must be loop invariant 8136 return getUDivExpr(LHS, RHS); 8137 } 8138 8139 // If this is a loop recurrence for a loop that does not contain L, then we 8140 // are dealing with the final value computed by the loop. 8141 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8142 // First, attempt to evaluate each operand. 8143 // Avoid performing the look-up in the common case where the specified 8144 // expression has no loop-variant portions. 8145 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8146 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8147 if (OpAtScope == AddRec->getOperand(i)) 8148 continue; 8149 8150 // Okay, at least one of these operands is loop variant but might be 8151 // foldable. Build a new instance of the folded commutative expression. 8152 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8153 AddRec->op_begin()+i); 8154 NewOps.push_back(OpAtScope); 8155 for (++i; i != e; ++i) 8156 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8157 8158 const SCEV *FoldedRec = 8159 getAddRecExpr(NewOps, AddRec->getLoop(), 8160 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8161 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8162 // The addrec may be folded to a nonrecurrence, for example, if the 8163 // induction variable is multiplied by zero after constant folding. Go 8164 // ahead and return the folded value. 8165 if (!AddRec) 8166 return FoldedRec; 8167 break; 8168 } 8169 8170 // If the scope is outside the addrec's loop, evaluate it by using the 8171 // loop exit value of the addrec. 8172 if (!AddRec->getLoop()->contains(L)) { 8173 // To evaluate this recurrence, we need to know how many times the AddRec 8174 // loop iterates. Compute this now. 8175 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8176 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8177 8178 // Then, evaluate the AddRec. 8179 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8180 } 8181 8182 return AddRec; 8183 } 8184 8185 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8186 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8187 if (Op == Cast->getOperand()) 8188 return Cast; // must be loop invariant 8189 return getZeroExtendExpr(Op, Cast->getType()); 8190 } 8191 8192 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8193 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8194 if (Op == Cast->getOperand()) 8195 return Cast; // must be loop invariant 8196 return getSignExtendExpr(Op, Cast->getType()); 8197 } 8198 8199 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8200 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8201 if (Op == Cast->getOperand()) 8202 return Cast; // must be loop invariant 8203 return getTruncateExpr(Op, Cast->getType()); 8204 } 8205 8206 llvm_unreachable("Unknown SCEV type!"); 8207 } 8208 8209 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8210 return getSCEVAtScope(getSCEV(V), L); 8211 } 8212 8213 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8214 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8215 return stripInjectiveFunctions(ZExt->getOperand()); 8216 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8217 return stripInjectiveFunctions(SExt->getOperand()); 8218 return S; 8219 } 8220 8221 /// Finds the minimum unsigned root of the following equation: 8222 /// 8223 /// A * X = B (mod N) 8224 /// 8225 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8226 /// A and B isn't important. 8227 /// 8228 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8229 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8230 ScalarEvolution &SE) { 8231 uint32_t BW = A.getBitWidth(); 8232 assert(BW == SE.getTypeSizeInBits(B->getType())); 8233 assert(A != 0 && "A must be non-zero."); 8234 8235 // 1. D = gcd(A, N) 8236 // 8237 // The gcd of A and N may have only one prime factor: 2. The number of 8238 // trailing zeros in A is its multiplicity 8239 uint32_t Mult2 = A.countTrailingZeros(); 8240 // D = 2^Mult2 8241 8242 // 2. Check if B is divisible by D. 8243 // 8244 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8245 // is not less than multiplicity of this prime factor for D. 8246 if (SE.GetMinTrailingZeros(B) < Mult2) 8247 return SE.getCouldNotCompute(); 8248 8249 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8250 // modulo (N / D). 8251 // 8252 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8253 // (N / D) in general. The inverse itself always fits into BW bits, though, 8254 // so we immediately truncate it. 8255 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8256 APInt Mod(BW + 1, 0); 8257 Mod.setBit(BW - Mult2); // Mod = N / D 8258 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8259 8260 // 4. Compute the minimum unsigned root of the equation: 8261 // I * (B / D) mod (N / D) 8262 // To simplify the computation, we factor out the divide by D: 8263 // (I * B mod N) / D 8264 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8265 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8266 } 8267 8268 /// Find the roots of the quadratic equation for the given quadratic chrec 8269 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8270 /// two SCEVCouldNotCompute objects. 8271 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8272 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8273 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8274 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8275 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8276 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8277 8278 // We currently can only solve this if the coefficients are constants. 8279 if (!LC || !MC || !NC) 8280 return None; 8281 8282 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8283 const APInt &L = LC->getAPInt(); 8284 const APInt &M = MC->getAPInt(); 8285 const APInt &N = NC->getAPInt(); 8286 APInt Two(BitWidth, 2); 8287 8288 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8289 8290 // The A coefficient is N/2 8291 APInt A = N.sdiv(Two); 8292 8293 // The B coefficient is M-N/2 8294 APInt B = M; 8295 B -= A; // A is the same as N/2. 8296 8297 // The C coefficient is L. 8298 const APInt& C = L; 8299 8300 // Compute the B^2-4ac term. 8301 APInt SqrtTerm = B; 8302 SqrtTerm *= B; 8303 SqrtTerm -= 4 * (A * C); 8304 8305 if (SqrtTerm.isNegative()) { 8306 // The loop is provably infinite. 8307 return None; 8308 } 8309 8310 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8311 // integer value or else APInt::sqrt() will assert. 8312 APInt SqrtVal = SqrtTerm.sqrt(); 8313 8314 // Compute the two solutions for the quadratic formula. 8315 // The divisions must be performed as signed divisions. 8316 APInt NegB = -std::move(B); 8317 APInt TwoA = std::move(A); 8318 TwoA <<= 1; 8319 if (TwoA.isNullValue()) 8320 return None; 8321 8322 LLVMContext &Context = SE.getContext(); 8323 8324 ConstantInt *Solution1 = 8325 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8326 ConstantInt *Solution2 = 8327 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8328 8329 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8330 cast<SCEVConstant>(SE.getConstant(Solution2))); 8331 } 8332 8333 ScalarEvolution::ExitLimit 8334 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8335 bool AllowPredicates) { 8336 8337 // This is only used for loops with a "x != y" exit test. The exit condition 8338 // is now expressed as a single expression, V = x-y. So the exit test is 8339 // effectively V != 0. We know and take advantage of the fact that this 8340 // expression only being used in a comparison by zero context. 8341 8342 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8343 // If the value is a constant 8344 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8345 // If the value is already zero, the branch will execute zero times. 8346 if (C->getValue()->isZero()) return C; 8347 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8348 } 8349 8350 const SCEVAddRecExpr *AddRec = 8351 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8352 8353 if (!AddRec && AllowPredicates) 8354 // Try to make this an AddRec using runtime tests, in the first X 8355 // iterations of this loop, where X is the SCEV expression found by the 8356 // algorithm below. 8357 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8358 8359 if (!AddRec || AddRec->getLoop() != L) 8360 return getCouldNotCompute(); 8361 8362 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8363 // the quadratic equation to solve it. 8364 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8365 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8366 const SCEVConstant *R1 = Roots->first; 8367 const SCEVConstant *R2 = Roots->second; 8368 // Pick the smallest positive root value. 8369 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8370 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8371 if (!CB->getZExtValue()) 8372 std::swap(R1, R2); // R1 is the minimum root now. 8373 8374 // We can only use this value if the chrec ends up with an exact zero 8375 // value at this index. When solving for "X*X != 5", for example, we 8376 // should not accept a root of 2. 8377 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8378 if (Val->isZero()) 8379 // We found a quadratic root! 8380 return ExitLimit(R1, R1, false, Predicates); 8381 } 8382 } 8383 return getCouldNotCompute(); 8384 } 8385 8386 // Otherwise we can only handle this if it is affine. 8387 if (!AddRec->isAffine()) 8388 return getCouldNotCompute(); 8389 8390 // If this is an affine expression, the execution count of this branch is 8391 // the minimum unsigned root of the following equation: 8392 // 8393 // Start + Step*N = 0 (mod 2^BW) 8394 // 8395 // equivalent to: 8396 // 8397 // Step*N = -Start (mod 2^BW) 8398 // 8399 // where BW is the common bit width of Start and Step. 8400 8401 // Get the initial value for the loop. 8402 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8403 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8404 8405 // For now we handle only constant steps. 8406 // 8407 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8408 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8409 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8410 // We have not yet seen any such cases. 8411 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8412 if (!StepC || StepC->getValue()->isZero()) 8413 return getCouldNotCompute(); 8414 8415 // For positive steps (counting up until unsigned overflow): 8416 // N = -Start/Step (as unsigned) 8417 // For negative steps (counting down to zero): 8418 // N = Start/-Step 8419 // First compute the unsigned distance from zero in the direction of Step. 8420 bool CountDown = StepC->getAPInt().isNegative(); 8421 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8422 8423 // Handle unitary steps, which cannot wraparound. 8424 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8425 // N = Distance (as unsigned) 8426 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8427 APInt MaxBECount = getUnsignedRangeMax(Distance); 8428 8429 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8430 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8431 // case, and see if we can improve the bound. 8432 // 8433 // Explicitly handling this here is necessary because getUnsignedRange 8434 // isn't context-sensitive; it doesn't know that we only care about the 8435 // range inside the loop. 8436 const SCEV *Zero = getZero(Distance->getType()); 8437 const SCEV *One = getOne(Distance->getType()); 8438 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8439 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8440 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8441 // as "unsigned_max(Distance + 1) - 1". 8442 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8443 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8444 } 8445 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8446 } 8447 8448 // If the condition controls loop exit (the loop exits only if the expression 8449 // is true) and the addition is no-wrap we can use unsigned divide to 8450 // compute the backedge count. In this case, the step may not divide the 8451 // distance, but we don't care because if the condition is "missed" the loop 8452 // will have undefined behavior due to wrapping. 8453 if (ControlsExit && AddRec->hasNoSelfWrap() && 8454 loopHasNoAbnormalExits(AddRec->getLoop())) { 8455 const SCEV *Exact = 8456 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8457 const SCEV *Max = 8458 Exact == getCouldNotCompute() 8459 ? Exact 8460 : getConstant(getUnsignedRangeMax(Exact)); 8461 return ExitLimit(Exact, Max, false, Predicates); 8462 } 8463 8464 // Solve the general equation. 8465 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8466 getNegativeSCEV(Start), *this); 8467 const SCEV *M = E == getCouldNotCompute() 8468 ? E 8469 : getConstant(getUnsignedRangeMax(E)); 8470 return ExitLimit(E, M, false, Predicates); 8471 } 8472 8473 ScalarEvolution::ExitLimit 8474 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8475 // Loops that look like: while (X == 0) are very strange indeed. We don't 8476 // handle them yet except for the trivial case. This could be expanded in the 8477 // future as needed. 8478 8479 // If the value is a constant, check to see if it is known to be non-zero 8480 // already. If so, the backedge will execute zero times. 8481 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8482 if (!C->getValue()->isZero()) 8483 return getZero(C->getType()); 8484 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8485 } 8486 8487 // We could implement others, but I really doubt anyone writes loops like 8488 // this, and if they did, they would already be constant folded. 8489 return getCouldNotCompute(); 8490 } 8491 8492 std::pair<BasicBlock *, BasicBlock *> 8493 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8494 // If the block has a unique predecessor, then there is no path from the 8495 // predecessor to the block that does not go through the direct edge 8496 // from the predecessor to the block. 8497 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8498 return {Pred, BB}; 8499 8500 // A loop's header is defined to be a block that dominates the loop. 8501 // If the header has a unique predecessor outside the loop, it must be 8502 // a block that has exactly one successor that can reach the loop. 8503 if (Loop *L = LI.getLoopFor(BB)) 8504 return {L->getLoopPredecessor(), L->getHeader()}; 8505 8506 return {nullptr, nullptr}; 8507 } 8508 8509 /// SCEV structural equivalence is usually sufficient for testing whether two 8510 /// expressions are equal, however for the purposes of looking for a condition 8511 /// guarding a loop, it can be useful to be a little more general, since a 8512 /// front-end may have replicated the controlling expression. 8513 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8514 // Quick check to see if they are the same SCEV. 8515 if (A == B) return true; 8516 8517 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8518 // Not all instructions that are "identical" compute the same value. For 8519 // instance, two distinct alloca instructions allocating the same type are 8520 // identical and do not read memory; but compute distinct values. 8521 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8522 }; 8523 8524 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8525 // two different instructions with the same value. Check for this case. 8526 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8527 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8528 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8529 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8530 if (ComputesEqualValues(AI, BI)) 8531 return true; 8532 8533 // Otherwise assume they may have a different value. 8534 return false; 8535 } 8536 8537 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8538 const SCEV *&LHS, const SCEV *&RHS, 8539 unsigned Depth) { 8540 bool Changed = false; 8541 8542 // If we hit the max recursion limit bail out. 8543 if (Depth >= 3) 8544 return false; 8545 8546 // Canonicalize a constant to the right side. 8547 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8548 // Check for both operands constant. 8549 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8550 if (ConstantExpr::getICmp(Pred, 8551 LHSC->getValue(), 8552 RHSC->getValue())->isNullValue()) 8553 goto trivially_false; 8554 else 8555 goto trivially_true; 8556 } 8557 // Otherwise swap the operands to put the constant on the right. 8558 std::swap(LHS, RHS); 8559 Pred = ICmpInst::getSwappedPredicate(Pred); 8560 Changed = true; 8561 } 8562 8563 // If we're comparing an addrec with a value which is loop-invariant in the 8564 // addrec's loop, put the addrec on the left. Also make a dominance check, 8565 // as both operands could be addrecs loop-invariant in each other's loop. 8566 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8567 const Loop *L = AR->getLoop(); 8568 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8569 std::swap(LHS, RHS); 8570 Pred = ICmpInst::getSwappedPredicate(Pred); 8571 Changed = true; 8572 } 8573 } 8574 8575 // If there's a constant operand, canonicalize comparisons with boundary 8576 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8577 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8578 const APInt &RA = RC->getAPInt(); 8579 8580 bool SimplifiedByConstantRange = false; 8581 8582 if (!ICmpInst::isEquality(Pred)) { 8583 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8584 if (ExactCR.isFullSet()) 8585 goto trivially_true; 8586 else if (ExactCR.isEmptySet()) 8587 goto trivially_false; 8588 8589 APInt NewRHS; 8590 CmpInst::Predicate NewPred; 8591 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8592 ICmpInst::isEquality(NewPred)) { 8593 // We were able to convert an inequality to an equality. 8594 Pred = NewPred; 8595 RHS = getConstant(NewRHS); 8596 Changed = SimplifiedByConstantRange = true; 8597 } 8598 } 8599 8600 if (!SimplifiedByConstantRange) { 8601 switch (Pred) { 8602 default: 8603 break; 8604 case ICmpInst::ICMP_EQ: 8605 case ICmpInst::ICMP_NE: 8606 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8607 if (!RA) 8608 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8609 if (const SCEVMulExpr *ME = 8610 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8611 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8612 ME->getOperand(0)->isAllOnesValue()) { 8613 RHS = AE->getOperand(1); 8614 LHS = ME->getOperand(1); 8615 Changed = true; 8616 } 8617 break; 8618 8619 8620 // The "Should have been caught earlier!" messages refer to the fact 8621 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8622 // should have fired on the corresponding cases, and canonicalized the 8623 // check to trivially_true or trivially_false. 8624 8625 case ICmpInst::ICMP_UGE: 8626 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8627 Pred = ICmpInst::ICMP_UGT; 8628 RHS = getConstant(RA - 1); 8629 Changed = true; 8630 break; 8631 case ICmpInst::ICMP_ULE: 8632 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8633 Pred = ICmpInst::ICMP_ULT; 8634 RHS = getConstant(RA + 1); 8635 Changed = true; 8636 break; 8637 case ICmpInst::ICMP_SGE: 8638 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8639 Pred = ICmpInst::ICMP_SGT; 8640 RHS = getConstant(RA - 1); 8641 Changed = true; 8642 break; 8643 case ICmpInst::ICMP_SLE: 8644 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8645 Pred = ICmpInst::ICMP_SLT; 8646 RHS = getConstant(RA + 1); 8647 Changed = true; 8648 break; 8649 } 8650 } 8651 } 8652 8653 // Check for obvious equality. 8654 if (HasSameValue(LHS, RHS)) { 8655 if (ICmpInst::isTrueWhenEqual(Pred)) 8656 goto trivially_true; 8657 if (ICmpInst::isFalseWhenEqual(Pred)) 8658 goto trivially_false; 8659 } 8660 8661 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8662 // adding or subtracting 1 from one of the operands. 8663 switch (Pred) { 8664 case ICmpInst::ICMP_SLE: 8665 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8666 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8667 SCEV::FlagNSW); 8668 Pred = ICmpInst::ICMP_SLT; 8669 Changed = true; 8670 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8671 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8672 SCEV::FlagNSW); 8673 Pred = ICmpInst::ICMP_SLT; 8674 Changed = true; 8675 } 8676 break; 8677 case ICmpInst::ICMP_SGE: 8678 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8679 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8680 SCEV::FlagNSW); 8681 Pred = ICmpInst::ICMP_SGT; 8682 Changed = true; 8683 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8684 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8685 SCEV::FlagNSW); 8686 Pred = ICmpInst::ICMP_SGT; 8687 Changed = true; 8688 } 8689 break; 8690 case ICmpInst::ICMP_ULE: 8691 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8692 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8693 SCEV::FlagNUW); 8694 Pred = ICmpInst::ICMP_ULT; 8695 Changed = true; 8696 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8697 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8698 Pred = ICmpInst::ICMP_ULT; 8699 Changed = true; 8700 } 8701 break; 8702 case ICmpInst::ICMP_UGE: 8703 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8704 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8705 Pred = ICmpInst::ICMP_UGT; 8706 Changed = true; 8707 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8708 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8709 SCEV::FlagNUW); 8710 Pred = ICmpInst::ICMP_UGT; 8711 Changed = true; 8712 } 8713 break; 8714 default: 8715 break; 8716 } 8717 8718 // TODO: More simplifications are possible here. 8719 8720 // Recursively simplify until we either hit a recursion limit or nothing 8721 // changes. 8722 if (Changed) 8723 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8724 8725 return Changed; 8726 8727 trivially_true: 8728 // Return 0 == 0. 8729 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8730 Pred = ICmpInst::ICMP_EQ; 8731 return true; 8732 8733 trivially_false: 8734 // Return 0 != 0. 8735 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8736 Pred = ICmpInst::ICMP_NE; 8737 return true; 8738 } 8739 8740 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8741 return getSignedRangeMax(S).isNegative(); 8742 } 8743 8744 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8745 return getSignedRangeMin(S).isStrictlyPositive(); 8746 } 8747 8748 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8749 return !getSignedRangeMin(S).isNegative(); 8750 } 8751 8752 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8753 return !getSignedRangeMax(S).isStrictlyPositive(); 8754 } 8755 8756 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8757 return isKnownNegative(S) || isKnownPositive(S); 8758 } 8759 8760 std::pair<const SCEV *, const SCEV *> 8761 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8762 // Compute SCEV on entry of loop L. 8763 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8764 if (Start == getCouldNotCompute()) 8765 return { Start, Start }; 8766 // Compute post increment SCEV for loop L. 8767 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8768 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8769 return { Start, PostInc }; 8770 } 8771 8772 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8773 const SCEV *LHS, const SCEV *RHS) { 8774 // First collect all loops. 8775 SmallPtrSet<const Loop *, 8> LoopsUsed; 8776 getUsedLoops(LHS, LoopsUsed); 8777 getUsedLoops(RHS, LoopsUsed); 8778 8779 if (LoopsUsed.empty()) 8780 return false; 8781 8782 // Domination relationship must be a linear order on collected loops. 8783 #ifndef NDEBUG 8784 for (auto *L1 : LoopsUsed) 8785 for (auto *L2 : LoopsUsed) 8786 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8787 DT.dominates(L2->getHeader(), L1->getHeader())) && 8788 "Domination relationship is not a linear order"); 8789 #endif 8790 8791 const Loop *MDL = 8792 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8793 [&](const Loop *L1, const Loop *L2) { 8794 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 8795 }); 8796 8797 // Get init and post increment value for LHS. 8798 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 8799 // if LHS contains unknown non-invariant SCEV then bail out. 8800 if (SplitLHS.first == getCouldNotCompute()) 8801 return false; 8802 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 8803 // Get init and post increment value for RHS. 8804 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 8805 // if RHS contains unknown non-invariant SCEV then bail out. 8806 if (SplitRHS.first == getCouldNotCompute()) 8807 return false; 8808 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 8809 // It is possible that init SCEV contains an invariant load but it does 8810 // not dominate MDL and is not available at MDL loop entry, so we should 8811 // check it here. 8812 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 8813 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 8814 return false; 8815 8816 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 8817 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 8818 SplitRHS.second); 8819 } 8820 8821 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8822 const SCEV *LHS, const SCEV *RHS) { 8823 // Canonicalize the inputs first. 8824 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8825 8826 if (isKnownViaInduction(Pred, LHS, RHS)) 8827 return true; 8828 8829 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8830 return true; 8831 8832 // Otherwise see what can be done with some simple reasoning. 8833 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 8834 } 8835 8836 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 8837 const SCEVAddRecExpr *LHS, 8838 const SCEV *RHS) { 8839 const Loop *L = LHS->getLoop(); 8840 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 8841 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 8842 } 8843 8844 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8845 ICmpInst::Predicate Pred, 8846 bool &Increasing) { 8847 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8848 8849 #ifndef NDEBUG 8850 // Verify an invariant: inverting the predicate should turn a monotonically 8851 // increasing change to a monotonically decreasing one, and vice versa. 8852 bool IncreasingSwapped; 8853 bool ResultSwapped = isMonotonicPredicateImpl( 8854 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8855 8856 assert(Result == ResultSwapped && "should be able to analyze both!"); 8857 if (ResultSwapped) 8858 assert(Increasing == !IncreasingSwapped && 8859 "monotonicity should flip as we flip the predicate"); 8860 #endif 8861 8862 return Result; 8863 } 8864 8865 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8866 ICmpInst::Predicate Pred, 8867 bool &Increasing) { 8868 8869 // A zero step value for LHS means the induction variable is essentially a 8870 // loop invariant value. We don't really depend on the predicate actually 8871 // flipping from false to true (for increasing predicates, and the other way 8872 // around for decreasing predicates), all we care about is that *if* the 8873 // predicate changes then it only changes from false to true. 8874 // 8875 // A zero step value in itself is not very useful, but there may be places 8876 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8877 // as general as possible. 8878 8879 switch (Pred) { 8880 default: 8881 return false; // Conservative answer 8882 8883 case ICmpInst::ICMP_UGT: 8884 case ICmpInst::ICMP_UGE: 8885 case ICmpInst::ICMP_ULT: 8886 case ICmpInst::ICMP_ULE: 8887 if (!LHS->hasNoUnsignedWrap()) 8888 return false; 8889 8890 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8891 return true; 8892 8893 case ICmpInst::ICMP_SGT: 8894 case ICmpInst::ICMP_SGE: 8895 case ICmpInst::ICMP_SLT: 8896 case ICmpInst::ICMP_SLE: { 8897 if (!LHS->hasNoSignedWrap()) 8898 return false; 8899 8900 const SCEV *Step = LHS->getStepRecurrence(*this); 8901 8902 if (isKnownNonNegative(Step)) { 8903 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8904 return true; 8905 } 8906 8907 if (isKnownNonPositive(Step)) { 8908 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8909 return true; 8910 } 8911 8912 return false; 8913 } 8914 8915 } 8916 8917 llvm_unreachable("switch has default clause!"); 8918 } 8919 8920 bool ScalarEvolution::isLoopInvariantPredicate( 8921 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8922 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8923 const SCEV *&InvariantRHS) { 8924 8925 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8926 if (!isLoopInvariant(RHS, L)) { 8927 if (!isLoopInvariant(LHS, L)) 8928 return false; 8929 8930 std::swap(LHS, RHS); 8931 Pred = ICmpInst::getSwappedPredicate(Pred); 8932 } 8933 8934 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8935 if (!ArLHS || ArLHS->getLoop() != L) 8936 return false; 8937 8938 bool Increasing; 8939 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8940 return false; 8941 8942 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8943 // true as the loop iterates, and the backedge is control dependent on 8944 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8945 // 8946 // * if the predicate was false in the first iteration then the predicate 8947 // is never evaluated again, since the loop exits without taking the 8948 // backedge. 8949 // * if the predicate was true in the first iteration then it will 8950 // continue to be true for all future iterations since it is 8951 // monotonically increasing. 8952 // 8953 // For both the above possibilities, we can replace the loop varying 8954 // predicate with its value on the first iteration of the loop (which is 8955 // loop invariant). 8956 // 8957 // A similar reasoning applies for a monotonically decreasing predicate, by 8958 // replacing true with false and false with true in the above two bullets. 8959 8960 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8961 8962 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8963 return false; 8964 8965 InvariantPred = Pred; 8966 InvariantLHS = ArLHS->getStart(); 8967 InvariantRHS = RHS; 8968 return true; 8969 } 8970 8971 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8972 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8973 if (HasSameValue(LHS, RHS)) 8974 return ICmpInst::isTrueWhenEqual(Pred); 8975 8976 // This code is split out from isKnownPredicate because it is called from 8977 // within isLoopEntryGuardedByCond. 8978 8979 auto CheckRanges = 8980 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8981 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8982 .contains(RangeLHS); 8983 }; 8984 8985 // The check at the top of the function catches the case where the values are 8986 // known to be equal. 8987 if (Pred == CmpInst::ICMP_EQ) 8988 return false; 8989 8990 if (Pred == CmpInst::ICMP_NE) 8991 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8992 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8993 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8994 8995 if (CmpInst::isSigned(Pred)) 8996 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8997 8998 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8999 } 9000 9001 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9002 const SCEV *LHS, 9003 const SCEV *RHS) { 9004 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9005 // Return Y via OutY. 9006 auto MatchBinaryAddToConst = 9007 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9008 SCEV::NoWrapFlags ExpectedFlags) { 9009 const SCEV *NonConstOp, *ConstOp; 9010 SCEV::NoWrapFlags FlagsPresent; 9011 9012 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9013 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9014 return false; 9015 9016 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9017 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9018 }; 9019 9020 APInt C; 9021 9022 switch (Pred) { 9023 default: 9024 break; 9025 9026 case ICmpInst::ICMP_SGE: 9027 std::swap(LHS, RHS); 9028 LLVM_FALLTHROUGH; 9029 case ICmpInst::ICMP_SLE: 9030 // X s<= (X + C)<nsw> if C >= 0 9031 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9032 return true; 9033 9034 // (X + C)<nsw> s<= X if C <= 0 9035 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9036 !C.isStrictlyPositive()) 9037 return true; 9038 break; 9039 9040 case ICmpInst::ICMP_SGT: 9041 std::swap(LHS, RHS); 9042 LLVM_FALLTHROUGH; 9043 case ICmpInst::ICMP_SLT: 9044 // X s< (X + C)<nsw> if C > 0 9045 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9046 C.isStrictlyPositive()) 9047 return true; 9048 9049 // (X + C)<nsw> s< X if C < 0 9050 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9051 return true; 9052 break; 9053 } 9054 9055 return false; 9056 } 9057 9058 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9059 const SCEV *LHS, 9060 const SCEV *RHS) { 9061 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9062 return false; 9063 9064 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9065 // the stack can result in exponential time complexity. 9066 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9067 9068 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9069 // 9070 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9071 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9072 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9073 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9074 // use isKnownPredicate later if needed. 9075 return isKnownNonNegative(RHS) && 9076 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9077 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9078 } 9079 9080 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9081 ICmpInst::Predicate Pred, 9082 const SCEV *LHS, const SCEV *RHS) { 9083 // No need to even try if we know the module has no guards. 9084 if (!HasGuards) 9085 return false; 9086 9087 return any_of(*BB, [&](Instruction &I) { 9088 using namespace llvm::PatternMatch; 9089 9090 Value *Condition; 9091 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9092 m_Value(Condition))) && 9093 isImpliedCond(Pred, LHS, RHS, Condition, false); 9094 }); 9095 } 9096 9097 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9098 /// protected by a conditional between LHS and RHS. This is used to 9099 /// to eliminate casts. 9100 bool 9101 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9102 ICmpInst::Predicate Pred, 9103 const SCEV *LHS, const SCEV *RHS) { 9104 // Interpret a null as meaning no loop, where there is obviously no guard 9105 // (interprocedural conditions notwithstanding). 9106 if (!L) return true; 9107 9108 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9109 return true; 9110 9111 BasicBlock *Latch = L->getLoopLatch(); 9112 if (!Latch) 9113 return false; 9114 9115 BranchInst *LoopContinuePredicate = 9116 dyn_cast<BranchInst>(Latch->getTerminator()); 9117 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9118 isImpliedCond(Pred, LHS, RHS, 9119 LoopContinuePredicate->getCondition(), 9120 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9121 return true; 9122 9123 // We don't want more than one activation of the following loops on the stack 9124 // -- that can lead to O(n!) time complexity. 9125 if (WalkingBEDominatingConds) 9126 return false; 9127 9128 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9129 9130 // See if we can exploit a trip count to prove the predicate. 9131 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9132 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9133 if (LatchBECount != getCouldNotCompute()) { 9134 // We know that Latch branches back to the loop header exactly 9135 // LatchBECount times. This means the backdege condition at Latch is 9136 // equivalent to "{0,+,1} u< LatchBECount". 9137 Type *Ty = LatchBECount->getType(); 9138 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9139 const SCEV *LoopCounter = 9140 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9141 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9142 LatchBECount)) 9143 return true; 9144 } 9145 9146 // Check conditions due to any @llvm.assume intrinsics. 9147 for (auto &AssumeVH : AC.assumptions()) { 9148 if (!AssumeVH) 9149 continue; 9150 auto *CI = cast<CallInst>(AssumeVH); 9151 if (!DT.dominates(CI, Latch->getTerminator())) 9152 continue; 9153 9154 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9155 return true; 9156 } 9157 9158 // If the loop is not reachable from the entry block, we risk running into an 9159 // infinite loop as we walk up into the dom tree. These loops do not matter 9160 // anyway, so we just return a conservative answer when we see them. 9161 if (!DT.isReachableFromEntry(L->getHeader())) 9162 return false; 9163 9164 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9165 return true; 9166 9167 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9168 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9169 assert(DTN && "should reach the loop header before reaching the root!"); 9170 9171 BasicBlock *BB = DTN->getBlock(); 9172 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9173 return true; 9174 9175 BasicBlock *PBB = BB->getSinglePredecessor(); 9176 if (!PBB) 9177 continue; 9178 9179 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9180 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9181 continue; 9182 9183 Value *Condition = ContinuePredicate->getCondition(); 9184 9185 // If we have an edge `E` within the loop body that dominates the only 9186 // latch, the condition guarding `E` also guards the backedge. This 9187 // reasoning works only for loops with a single latch. 9188 9189 BasicBlockEdge DominatingEdge(PBB, BB); 9190 if (DominatingEdge.isSingleEdge()) { 9191 // We're constructively (and conservatively) enumerating edges within the 9192 // loop body that dominate the latch. The dominator tree better agree 9193 // with us on this: 9194 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9195 9196 if (isImpliedCond(Pred, LHS, RHS, Condition, 9197 BB != ContinuePredicate->getSuccessor(0))) 9198 return true; 9199 } 9200 } 9201 9202 return false; 9203 } 9204 9205 bool 9206 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9207 ICmpInst::Predicate Pred, 9208 const SCEV *LHS, const SCEV *RHS) { 9209 // Interpret a null as meaning no loop, where there is obviously no guard 9210 // (interprocedural conditions notwithstanding). 9211 if (!L) return false; 9212 9213 // Both LHS and RHS must be available at loop entry. 9214 assert(isAvailableAtLoopEntry(LHS, L) && 9215 "LHS is not available at Loop Entry"); 9216 assert(isAvailableAtLoopEntry(RHS, L) && 9217 "RHS is not available at Loop Entry"); 9218 9219 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9220 return true; 9221 9222 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9223 // the facts (a >= b && a != b) separately. A typical situation is when the 9224 // non-strict comparison is known from ranges and non-equality is known from 9225 // dominating predicates. If we are proving strict comparison, we always try 9226 // to prove non-equality and non-strict comparison separately. 9227 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9228 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9229 bool ProvedNonStrictComparison = false; 9230 bool ProvedNonEquality = false; 9231 9232 if (ProvingStrictComparison) { 9233 ProvedNonStrictComparison = 9234 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9235 ProvedNonEquality = 9236 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9237 if (ProvedNonStrictComparison && ProvedNonEquality) 9238 return true; 9239 } 9240 9241 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9242 auto ProveViaGuard = [&](BasicBlock *Block) { 9243 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9244 return true; 9245 if (ProvingStrictComparison) { 9246 if (!ProvedNonStrictComparison) 9247 ProvedNonStrictComparison = 9248 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9249 if (!ProvedNonEquality) 9250 ProvedNonEquality = 9251 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9252 if (ProvedNonStrictComparison && ProvedNonEquality) 9253 return true; 9254 } 9255 return false; 9256 }; 9257 9258 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9259 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9260 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9261 return true; 9262 if (ProvingStrictComparison) { 9263 if (!ProvedNonStrictComparison) 9264 ProvedNonStrictComparison = 9265 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9266 if (!ProvedNonEquality) 9267 ProvedNonEquality = 9268 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9269 if (ProvedNonStrictComparison && ProvedNonEquality) 9270 return true; 9271 } 9272 return false; 9273 }; 9274 9275 // Starting at the loop predecessor, climb up the predecessor chain, as long 9276 // as there are predecessors that can be found that have unique successors 9277 // leading to the original header. 9278 for (std::pair<BasicBlock *, BasicBlock *> 9279 Pair(L->getLoopPredecessor(), L->getHeader()); 9280 Pair.first; 9281 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9282 9283 if (ProveViaGuard(Pair.first)) 9284 return true; 9285 9286 BranchInst *LoopEntryPredicate = 9287 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9288 if (!LoopEntryPredicate || 9289 LoopEntryPredicate->isUnconditional()) 9290 continue; 9291 9292 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9293 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9294 return true; 9295 } 9296 9297 // Check conditions due to any @llvm.assume intrinsics. 9298 for (auto &AssumeVH : AC.assumptions()) { 9299 if (!AssumeVH) 9300 continue; 9301 auto *CI = cast<CallInst>(AssumeVH); 9302 if (!DT.dominates(CI, L->getHeader())) 9303 continue; 9304 9305 if (ProveViaCond(CI->getArgOperand(0), false)) 9306 return true; 9307 } 9308 9309 return false; 9310 } 9311 9312 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9313 const SCEV *LHS, const SCEV *RHS, 9314 Value *FoundCondValue, 9315 bool Inverse) { 9316 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9317 return false; 9318 9319 auto ClearOnExit = 9320 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9321 9322 // Recursively handle And and Or conditions. 9323 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9324 if (BO->getOpcode() == Instruction::And) { 9325 if (!Inverse) 9326 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9327 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9328 } else if (BO->getOpcode() == Instruction::Or) { 9329 if (Inverse) 9330 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9331 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9332 } 9333 } 9334 9335 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9336 if (!ICI) return false; 9337 9338 // Now that we found a conditional branch that dominates the loop or controls 9339 // the loop latch. Check to see if it is the comparison we are looking for. 9340 ICmpInst::Predicate FoundPred; 9341 if (Inverse) 9342 FoundPred = ICI->getInversePredicate(); 9343 else 9344 FoundPred = ICI->getPredicate(); 9345 9346 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9347 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9348 9349 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9350 } 9351 9352 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9353 const SCEV *RHS, 9354 ICmpInst::Predicate FoundPred, 9355 const SCEV *FoundLHS, 9356 const SCEV *FoundRHS) { 9357 // Balance the types. 9358 if (getTypeSizeInBits(LHS->getType()) < 9359 getTypeSizeInBits(FoundLHS->getType())) { 9360 if (CmpInst::isSigned(Pred)) { 9361 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9362 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9363 } else { 9364 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9365 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9366 } 9367 } else if (getTypeSizeInBits(LHS->getType()) > 9368 getTypeSizeInBits(FoundLHS->getType())) { 9369 if (CmpInst::isSigned(FoundPred)) { 9370 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9371 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9372 } else { 9373 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9374 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9375 } 9376 } 9377 9378 // Canonicalize the query to match the way instcombine will have 9379 // canonicalized the comparison. 9380 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9381 if (LHS == RHS) 9382 return CmpInst::isTrueWhenEqual(Pred); 9383 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9384 if (FoundLHS == FoundRHS) 9385 return CmpInst::isFalseWhenEqual(FoundPred); 9386 9387 // Check to see if we can make the LHS or RHS match. 9388 if (LHS == FoundRHS || RHS == FoundLHS) { 9389 if (isa<SCEVConstant>(RHS)) { 9390 std::swap(FoundLHS, FoundRHS); 9391 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9392 } else { 9393 std::swap(LHS, RHS); 9394 Pred = ICmpInst::getSwappedPredicate(Pred); 9395 } 9396 } 9397 9398 // Check whether the found predicate is the same as the desired predicate. 9399 if (FoundPred == Pred) 9400 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9401 9402 // Check whether swapping the found predicate makes it the same as the 9403 // desired predicate. 9404 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9405 if (isa<SCEVConstant>(RHS)) 9406 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9407 else 9408 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9409 RHS, LHS, FoundLHS, FoundRHS); 9410 } 9411 9412 // Unsigned comparison is the same as signed comparison when both the operands 9413 // are non-negative. 9414 if (CmpInst::isUnsigned(FoundPred) && 9415 CmpInst::getSignedPredicate(FoundPred) == Pred && 9416 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9417 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9418 9419 // Check if we can make progress by sharpening ranges. 9420 if (FoundPred == ICmpInst::ICMP_NE && 9421 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9422 9423 const SCEVConstant *C = nullptr; 9424 const SCEV *V = nullptr; 9425 9426 if (isa<SCEVConstant>(FoundLHS)) { 9427 C = cast<SCEVConstant>(FoundLHS); 9428 V = FoundRHS; 9429 } else { 9430 C = cast<SCEVConstant>(FoundRHS); 9431 V = FoundLHS; 9432 } 9433 9434 // The guarding predicate tells us that C != V. If the known range 9435 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9436 // range we consider has to correspond to same signedness as the 9437 // predicate we're interested in folding. 9438 9439 APInt Min = ICmpInst::isSigned(Pred) ? 9440 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9441 9442 if (Min == C->getAPInt()) { 9443 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9444 // This is true even if (Min + 1) wraps around -- in case of 9445 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9446 9447 APInt SharperMin = Min + 1; 9448 9449 switch (Pred) { 9450 case ICmpInst::ICMP_SGE: 9451 case ICmpInst::ICMP_UGE: 9452 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9453 // RHS, we're done. 9454 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9455 getConstant(SharperMin))) 9456 return true; 9457 LLVM_FALLTHROUGH; 9458 9459 case ICmpInst::ICMP_SGT: 9460 case ICmpInst::ICMP_UGT: 9461 // We know from the range information that (V `Pred` Min || 9462 // V == Min). We know from the guarding condition that !(V 9463 // == Min). This gives us 9464 // 9465 // V `Pred` Min || V == Min && !(V == Min) 9466 // => V `Pred` Min 9467 // 9468 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9469 9470 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9471 return true; 9472 LLVM_FALLTHROUGH; 9473 9474 default: 9475 // No change 9476 break; 9477 } 9478 } 9479 } 9480 9481 // Check whether the actual condition is beyond sufficient. 9482 if (FoundPred == ICmpInst::ICMP_EQ) 9483 if (ICmpInst::isTrueWhenEqual(Pred)) 9484 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9485 return true; 9486 if (Pred == ICmpInst::ICMP_NE) 9487 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9488 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9489 return true; 9490 9491 // Otherwise assume the worst. 9492 return false; 9493 } 9494 9495 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9496 const SCEV *&L, const SCEV *&R, 9497 SCEV::NoWrapFlags &Flags) { 9498 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9499 if (!AE || AE->getNumOperands() != 2) 9500 return false; 9501 9502 L = AE->getOperand(0); 9503 R = AE->getOperand(1); 9504 Flags = AE->getNoWrapFlags(); 9505 return true; 9506 } 9507 9508 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9509 const SCEV *Less) { 9510 // We avoid subtracting expressions here because this function is usually 9511 // fairly deep in the call stack (i.e. is called many times). 9512 9513 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9514 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9515 const auto *MAR = cast<SCEVAddRecExpr>(More); 9516 9517 if (LAR->getLoop() != MAR->getLoop()) 9518 return None; 9519 9520 // We look at affine expressions only; not for correctness but to keep 9521 // getStepRecurrence cheap. 9522 if (!LAR->isAffine() || !MAR->isAffine()) 9523 return None; 9524 9525 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9526 return None; 9527 9528 Less = LAR->getStart(); 9529 More = MAR->getStart(); 9530 9531 // fall through 9532 } 9533 9534 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9535 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9536 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9537 return M - L; 9538 } 9539 9540 SCEV::NoWrapFlags Flags; 9541 const SCEV *LLess = nullptr, *RLess = nullptr; 9542 const SCEV *LMore = nullptr, *RMore = nullptr; 9543 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9544 // Compare (X + C1) vs X. 9545 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9546 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9547 if (RLess == More) 9548 return -(C1->getAPInt()); 9549 9550 // Compare X vs (X + C2). 9551 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9552 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9553 if (RMore == Less) 9554 return C2->getAPInt(); 9555 9556 // Compare (X + C1) vs (X + C2). 9557 if (C1 && C2 && RLess == RMore) 9558 return C2->getAPInt() - C1->getAPInt(); 9559 9560 return None; 9561 } 9562 9563 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9564 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9565 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9566 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9567 return false; 9568 9569 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9570 if (!AddRecLHS) 9571 return false; 9572 9573 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9574 if (!AddRecFoundLHS) 9575 return false; 9576 9577 // We'd like to let SCEV reason about control dependencies, so we constrain 9578 // both the inequalities to be about add recurrences on the same loop. This 9579 // way we can use isLoopEntryGuardedByCond later. 9580 9581 const Loop *L = AddRecFoundLHS->getLoop(); 9582 if (L != AddRecLHS->getLoop()) 9583 return false; 9584 9585 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9586 // 9587 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9588 // ... (2) 9589 // 9590 // Informal proof for (2), assuming (1) [*]: 9591 // 9592 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9593 // 9594 // Then 9595 // 9596 // FoundLHS s< FoundRHS s< INT_MIN - C 9597 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9598 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9599 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9600 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9601 // <=> FoundLHS + C s< FoundRHS + C 9602 // 9603 // [*]: (1) can be proved by ruling out overflow. 9604 // 9605 // [**]: This can be proved by analyzing all the four possibilities: 9606 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9607 // (A s>= 0, B s>= 0). 9608 // 9609 // Note: 9610 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9611 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9612 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9613 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9614 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9615 // C)". 9616 9617 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9618 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9619 if (!LDiff || !RDiff || *LDiff != *RDiff) 9620 return false; 9621 9622 if (LDiff->isMinValue()) 9623 return true; 9624 9625 APInt FoundRHSLimit; 9626 9627 if (Pred == CmpInst::ICMP_ULT) { 9628 FoundRHSLimit = -(*RDiff); 9629 } else { 9630 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9631 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9632 } 9633 9634 // Try to prove (1) or (2), as needed. 9635 return isAvailableAtLoopEntry(FoundRHS, L) && 9636 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9637 getConstant(FoundRHSLimit)); 9638 } 9639 9640 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9641 const SCEV *LHS, const SCEV *RHS, 9642 const SCEV *FoundLHS, 9643 const SCEV *FoundRHS, unsigned Depth) { 9644 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9645 9646 auto ClearOnExit = make_scope_exit([&]() { 9647 if (LPhi) { 9648 bool Erased = PendingMerges.erase(LPhi); 9649 assert(Erased && "Failed to erase LPhi!"); 9650 (void)Erased; 9651 } 9652 if (RPhi) { 9653 bool Erased = PendingMerges.erase(RPhi); 9654 assert(Erased && "Failed to erase RPhi!"); 9655 (void)Erased; 9656 } 9657 }); 9658 9659 // Find respective Phis and check that they are not being pending. 9660 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9661 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9662 if (!PendingMerges.insert(Phi).second) 9663 return false; 9664 LPhi = Phi; 9665 } 9666 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9667 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9668 // If we detect a loop of Phi nodes being processed by this method, for 9669 // example: 9670 // 9671 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9672 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9673 // 9674 // we don't want to deal with a case that complex, so return conservative 9675 // answer false. 9676 if (!PendingMerges.insert(Phi).second) 9677 return false; 9678 RPhi = Phi; 9679 } 9680 9681 // If none of LHS, RHS is a Phi, nothing to do here. 9682 if (!LPhi && !RPhi) 9683 return false; 9684 9685 // If there is a SCEVUnknown Phi we are interested in, make it left. 9686 if (!LPhi) { 9687 std::swap(LHS, RHS); 9688 std::swap(FoundLHS, FoundRHS); 9689 std::swap(LPhi, RPhi); 9690 Pred = ICmpInst::getSwappedPredicate(Pred); 9691 } 9692 9693 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9694 const BasicBlock *LBB = LPhi->getParent(); 9695 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9696 9697 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9698 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9699 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9700 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9701 }; 9702 9703 if (RPhi && RPhi->getParent() == LBB) { 9704 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9705 // If we compare two Phis from the same block, and for each entry block 9706 // the predicate is true for incoming values from this block, then the 9707 // predicate is also true for the Phis. 9708 for (const BasicBlock *IncBB : predecessors(LBB)) { 9709 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9710 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9711 if (!ProvedEasily(L, R)) 9712 return false; 9713 } 9714 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9715 // Case two: RHS is also a Phi from the same basic block, and it is an 9716 // AddRec. It means that there is a loop which has both AddRec and Unknown 9717 // PHIs, for it we can compare incoming values of AddRec from above the loop 9718 // and latch with their respective incoming values of LPhi. 9719 // TODO: Generalize to handle loops with many inputs in a header. 9720 if (LPhi->getNumIncomingValues() != 2) return false; 9721 9722 auto *RLoop = RAR->getLoop(); 9723 auto *Predecessor = RLoop->getLoopPredecessor(); 9724 assert(Predecessor && "Loop with AddRec with no predecessor?"); 9725 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 9726 if (!ProvedEasily(L1, RAR->getStart())) 9727 return false; 9728 auto *Latch = RLoop->getLoopLatch(); 9729 assert(Latch && "Loop with AddRec with no latch?"); 9730 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 9731 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 9732 return false; 9733 } else { 9734 // In all other cases go over inputs of LHS and compare each of them to RHS, 9735 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 9736 // At this point RHS is either a non-Phi, or it is a Phi from some block 9737 // different from LBB. 9738 for (const BasicBlock *IncBB : predecessors(LBB)) { 9739 // Check that RHS is available in this block. 9740 if (!dominates(RHS, IncBB)) 9741 return false; 9742 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9743 if (!ProvedEasily(L, RHS)) 9744 return false; 9745 } 9746 } 9747 return true; 9748 } 9749 9750 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9751 const SCEV *LHS, const SCEV *RHS, 9752 const SCEV *FoundLHS, 9753 const SCEV *FoundRHS) { 9754 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9755 return true; 9756 9757 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9758 return true; 9759 9760 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9761 FoundLHS, FoundRHS) || 9762 // ~x < ~y --> x > y 9763 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9764 getNotSCEV(FoundRHS), 9765 getNotSCEV(FoundLHS)); 9766 } 9767 9768 /// If Expr computes ~A, return A else return nullptr 9769 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9770 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9771 if (!Add || Add->getNumOperands() != 2 || 9772 !Add->getOperand(0)->isAllOnesValue()) 9773 return nullptr; 9774 9775 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9776 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9777 !AddRHS->getOperand(0)->isAllOnesValue()) 9778 return nullptr; 9779 9780 return AddRHS->getOperand(1); 9781 } 9782 9783 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9784 template<typename MaxExprType> 9785 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9786 const SCEV *Candidate) { 9787 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9788 if (!MaxExpr) return false; 9789 9790 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9791 } 9792 9793 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9794 template<typename MaxExprType> 9795 static bool IsMinConsistingOf(ScalarEvolution &SE, 9796 const SCEV *MaybeMinExpr, 9797 const SCEV *Candidate) { 9798 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9799 if (!MaybeMaxExpr) 9800 return false; 9801 9802 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9803 } 9804 9805 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9806 ICmpInst::Predicate Pred, 9807 const SCEV *LHS, const SCEV *RHS) { 9808 // If both sides are affine addrecs for the same loop, with equal 9809 // steps, and we know the recurrences don't wrap, then we only 9810 // need to check the predicate on the starting values. 9811 9812 if (!ICmpInst::isRelational(Pred)) 9813 return false; 9814 9815 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9816 if (!LAR) 9817 return false; 9818 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9819 if (!RAR) 9820 return false; 9821 if (LAR->getLoop() != RAR->getLoop()) 9822 return false; 9823 if (!LAR->isAffine() || !RAR->isAffine()) 9824 return false; 9825 9826 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9827 return false; 9828 9829 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9830 SCEV::FlagNSW : SCEV::FlagNUW; 9831 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9832 return false; 9833 9834 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9835 } 9836 9837 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9838 /// expression? 9839 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9840 ICmpInst::Predicate Pred, 9841 const SCEV *LHS, const SCEV *RHS) { 9842 switch (Pred) { 9843 default: 9844 return false; 9845 9846 case ICmpInst::ICMP_SGE: 9847 std::swap(LHS, RHS); 9848 LLVM_FALLTHROUGH; 9849 case ICmpInst::ICMP_SLE: 9850 return 9851 // min(A, ...) <= A 9852 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9853 // A <= max(A, ...) 9854 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9855 9856 case ICmpInst::ICMP_UGE: 9857 std::swap(LHS, RHS); 9858 LLVM_FALLTHROUGH; 9859 case ICmpInst::ICMP_ULE: 9860 return 9861 // min(A, ...) <= A 9862 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9863 // A <= max(A, ...) 9864 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9865 } 9866 9867 llvm_unreachable("covered switch fell through?!"); 9868 } 9869 9870 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9871 const SCEV *LHS, const SCEV *RHS, 9872 const SCEV *FoundLHS, 9873 const SCEV *FoundRHS, 9874 unsigned Depth) { 9875 assert(getTypeSizeInBits(LHS->getType()) == 9876 getTypeSizeInBits(RHS->getType()) && 9877 "LHS and RHS have different sizes?"); 9878 assert(getTypeSizeInBits(FoundLHS->getType()) == 9879 getTypeSizeInBits(FoundRHS->getType()) && 9880 "FoundLHS and FoundRHS have different sizes?"); 9881 // We want to avoid hurting the compile time with analysis of too big trees. 9882 if (Depth > MaxSCEVOperationsImplicationDepth) 9883 return false; 9884 // We only want to work with ICMP_SGT comparison so far. 9885 // TODO: Extend to ICMP_UGT? 9886 if (Pred == ICmpInst::ICMP_SLT) { 9887 Pred = ICmpInst::ICMP_SGT; 9888 std::swap(LHS, RHS); 9889 std::swap(FoundLHS, FoundRHS); 9890 } 9891 if (Pred != ICmpInst::ICMP_SGT) 9892 return false; 9893 9894 auto GetOpFromSExt = [&](const SCEV *S) { 9895 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9896 return Ext->getOperand(); 9897 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9898 // the constant in some cases. 9899 return S; 9900 }; 9901 9902 // Acquire values from extensions. 9903 auto *OrigLHS = LHS; 9904 auto *OrigFoundLHS = FoundLHS; 9905 LHS = GetOpFromSExt(LHS); 9906 FoundLHS = GetOpFromSExt(FoundLHS); 9907 9908 // Is the SGT predicate can be proved trivially or using the found context. 9909 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9910 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9911 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9912 FoundRHS, Depth + 1); 9913 }; 9914 9915 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9916 // We want to avoid creation of any new non-constant SCEV. Since we are 9917 // going to compare the operands to RHS, we should be certain that we don't 9918 // need any size extensions for this. So let's decline all cases when the 9919 // sizes of types of LHS and RHS do not match. 9920 // TODO: Maybe try to get RHS from sext to catch more cases? 9921 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9922 return false; 9923 9924 // Should not overflow. 9925 if (!LHSAddExpr->hasNoSignedWrap()) 9926 return false; 9927 9928 auto *LL = LHSAddExpr->getOperand(0); 9929 auto *LR = LHSAddExpr->getOperand(1); 9930 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9931 9932 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9933 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9934 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9935 }; 9936 // Try to prove the following rule: 9937 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9938 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9939 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9940 return true; 9941 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9942 Value *LL, *LR; 9943 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9944 9945 using namespace llvm::PatternMatch; 9946 9947 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9948 // Rules for division. 9949 // We are going to perform some comparisons with Denominator and its 9950 // derivative expressions. In general case, creating a SCEV for it may 9951 // lead to a complex analysis of the entire graph, and in particular it 9952 // can request trip count recalculation for the same loop. This would 9953 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9954 // this, we only want to create SCEVs that are constants in this section. 9955 // So we bail if Denominator is not a constant. 9956 if (!isa<ConstantInt>(LR)) 9957 return false; 9958 9959 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9960 9961 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9962 // then a SCEV for the numerator already exists and matches with FoundLHS. 9963 auto *Numerator = getExistingSCEV(LL); 9964 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9965 return false; 9966 9967 // Make sure that the numerator matches with FoundLHS and the denominator 9968 // is positive. 9969 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9970 return false; 9971 9972 auto *DTy = Denominator->getType(); 9973 auto *FRHSTy = FoundRHS->getType(); 9974 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9975 // One of types is a pointer and another one is not. We cannot extend 9976 // them properly to a wider type, so let us just reject this case. 9977 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9978 // to avoid this check. 9979 return false; 9980 9981 // Given that: 9982 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9983 auto *WTy = getWiderType(DTy, FRHSTy); 9984 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9985 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9986 9987 // Try to prove the following rule: 9988 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9989 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9990 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9991 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9992 if (isKnownNonPositive(RHS) && 9993 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9994 return true; 9995 9996 // Try to prove the following rule: 9997 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9998 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9999 // If we divide it by Denominator > 2, then: 10000 // 1. If FoundLHS is negative, then the result is 0. 10001 // 2. If FoundLHS is non-negative, then the result is non-negative. 10002 // Anyways, the result is non-negative. 10003 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10004 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10005 if (isKnownNegative(RHS) && 10006 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10007 return true; 10008 } 10009 } 10010 10011 // If our expression contained SCEVUnknown Phis, and we split it down and now 10012 // need to prove something for them, try to prove the predicate for every 10013 // possible incoming values of those Phis. 10014 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10015 return true; 10016 10017 return false; 10018 } 10019 10020 bool 10021 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10022 const SCEV *LHS, const SCEV *RHS) { 10023 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10024 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10025 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10026 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10027 } 10028 10029 bool 10030 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10031 const SCEV *LHS, const SCEV *RHS, 10032 const SCEV *FoundLHS, 10033 const SCEV *FoundRHS) { 10034 switch (Pred) { 10035 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10036 case ICmpInst::ICMP_EQ: 10037 case ICmpInst::ICMP_NE: 10038 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10039 return true; 10040 break; 10041 case ICmpInst::ICMP_SLT: 10042 case ICmpInst::ICMP_SLE: 10043 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10044 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10045 return true; 10046 break; 10047 case ICmpInst::ICMP_SGT: 10048 case ICmpInst::ICMP_SGE: 10049 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10050 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10051 return true; 10052 break; 10053 case ICmpInst::ICMP_ULT: 10054 case ICmpInst::ICMP_ULE: 10055 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10056 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10057 return true; 10058 break; 10059 case ICmpInst::ICMP_UGT: 10060 case ICmpInst::ICMP_UGE: 10061 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10062 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10063 return true; 10064 break; 10065 } 10066 10067 // Maybe it can be proved via operations? 10068 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10069 return true; 10070 10071 return false; 10072 } 10073 10074 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10075 const SCEV *LHS, 10076 const SCEV *RHS, 10077 const SCEV *FoundLHS, 10078 const SCEV *FoundRHS) { 10079 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10080 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10081 // reduce the compile time impact of this optimization. 10082 return false; 10083 10084 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10085 if (!Addend) 10086 return false; 10087 10088 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10089 10090 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10091 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10092 ConstantRange FoundLHSRange = 10093 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10094 10095 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10096 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10097 10098 // We can also compute the range of values for `LHS` that satisfy the 10099 // consequent, "`LHS` `Pred` `RHS`": 10100 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10101 ConstantRange SatisfyingLHSRange = 10102 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10103 10104 // The antecedent implies the consequent if every value of `LHS` that 10105 // satisfies the antecedent also satisfies the consequent. 10106 return SatisfyingLHSRange.contains(LHSRange); 10107 } 10108 10109 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10110 bool IsSigned, bool NoWrap) { 10111 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10112 10113 if (NoWrap) return false; 10114 10115 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10116 const SCEV *One = getOne(Stride->getType()); 10117 10118 if (IsSigned) { 10119 APInt MaxRHS = getSignedRangeMax(RHS); 10120 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10121 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10122 10123 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10124 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10125 } 10126 10127 APInt MaxRHS = getUnsignedRangeMax(RHS); 10128 APInt MaxValue = APInt::getMaxValue(BitWidth); 10129 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10130 10131 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10132 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10133 } 10134 10135 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10136 bool IsSigned, bool NoWrap) { 10137 if (NoWrap) return false; 10138 10139 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10140 const SCEV *One = getOne(Stride->getType()); 10141 10142 if (IsSigned) { 10143 APInt MinRHS = getSignedRangeMin(RHS); 10144 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10145 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10146 10147 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10148 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10149 } 10150 10151 APInt MinRHS = getUnsignedRangeMin(RHS); 10152 APInt MinValue = APInt::getMinValue(BitWidth); 10153 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10154 10155 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10156 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10157 } 10158 10159 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10160 bool Equality) { 10161 const SCEV *One = getOne(Step->getType()); 10162 Delta = Equality ? getAddExpr(Delta, Step) 10163 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10164 return getUDivExpr(Delta, Step); 10165 } 10166 10167 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10168 const SCEV *Stride, 10169 const SCEV *End, 10170 unsigned BitWidth, 10171 bool IsSigned) { 10172 10173 assert(!isKnownNonPositive(Stride) && 10174 "Stride is expected strictly positive!"); 10175 // Calculate the maximum backedge count based on the range of values 10176 // permitted by Start, End, and Stride. 10177 const SCEV *MaxBECount; 10178 APInt MinStart = 10179 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10180 10181 APInt StrideForMaxBECount = 10182 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10183 10184 // We already know that the stride is positive, so we paper over conservatism 10185 // in our range computation by forcing StrideForMaxBECount to be at least one. 10186 // In theory this is unnecessary, but we expect MaxBECount to be a 10187 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10188 // is nothing to constant fold it to). 10189 APInt One(BitWidth, 1, IsSigned); 10190 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10191 10192 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10193 : APInt::getMaxValue(BitWidth); 10194 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10195 10196 // Although End can be a MAX expression we estimate MaxEnd considering only 10197 // the case End = RHS of the loop termination condition. This is safe because 10198 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10199 // taken count. 10200 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10201 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10202 10203 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10204 getConstant(StrideForMaxBECount) /* Step */, 10205 false /* Equality */); 10206 10207 return MaxBECount; 10208 } 10209 10210 ScalarEvolution::ExitLimit 10211 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10212 const Loop *L, bool IsSigned, 10213 bool ControlsExit, bool AllowPredicates) { 10214 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10215 10216 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10217 bool PredicatedIV = false; 10218 10219 if (!IV && AllowPredicates) { 10220 // Try to make this an AddRec using runtime tests, in the first X 10221 // iterations of this loop, where X is the SCEV expression found by the 10222 // algorithm below. 10223 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10224 PredicatedIV = true; 10225 } 10226 10227 // Avoid weird loops 10228 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10229 return getCouldNotCompute(); 10230 10231 bool NoWrap = ControlsExit && 10232 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10233 10234 const SCEV *Stride = IV->getStepRecurrence(*this); 10235 10236 bool PositiveStride = isKnownPositive(Stride); 10237 10238 // Avoid negative or zero stride values. 10239 if (!PositiveStride) { 10240 // We can compute the correct backedge taken count for loops with unknown 10241 // strides if we can prove that the loop is not an infinite loop with side 10242 // effects. Here's the loop structure we are trying to handle - 10243 // 10244 // i = start 10245 // do { 10246 // A[i] = i; 10247 // i += s; 10248 // } while (i < end); 10249 // 10250 // The backedge taken count for such loops is evaluated as - 10251 // (max(end, start + stride) - start - 1) /u stride 10252 // 10253 // The additional preconditions that we need to check to prove correctness 10254 // of the above formula is as follows - 10255 // 10256 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10257 // NoWrap flag). 10258 // b) loop is single exit with no side effects. 10259 // 10260 // 10261 // Precondition a) implies that if the stride is negative, this is a single 10262 // trip loop. The backedge taken count formula reduces to zero in this case. 10263 // 10264 // Precondition b) implies that the unknown stride cannot be zero otherwise 10265 // we have UB. 10266 // 10267 // The positive stride case is the same as isKnownPositive(Stride) returning 10268 // true (original behavior of the function). 10269 // 10270 // We want to make sure that the stride is truly unknown as there are edge 10271 // cases where ScalarEvolution propagates no wrap flags to the 10272 // post-increment/decrement IV even though the increment/decrement operation 10273 // itself is wrapping. The computed backedge taken count may be wrong in 10274 // such cases. This is prevented by checking that the stride is not known to 10275 // be either positive or non-positive. For example, no wrap flags are 10276 // propagated to the post-increment IV of this loop with a trip count of 2 - 10277 // 10278 // unsigned char i; 10279 // for(i=127; i<128; i+=129) 10280 // A[i] = i; 10281 // 10282 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10283 !loopHasNoSideEffects(L)) 10284 return getCouldNotCompute(); 10285 } else if (!Stride->isOne() && 10286 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10287 // Avoid proven overflow cases: this will ensure that the backedge taken 10288 // count will not generate any unsigned overflow. Relaxed no-overflow 10289 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10290 // undefined behaviors like the case of C language. 10291 return getCouldNotCompute(); 10292 10293 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10294 : ICmpInst::ICMP_ULT; 10295 const SCEV *Start = IV->getStart(); 10296 const SCEV *End = RHS; 10297 // When the RHS is not invariant, we do not know the end bound of the loop and 10298 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10299 // calculate the MaxBECount, given the start, stride and max value for the end 10300 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10301 // checked above). 10302 if (!isLoopInvariant(RHS, L)) { 10303 const SCEV *MaxBECount = computeMaxBECountForLT( 10304 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10305 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10306 false /*MaxOrZero*/, Predicates); 10307 } 10308 // If the backedge is taken at least once, then it will be taken 10309 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10310 // is the LHS value of the less-than comparison the first time it is evaluated 10311 // and End is the RHS. 10312 const SCEV *BECountIfBackedgeTaken = 10313 computeBECount(getMinusSCEV(End, Start), Stride, false); 10314 // If the loop entry is guarded by the result of the backedge test of the 10315 // first loop iteration, then we know the backedge will be taken at least 10316 // once and so the backedge taken count is as above. If not then we use the 10317 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10318 // as if the backedge is taken at least once max(End,Start) is End and so the 10319 // result is as above, and if not max(End,Start) is Start so we get a backedge 10320 // count of zero. 10321 const SCEV *BECount; 10322 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10323 BECount = BECountIfBackedgeTaken; 10324 else { 10325 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10326 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10327 } 10328 10329 const SCEV *MaxBECount; 10330 bool MaxOrZero = false; 10331 if (isa<SCEVConstant>(BECount)) 10332 MaxBECount = BECount; 10333 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10334 // If we know exactly how many times the backedge will be taken if it's 10335 // taken at least once, then the backedge count will either be that or 10336 // zero. 10337 MaxBECount = BECountIfBackedgeTaken; 10338 MaxOrZero = true; 10339 } else { 10340 MaxBECount = computeMaxBECountForLT( 10341 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10342 } 10343 10344 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10345 !isa<SCEVCouldNotCompute>(BECount)) 10346 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10347 10348 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10349 } 10350 10351 ScalarEvolution::ExitLimit 10352 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10353 const Loop *L, bool IsSigned, 10354 bool ControlsExit, bool AllowPredicates) { 10355 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10356 // We handle only IV > Invariant 10357 if (!isLoopInvariant(RHS, L)) 10358 return getCouldNotCompute(); 10359 10360 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10361 if (!IV && AllowPredicates) 10362 // Try to make this an AddRec using runtime tests, in the first X 10363 // iterations of this loop, where X is the SCEV expression found by the 10364 // algorithm below. 10365 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10366 10367 // Avoid weird loops 10368 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10369 return getCouldNotCompute(); 10370 10371 bool NoWrap = ControlsExit && 10372 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10373 10374 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10375 10376 // Avoid negative or zero stride values 10377 if (!isKnownPositive(Stride)) 10378 return getCouldNotCompute(); 10379 10380 // Avoid proven overflow cases: this will ensure that the backedge taken count 10381 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10382 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10383 // behaviors like the case of C language. 10384 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10385 return getCouldNotCompute(); 10386 10387 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10388 : ICmpInst::ICMP_UGT; 10389 10390 const SCEV *Start = IV->getStart(); 10391 const SCEV *End = RHS; 10392 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10393 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10394 10395 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10396 10397 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10398 : getUnsignedRangeMax(Start); 10399 10400 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10401 : getUnsignedRangeMin(Stride); 10402 10403 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10404 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10405 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10406 10407 // Although End can be a MIN expression we estimate MinEnd considering only 10408 // the case End = RHS. This is safe because in the other case (Start - End) 10409 // is zero, leading to a zero maximum backedge taken count. 10410 APInt MinEnd = 10411 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10412 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10413 10414 10415 const SCEV *MaxBECount = getCouldNotCompute(); 10416 if (isa<SCEVConstant>(BECount)) 10417 MaxBECount = BECount; 10418 else 10419 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10420 getConstant(MinStride), false); 10421 10422 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10423 MaxBECount = BECount; 10424 10425 return ExitLimit(BECount, MaxBECount, false, Predicates); 10426 } 10427 10428 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10429 ScalarEvolution &SE) const { 10430 if (Range.isFullSet()) // Infinite loop. 10431 return SE.getCouldNotCompute(); 10432 10433 // If the start is a non-zero constant, shift the range to simplify things. 10434 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10435 if (!SC->getValue()->isZero()) { 10436 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10437 Operands[0] = SE.getZero(SC->getType()); 10438 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10439 getNoWrapFlags(FlagNW)); 10440 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10441 return ShiftedAddRec->getNumIterationsInRange( 10442 Range.subtract(SC->getAPInt()), SE); 10443 // This is strange and shouldn't happen. 10444 return SE.getCouldNotCompute(); 10445 } 10446 10447 // The only time we can solve this is when we have all constant indices. 10448 // Otherwise, we cannot determine the overflow conditions. 10449 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10450 return SE.getCouldNotCompute(); 10451 10452 // Okay at this point we know that all elements of the chrec are constants and 10453 // that the start element is zero. 10454 10455 // First check to see if the range contains zero. If not, the first 10456 // iteration exits. 10457 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10458 if (!Range.contains(APInt(BitWidth, 0))) 10459 return SE.getZero(getType()); 10460 10461 if (isAffine()) { 10462 // If this is an affine expression then we have this situation: 10463 // Solve {0,+,A} in Range === Ax in Range 10464 10465 // We know that zero is in the range. If A is positive then we know that 10466 // the upper value of the range must be the first possible exit value. 10467 // If A is negative then the lower of the range is the last possible loop 10468 // value. Also note that we already checked for a full range. 10469 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10470 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10471 10472 // The exit value should be (End+A)/A. 10473 APInt ExitVal = (End + A).udiv(A); 10474 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10475 10476 // Evaluate at the exit value. If we really did fall out of the valid 10477 // range, then we computed our trip count, otherwise wrap around or other 10478 // things must have happened. 10479 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10480 if (Range.contains(Val->getValue())) 10481 return SE.getCouldNotCompute(); // Something strange happened 10482 10483 // Ensure that the previous value is in the range. This is a sanity check. 10484 assert(Range.contains( 10485 EvaluateConstantChrecAtConstant(this, 10486 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10487 "Linear scev computation is off in a bad way!"); 10488 return SE.getConstant(ExitValue); 10489 } else if (isQuadratic()) { 10490 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10491 // quadratic equation to solve it. To do this, we must frame our problem in 10492 // terms of figuring out when zero is crossed, instead of when 10493 // Range.getUpper() is crossed. 10494 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10495 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10496 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10497 10498 // Next, solve the constructed addrec 10499 if (auto Roots = 10500 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10501 const SCEVConstant *R1 = Roots->first; 10502 const SCEVConstant *R2 = Roots->second; 10503 // Pick the smallest positive root value. 10504 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10505 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10506 if (!CB->getZExtValue()) 10507 std::swap(R1, R2); // R1 is the minimum root now. 10508 10509 // Make sure the root is not off by one. The returned iteration should 10510 // not be in the range, but the previous one should be. When solving 10511 // for "X*X < 5", for example, we should not return a root of 2. 10512 ConstantInt *R1Val = 10513 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10514 if (Range.contains(R1Val->getValue())) { 10515 // The next iteration must be out of the range... 10516 ConstantInt *NextVal = 10517 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10518 10519 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10520 if (!Range.contains(R1Val->getValue())) 10521 return SE.getConstant(NextVal); 10522 return SE.getCouldNotCompute(); // Something strange happened 10523 } 10524 10525 // If R1 was not in the range, then it is a good return value. Make 10526 // sure that R1-1 WAS in the range though, just in case. 10527 ConstantInt *NextVal = 10528 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10529 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10530 if (Range.contains(R1Val->getValue())) 10531 return R1; 10532 return SE.getCouldNotCompute(); // Something strange happened 10533 } 10534 } 10535 } 10536 10537 return SE.getCouldNotCompute(); 10538 } 10539 10540 const SCEVAddRecExpr * 10541 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10542 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10543 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10544 // but in this case we cannot guarantee that the value returned will be an 10545 // AddRec because SCEV does not have a fixed point where it stops 10546 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10547 // may happen if we reach arithmetic depth limit while simplifying. So we 10548 // construct the returned value explicitly. 10549 SmallVector<const SCEV *, 3> Ops; 10550 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10551 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10552 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10553 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10554 // We know that the last operand is not a constant zero (otherwise it would 10555 // have been popped out earlier). This guarantees us that if the result has 10556 // the same last operand, then it will also not be popped out, meaning that 10557 // the returned value will be an AddRec. 10558 const SCEV *Last = getOperand(getNumOperands() - 1); 10559 assert(!Last->isZero() && "Recurrency with zero step?"); 10560 Ops.push_back(Last); 10561 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10562 SCEV::FlagAnyWrap)); 10563 } 10564 10565 // Return true when S contains at least an undef value. 10566 static inline bool containsUndefs(const SCEV *S) { 10567 return SCEVExprContains(S, [](const SCEV *S) { 10568 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10569 return isa<UndefValue>(SU->getValue()); 10570 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10571 return isa<UndefValue>(SC->getValue()); 10572 return false; 10573 }); 10574 } 10575 10576 namespace { 10577 10578 // Collect all steps of SCEV expressions. 10579 struct SCEVCollectStrides { 10580 ScalarEvolution &SE; 10581 SmallVectorImpl<const SCEV *> &Strides; 10582 10583 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10584 : SE(SE), Strides(S) {} 10585 10586 bool follow(const SCEV *S) { 10587 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10588 Strides.push_back(AR->getStepRecurrence(SE)); 10589 return true; 10590 } 10591 10592 bool isDone() const { return false; } 10593 }; 10594 10595 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10596 struct SCEVCollectTerms { 10597 SmallVectorImpl<const SCEV *> &Terms; 10598 10599 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10600 10601 bool follow(const SCEV *S) { 10602 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10603 isa<SCEVSignExtendExpr>(S)) { 10604 if (!containsUndefs(S)) 10605 Terms.push_back(S); 10606 10607 // Stop recursion: once we collected a term, do not walk its operands. 10608 return false; 10609 } 10610 10611 // Keep looking. 10612 return true; 10613 } 10614 10615 bool isDone() const { return false; } 10616 }; 10617 10618 // Check if a SCEV contains an AddRecExpr. 10619 struct SCEVHasAddRec { 10620 bool &ContainsAddRec; 10621 10622 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10623 ContainsAddRec = false; 10624 } 10625 10626 bool follow(const SCEV *S) { 10627 if (isa<SCEVAddRecExpr>(S)) { 10628 ContainsAddRec = true; 10629 10630 // Stop recursion: once we collected a term, do not walk its operands. 10631 return false; 10632 } 10633 10634 // Keep looking. 10635 return true; 10636 } 10637 10638 bool isDone() const { return false; } 10639 }; 10640 10641 // Find factors that are multiplied with an expression that (possibly as a 10642 // subexpression) contains an AddRecExpr. In the expression: 10643 // 10644 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10645 // 10646 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10647 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10648 // parameters as they form a product with an induction variable. 10649 // 10650 // This collector expects all array size parameters to be in the same MulExpr. 10651 // It might be necessary to later add support for collecting parameters that are 10652 // spread over different nested MulExpr. 10653 struct SCEVCollectAddRecMultiplies { 10654 SmallVectorImpl<const SCEV *> &Terms; 10655 ScalarEvolution &SE; 10656 10657 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10658 : Terms(T), SE(SE) {} 10659 10660 bool follow(const SCEV *S) { 10661 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10662 bool HasAddRec = false; 10663 SmallVector<const SCEV *, 0> Operands; 10664 for (auto Op : Mul->operands()) { 10665 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10666 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10667 Operands.push_back(Op); 10668 } else if (Unknown) { 10669 HasAddRec = true; 10670 } else { 10671 bool ContainsAddRec; 10672 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10673 visitAll(Op, ContiansAddRec); 10674 HasAddRec |= ContainsAddRec; 10675 } 10676 } 10677 if (Operands.size() == 0) 10678 return true; 10679 10680 if (!HasAddRec) 10681 return false; 10682 10683 Terms.push_back(SE.getMulExpr(Operands)); 10684 // Stop recursion: once we collected a term, do not walk its operands. 10685 return false; 10686 } 10687 10688 // Keep looking. 10689 return true; 10690 } 10691 10692 bool isDone() const { return false; } 10693 }; 10694 10695 } // end anonymous namespace 10696 10697 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10698 /// two places: 10699 /// 1) The strides of AddRec expressions. 10700 /// 2) Unknowns that are multiplied with AddRec expressions. 10701 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10702 SmallVectorImpl<const SCEV *> &Terms) { 10703 SmallVector<const SCEV *, 4> Strides; 10704 SCEVCollectStrides StrideCollector(*this, Strides); 10705 visitAll(Expr, StrideCollector); 10706 10707 LLVM_DEBUG({ 10708 dbgs() << "Strides:\n"; 10709 for (const SCEV *S : Strides) 10710 dbgs() << *S << "\n"; 10711 }); 10712 10713 for (const SCEV *S : Strides) { 10714 SCEVCollectTerms TermCollector(Terms); 10715 visitAll(S, TermCollector); 10716 } 10717 10718 LLVM_DEBUG({ 10719 dbgs() << "Terms:\n"; 10720 for (const SCEV *T : Terms) 10721 dbgs() << *T << "\n"; 10722 }); 10723 10724 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10725 visitAll(Expr, MulCollector); 10726 } 10727 10728 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10729 SmallVectorImpl<const SCEV *> &Terms, 10730 SmallVectorImpl<const SCEV *> &Sizes) { 10731 int Last = Terms.size() - 1; 10732 const SCEV *Step = Terms[Last]; 10733 10734 // End of recursion. 10735 if (Last == 0) { 10736 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10737 SmallVector<const SCEV *, 2> Qs; 10738 for (const SCEV *Op : M->operands()) 10739 if (!isa<SCEVConstant>(Op)) 10740 Qs.push_back(Op); 10741 10742 Step = SE.getMulExpr(Qs); 10743 } 10744 10745 Sizes.push_back(Step); 10746 return true; 10747 } 10748 10749 for (const SCEV *&Term : Terms) { 10750 // Normalize the terms before the next call to findArrayDimensionsRec. 10751 const SCEV *Q, *R; 10752 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10753 10754 // Bail out when GCD does not evenly divide one of the terms. 10755 if (!R->isZero()) 10756 return false; 10757 10758 Term = Q; 10759 } 10760 10761 // Remove all SCEVConstants. 10762 Terms.erase( 10763 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10764 Terms.end()); 10765 10766 if (Terms.size() > 0) 10767 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10768 return false; 10769 10770 Sizes.push_back(Step); 10771 return true; 10772 } 10773 10774 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10775 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10776 for (const SCEV *T : Terms) 10777 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10778 return true; 10779 return false; 10780 } 10781 10782 // Return the number of product terms in S. 10783 static inline int numberOfTerms(const SCEV *S) { 10784 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10785 return Expr->getNumOperands(); 10786 return 1; 10787 } 10788 10789 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10790 if (isa<SCEVConstant>(T)) 10791 return nullptr; 10792 10793 if (isa<SCEVUnknown>(T)) 10794 return T; 10795 10796 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10797 SmallVector<const SCEV *, 2> Factors; 10798 for (const SCEV *Op : M->operands()) 10799 if (!isa<SCEVConstant>(Op)) 10800 Factors.push_back(Op); 10801 10802 return SE.getMulExpr(Factors); 10803 } 10804 10805 return T; 10806 } 10807 10808 /// Return the size of an element read or written by Inst. 10809 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10810 Type *Ty; 10811 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10812 Ty = Store->getValueOperand()->getType(); 10813 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10814 Ty = Load->getType(); 10815 else 10816 return nullptr; 10817 10818 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10819 return getSizeOfExpr(ETy, Ty); 10820 } 10821 10822 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10823 SmallVectorImpl<const SCEV *> &Sizes, 10824 const SCEV *ElementSize) { 10825 if (Terms.size() < 1 || !ElementSize) 10826 return; 10827 10828 // Early return when Terms do not contain parameters: we do not delinearize 10829 // non parametric SCEVs. 10830 if (!containsParameters(Terms)) 10831 return; 10832 10833 LLVM_DEBUG({ 10834 dbgs() << "Terms:\n"; 10835 for (const SCEV *T : Terms) 10836 dbgs() << *T << "\n"; 10837 }); 10838 10839 // Remove duplicates. 10840 array_pod_sort(Terms.begin(), Terms.end()); 10841 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10842 10843 // Put larger terms first. 10844 llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10845 return numberOfTerms(LHS) > numberOfTerms(RHS); 10846 }); 10847 10848 // Try to divide all terms by the element size. If term is not divisible by 10849 // element size, proceed with the original term. 10850 for (const SCEV *&Term : Terms) { 10851 const SCEV *Q, *R; 10852 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10853 if (!Q->isZero()) 10854 Term = Q; 10855 } 10856 10857 SmallVector<const SCEV *, 4> NewTerms; 10858 10859 // Remove constant factors. 10860 for (const SCEV *T : Terms) 10861 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10862 NewTerms.push_back(NewT); 10863 10864 LLVM_DEBUG({ 10865 dbgs() << "Terms after sorting:\n"; 10866 for (const SCEV *T : NewTerms) 10867 dbgs() << *T << "\n"; 10868 }); 10869 10870 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10871 Sizes.clear(); 10872 return; 10873 } 10874 10875 // The last element to be pushed into Sizes is the size of an element. 10876 Sizes.push_back(ElementSize); 10877 10878 LLVM_DEBUG({ 10879 dbgs() << "Sizes:\n"; 10880 for (const SCEV *S : Sizes) 10881 dbgs() << *S << "\n"; 10882 }); 10883 } 10884 10885 void ScalarEvolution::computeAccessFunctions( 10886 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10887 SmallVectorImpl<const SCEV *> &Sizes) { 10888 // Early exit in case this SCEV is not an affine multivariate function. 10889 if (Sizes.empty()) 10890 return; 10891 10892 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10893 if (!AR->isAffine()) 10894 return; 10895 10896 const SCEV *Res = Expr; 10897 int Last = Sizes.size() - 1; 10898 for (int i = Last; i >= 0; i--) { 10899 const SCEV *Q, *R; 10900 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10901 10902 LLVM_DEBUG({ 10903 dbgs() << "Res: " << *Res << "\n"; 10904 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10905 dbgs() << "Res divided by Sizes[i]:\n"; 10906 dbgs() << "Quotient: " << *Q << "\n"; 10907 dbgs() << "Remainder: " << *R << "\n"; 10908 }); 10909 10910 Res = Q; 10911 10912 // Do not record the last subscript corresponding to the size of elements in 10913 // the array. 10914 if (i == Last) { 10915 10916 // Bail out if the remainder is too complex. 10917 if (isa<SCEVAddRecExpr>(R)) { 10918 Subscripts.clear(); 10919 Sizes.clear(); 10920 return; 10921 } 10922 10923 continue; 10924 } 10925 10926 // Record the access function for the current subscript. 10927 Subscripts.push_back(R); 10928 } 10929 10930 // Also push in last position the remainder of the last division: it will be 10931 // the access function of the innermost dimension. 10932 Subscripts.push_back(Res); 10933 10934 std::reverse(Subscripts.begin(), Subscripts.end()); 10935 10936 LLVM_DEBUG({ 10937 dbgs() << "Subscripts:\n"; 10938 for (const SCEV *S : Subscripts) 10939 dbgs() << *S << "\n"; 10940 }); 10941 } 10942 10943 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10944 /// sizes of an array access. Returns the remainder of the delinearization that 10945 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10946 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10947 /// expressions in the stride and base of a SCEV corresponding to the 10948 /// computation of a GCD (greatest common divisor) of base and stride. When 10949 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10950 /// 10951 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10952 /// 10953 /// void foo(long n, long m, long o, double A[n][m][o]) { 10954 /// 10955 /// for (long i = 0; i < n; i++) 10956 /// for (long j = 0; j < m; j++) 10957 /// for (long k = 0; k < o; k++) 10958 /// A[i][j][k] = 1.0; 10959 /// } 10960 /// 10961 /// the delinearization input is the following AddRec SCEV: 10962 /// 10963 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10964 /// 10965 /// From this SCEV, we are able to say that the base offset of the access is %A 10966 /// because it appears as an offset that does not divide any of the strides in 10967 /// the loops: 10968 /// 10969 /// CHECK: Base offset: %A 10970 /// 10971 /// and then SCEV->delinearize determines the size of some of the dimensions of 10972 /// the array as these are the multiples by which the strides are happening: 10973 /// 10974 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10975 /// 10976 /// Note that the outermost dimension remains of UnknownSize because there are 10977 /// no strides that would help identifying the size of the last dimension: when 10978 /// the array has been statically allocated, one could compute the size of that 10979 /// dimension by dividing the overall size of the array by the size of the known 10980 /// dimensions: %m * %o * 8. 10981 /// 10982 /// Finally delinearize provides the access functions for the array reference 10983 /// that does correspond to A[i][j][k] of the above C testcase: 10984 /// 10985 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10986 /// 10987 /// The testcases are checking the output of a function pass: 10988 /// DelinearizationPass that walks through all loads and stores of a function 10989 /// asking for the SCEV of the memory access with respect to all enclosing 10990 /// loops, calling SCEV->delinearize on that and printing the results. 10991 void ScalarEvolution::delinearize(const SCEV *Expr, 10992 SmallVectorImpl<const SCEV *> &Subscripts, 10993 SmallVectorImpl<const SCEV *> &Sizes, 10994 const SCEV *ElementSize) { 10995 // First step: collect parametric terms. 10996 SmallVector<const SCEV *, 4> Terms; 10997 collectParametricTerms(Expr, Terms); 10998 10999 if (Terms.empty()) 11000 return; 11001 11002 // Second step: find subscript sizes. 11003 findArrayDimensions(Terms, Sizes, ElementSize); 11004 11005 if (Sizes.empty()) 11006 return; 11007 11008 // Third step: compute the access functions for each subscript. 11009 computeAccessFunctions(Expr, Subscripts, Sizes); 11010 11011 if (Subscripts.empty()) 11012 return; 11013 11014 LLVM_DEBUG({ 11015 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11016 dbgs() << "ArrayDecl[UnknownSize]"; 11017 for (const SCEV *S : Sizes) 11018 dbgs() << "[" << *S << "]"; 11019 11020 dbgs() << "\nArrayRef"; 11021 for (const SCEV *S : Subscripts) 11022 dbgs() << "[" << *S << "]"; 11023 dbgs() << "\n"; 11024 }); 11025 } 11026 11027 //===----------------------------------------------------------------------===// 11028 // SCEVCallbackVH Class Implementation 11029 //===----------------------------------------------------------------------===// 11030 11031 void ScalarEvolution::SCEVCallbackVH::deleted() { 11032 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11033 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11034 SE->ConstantEvolutionLoopExitValue.erase(PN); 11035 SE->eraseValueFromMap(getValPtr()); 11036 // this now dangles! 11037 } 11038 11039 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11040 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11041 11042 // Forget all the expressions associated with users of the old value, 11043 // so that future queries will recompute the expressions using the new 11044 // value. 11045 Value *Old = getValPtr(); 11046 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11047 SmallPtrSet<User *, 8> Visited; 11048 while (!Worklist.empty()) { 11049 User *U = Worklist.pop_back_val(); 11050 // Deleting the Old value will cause this to dangle. Postpone 11051 // that until everything else is done. 11052 if (U == Old) 11053 continue; 11054 if (!Visited.insert(U).second) 11055 continue; 11056 if (PHINode *PN = dyn_cast<PHINode>(U)) 11057 SE->ConstantEvolutionLoopExitValue.erase(PN); 11058 SE->eraseValueFromMap(U); 11059 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11060 } 11061 // Delete the Old value. 11062 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11063 SE->ConstantEvolutionLoopExitValue.erase(PN); 11064 SE->eraseValueFromMap(Old); 11065 // this now dangles! 11066 } 11067 11068 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11069 : CallbackVH(V), SE(se) {} 11070 11071 //===----------------------------------------------------------------------===// 11072 // ScalarEvolution Class Implementation 11073 //===----------------------------------------------------------------------===// 11074 11075 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11076 AssumptionCache &AC, DominatorTree &DT, 11077 LoopInfo &LI) 11078 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11079 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11080 LoopDispositions(64), BlockDispositions(64) { 11081 // To use guards for proving predicates, we need to scan every instruction in 11082 // relevant basic blocks, and not just terminators. Doing this is a waste of 11083 // time if the IR does not actually contain any calls to 11084 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11085 // 11086 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11087 // to _add_ guards to the module when there weren't any before, and wants 11088 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11089 // efficient in lieu of being smart in that rather obscure case. 11090 11091 auto *GuardDecl = F.getParent()->getFunction( 11092 Intrinsic::getName(Intrinsic::experimental_guard)); 11093 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11094 } 11095 11096 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11097 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11098 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11099 ValueExprMap(std::move(Arg.ValueExprMap)), 11100 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11101 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11102 PendingMerges(std::move(Arg.PendingMerges)), 11103 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11104 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11105 PredicatedBackedgeTakenCounts( 11106 std::move(Arg.PredicatedBackedgeTakenCounts)), 11107 ConstantEvolutionLoopExitValue( 11108 std::move(Arg.ConstantEvolutionLoopExitValue)), 11109 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11110 LoopDispositions(std::move(Arg.LoopDispositions)), 11111 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11112 BlockDispositions(std::move(Arg.BlockDispositions)), 11113 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11114 SignedRanges(std::move(Arg.SignedRanges)), 11115 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11116 UniquePreds(std::move(Arg.UniquePreds)), 11117 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11118 LoopUsers(std::move(Arg.LoopUsers)), 11119 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11120 FirstUnknown(Arg.FirstUnknown) { 11121 Arg.FirstUnknown = nullptr; 11122 } 11123 11124 ScalarEvolution::~ScalarEvolution() { 11125 // Iterate through all the SCEVUnknown instances and call their 11126 // destructors, so that they release their references to their values. 11127 for (SCEVUnknown *U = FirstUnknown; U;) { 11128 SCEVUnknown *Tmp = U; 11129 U = U->Next; 11130 Tmp->~SCEVUnknown(); 11131 } 11132 FirstUnknown = nullptr; 11133 11134 ExprValueMap.clear(); 11135 ValueExprMap.clear(); 11136 HasRecMap.clear(); 11137 11138 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11139 // that a loop had multiple computable exits. 11140 for (auto &BTCI : BackedgeTakenCounts) 11141 BTCI.second.clear(); 11142 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11143 BTCI.second.clear(); 11144 11145 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11146 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11147 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11148 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11149 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11150 } 11151 11152 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11153 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11154 } 11155 11156 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11157 const Loop *L) { 11158 // Print all inner loops first 11159 for (Loop *I : *L) 11160 PrintLoopInfo(OS, SE, I); 11161 11162 OS << "Loop "; 11163 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11164 OS << ": "; 11165 11166 SmallVector<BasicBlock *, 8> ExitBlocks; 11167 L->getExitBlocks(ExitBlocks); 11168 if (ExitBlocks.size() != 1) 11169 OS << "<multiple exits> "; 11170 11171 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11172 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11173 } else { 11174 OS << "Unpredictable backedge-taken count. "; 11175 } 11176 11177 OS << "\n" 11178 "Loop "; 11179 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11180 OS << ": "; 11181 11182 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11183 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11184 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11185 OS << ", actual taken count either this or zero."; 11186 } else { 11187 OS << "Unpredictable max backedge-taken count. "; 11188 } 11189 11190 OS << "\n" 11191 "Loop "; 11192 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11193 OS << ": "; 11194 11195 SCEVUnionPredicate Pred; 11196 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11197 if (!isa<SCEVCouldNotCompute>(PBT)) { 11198 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11199 OS << " Predicates:\n"; 11200 Pred.print(OS, 4); 11201 } else { 11202 OS << "Unpredictable predicated backedge-taken count. "; 11203 } 11204 OS << "\n"; 11205 11206 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11207 OS << "Loop "; 11208 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11209 OS << ": "; 11210 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11211 } 11212 } 11213 11214 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11215 switch (LD) { 11216 case ScalarEvolution::LoopVariant: 11217 return "Variant"; 11218 case ScalarEvolution::LoopInvariant: 11219 return "Invariant"; 11220 case ScalarEvolution::LoopComputable: 11221 return "Computable"; 11222 } 11223 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11224 } 11225 11226 void ScalarEvolution::print(raw_ostream &OS) const { 11227 // ScalarEvolution's implementation of the print method is to print 11228 // out SCEV values of all instructions that are interesting. Doing 11229 // this potentially causes it to create new SCEV objects though, 11230 // which technically conflicts with the const qualifier. This isn't 11231 // observable from outside the class though, so casting away the 11232 // const isn't dangerous. 11233 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11234 11235 OS << "Classifying expressions for: "; 11236 F.printAsOperand(OS, /*PrintType=*/false); 11237 OS << "\n"; 11238 for (Instruction &I : instructions(F)) 11239 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11240 OS << I << '\n'; 11241 OS << " --> "; 11242 const SCEV *SV = SE.getSCEV(&I); 11243 SV->print(OS); 11244 if (!isa<SCEVCouldNotCompute>(SV)) { 11245 OS << " U: "; 11246 SE.getUnsignedRange(SV).print(OS); 11247 OS << " S: "; 11248 SE.getSignedRange(SV).print(OS); 11249 } 11250 11251 const Loop *L = LI.getLoopFor(I.getParent()); 11252 11253 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11254 if (AtUse != SV) { 11255 OS << " --> "; 11256 AtUse->print(OS); 11257 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11258 OS << " U: "; 11259 SE.getUnsignedRange(AtUse).print(OS); 11260 OS << " S: "; 11261 SE.getSignedRange(AtUse).print(OS); 11262 } 11263 } 11264 11265 if (L) { 11266 OS << "\t\t" "Exits: "; 11267 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11268 if (!SE.isLoopInvariant(ExitValue, L)) { 11269 OS << "<<Unknown>>"; 11270 } else { 11271 OS << *ExitValue; 11272 } 11273 11274 bool First = true; 11275 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11276 if (First) { 11277 OS << "\t\t" "LoopDispositions: { "; 11278 First = false; 11279 } else { 11280 OS << ", "; 11281 } 11282 11283 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11284 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11285 } 11286 11287 for (auto *InnerL : depth_first(L)) { 11288 if (InnerL == L) 11289 continue; 11290 if (First) { 11291 OS << "\t\t" "LoopDispositions: { "; 11292 First = false; 11293 } else { 11294 OS << ", "; 11295 } 11296 11297 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11298 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11299 } 11300 11301 OS << " }"; 11302 } 11303 11304 OS << "\n"; 11305 } 11306 11307 OS << "Determining loop execution counts for: "; 11308 F.printAsOperand(OS, /*PrintType=*/false); 11309 OS << "\n"; 11310 for (Loop *I : LI) 11311 PrintLoopInfo(OS, &SE, I); 11312 } 11313 11314 ScalarEvolution::LoopDisposition 11315 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11316 auto &Values = LoopDispositions[S]; 11317 for (auto &V : Values) { 11318 if (V.getPointer() == L) 11319 return V.getInt(); 11320 } 11321 Values.emplace_back(L, LoopVariant); 11322 LoopDisposition D = computeLoopDisposition(S, L); 11323 auto &Values2 = LoopDispositions[S]; 11324 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11325 if (V.getPointer() == L) { 11326 V.setInt(D); 11327 break; 11328 } 11329 } 11330 return D; 11331 } 11332 11333 ScalarEvolution::LoopDisposition 11334 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11335 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11336 case scConstant: 11337 return LoopInvariant; 11338 case scTruncate: 11339 case scZeroExtend: 11340 case scSignExtend: 11341 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11342 case scAddRecExpr: { 11343 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11344 11345 // If L is the addrec's loop, it's computable. 11346 if (AR->getLoop() == L) 11347 return LoopComputable; 11348 11349 // Add recurrences are never invariant in the function-body (null loop). 11350 if (!L) 11351 return LoopVariant; 11352 11353 // Everything that is not defined at loop entry is variant. 11354 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11355 return LoopVariant; 11356 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11357 " dominate the contained loop's header?"); 11358 11359 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11360 if (AR->getLoop()->contains(L)) 11361 return LoopInvariant; 11362 11363 // This recurrence is variant w.r.t. L if any of its operands 11364 // are variant. 11365 for (auto *Op : AR->operands()) 11366 if (!isLoopInvariant(Op, L)) 11367 return LoopVariant; 11368 11369 // Otherwise it's loop-invariant. 11370 return LoopInvariant; 11371 } 11372 case scAddExpr: 11373 case scMulExpr: 11374 case scUMaxExpr: 11375 case scSMaxExpr: { 11376 bool HasVarying = false; 11377 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11378 LoopDisposition D = getLoopDisposition(Op, L); 11379 if (D == LoopVariant) 11380 return LoopVariant; 11381 if (D == LoopComputable) 11382 HasVarying = true; 11383 } 11384 return HasVarying ? LoopComputable : LoopInvariant; 11385 } 11386 case scUDivExpr: { 11387 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11388 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11389 if (LD == LoopVariant) 11390 return LoopVariant; 11391 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11392 if (RD == LoopVariant) 11393 return LoopVariant; 11394 return (LD == LoopInvariant && RD == LoopInvariant) ? 11395 LoopInvariant : LoopComputable; 11396 } 11397 case scUnknown: 11398 // All non-instruction values are loop invariant. All instructions are loop 11399 // invariant if they are not contained in the specified loop. 11400 // Instructions are never considered invariant in the function body 11401 // (null loop) because they are defined within the "loop". 11402 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11403 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11404 return LoopInvariant; 11405 case scCouldNotCompute: 11406 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11407 } 11408 llvm_unreachable("Unknown SCEV kind!"); 11409 } 11410 11411 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11412 return getLoopDisposition(S, L) == LoopInvariant; 11413 } 11414 11415 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11416 return getLoopDisposition(S, L) == LoopComputable; 11417 } 11418 11419 ScalarEvolution::BlockDisposition 11420 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11421 auto &Values = BlockDispositions[S]; 11422 for (auto &V : Values) { 11423 if (V.getPointer() == BB) 11424 return V.getInt(); 11425 } 11426 Values.emplace_back(BB, DoesNotDominateBlock); 11427 BlockDisposition D = computeBlockDisposition(S, BB); 11428 auto &Values2 = BlockDispositions[S]; 11429 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11430 if (V.getPointer() == BB) { 11431 V.setInt(D); 11432 break; 11433 } 11434 } 11435 return D; 11436 } 11437 11438 ScalarEvolution::BlockDisposition 11439 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11440 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11441 case scConstant: 11442 return ProperlyDominatesBlock; 11443 case scTruncate: 11444 case scZeroExtend: 11445 case scSignExtend: 11446 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11447 case scAddRecExpr: { 11448 // This uses a "dominates" query instead of "properly dominates" query 11449 // to test for proper dominance too, because the instruction which 11450 // produces the addrec's value is a PHI, and a PHI effectively properly 11451 // dominates its entire containing block. 11452 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11453 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11454 return DoesNotDominateBlock; 11455 11456 // Fall through into SCEVNAryExpr handling. 11457 LLVM_FALLTHROUGH; 11458 } 11459 case scAddExpr: 11460 case scMulExpr: 11461 case scUMaxExpr: 11462 case scSMaxExpr: { 11463 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11464 bool Proper = true; 11465 for (const SCEV *NAryOp : NAry->operands()) { 11466 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11467 if (D == DoesNotDominateBlock) 11468 return DoesNotDominateBlock; 11469 if (D == DominatesBlock) 11470 Proper = false; 11471 } 11472 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11473 } 11474 case scUDivExpr: { 11475 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11476 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11477 BlockDisposition LD = getBlockDisposition(LHS, BB); 11478 if (LD == DoesNotDominateBlock) 11479 return DoesNotDominateBlock; 11480 BlockDisposition RD = getBlockDisposition(RHS, BB); 11481 if (RD == DoesNotDominateBlock) 11482 return DoesNotDominateBlock; 11483 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11484 ProperlyDominatesBlock : DominatesBlock; 11485 } 11486 case scUnknown: 11487 if (Instruction *I = 11488 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11489 if (I->getParent() == BB) 11490 return DominatesBlock; 11491 if (DT.properlyDominates(I->getParent(), BB)) 11492 return ProperlyDominatesBlock; 11493 return DoesNotDominateBlock; 11494 } 11495 return ProperlyDominatesBlock; 11496 case scCouldNotCompute: 11497 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11498 } 11499 llvm_unreachable("Unknown SCEV kind!"); 11500 } 11501 11502 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11503 return getBlockDisposition(S, BB) >= DominatesBlock; 11504 } 11505 11506 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11507 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11508 } 11509 11510 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11511 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11512 } 11513 11514 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11515 auto IsS = [&](const SCEV *X) { return S == X; }; 11516 auto ContainsS = [&](const SCEV *X) { 11517 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11518 }; 11519 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11520 } 11521 11522 void 11523 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11524 ValuesAtScopes.erase(S); 11525 LoopDispositions.erase(S); 11526 BlockDispositions.erase(S); 11527 UnsignedRanges.erase(S); 11528 SignedRanges.erase(S); 11529 ExprValueMap.erase(S); 11530 HasRecMap.erase(S); 11531 MinTrailingZerosCache.erase(S); 11532 11533 for (auto I = PredicatedSCEVRewrites.begin(); 11534 I != PredicatedSCEVRewrites.end();) { 11535 std::pair<const SCEV *, const Loop *> Entry = I->first; 11536 if (Entry.first == S) 11537 PredicatedSCEVRewrites.erase(I++); 11538 else 11539 ++I; 11540 } 11541 11542 auto RemoveSCEVFromBackedgeMap = 11543 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11544 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11545 BackedgeTakenInfo &BEInfo = I->second; 11546 if (BEInfo.hasOperand(S, this)) { 11547 BEInfo.clear(); 11548 Map.erase(I++); 11549 } else 11550 ++I; 11551 } 11552 }; 11553 11554 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11555 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11556 } 11557 11558 void 11559 ScalarEvolution::getUsedLoops(const SCEV *S, 11560 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11561 struct FindUsedLoops { 11562 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11563 : LoopsUsed(LoopsUsed) {} 11564 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11565 bool follow(const SCEV *S) { 11566 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11567 LoopsUsed.insert(AR->getLoop()); 11568 return true; 11569 } 11570 11571 bool isDone() const { return false; } 11572 }; 11573 11574 FindUsedLoops F(LoopsUsed); 11575 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11576 } 11577 11578 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11579 SmallPtrSet<const Loop *, 8> LoopsUsed; 11580 getUsedLoops(S, LoopsUsed); 11581 for (auto *L : LoopsUsed) 11582 LoopUsers[L].push_back(S); 11583 } 11584 11585 void ScalarEvolution::verify() const { 11586 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11587 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11588 11589 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11590 11591 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11592 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11593 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11594 11595 const SCEV *visitConstant(const SCEVConstant *Constant) { 11596 return SE.getConstant(Constant->getAPInt()); 11597 } 11598 11599 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11600 return SE.getUnknown(Expr->getValue()); 11601 } 11602 11603 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11604 return SE.getCouldNotCompute(); 11605 } 11606 }; 11607 11608 SCEVMapper SCM(SE2); 11609 11610 while (!LoopStack.empty()) { 11611 auto *L = LoopStack.pop_back_val(); 11612 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11613 11614 auto *CurBECount = SCM.visit( 11615 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11616 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11617 11618 if (CurBECount == SE2.getCouldNotCompute() || 11619 NewBECount == SE2.getCouldNotCompute()) { 11620 // NB! This situation is legal, but is very suspicious -- whatever pass 11621 // change the loop to make a trip count go from could not compute to 11622 // computable or vice-versa *should have* invalidated SCEV. However, we 11623 // choose not to assert here (for now) since we don't want false 11624 // positives. 11625 continue; 11626 } 11627 11628 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11629 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11630 // not propagate undef aggressively). This means we can (and do) fail 11631 // verification in cases where a transform makes the trip count of a loop 11632 // go from "undef" to "undef+1" (say). The transform is fine, since in 11633 // both cases the loop iterates "undef" times, but SCEV thinks we 11634 // increased the trip count of the loop by 1 incorrectly. 11635 continue; 11636 } 11637 11638 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11639 SE.getTypeSizeInBits(NewBECount->getType())) 11640 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11641 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11642 SE.getTypeSizeInBits(NewBECount->getType())) 11643 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11644 11645 auto *ConstantDelta = 11646 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11647 11648 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11649 dbgs() << "Trip Count Changed!\n"; 11650 dbgs() << "Old: " << *CurBECount << "\n"; 11651 dbgs() << "New: " << *NewBECount << "\n"; 11652 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11653 std::abort(); 11654 } 11655 } 11656 } 11657 11658 bool ScalarEvolution::invalidate( 11659 Function &F, const PreservedAnalyses &PA, 11660 FunctionAnalysisManager::Invalidator &Inv) { 11661 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11662 // of its dependencies is invalidated. 11663 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11664 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11665 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11666 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11667 Inv.invalidate<LoopAnalysis>(F, PA); 11668 } 11669 11670 AnalysisKey ScalarEvolutionAnalysis::Key; 11671 11672 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11673 FunctionAnalysisManager &AM) { 11674 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11675 AM.getResult<AssumptionAnalysis>(F), 11676 AM.getResult<DominatorTreeAnalysis>(F), 11677 AM.getResult<LoopAnalysis>(F)); 11678 } 11679 11680 PreservedAnalyses 11681 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11682 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11683 return PreservedAnalyses::all(); 11684 } 11685 11686 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11687 "Scalar Evolution Analysis", false, true) 11688 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11689 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11690 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11691 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11692 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11693 "Scalar Evolution Analysis", false, true) 11694 11695 char ScalarEvolutionWrapperPass::ID = 0; 11696 11697 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11698 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11699 } 11700 11701 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11702 SE.reset(new ScalarEvolution( 11703 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11704 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11705 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11706 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11707 return false; 11708 } 11709 11710 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11711 11712 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11713 SE->print(OS); 11714 } 11715 11716 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11717 if (!VerifySCEV) 11718 return; 11719 11720 SE->verify(); 11721 } 11722 11723 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11724 AU.setPreservesAll(); 11725 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11726 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11727 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11728 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11729 } 11730 11731 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11732 const SCEV *RHS) { 11733 FoldingSetNodeID ID; 11734 assert(LHS->getType() == RHS->getType() && 11735 "Type mismatch between LHS and RHS"); 11736 // Unique this node based on the arguments 11737 ID.AddInteger(SCEVPredicate::P_Equal); 11738 ID.AddPointer(LHS); 11739 ID.AddPointer(RHS); 11740 void *IP = nullptr; 11741 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11742 return S; 11743 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11744 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11745 UniquePreds.InsertNode(Eq, IP); 11746 return Eq; 11747 } 11748 11749 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11750 const SCEVAddRecExpr *AR, 11751 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11752 FoldingSetNodeID ID; 11753 // Unique this node based on the arguments 11754 ID.AddInteger(SCEVPredicate::P_Wrap); 11755 ID.AddPointer(AR); 11756 ID.AddInteger(AddedFlags); 11757 void *IP = nullptr; 11758 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11759 return S; 11760 auto *OF = new (SCEVAllocator) 11761 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11762 UniquePreds.InsertNode(OF, IP); 11763 return OF; 11764 } 11765 11766 namespace { 11767 11768 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11769 public: 11770 11771 /// Rewrites \p S in the context of a loop L and the SCEV predication 11772 /// infrastructure. 11773 /// 11774 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11775 /// equivalences present in \p Pred. 11776 /// 11777 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11778 /// \p NewPreds such that the result will be an AddRecExpr. 11779 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11780 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11781 SCEVUnionPredicate *Pred) { 11782 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11783 return Rewriter.visit(S); 11784 } 11785 11786 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11787 if (Pred) { 11788 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11789 for (auto *Pred : ExprPreds) 11790 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11791 if (IPred->getLHS() == Expr) 11792 return IPred->getRHS(); 11793 } 11794 return convertToAddRecWithPreds(Expr); 11795 } 11796 11797 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11798 const SCEV *Operand = visit(Expr->getOperand()); 11799 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11800 if (AR && AR->getLoop() == L && AR->isAffine()) { 11801 // This couldn't be folded because the operand didn't have the nuw 11802 // flag. Add the nusw flag as an assumption that we could make. 11803 const SCEV *Step = AR->getStepRecurrence(SE); 11804 Type *Ty = Expr->getType(); 11805 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11806 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11807 SE.getSignExtendExpr(Step, Ty), L, 11808 AR->getNoWrapFlags()); 11809 } 11810 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11811 } 11812 11813 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11814 const SCEV *Operand = visit(Expr->getOperand()); 11815 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11816 if (AR && AR->getLoop() == L && AR->isAffine()) { 11817 // This couldn't be folded because the operand didn't have the nsw 11818 // flag. Add the nssw flag as an assumption that we could make. 11819 const SCEV *Step = AR->getStepRecurrence(SE); 11820 Type *Ty = Expr->getType(); 11821 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11822 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11823 SE.getSignExtendExpr(Step, Ty), L, 11824 AR->getNoWrapFlags()); 11825 } 11826 return SE.getSignExtendExpr(Operand, Expr->getType()); 11827 } 11828 11829 private: 11830 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11831 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11832 SCEVUnionPredicate *Pred) 11833 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11834 11835 bool addOverflowAssumption(const SCEVPredicate *P) { 11836 if (!NewPreds) { 11837 // Check if we've already made this assumption. 11838 return Pred && Pred->implies(P); 11839 } 11840 NewPreds->insert(P); 11841 return true; 11842 } 11843 11844 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11845 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11846 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11847 return addOverflowAssumption(A); 11848 } 11849 11850 // If \p Expr represents a PHINode, we try to see if it can be represented 11851 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11852 // to add this predicate as a runtime overflow check, we return the AddRec. 11853 // If \p Expr does not meet these conditions (is not a PHI node, or we 11854 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11855 // return \p Expr. 11856 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11857 if (!isa<PHINode>(Expr->getValue())) 11858 return Expr; 11859 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11860 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11861 if (!PredicatedRewrite) 11862 return Expr; 11863 for (auto *P : PredicatedRewrite->second){ 11864 // Wrap predicates from outer loops are not supported. 11865 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 11866 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 11867 if (L != AR->getLoop()) 11868 return Expr; 11869 } 11870 if (!addOverflowAssumption(P)) 11871 return Expr; 11872 } 11873 return PredicatedRewrite->first; 11874 } 11875 11876 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11877 SCEVUnionPredicate *Pred; 11878 const Loop *L; 11879 }; 11880 11881 } // end anonymous namespace 11882 11883 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11884 SCEVUnionPredicate &Preds) { 11885 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11886 } 11887 11888 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11889 const SCEV *S, const Loop *L, 11890 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11891 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11892 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11893 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11894 11895 if (!AddRec) 11896 return nullptr; 11897 11898 // Since the transformation was successful, we can now transfer the SCEV 11899 // predicates. 11900 for (auto *P : TransformPreds) 11901 Preds.insert(P); 11902 11903 return AddRec; 11904 } 11905 11906 /// SCEV predicates 11907 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11908 SCEVPredicateKind Kind) 11909 : FastID(ID), Kind(Kind) {} 11910 11911 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11912 const SCEV *LHS, const SCEV *RHS) 11913 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11914 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11915 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11916 } 11917 11918 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11919 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11920 11921 if (!Op) 11922 return false; 11923 11924 return Op->LHS == LHS && Op->RHS == RHS; 11925 } 11926 11927 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11928 11929 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11930 11931 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11932 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11933 } 11934 11935 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11936 const SCEVAddRecExpr *AR, 11937 IncrementWrapFlags Flags) 11938 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11939 11940 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11941 11942 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11943 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11944 11945 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11946 } 11947 11948 bool SCEVWrapPredicate::isAlwaysTrue() const { 11949 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11950 IncrementWrapFlags IFlags = Flags; 11951 11952 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11953 IFlags = clearFlags(IFlags, IncrementNSSW); 11954 11955 return IFlags == IncrementAnyWrap; 11956 } 11957 11958 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11959 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11960 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11961 OS << "<nusw>"; 11962 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11963 OS << "<nssw>"; 11964 OS << "\n"; 11965 } 11966 11967 SCEVWrapPredicate::IncrementWrapFlags 11968 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11969 ScalarEvolution &SE) { 11970 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11971 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11972 11973 // We can safely transfer the NSW flag as NSSW. 11974 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11975 ImpliedFlags = IncrementNSSW; 11976 11977 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11978 // If the increment is positive, the SCEV NUW flag will also imply the 11979 // WrapPredicate NUSW flag. 11980 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11981 if (Step->getValue()->getValue().isNonNegative()) 11982 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11983 } 11984 11985 return ImpliedFlags; 11986 } 11987 11988 /// Union predicates don't get cached so create a dummy set ID for it. 11989 SCEVUnionPredicate::SCEVUnionPredicate() 11990 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11991 11992 bool SCEVUnionPredicate::isAlwaysTrue() const { 11993 return all_of(Preds, 11994 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11995 } 11996 11997 ArrayRef<const SCEVPredicate *> 11998 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11999 auto I = SCEVToPreds.find(Expr); 12000 if (I == SCEVToPreds.end()) 12001 return ArrayRef<const SCEVPredicate *>(); 12002 return I->second; 12003 } 12004 12005 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12006 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12007 return all_of(Set->Preds, 12008 [this](const SCEVPredicate *I) { return this->implies(I); }); 12009 12010 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12011 if (ScevPredsIt == SCEVToPreds.end()) 12012 return false; 12013 auto &SCEVPreds = ScevPredsIt->second; 12014 12015 return any_of(SCEVPreds, 12016 [N](const SCEVPredicate *I) { return I->implies(N); }); 12017 } 12018 12019 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12020 12021 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12022 for (auto Pred : Preds) 12023 Pred->print(OS, Depth); 12024 } 12025 12026 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12027 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12028 for (auto Pred : Set->Preds) 12029 add(Pred); 12030 return; 12031 } 12032 12033 if (implies(N)) 12034 return; 12035 12036 const SCEV *Key = N->getExpr(); 12037 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12038 " associated expression!"); 12039 12040 SCEVToPreds[Key].push_back(N); 12041 Preds.push_back(N); 12042 } 12043 12044 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12045 Loop &L) 12046 : SE(SE), L(L) {} 12047 12048 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12049 const SCEV *Expr = SE.getSCEV(V); 12050 RewriteEntry &Entry = RewriteMap[Expr]; 12051 12052 // If we already have an entry and the version matches, return it. 12053 if (Entry.second && Generation == Entry.first) 12054 return Entry.second; 12055 12056 // We found an entry but it's stale. Rewrite the stale entry 12057 // according to the current predicate. 12058 if (Entry.second) 12059 Expr = Entry.second; 12060 12061 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12062 Entry = {Generation, NewSCEV}; 12063 12064 return NewSCEV; 12065 } 12066 12067 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12068 if (!BackedgeCount) { 12069 SCEVUnionPredicate BackedgePred; 12070 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12071 addPredicate(BackedgePred); 12072 } 12073 return BackedgeCount; 12074 } 12075 12076 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12077 if (Preds.implies(&Pred)) 12078 return; 12079 Preds.add(&Pred); 12080 updateGeneration(); 12081 } 12082 12083 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12084 return Preds; 12085 } 12086 12087 void PredicatedScalarEvolution::updateGeneration() { 12088 // If the generation number wrapped recompute everything. 12089 if (++Generation == 0) { 12090 for (auto &II : RewriteMap) { 12091 const SCEV *Rewritten = II.second.second; 12092 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12093 } 12094 } 12095 } 12096 12097 void PredicatedScalarEvolution::setNoOverflow( 12098 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12099 const SCEV *Expr = getSCEV(V); 12100 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12101 12102 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12103 12104 // Clear the statically implied flags. 12105 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12106 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12107 12108 auto II = FlagsMap.insert({V, Flags}); 12109 if (!II.second) 12110 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12111 } 12112 12113 bool PredicatedScalarEvolution::hasNoOverflow( 12114 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12115 const SCEV *Expr = getSCEV(V); 12116 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12117 12118 Flags = SCEVWrapPredicate::clearFlags( 12119 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12120 12121 auto II = FlagsMap.find(V); 12122 12123 if (II != FlagsMap.end()) 12124 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12125 12126 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12127 } 12128 12129 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12130 const SCEV *Expr = this->getSCEV(V); 12131 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12132 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12133 12134 if (!New) 12135 return nullptr; 12136 12137 for (auto *P : NewPreds) 12138 Preds.add(P); 12139 12140 updateGeneration(); 12141 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12142 return New; 12143 } 12144 12145 PredicatedScalarEvolution::PredicatedScalarEvolution( 12146 const PredicatedScalarEvolution &Init) 12147 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12148 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12149 for (const auto &I : Init.FlagsMap) 12150 FlagsMap.insert(I); 12151 } 12152 12153 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12154 // For each block. 12155 for (auto *BB : L.getBlocks()) 12156 for (auto &I : *BB) { 12157 if (!SE.isSCEVable(I.getType())) 12158 continue; 12159 12160 auto *Expr = SE.getSCEV(&I); 12161 auto II = RewriteMap.find(Expr); 12162 12163 if (II == RewriteMap.end()) 12164 continue; 12165 12166 // Don't print things that are not interesting. 12167 if (II->second.second == Expr) 12168 continue; 12169 12170 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12171 OS.indent(Depth + 2) << *Expr << "\n"; 12172 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12173 } 12174 } 12175 12176 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12177 // arbitrary expressions. 12178 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12179 // 4, A / B becomes X / 8). 12180 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12181 const SCEV *&RHS) { 12182 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12183 if (Add == nullptr || Add->getNumOperands() != 2) 12184 return false; 12185 12186 const SCEV *A = Add->getOperand(1); 12187 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12188 12189 if (Mul == nullptr) 12190 return false; 12191 12192 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12193 // (SomeExpr + (-(SomeExpr / B) * B)). 12194 if (Expr == getURemExpr(A, B)) { 12195 LHS = A; 12196 RHS = B; 12197 return true; 12198 } 12199 return false; 12200 }; 12201 12202 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12203 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12204 return MatchURemWithDivisor(Mul->getOperand(1)) || 12205 MatchURemWithDivisor(Mul->getOperand(2)); 12206 12207 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12208 if (Mul->getNumOperands() == 2) 12209 return MatchURemWithDivisor(Mul->getOperand(1)) || 12210 MatchURemWithDivisor(Mul->getOperand(0)) || 12211 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12212 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12213 return false; 12214 } 12215