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 // Lexicographically compare. 696 for (unsigned i = 0; i != LNumOps; ++i) { 697 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 698 LA->getOperand(i), RA->getOperand(i), DT, 699 Depth + 1); 700 if (X != 0) 701 return X; 702 } 703 EqCacheSCEV.unionSets(LHS, RHS); 704 return 0; 705 } 706 707 case scAddExpr: 708 case scMulExpr: 709 case scSMaxExpr: 710 case scUMaxExpr: { 711 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 712 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 713 714 // Lexicographically compare n-ary expressions. 715 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 716 if (LNumOps != RNumOps) 717 return (int)LNumOps - (int)RNumOps; 718 719 for (unsigned i = 0; i != LNumOps; ++i) { 720 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 721 LC->getOperand(i), RC->getOperand(i), DT, 722 Depth + 1); 723 if (X != 0) 724 return X; 725 } 726 EqCacheSCEV.unionSets(LHS, RHS); 727 return 0; 728 } 729 730 case scUDivExpr: { 731 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 732 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 733 734 // Lexicographically compare udiv expressions. 735 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 736 RC->getLHS(), DT, Depth + 1); 737 if (X != 0) 738 return X; 739 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 740 RC->getRHS(), DT, Depth + 1); 741 if (X == 0) 742 EqCacheSCEV.unionSets(LHS, RHS); 743 return X; 744 } 745 746 case scTruncate: 747 case scZeroExtend: 748 case scSignExtend: { 749 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 750 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 751 752 // Compare cast expressions by operand. 753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 754 LC->getOperand(), RC->getOperand(), DT, 755 Depth + 1); 756 if (X == 0) 757 EqCacheSCEV.unionSets(LHS, RHS); 758 return X; 759 } 760 761 case scCouldNotCompute: 762 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 763 } 764 llvm_unreachable("Unknown SCEV kind!"); 765 } 766 767 /// Given a list of SCEV objects, order them by their complexity, and group 768 /// objects of the same complexity together by value. When this routine is 769 /// finished, we know that any duplicates in the vector are consecutive and that 770 /// complexity is monotonically increasing. 771 /// 772 /// Note that we go take special precautions to ensure that we get deterministic 773 /// results from this routine. In other words, we don't want the results of 774 /// this to depend on where the addresses of various SCEV objects happened to 775 /// land in memory. 776 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 777 LoopInfo *LI, DominatorTree &DT) { 778 if (Ops.size() < 2) return; // Noop 779 780 EquivalenceClasses<const SCEV *> EqCacheSCEV; 781 EquivalenceClasses<const Value *> EqCacheValue; 782 if (Ops.size() == 2) { 783 // This is the common case, which also happens to be trivially simple. 784 // Special case it. 785 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 786 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 787 std::swap(LHS, RHS); 788 return; 789 } 790 791 // Do the rough sort by complexity. 792 std::stable_sort(Ops.begin(), Ops.end(), 793 [&](const SCEV *LHS, const SCEV *RHS) { 794 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 795 LHS, RHS, DT) < 0; 796 }); 797 798 // Now that we are sorted by complexity, group elements of the same 799 // complexity. Note that this is, at worst, N^2, but the vector is likely to 800 // be extremely short in practice. Note that we take this approach because we 801 // do not want to depend on the addresses of the objects we are grouping. 802 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 803 const SCEV *S = Ops[i]; 804 unsigned Complexity = S->getSCEVType(); 805 806 // If there are any objects of the same complexity and same value as this 807 // one, group them. 808 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 809 if (Ops[j] == S) { // Found a duplicate. 810 // Move it to immediately after i'th element. 811 std::swap(Ops[i+1], Ops[j]); 812 ++i; // no need to rescan it. 813 if (i == e-2) return; // Done! 814 } 815 } 816 } 817 } 818 819 // Returns the size of the SCEV S. 820 static inline int sizeOfSCEV(const SCEV *S) { 821 struct FindSCEVSize { 822 int Size = 0; 823 824 FindSCEVSize() = default; 825 826 bool follow(const SCEV *S) { 827 ++Size; 828 // Keep looking at all operands of S. 829 return true; 830 } 831 832 bool isDone() const { 833 return false; 834 } 835 }; 836 837 FindSCEVSize F; 838 SCEVTraversal<FindSCEVSize> ST(F); 839 ST.visitAll(S); 840 return F.Size; 841 } 842 843 namespace { 844 845 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 846 public: 847 // Computes the Quotient and Remainder of the division of Numerator by 848 // Denominator. 849 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 850 const SCEV *Denominator, const SCEV **Quotient, 851 const SCEV **Remainder) { 852 assert(Numerator && Denominator && "Uninitialized SCEV"); 853 854 SCEVDivision D(SE, Numerator, Denominator); 855 856 // Check for the trivial case here to avoid having to check for it in the 857 // rest of the code. 858 if (Numerator == Denominator) { 859 *Quotient = D.One; 860 *Remainder = D.Zero; 861 return; 862 } 863 864 if (Numerator->isZero()) { 865 *Quotient = D.Zero; 866 *Remainder = D.Zero; 867 return; 868 } 869 870 // A simple case when N/1. The quotient is N. 871 if (Denominator->isOne()) { 872 *Quotient = Numerator; 873 *Remainder = D.Zero; 874 return; 875 } 876 877 // Split the Denominator when it is a product. 878 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 879 const SCEV *Q, *R; 880 *Quotient = Numerator; 881 for (const SCEV *Op : T->operands()) { 882 divide(SE, *Quotient, Op, &Q, &R); 883 *Quotient = Q; 884 885 // Bail out when the Numerator is not divisible by one of the terms of 886 // the Denominator. 887 if (!R->isZero()) { 888 *Quotient = D.Zero; 889 *Remainder = Numerator; 890 return; 891 } 892 } 893 *Remainder = D.Zero; 894 return; 895 } 896 897 D.visit(Numerator); 898 *Quotient = D.Quotient; 899 *Remainder = D.Remainder; 900 } 901 902 // Except in the trivial case described above, we do not know how to divide 903 // Expr by Denominator for the following functions with empty implementation. 904 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 905 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 906 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 907 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 908 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 909 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 910 void visitUnknown(const SCEVUnknown *Numerator) {} 911 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 912 913 void visitConstant(const SCEVConstant *Numerator) { 914 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 915 APInt NumeratorVal = Numerator->getAPInt(); 916 APInt DenominatorVal = D->getAPInt(); 917 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 918 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 919 920 if (NumeratorBW > DenominatorBW) 921 DenominatorVal = DenominatorVal.sext(NumeratorBW); 922 else if (NumeratorBW < DenominatorBW) 923 NumeratorVal = NumeratorVal.sext(DenominatorBW); 924 925 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 926 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 927 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 928 Quotient = SE.getConstant(QuotientVal); 929 Remainder = SE.getConstant(RemainderVal); 930 return; 931 } 932 } 933 934 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 935 const SCEV *StartQ, *StartR, *StepQ, *StepR; 936 if (!Numerator->isAffine()) 937 return cannotDivide(Numerator); 938 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 939 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 940 // Bail out if the types do not match. 941 Type *Ty = Denominator->getType(); 942 if (Ty != StartQ->getType() || Ty != StartR->getType() || 943 Ty != StepQ->getType() || Ty != StepR->getType()) 944 return cannotDivide(Numerator); 945 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 946 Numerator->getNoWrapFlags()); 947 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 948 Numerator->getNoWrapFlags()); 949 } 950 951 void visitAddExpr(const SCEVAddExpr *Numerator) { 952 SmallVector<const SCEV *, 2> Qs, Rs; 953 Type *Ty = Denominator->getType(); 954 955 for (const SCEV *Op : Numerator->operands()) { 956 const SCEV *Q, *R; 957 divide(SE, Op, Denominator, &Q, &R); 958 959 // Bail out if types do not match. 960 if (Ty != Q->getType() || Ty != R->getType()) 961 return cannotDivide(Numerator); 962 963 Qs.push_back(Q); 964 Rs.push_back(R); 965 } 966 967 if (Qs.size() == 1) { 968 Quotient = Qs[0]; 969 Remainder = Rs[0]; 970 return; 971 } 972 973 Quotient = SE.getAddExpr(Qs); 974 Remainder = SE.getAddExpr(Rs); 975 } 976 977 void visitMulExpr(const SCEVMulExpr *Numerator) { 978 SmallVector<const SCEV *, 2> Qs; 979 Type *Ty = Denominator->getType(); 980 981 bool FoundDenominatorTerm = false; 982 for (const SCEV *Op : Numerator->operands()) { 983 // Bail out if types do not match. 984 if (Ty != Op->getType()) 985 return cannotDivide(Numerator); 986 987 if (FoundDenominatorTerm) { 988 Qs.push_back(Op); 989 continue; 990 } 991 992 // Check whether Denominator divides one of the product operands. 993 const SCEV *Q, *R; 994 divide(SE, Op, Denominator, &Q, &R); 995 if (!R->isZero()) { 996 Qs.push_back(Op); 997 continue; 998 } 999 1000 // Bail out if types do not match. 1001 if (Ty != Q->getType()) 1002 return cannotDivide(Numerator); 1003 1004 FoundDenominatorTerm = true; 1005 Qs.push_back(Q); 1006 } 1007 1008 if (FoundDenominatorTerm) { 1009 Remainder = Zero; 1010 if (Qs.size() == 1) 1011 Quotient = Qs[0]; 1012 else 1013 Quotient = SE.getMulExpr(Qs); 1014 return; 1015 } 1016 1017 if (!isa<SCEVUnknown>(Denominator)) 1018 return cannotDivide(Numerator); 1019 1020 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1021 ValueToValueMap RewriteMap; 1022 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1023 cast<SCEVConstant>(Zero)->getValue(); 1024 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1025 1026 if (Remainder->isZero()) { 1027 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1028 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1029 cast<SCEVConstant>(One)->getValue(); 1030 Quotient = 1031 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1032 return; 1033 } 1034 1035 // Quotient is (Numerator - Remainder) divided by Denominator. 1036 const SCEV *Q, *R; 1037 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1038 // This SCEV does not seem to simplify: fail the division here. 1039 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1040 return cannotDivide(Numerator); 1041 divide(SE, Diff, Denominator, &Q, &R); 1042 if (R != Zero) 1043 return cannotDivide(Numerator); 1044 Quotient = Q; 1045 } 1046 1047 private: 1048 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1049 const SCEV *Denominator) 1050 : SE(S), Denominator(Denominator) { 1051 Zero = SE.getZero(Denominator->getType()); 1052 One = SE.getOne(Denominator->getType()); 1053 1054 // We generally do not know how to divide Expr by Denominator. We 1055 // initialize the division to a "cannot divide" state to simplify the rest 1056 // of the code. 1057 cannotDivide(Numerator); 1058 } 1059 1060 // Convenience function for giving up on the division. We set the quotient to 1061 // be equal to zero and the remainder to be equal to the numerator. 1062 void cannotDivide(const SCEV *Numerator) { 1063 Quotient = Zero; 1064 Remainder = Numerator; 1065 } 1066 1067 ScalarEvolution &SE; 1068 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1069 }; 1070 1071 } // end anonymous namespace 1072 1073 //===----------------------------------------------------------------------===// 1074 // Simple SCEV method implementations 1075 //===----------------------------------------------------------------------===// 1076 1077 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1078 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1079 ScalarEvolution &SE, 1080 Type *ResultTy) { 1081 // Handle the simplest case efficiently. 1082 if (K == 1) 1083 return SE.getTruncateOrZeroExtend(It, ResultTy); 1084 1085 // We are using the following formula for BC(It, K): 1086 // 1087 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1088 // 1089 // Suppose, W is the bitwidth of the return value. We must be prepared for 1090 // overflow. Hence, we must assure that the result of our computation is 1091 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1092 // safe in modular arithmetic. 1093 // 1094 // However, this code doesn't use exactly that formula; the formula it uses 1095 // is something like the following, where T is the number of factors of 2 in 1096 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1097 // exponentiation: 1098 // 1099 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1100 // 1101 // This formula is trivially equivalent to the previous formula. However, 1102 // this formula can be implemented much more efficiently. The trick is that 1103 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1104 // arithmetic. To do exact division in modular arithmetic, all we have 1105 // to do is multiply by the inverse. Therefore, this step can be done at 1106 // width W. 1107 // 1108 // The next issue is how to safely do the division by 2^T. The way this 1109 // is done is by doing the multiplication step at a width of at least W + T 1110 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1111 // when we perform the division by 2^T (which is equivalent to a right shift 1112 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1113 // truncated out after the division by 2^T. 1114 // 1115 // In comparison to just directly using the first formula, this technique 1116 // is much more efficient; using the first formula requires W * K bits, 1117 // but this formula less than W + K bits. Also, the first formula requires 1118 // a division step, whereas this formula only requires multiplies and shifts. 1119 // 1120 // It doesn't matter whether the subtraction step is done in the calculation 1121 // width or the input iteration count's width; if the subtraction overflows, 1122 // the result must be zero anyway. We prefer here to do it in the width of 1123 // the induction variable because it helps a lot for certain cases; CodeGen 1124 // isn't smart enough to ignore the overflow, which leads to much less 1125 // efficient code if the width of the subtraction is wider than the native 1126 // register width. 1127 // 1128 // (It's possible to not widen at all by pulling out factors of 2 before 1129 // the multiplication; for example, K=2 can be calculated as 1130 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1131 // extra arithmetic, so it's not an obvious win, and it gets 1132 // much more complicated for K > 3.) 1133 1134 // Protection from insane SCEVs; this bound is conservative, 1135 // but it probably doesn't matter. 1136 if (K > 1000) 1137 return SE.getCouldNotCompute(); 1138 1139 unsigned W = SE.getTypeSizeInBits(ResultTy); 1140 1141 // Calculate K! / 2^T and T; we divide out the factors of two before 1142 // multiplying for calculating K! / 2^T to avoid overflow. 1143 // Other overflow doesn't matter because we only care about the bottom 1144 // W bits of the result. 1145 APInt OddFactorial(W, 1); 1146 unsigned T = 1; 1147 for (unsigned i = 3; i <= K; ++i) { 1148 APInt Mult(W, i); 1149 unsigned TwoFactors = Mult.countTrailingZeros(); 1150 T += TwoFactors; 1151 Mult.lshrInPlace(TwoFactors); 1152 OddFactorial *= Mult; 1153 } 1154 1155 // We need at least W + T bits for the multiplication step 1156 unsigned CalculationBits = W + T; 1157 1158 // Calculate 2^T, at width T+W. 1159 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1160 1161 // Calculate the multiplicative inverse of K! / 2^T; 1162 // this multiplication factor will perform the exact division by 1163 // K! / 2^T. 1164 APInt Mod = APInt::getSignedMinValue(W+1); 1165 APInt MultiplyFactor = OddFactorial.zext(W+1); 1166 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1167 MultiplyFactor = MultiplyFactor.trunc(W); 1168 1169 // Calculate the product, at width T+W 1170 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1171 CalculationBits); 1172 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1173 for (unsigned i = 1; i != K; ++i) { 1174 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1175 Dividend = SE.getMulExpr(Dividend, 1176 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1177 } 1178 1179 // Divide by 2^T 1180 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1181 1182 // Truncate the result, and divide by K! / 2^T. 1183 1184 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1185 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1186 } 1187 1188 /// Return the value of this chain of recurrences at the specified iteration 1189 /// number. We can evaluate this recurrence by multiplying each element in the 1190 /// chain by the binomial coefficient corresponding to it. In other words, we 1191 /// can evaluate {A,+,B,+,C,+,D} as: 1192 /// 1193 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1194 /// 1195 /// where BC(It, k) stands for binomial coefficient. 1196 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1197 ScalarEvolution &SE) const { 1198 const SCEV *Result = getStart(); 1199 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1200 // The computation is correct in the face of overflow provided that the 1201 // multiplication is performed _after_ the evaluation of the binomial 1202 // coefficient. 1203 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1204 if (isa<SCEVCouldNotCompute>(Coeff)) 1205 return Coeff; 1206 1207 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1208 } 1209 return Result; 1210 } 1211 1212 //===----------------------------------------------------------------------===// 1213 // SCEV Expression folder implementations 1214 //===----------------------------------------------------------------------===// 1215 1216 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1217 Type *Ty) { 1218 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1219 "This is not a truncating conversion!"); 1220 assert(isSCEVable(Ty) && 1221 "This is not a conversion to a SCEVable type!"); 1222 Ty = getEffectiveSCEVType(Ty); 1223 1224 FoldingSetNodeID ID; 1225 ID.AddInteger(scTruncate); 1226 ID.AddPointer(Op); 1227 ID.AddPointer(Ty); 1228 void *IP = nullptr; 1229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1230 1231 // Fold if the operand is constant. 1232 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1233 return getConstant( 1234 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1235 1236 // trunc(trunc(x)) --> trunc(x) 1237 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1238 return getTruncateExpr(ST->getOperand(), Ty); 1239 1240 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1241 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1242 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1243 1244 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1245 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1246 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1247 1248 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1249 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1250 // if after transforming we have at most one truncate, not counting truncates 1251 // that replace other casts. 1252 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1253 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1254 SmallVector<const SCEV *, 4> Operands; 1255 unsigned numTruncs = 0; 1256 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1257 ++i) { 1258 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty); 1259 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1260 numTruncs++; 1261 Operands.push_back(S); 1262 } 1263 if (numTruncs < 2) { 1264 if (isa<SCEVAddExpr>(Op)) 1265 return getAddExpr(Operands); 1266 else if (isa<SCEVMulExpr>(Op)) 1267 return getMulExpr(Operands); 1268 else 1269 llvm_unreachable("Unexpected SCEV type for Op."); 1270 } 1271 // Although we checked in the beginning that ID is not in the cache, it is 1272 // possible that during recursion and different modification ID was inserted 1273 // into the cache. So if we find it, just return it. 1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1275 return S; 1276 } 1277 1278 // If the input value is a chrec scev, truncate the chrec's operands. 1279 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1280 SmallVector<const SCEV *, 4> Operands; 1281 for (const SCEV *Op : AddRec->operands()) 1282 Operands.push_back(getTruncateExpr(Op, Ty)); 1283 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1284 } 1285 1286 // The cast wasn't folded; create an explicit cast node. We can reuse 1287 // the existing insert position since if we get here, we won't have 1288 // made any changes which would invalidate it. 1289 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1290 Op, Ty); 1291 UniqueSCEVs.InsertNode(S, IP); 1292 addToLoopUseLists(S); 1293 return S; 1294 } 1295 1296 // Get the limit of a recurrence such that incrementing by Step cannot cause 1297 // signed overflow as long as the value of the recurrence within the 1298 // loop does not exceed this limit before incrementing. 1299 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1300 ICmpInst::Predicate *Pred, 1301 ScalarEvolution *SE) { 1302 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1303 if (SE->isKnownPositive(Step)) { 1304 *Pred = ICmpInst::ICMP_SLT; 1305 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1306 SE->getSignedRangeMax(Step)); 1307 } 1308 if (SE->isKnownNegative(Step)) { 1309 *Pred = ICmpInst::ICMP_SGT; 1310 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1311 SE->getSignedRangeMin(Step)); 1312 } 1313 return nullptr; 1314 } 1315 1316 // Get the limit of a recurrence such that incrementing by Step cannot cause 1317 // unsigned overflow as long as the value of the recurrence within the loop does 1318 // not exceed this limit before incrementing. 1319 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1320 ICmpInst::Predicate *Pred, 1321 ScalarEvolution *SE) { 1322 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1323 *Pred = ICmpInst::ICMP_ULT; 1324 1325 return SE->getConstant(APInt::getMinValue(BitWidth) - 1326 SE->getUnsignedRangeMax(Step)); 1327 } 1328 1329 namespace { 1330 1331 struct ExtendOpTraitsBase { 1332 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1333 unsigned); 1334 }; 1335 1336 // Used to make code generic over signed and unsigned overflow. 1337 template <typename ExtendOp> struct ExtendOpTraits { 1338 // Members present: 1339 // 1340 // static const SCEV::NoWrapFlags WrapType; 1341 // 1342 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1343 // 1344 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1345 // ICmpInst::Predicate *Pred, 1346 // ScalarEvolution *SE); 1347 }; 1348 1349 template <> 1350 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1351 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1352 1353 static const GetExtendExprTy GetExtendExpr; 1354 1355 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1356 ICmpInst::Predicate *Pred, 1357 ScalarEvolution *SE) { 1358 return getSignedOverflowLimitForStep(Step, Pred, SE); 1359 } 1360 }; 1361 1362 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1363 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1364 1365 template <> 1366 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1367 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1368 1369 static const GetExtendExprTy GetExtendExpr; 1370 1371 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1372 ICmpInst::Predicate *Pred, 1373 ScalarEvolution *SE) { 1374 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1375 } 1376 }; 1377 1378 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1379 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1380 1381 } // end anonymous namespace 1382 1383 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1384 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1385 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1386 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1387 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1388 // expression "Step + sext/zext(PreIncAR)" is congruent with 1389 // "sext/zext(PostIncAR)" 1390 template <typename ExtendOpTy> 1391 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1392 ScalarEvolution *SE, unsigned Depth) { 1393 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1394 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1395 1396 const Loop *L = AR->getLoop(); 1397 const SCEV *Start = AR->getStart(); 1398 const SCEV *Step = AR->getStepRecurrence(*SE); 1399 1400 // Check for a simple looking step prior to loop entry. 1401 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1402 if (!SA) 1403 return nullptr; 1404 1405 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1406 // subtraction is expensive. For this purpose, perform a quick and dirty 1407 // difference, by checking for Step in the operand list. 1408 SmallVector<const SCEV *, 4> DiffOps; 1409 for (const SCEV *Op : SA->operands()) 1410 if (Op != Step) 1411 DiffOps.push_back(Op); 1412 1413 if (DiffOps.size() == SA->getNumOperands()) 1414 return nullptr; 1415 1416 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1417 // `Step`: 1418 1419 // 1. NSW/NUW flags on the step increment. 1420 auto PreStartFlags = 1421 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1422 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1423 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1424 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1425 1426 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1427 // "S+X does not sign/unsign-overflow". 1428 // 1429 1430 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1431 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1432 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1433 return PreStart; 1434 1435 // 2. Direct overflow check on the step operation's expression. 1436 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1437 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1438 const SCEV *OperandExtendedStart = 1439 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1440 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1441 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1442 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1443 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1444 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1445 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1446 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1447 } 1448 return PreStart; 1449 } 1450 1451 // 3. Loop precondition. 1452 ICmpInst::Predicate Pred; 1453 const SCEV *OverflowLimit = 1454 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1455 1456 if (OverflowLimit && 1457 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1458 return PreStart; 1459 1460 return nullptr; 1461 } 1462 1463 // Get the normalized zero or sign extended expression for this AddRec's Start. 1464 template <typename ExtendOpTy> 1465 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1466 ScalarEvolution *SE, 1467 unsigned Depth) { 1468 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1469 1470 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1471 if (!PreStart) 1472 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1473 1474 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1475 Depth), 1476 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1477 } 1478 1479 // Try to prove away overflow by looking at "nearby" add recurrences. A 1480 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1481 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1482 // 1483 // Formally: 1484 // 1485 // {S,+,X} == {S-T,+,X} + T 1486 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1487 // 1488 // If ({S-T,+,X} + T) does not overflow ... (1) 1489 // 1490 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1491 // 1492 // If {S-T,+,X} does not overflow ... (2) 1493 // 1494 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1495 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1496 // 1497 // If (S-T)+T does not overflow ... (3) 1498 // 1499 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1500 // == {Ext(S),+,Ext(X)} == LHS 1501 // 1502 // Thus, if (1), (2) and (3) are true for some T, then 1503 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1504 // 1505 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1506 // does not overflow" restricted to the 0th iteration. Therefore we only need 1507 // to check for (1) and (2). 1508 // 1509 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1510 // is `Delta` (defined below). 1511 template <typename ExtendOpTy> 1512 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1513 const SCEV *Step, 1514 const Loop *L) { 1515 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1516 1517 // We restrict `Start` to a constant to prevent SCEV from spending too much 1518 // time here. It is correct (but more expensive) to continue with a 1519 // non-constant `Start` and do a general SCEV subtraction to compute 1520 // `PreStart` below. 1521 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1522 if (!StartC) 1523 return false; 1524 1525 APInt StartAI = StartC->getAPInt(); 1526 1527 for (unsigned Delta : {-2, -1, 1, 2}) { 1528 const SCEV *PreStart = getConstant(StartAI - Delta); 1529 1530 FoldingSetNodeID ID; 1531 ID.AddInteger(scAddRecExpr); 1532 ID.AddPointer(PreStart); 1533 ID.AddPointer(Step); 1534 ID.AddPointer(L); 1535 void *IP = nullptr; 1536 const auto *PreAR = 1537 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1538 1539 // Give up if we don't already have the add recurrence we need because 1540 // actually constructing an add recurrence is relatively expensive. 1541 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1542 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1543 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1544 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1545 DeltaS, &Pred, this); 1546 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1547 return true; 1548 } 1549 } 1550 1551 return false; 1552 } 1553 1554 // Finds an integer D for an expression (C + x + y + ...) such that the top 1555 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1556 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1557 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1558 // the (C + x + y + ...) expression is \p WholeAddExpr. 1559 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1560 const SCEVConstant *ConstantTerm, 1561 const SCEVAddExpr *WholeAddExpr) { 1562 const APInt C = ConstantTerm->getAPInt(); 1563 const unsigned BitWidth = C.getBitWidth(); 1564 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1565 uint32_t TZ = BitWidth; 1566 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1567 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1568 if (TZ) { 1569 // Set D to be as many least significant bits of C as possible while still 1570 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1571 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1572 } 1573 return APInt(BitWidth, 0); 1574 } 1575 1576 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1577 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1578 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1579 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1580 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1581 const APInt &ConstantStart, 1582 const SCEV *Step) { 1583 const unsigned BitWidth = ConstantStart.getBitWidth(); 1584 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1585 if (TZ) 1586 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1587 : ConstantStart; 1588 return APInt(BitWidth, 0); 1589 } 1590 1591 const SCEV * 1592 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1593 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1594 "This is not an extending conversion!"); 1595 assert(isSCEVable(Ty) && 1596 "This is not a conversion to a SCEVable type!"); 1597 Ty = getEffectiveSCEVType(Ty); 1598 1599 // Fold if the operand is constant. 1600 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1601 return getConstant( 1602 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1603 1604 // zext(zext(x)) --> zext(x) 1605 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1606 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1607 1608 // Before doing any expensive analysis, check to see if we've already 1609 // computed a SCEV for this Op and Ty. 1610 FoldingSetNodeID ID; 1611 ID.AddInteger(scZeroExtend); 1612 ID.AddPointer(Op); 1613 ID.AddPointer(Ty); 1614 void *IP = nullptr; 1615 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1616 if (Depth > MaxExtDepth) { 1617 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1618 Op, Ty); 1619 UniqueSCEVs.InsertNode(S, IP); 1620 addToLoopUseLists(S); 1621 return S; 1622 } 1623 1624 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1625 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1626 // It's possible the bits taken off by the truncate were all zero bits. If 1627 // so, we should be able to simplify this further. 1628 const SCEV *X = ST->getOperand(); 1629 ConstantRange CR = getUnsignedRange(X); 1630 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1631 unsigned NewBits = getTypeSizeInBits(Ty); 1632 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1633 CR.zextOrTrunc(NewBits))) 1634 return getTruncateOrZeroExtend(X, Ty); 1635 } 1636 1637 // If the input value is a chrec scev, and we can prove that the value 1638 // did not overflow the old, smaller, value, we can zero extend all of the 1639 // operands (often constants). This allows analysis of something like 1640 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1641 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1642 if (AR->isAffine()) { 1643 const SCEV *Start = AR->getStart(); 1644 const SCEV *Step = AR->getStepRecurrence(*this); 1645 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1646 const Loop *L = AR->getLoop(); 1647 1648 if (!AR->hasNoUnsignedWrap()) { 1649 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1650 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1651 } 1652 1653 // If we have special knowledge that this addrec won't overflow, 1654 // we don't need to do any further analysis. 1655 if (AR->hasNoUnsignedWrap()) 1656 return getAddRecExpr( 1657 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1658 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1659 1660 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1661 // Note that this serves two purposes: It filters out loops that are 1662 // simply not analyzable, and it covers the case where this code is 1663 // being called from within backedge-taken count analysis, such that 1664 // attempting to ask for the backedge-taken count would likely result 1665 // in infinite recursion. In the later case, the analysis code will 1666 // cope with a conservative value, and it will take care to purge 1667 // that value once it has finished. 1668 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1669 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1670 // Manually compute the final value for AR, checking for 1671 // overflow. 1672 1673 // Check whether the backedge-taken count can be losslessly casted to 1674 // the addrec's type. The count is always unsigned. 1675 const SCEV *CastedMaxBECount = 1676 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1677 const SCEV *RecastedMaxBECount = 1678 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1679 if (MaxBECount == RecastedMaxBECount) { 1680 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1681 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1682 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1683 SCEV::FlagAnyWrap, Depth + 1); 1684 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1685 SCEV::FlagAnyWrap, 1686 Depth + 1), 1687 WideTy, Depth + 1); 1688 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1689 const SCEV *WideMaxBECount = 1690 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1691 const SCEV *OperandExtendedAdd = 1692 getAddExpr(WideStart, 1693 getMulExpr(WideMaxBECount, 1694 getZeroExtendExpr(Step, WideTy, Depth + 1), 1695 SCEV::FlagAnyWrap, Depth + 1), 1696 SCEV::FlagAnyWrap, Depth + 1); 1697 if (ZAdd == OperandExtendedAdd) { 1698 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1700 // Return the expression with the addrec on the outside. 1701 return getAddRecExpr( 1702 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1703 Depth + 1), 1704 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1705 AR->getNoWrapFlags()); 1706 } 1707 // Similar to above, only this time treat the step value as signed. 1708 // This covers loops that count down. 1709 OperandExtendedAdd = 1710 getAddExpr(WideStart, 1711 getMulExpr(WideMaxBECount, 1712 getSignExtendExpr(Step, WideTy, Depth + 1), 1713 SCEV::FlagAnyWrap, Depth + 1), 1714 SCEV::FlagAnyWrap, Depth + 1); 1715 if (ZAdd == OperandExtendedAdd) { 1716 // Cache knowledge of AR NW, which is propagated to this AddRec. 1717 // Negative step causes unsigned wrap, but it still can't self-wrap. 1718 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1719 // Return the expression with the addrec on the outside. 1720 return getAddRecExpr( 1721 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1722 Depth + 1), 1723 getSignExtendExpr(Step, Ty, Depth + 1), L, 1724 AR->getNoWrapFlags()); 1725 } 1726 } 1727 } 1728 1729 // Normally, in the cases we can prove no-overflow via a 1730 // backedge guarding condition, we can also compute a backedge 1731 // taken count for the loop. The exceptions are assumptions and 1732 // guards present in the loop -- SCEV is not great at exploiting 1733 // these to compute max backedge taken counts, but can still use 1734 // these to prove lack of overflow. Use this fact to avoid 1735 // doing extra work that may not pay off. 1736 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1737 !AC.assumptions().empty()) { 1738 // If the backedge is guarded by a comparison with the pre-inc 1739 // value the addrec is safe. Also, if the entry is guarded by 1740 // a comparison with the start value and the backedge is 1741 // guarded by a comparison with the post-inc value, the addrec 1742 // is safe. 1743 if (isKnownPositive(Step)) { 1744 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1745 getUnsignedRangeMax(Step)); 1746 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1747 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1748 // Cache knowledge of AR NUW, which is propagated to this 1749 // AddRec. 1750 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1751 // Return the expression with the addrec on the outside. 1752 return getAddRecExpr( 1753 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1754 Depth + 1), 1755 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1756 AR->getNoWrapFlags()); 1757 } 1758 } else if (isKnownNegative(Step)) { 1759 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1760 getSignedRangeMin(Step)); 1761 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1762 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1763 // Cache knowledge of AR NW, which is propagated to this 1764 // AddRec. Negative step causes unsigned wrap, but it 1765 // still can't self-wrap. 1766 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1767 // Return the expression with the addrec on the outside. 1768 return getAddRecExpr( 1769 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1770 Depth + 1), 1771 getSignExtendExpr(Step, Ty, Depth + 1), L, 1772 AR->getNoWrapFlags()); 1773 } 1774 } 1775 } 1776 1777 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1778 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1779 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1780 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1781 const APInt &C = SC->getAPInt(); 1782 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1783 if (D != 0) { 1784 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1785 const SCEV *SResidual = 1786 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1787 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1788 return getAddExpr(SZExtD, SZExtR, 1789 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1790 Depth + 1); 1791 } 1792 } 1793 1794 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1795 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1796 return getAddRecExpr( 1797 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1798 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1799 } 1800 } 1801 1802 // zext(A % B) --> zext(A) % zext(B) 1803 { 1804 const SCEV *LHS; 1805 const SCEV *RHS; 1806 if (matchURem(Op, LHS, RHS)) 1807 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1808 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1809 } 1810 1811 // zext(A / B) --> zext(A) / zext(B). 1812 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1813 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1814 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1815 1816 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1817 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1818 if (SA->hasNoUnsignedWrap()) { 1819 // If the addition does not unsign overflow then we can, by definition, 1820 // commute the zero extension with the addition operation. 1821 SmallVector<const SCEV *, 4> Ops; 1822 for (const auto *Op : SA->operands()) 1823 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1824 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1825 } 1826 1827 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1828 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1829 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1830 // 1831 // Often address arithmetics contain expressions like 1832 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1833 // This transformation is useful while proving that such expressions are 1834 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1835 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1836 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1837 if (D != 0) { 1838 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1839 const SCEV *SResidual = 1840 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1841 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1842 return getAddExpr(SZExtD, SZExtR, 1843 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1844 Depth + 1); 1845 } 1846 } 1847 } 1848 1849 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1850 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1851 if (SM->hasNoUnsignedWrap()) { 1852 // If the multiply does not unsign overflow then we can, by definition, 1853 // commute the zero extension with the multiply operation. 1854 SmallVector<const SCEV *, 4> Ops; 1855 for (const auto *Op : SM->operands()) 1856 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1857 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1858 } 1859 1860 // zext(2^K * (trunc X to iN)) to iM -> 1861 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1862 // 1863 // Proof: 1864 // 1865 // zext(2^K * (trunc X to iN)) to iM 1866 // = zext((trunc X to iN) << K) to iM 1867 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1868 // (because shl removes the top K bits) 1869 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1870 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1871 // 1872 if (SM->getNumOperands() == 2) 1873 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1874 if (MulLHS->getAPInt().isPowerOf2()) 1875 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1876 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1877 MulLHS->getAPInt().logBase2(); 1878 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1879 return getMulExpr( 1880 getZeroExtendExpr(MulLHS, Ty), 1881 getZeroExtendExpr( 1882 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1883 SCEV::FlagNUW, Depth + 1); 1884 } 1885 } 1886 1887 // The cast wasn't folded; create an explicit cast node. 1888 // Recompute the insert position, as it may have been invalidated. 1889 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1890 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1891 Op, Ty); 1892 UniqueSCEVs.InsertNode(S, IP); 1893 addToLoopUseLists(S); 1894 return S; 1895 } 1896 1897 const SCEV * 1898 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1899 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1900 "This is not an extending conversion!"); 1901 assert(isSCEVable(Ty) && 1902 "This is not a conversion to a SCEVable type!"); 1903 Ty = getEffectiveSCEVType(Ty); 1904 1905 // Fold if the operand is constant. 1906 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1907 return getConstant( 1908 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1909 1910 // sext(sext(x)) --> sext(x) 1911 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1912 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1913 1914 // sext(zext(x)) --> zext(x) 1915 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1916 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1917 1918 // Before doing any expensive analysis, check to see if we've already 1919 // computed a SCEV for this Op and Ty. 1920 FoldingSetNodeID ID; 1921 ID.AddInteger(scSignExtend); 1922 ID.AddPointer(Op); 1923 ID.AddPointer(Ty); 1924 void *IP = nullptr; 1925 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1926 // Limit recursion depth. 1927 if (Depth > MaxExtDepth) { 1928 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1929 Op, Ty); 1930 UniqueSCEVs.InsertNode(S, IP); 1931 addToLoopUseLists(S); 1932 return S; 1933 } 1934 1935 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1936 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1937 // It's possible the bits taken off by the truncate were all sign bits. If 1938 // so, we should be able to simplify this further. 1939 const SCEV *X = ST->getOperand(); 1940 ConstantRange CR = getSignedRange(X); 1941 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1942 unsigned NewBits = getTypeSizeInBits(Ty); 1943 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1944 CR.sextOrTrunc(NewBits))) 1945 return getTruncateOrSignExtend(X, Ty); 1946 } 1947 1948 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1949 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1950 if (SA->hasNoSignedWrap()) { 1951 // If the addition does not sign overflow then we can, by definition, 1952 // commute the sign extension with the addition operation. 1953 SmallVector<const SCEV *, 4> Ops; 1954 for (const auto *Op : SA->operands()) 1955 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1956 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1957 } 1958 1959 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1960 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1961 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1962 // 1963 // For instance, this will bring two seemingly different expressions: 1964 // 1 + sext(5 + 20 * %x + 24 * %y) and 1965 // sext(6 + 20 * %x + 24 * %y) 1966 // to the same form: 1967 // 2 + sext(4 + 20 * %x + 24 * %y) 1968 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1969 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1970 if (D != 0) { 1971 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1972 const SCEV *SResidual = 1973 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1974 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1975 return getAddExpr(SSExtD, SSExtR, 1976 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1977 Depth + 1); 1978 } 1979 } 1980 } 1981 // If the input value is a chrec scev, and we can prove that the value 1982 // did not overflow the old, smaller, value, we can sign extend all of the 1983 // operands (often constants). This allows analysis of something like 1984 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1985 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1986 if (AR->isAffine()) { 1987 const SCEV *Start = AR->getStart(); 1988 const SCEV *Step = AR->getStepRecurrence(*this); 1989 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1990 const Loop *L = AR->getLoop(); 1991 1992 if (!AR->hasNoSignedWrap()) { 1993 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1994 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1995 } 1996 1997 // If we have special knowledge that this addrec won't overflow, 1998 // we don't need to do any further analysis. 1999 if (AR->hasNoSignedWrap()) 2000 return getAddRecExpr( 2001 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2002 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2003 2004 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2005 // Note that this serves two purposes: It filters out loops that are 2006 // simply not analyzable, and it covers the case where this code is 2007 // being called from within backedge-taken count analysis, such that 2008 // attempting to ask for the backedge-taken count would likely result 2009 // in infinite recursion. In the later case, the analysis code will 2010 // cope with a conservative value, and it will take care to purge 2011 // that value once it has finished. 2012 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 2013 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2014 // Manually compute the final value for AR, checking for 2015 // overflow. 2016 2017 // Check whether the backedge-taken count can be losslessly casted to 2018 // the addrec's type. The count is always unsigned. 2019 const SCEV *CastedMaxBECount = 2020 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 2021 const SCEV *RecastedMaxBECount = 2022 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 2023 if (MaxBECount == RecastedMaxBECount) { 2024 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2025 // Check whether Start+Step*MaxBECount has no signed overflow. 2026 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2027 SCEV::FlagAnyWrap, Depth + 1); 2028 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2029 SCEV::FlagAnyWrap, 2030 Depth + 1), 2031 WideTy, Depth + 1); 2032 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2033 const SCEV *WideMaxBECount = 2034 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2035 const SCEV *OperandExtendedAdd = 2036 getAddExpr(WideStart, 2037 getMulExpr(WideMaxBECount, 2038 getSignExtendExpr(Step, WideTy, Depth + 1), 2039 SCEV::FlagAnyWrap, Depth + 1), 2040 SCEV::FlagAnyWrap, Depth + 1); 2041 if (SAdd == OperandExtendedAdd) { 2042 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2043 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2044 // Return the expression with the addrec on the outside. 2045 return getAddRecExpr( 2046 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2047 Depth + 1), 2048 getSignExtendExpr(Step, Ty, Depth + 1), L, 2049 AR->getNoWrapFlags()); 2050 } 2051 // Similar to above, only this time treat the step value as unsigned. 2052 // This covers loops that count up with an unsigned step. 2053 OperandExtendedAdd = 2054 getAddExpr(WideStart, 2055 getMulExpr(WideMaxBECount, 2056 getZeroExtendExpr(Step, WideTy, Depth + 1), 2057 SCEV::FlagAnyWrap, Depth + 1), 2058 SCEV::FlagAnyWrap, Depth + 1); 2059 if (SAdd == OperandExtendedAdd) { 2060 // If AR wraps around then 2061 // 2062 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2063 // => SAdd != OperandExtendedAdd 2064 // 2065 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2066 // (SAdd == OperandExtendedAdd => AR is NW) 2067 2068 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2069 2070 // Return the expression with the addrec on the outside. 2071 return getAddRecExpr( 2072 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2073 Depth + 1), 2074 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2075 AR->getNoWrapFlags()); 2076 } 2077 } 2078 } 2079 2080 // Normally, in the cases we can prove no-overflow via a 2081 // backedge guarding condition, we can also compute a backedge 2082 // taken count for the loop. The exceptions are assumptions and 2083 // guards present in the loop -- SCEV is not great at exploiting 2084 // these to compute max backedge taken counts, but can still use 2085 // these to prove lack of overflow. Use this fact to avoid 2086 // doing extra work that may not pay off. 2087 2088 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2089 !AC.assumptions().empty()) { 2090 // If the backedge is guarded by a comparison with the pre-inc 2091 // value the addrec is safe. Also, if the entry is guarded by 2092 // a comparison with the start value and the backedge is 2093 // guarded by a comparison with the post-inc value, the addrec 2094 // is safe. 2095 ICmpInst::Predicate Pred; 2096 const SCEV *OverflowLimit = 2097 getSignedOverflowLimitForStep(Step, &Pred, this); 2098 if (OverflowLimit && 2099 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2100 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2101 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2102 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2103 return getAddRecExpr( 2104 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2105 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2106 } 2107 } 2108 2109 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2110 // if D + (C - D + Step * n) could be proven to not signed wrap 2111 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2112 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2113 const APInt &C = SC->getAPInt(); 2114 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2115 if (D != 0) { 2116 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2117 const SCEV *SResidual = 2118 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2119 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2120 return getAddExpr(SSExtD, SSExtR, 2121 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2122 Depth + 1); 2123 } 2124 } 2125 2126 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2127 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2128 return getAddRecExpr( 2129 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2130 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2131 } 2132 } 2133 2134 // If the input value is provably positive and we could not simplify 2135 // away the sext build a zext instead. 2136 if (isKnownNonNegative(Op)) 2137 return getZeroExtendExpr(Op, Ty, Depth + 1); 2138 2139 // The cast wasn't folded; create an explicit cast node. 2140 // Recompute the insert position, as it may have been invalidated. 2141 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2142 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2143 Op, Ty); 2144 UniqueSCEVs.InsertNode(S, IP); 2145 addToLoopUseLists(S); 2146 return S; 2147 } 2148 2149 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2150 /// unspecified bits out to the given type. 2151 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2152 Type *Ty) { 2153 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2154 "This is not an extending conversion!"); 2155 assert(isSCEVable(Ty) && 2156 "This is not a conversion to a SCEVable type!"); 2157 Ty = getEffectiveSCEVType(Ty); 2158 2159 // Sign-extend negative constants. 2160 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2161 if (SC->getAPInt().isNegative()) 2162 return getSignExtendExpr(Op, Ty); 2163 2164 // Peel off a truncate cast. 2165 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2166 const SCEV *NewOp = T->getOperand(); 2167 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2168 return getAnyExtendExpr(NewOp, Ty); 2169 return getTruncateOrNoop(NewOp, Ty); 2170 } 2171 2172 // Next try a zext cast. If the cast is folded, use it. 2173 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2174 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2175 return ZExt; 2176 2177 // Next try a sext cast. If the cast is folded, use it. 2178 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2179 if (!isa<SCEVSignExtendExpr>(SExt)) 2180 return SExt; 2181 2182 // Force the cast to be folded into the operands of an addrec. 2183 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2184 SmallVector<const SCEV *, 4> Ops; 2185 for (const SCEV *Op : AR->operands()) 2186 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2187 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2188 } 2189 2190 // If the expression is obviously signed, use the sext cast value. 2191 if (isa<SCEVSMaxExpr>(Op)) 2192 return SExt; 2193 2194 // Absent any other information, use the zext cast value. 2195 return ZExt; 2196 } 2197 2198 /// Process the given Ops list, which is a list of operands to be added under 2199 /// the given scale, update the given map. This is a helper function for 2200 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2201 /// that would form an add expression like this: 2202 /// 2203 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2204 /// 2205 /// where A and B are constants, update the map with these values: 2206 /// 2207 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2208 /// 2209 /// and add 13 + A*B*29 to AccumulatedConstant. 2210 /// This will allow getAddRecExpr to produce this: 2211 /// 2212 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2213 /// 2214 /// This form often exposes folding opportunities that are hidden in 2215 /// the original operand list. 2216 /// 2217 /// Return true iff it appears that any interesting folding opportunities 2218 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2219 /// the common case where no interesting opportunities are present, and 2220 /// is also used as a check to avoid infinite recursion. 2221 static bool 2222 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2223 SmallVectorImpl<const SCEV *> &NewOps, 2224 APInt &AccumulatedConstant, 2225 const SCEV *const *Ops, size_t NumOperands, 2226 const APInt &Scale, 2227 ScalarEvolution &SE) { 2228 bool Interesting = false; 2229 2230 // Iterate over the add operands. They are sorted, with constants first. 2231 unsigned i = 0; 2232 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2233 ++i; 2234 // Pull a buried constant out to the outside. 2235 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2236 Interesting = true; 2237 AccumulatedConstant += Scale * C->getAPInt(); 2238 } 2239 2240 // Next comes everything else. We're especially interested in multiplies 2241 // here, but they're in the middle, so just visit the rest with one loop. 2242 for (; i != NumOperands; ++i) { 2243 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2244 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2245 APInt NewScale = 2246 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2247 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2248 // A multiplication of a constant with another add; recurse. 2249 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2250 Interesting |= 2251 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2252 Add->op_begin(), Add->getNumOperands(), 2253 NewScale, SE); 2254 } else { 2255 // A multiplication of a constant with some other value. Update 2256 // the map. 2257 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2258 const SCEV *Key = SE.getMulExpr(MulOps); 2259 auto Pair = M.insert({Key, NewScale}); 2260 if (Pair.second) { 2261 NewOps.push_back(Pair.first->first); 2262 } else { 2263 Pair.first->second += NewScale; 2264 // The map already had an entry for this value, which may indicate 2265 // a folding opportunity. 2266 Interesting = true; 2267 } 2268 } 2269 } else { 2270 // An ordinary operand. Update the map. 2271 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2272 M.insert({Ops[i], Scale}); 2273 if (Pair.second) { 2274 NewOps.push_back(Pair.first->first); 2275 } else { 2276 Pair.first->second += Scale; 2277 // The map already had an entry for this value, which may indicate 2278 // a folding opportunity. 2279 Interesting = true; 2280 } 2281 } 2282 } 2283 2284 return Interesting; 2285 } 2286 2287 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2288 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2289 // can't-overflow flags for the operation if possible. 2290 static SCEV::NoWrapFlags 2291 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2292 const SmallVectorImpl<const SCEV *> &Ops, 2293 SCEV::NoWrapFlags Flags) { 2294 using namespace std::placeholders; 2295 2296 using OBO = OverflowingBinaryOperator; 2297 2298 bool CanAnalyze = 2299 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2300 (void)CanAnalyze; 2301 assert(CanAnalyze && "don't call from other places!"); 2302 2303 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2304 SCEV::NoWrapFlags SignOrUnsignWrap = 2305 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2306 2307 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2308 auto IsKnownNonNegative = [&](const SCEV *S) { 2309 return SE->isKnownNonNegative(S); 2310 }; 2311 2312 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2313 Flags = 2314 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2315 2316 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2317 2318 if (SignOrUnsignWrap != SignOrUnsignMask && 2319 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2320 isa<SCEVConstant>(Ops[0])) { 2321 2322 auto Opcode = [&] { 2323 switch (Type) { 2324 case scAddExpr: 2325 return Instruction::Add; 2326 case scMulExpr: 2327 return Instruction::Mul; 2328 default: 2329 llvm_unreachable("Unexpected SCEV op."); 2330 } 2331 }(); 2332 2333 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2334 2335 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2336 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2337 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2338 Opcode, C, OBO::NoSignedWrap); 2339 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2340 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2341 } 2342 2343 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2344 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2345 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2346 Opcode, C, OBO::NoUnsignedWrap); 2347 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2348 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2349 } 2350 } 2351 2352 return Flags; 2353 } 2354 2355 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2356 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2357 } 2358 2359 /// Get a canonical add expression, or something simpler if possible. 2360 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2361 SCEV::NoWrapFlags Flags, 2362 unsigned Depth) { 2363 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2364 "only nuw or nsw allowed"); 2365 assert(!Ops.empty() && "Cannot get empty add!"); 2366 if (Ops.size() == 1) return Ops[0]; 2367 #ifndef NDEBUG 2368 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2369 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2370 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2371 "SCEVAddExpr operand types don't match!"); 2372 #endif 2373 2374 // Sort by complexity, this groups all similar expression types together. 2375 GroupByComplexity(Ops, &LI, DT); 2376 2377 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2378 2379 // If there are any constants, fold them together. 2380 unsigned Idx = 0; 2381 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2382 ++Idx; 2383 assert(Idx < Ops.size()); 2384 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2385 // We found two constants, fold them together! 2386 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2387 if (Ops.size() == 2) return Ops[0]; 2388 Ops.erase(Ops.begin()+1); // Erase the folded element 2389 LHSC = cast<SCEVConstant>(Ops[0]); 2390 } 2391 2392 // If we are left with a constant zero being added, strip it off. 2393 if (LHSC->getValue()->isZero()) { 2394 Ops.erase(Ops.begin()); 2395 --Idx; 2396 } 2397 2398 if (Ops.size() == 1) return Ops[0]; 2399 } 2400 2401 // Limit recursion calls depth. 2402 if (Depth > MaxArithDepth) 2403 return getOrCreateAddExpr(Ops, Flags); 2404 2405 // Okay, check to see if the same value occurs in the operand list more than 2406 // once. If so, merge them together into an multiply expression. Since we 2407 // sorted the list, these values are required to be adjacent. 2408 Type *Ty = Ops[0]->getType(); 2409 bool FoundMatch = false; 2410 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2411 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2412 // Scan ahead to count how many equal operands there are. 2413 unsigned Count = 2; 2414 while (i+Count != e && Ops[i+Count] == Ops[i]) 2415 ++Count; 2416 // Merge the values into a multiply. 2417 const SCEV *Scale = getConstant(Ty, Count); 2418 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2419 if (Ops.size() == Count) 2420 return Mul; 2421 Ops[i] = Mul; 2422 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2423 --i; e -= Count - 1; 2424 FoundMatch = true; 2425 } 2426 if (FoundMatch) 2427 return getAddExpr(Ops, Flags, Depth + 1); 2428 2429 // Check for truncates. If all the operands are truncated from the same 2430 // type, see if factoring out the truncate would permit the result to be 2431 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2432 // if the contents of the resulting outer trunc fold to something simple. 2433 auto FindTruncSrcType = [&]() -> Type * { 2434 // We're ultimately looking to fold an addrec of truncs and muls of only 2435 // constants and truncs, so if we find any other types of SCEV 2436 // as operands of the addrec then we bail and return nullptr here. 2437 // Otherwise, we return the type of the operand of a trunc that we find. 2438 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2439 return T->getOperand()->getType(); 2440 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2441 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2442 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2443 return T->getOperand()->getType(); 2444 } 2445 return nullptr; 2446 }; 2447 if (auto *SrcType = FindTruncSrcType()) { 2448 SmallVector<const SCEV *, 8> LargeOps; 2449 bool Ok = true; 2450 // Check all the operands to see if they can be represented in the 2451 // source type of the truncate. 2452 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2453 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2454 if (T->getOperand()->getType() != SrcType) { 2455 Ok = false; 2456 break; 2457 } 2458 LargeOps.push_back(T->getOperand()); 2459 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2460 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2461 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2462 SmallVector<const SCEV *, 8> LargeMulOps; 2463 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2464 if (const SCEVTruncateExpr *T = 2465 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2466 if (T->getOperand()->getType() != SrcType) { 2467 Ok = false; 2468 break; 2469 } 2470 LargeMulOps.push_back(T->getOperand()); 2471 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2472 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2473 } else { 2474 Ok = false; 2475 break; 2476 } 2477 } 2478 if (Ok) 2479 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2480 } else { 2481 Ok = false; 2482 break; 2483 } 2484 } 2485 if (Ok) { 2486 // Evaluate the expression in the larger type. 2487 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2488 // If it folds to something simple, use it. Otherwise, don't. 2489 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2490 return getTruncateExpr(Fold, Ty); 2491 } 2492 } 2493 2494 // Skip past any other cast SCEVs. 2495 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2496 ++Idx; 2497 2498 // If there are add operands they would be next. 2499 if (Idx < Ops.size()) { 2500 bool DeletedAdd = false; 2501 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2502 if (Ops.size() > AddOpsInlineThreshold || 2503 Add->getNumOperands() > AddOpsInlineThreshold) 2504 break; 2505 // If we have an add, expand the add operands onto the end of the operands 2506 // list. 2507 Ops.erase(Ops.begin()+Idx); 2508 Ops.append(Add->op_begin(), Add->op_end()); 2509 DeletedAdd = true; 2510 } 2511 2512 // If we deleted at least one add, we added operands to the end of the list, 2513 // and they are not necessarily sorted. Recurse to resort and resimplify 2514 // any operands we just acquired. 2515 if (DeletedAdd) 2516 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2517 } 2518 2519 // Skip over the add expression until we get to a multiply. 2520 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2521 ++Idx; 2522 2523 // Check to see if there are any folding opportunities present with 2524 // operands multiplied by constant values. 2525 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2526 uint64_t BitWidth = getTypeSizeInBits(Ty); 2527 DenseMap<const SCEV *, APInt> M; 2528 SmallVector<const SCEV *, 8> NewOps; 2529 APInt AccumulatedConstant(BitWidth, 0); 2530 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2531 Ops.data(), Ops.size(), 2532 APInt(BitWidth, 1), *this)) { 2533 struct APIntCompare { 2534 bool operator()(const APInt &LHS, const APInt &RHS) const { 2535 return LHS.ult(RHS); 2536 } 2537 }; 2538 2539 // Some interesting folding opportunity is present, so its worthwhile to 2540 // re-generate the operands list. Group the operands by constant scale, 2541 // to avoid multiplying by the same constant scale multiple times. 2542 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2543 for (const SCEV *NewOp : NewOps) 2544 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2545 // Re-generate the operands list. 2546 Ops.clear(); 2547 if (AccumulatedConstant != 0) 2548 Ops.push_back(getConstant(AccumulatedConstant)); 2549 for (auto &MulOp : MulOpLists) 2550 if (MulOp.first != 0) 2551 Ops.push_back(getMulExpr( 2552 getConstant(MulOp.first), 2553 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2554 SCEV::FlagAnyWrap, Depth + 1)); 2555 if (Ops.empty()) 2556 return getZero(Ty); 2557 if (Ops.size() == 1) 2558 return Ops[0]; 2559 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2560 } 2561 } 2562 2563 // If we are adding something to a multiply expression, make sure the 2564 // something is not already an operand of the multiply. If so, merge it into 2565 // the multiply. 2566 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2567 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2568 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2569 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2570 if (isa<SCEVConstant>(MulOpSCEV)) 2571 continue; 2572 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2573 if (MulOpSCEV == Ops[AddOp]) { 2574 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2575 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2576 if (Mul->getNumOperands() != 2) { 2577 // If the multiply has more than two operands, we must get the 2578 // Y*Z term. 2579 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2580 Mul->op_begin()+MulOp); 2581 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2582 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2583 } 2584 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2585 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2586 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2587 SCEV::FlagAnyWrap, Depth + 1); 2588 if (Ops.size() == 2) return OuterMul; 2589 if (AddOp < Idx) { 2590 Ops.erase(Ops.begin()+AddOp); 2591 Ops.erase(Ops.begin()+Idx-1); 2592 } else { 2593 Ops.erase(Ops.begin()+Idx); 2594 Ops.erase(Ops.begin()+AddOp-1); 2595 } 2596 Ops.push_back(OuterMul); 2597 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2598 } 2599 2600 // Check this multiply against other multiplies being added together. 2601 for (unsigned OtherMulIdx = Idx+1; 2602 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2603 ++OtherMulIdx) { 2604 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2605 // If MulOp occurs in OtherMul, we can fold the two multiplies 2606 // together. 2607 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2608 OMulOp != e; ++OMulOp) 2609 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2610 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2611 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2612 if (Mul->getNumOperands() != 2) { 2613 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2614 Mul->op_begin()+MulOp); 2615 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2616 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2617 } 2618 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2619 if (OtherMul->getNumOperands() != 2) { 2620 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2621 OtherMul->op_begin()+OMulOp); 2622 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2623 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2624 } 2625 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2626 const SCEV *InnerMulSum = 2627 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2628 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2629 SCEV::FlagAnyWrap, Depth + 1); 2630 if (Ops.size() == 2) return OuterMul; 2631 Ops.erase(Ops.begin()+Idx); 2632 Ops.erase(Ops.begin()+OtherMulIdx-1); 2633 Ops.push_back(OuterMul); 2634 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2635 } 2636 } 2637 } 2638 } 2639 2640 // If there are any add recurrences in the operands list, see if any other 2641 // added values are loop invariant. If so, we can fold them into the 2642 // recurrence. 2643 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2644 ++Idx; 2645 2646 // Scan over all recurrences, trying to fold loop invariants into them. 2647 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2648 // Scan all of the other operands to this add and add them to the vector if 2649 // they are loop invariant w.r.t. the recurrence. 2650 SmallVector<const SCEV *, 8> LIOps; 2651 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2652 const Loop *AddRecLoop = AddRec->getLoop(); 2653 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2654 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2655 LIOps.push_back(Ops[i]); 2656 Ops.erase(Ops.begin()+i); 2657 --i; --e; 2658 } 2659 2660 // If we found some loop invariants, fold them into the recurrence. 2661 if (!LIOps.empty()) { 2662 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2663 LIOps.push_back(AddRec->getStart()); 2664 2665 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2666 AddRec->op_end()); 2667 // This follows from the fact that the no-wrap flags on the outer add 2668 // expression are applicable on the 0th iteration, when the add recurrence 2669 // will be equal to its start value. 2670 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2671 2672 // Build the new addrec. Propagate the NUW and NSW flags if both the 2673 // outer add and the inner addrec are guaranteed to have no overflow. 2674 // Always propagate NW. 2675 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2676 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2677 2678 // If all of the other operands were loop invariant, we are done. 2679 if (Ops.size() == 1) return NewRec; 2680 2681 // Otherwise, add the folded AddRec by the non-invariant parts. 2682 for (unsigned i = 0;; ++i) 2683 if (Ops[i] == AddRec) { 2684 Ops[i] = NewRec; 2685 break; 2686 } 2687 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2688 } 2689 2690 // Okay, if there weren't any loop invariants to be folded, check to see if 2691 // there are multiple AddRec's with the same loop induction variable being 2692 // added together. If so, we can fold them. 2693 for (unsigned OtherIdx = Idx+1; 2694 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2695 ++OtherIdx) { 2696 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2697 // so that the 1st found AddRecExpr is dominated by all others. 2698 assert(DT.dominates( 2699 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2700 AddRec->getLoop()->getHeader()) && 2701 "AddRecExprs are not sorted in reverse dominance order?"); 2702 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2703 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2704 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2705 AddRec->op_end()); 2706 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2707 ++OtherIdx) { 2708 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2709 if (OtherAddRec->getLoop() == AddRecLoop) { 2710 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2711 i != e; ++i) { 2712 if (i >= AddRecOps.size()) { 2713 AddRecOps.append(OtherAddRec->op_begin()+i, 2714 OtherAddRec->op_end()); 2715 break; 2716 } 2717 SmallVector<const SCEV *, 2> TwoOps = { 2718 AddRecOps[i], OtherAddRec->getOperand(i)}; 2719 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2720 } 2721 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2722 } 2723 } 2724 // Step size has changed, so we cannot guarantee no self-wraparound. 2725 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2726 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2727 } 2728 } 2729 2730 // Otherwise couldn't fold anything into this recurrence. Move onto the 2731 // next one. 2732 } 2733 2734 // Okay, it looks like we really DO need an add expr. Check to see if we 2735 // already have one, otherwise create a new one. 2736 return getOrCreateAddExpr(Ops, Flags); 2737 } 2738 2739 const SCEV * 2740 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2741 SCEV::NoWrapFlags Flags) { 2742 FoldingSetNodeID ID; 2743 ID.AddInteger(scAddExpr); 2744 for (const SCEV *Op : Ops) 2745 ID.AddPointer(Op); 2746 void *IP = nullptr; 2747 SCEVAddExpr *S = 2748 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2749 if (!S) { 2750 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2751 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2752 S = new (SCEVAllocator) 2753 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2754 UniqueSCEVs.InsertNode(S, IP); 2755 addToLoopUseLists(S); 2756 } 2757 S->setNoWrapFlags(Flags); 2758 return S; 2759 } 2760 2761 const SCEV * 2762 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2763 SCEV::NoWrapFlags Flags) { 2764 FoldingSetNodeID ID; 2765 ID.AddInteger(scMulExpr); 2766 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2767 ID.AddPointer(Ops[i]); 2768 void *IP = nullptr; 2769 SCEVMulExpr *S = 2770 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2771 if (!S) { 2772 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2773 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2774 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2775 O, Ops.size()); 2776 UniqueSCEVs.InsertNode(S, IP); 2777 addToLoopUseLists(S); 2778 } 2779 S->setNoWrapFlags(Flags); 2780 return S; 2781 } 2782 2783 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2784 uint64_t k = i*j; 2785 if (j > 1 && k / j != i) Overflow = true; 2786 return k; 2787 } 2788 2789 /// Compute the result of "n choose k", the binomial coefficient. If an 2790 /// intermediate computation overflows, Overflow will be set and the return will 2791 /// be garbage. Overflow is not cleared on absence of overflow. 2792 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2793 // We use the multiplicative formula: 2794 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2795 // At each iteration, we take the n-th term of the numeral and divide by the 2796 // (k-n)th term of the denominator. This division will always produce an 2797 // integral result, and helps reduce the chance of overflow in the 2798 // intermediate computations. However, we can still overflow even when the 2799 // final result would fit. 2800 2801 if (n == 0 || n == k) return 1; 2802 if (k > n) return 0; 2803 2804 if (k > n/2) 2805 k = n-k; 2806 2807 uint64_t r = 1; 2808 for (uint64_t i = 1; i <= k; ++i) { 2809 r = umul_ov(r, n-(i-1), Overflow); 2810 r /= i; 2811 } 2812 return r; 2813 } 2814 2815 /// Determine if any of the operands in this SCEV are a constant or if 2816 /// any of the add or multiply expressions in this SCEV contain a constant. 2817 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2818 struct FindConstantInAddMulChain { 2819 bool FoundConstant = false; 2820 2821 bool follow(const SCEV *S) { 2822 FoundConstant |= isa<SCEVConstant>(S); 2823 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2824 } 2825 2826 bool isDone() const { 2827 return FoundConstant; 2828 } 2829 }; 2830 2831 FindConstantInAddMulChain F; 2832 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2833 ST.visitAll(StartExpr); 2834 return F.FoundConstant; 2835 } 2836 2837 /// Get a canonical multiply expression, or something simpler if possible. 2838 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2839 SCEV::NoWrapFlags Flags, 2840 unsigned Depth) { 2841 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2842 "only nuw or nsw allowed"); 2843 assert(!Ops.empty() && "Cannot get empty mul!"); 2844 if (Ops.size() == 1) return Ops[0]; 2845 #ifndef NDEBUG 2846 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2847 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2848 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2849 "SCEVMulExpr operand types don't match!"); 2850 #endif 2851 2852 // Sort by complexity, this groups all similar expression types together. 2853 GroupByComplexity(Ops, &LI, DT); 2854 2855 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2856 2857 // Limit recursion calls depth. 2858 if (Depth > MaxArithDepth) 2859 return getOrCreateMulExpr(Ops, Flags); 2860 2861 // If there are any constants, fold them together. 2862 unsigned Idx = 0; 2863 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2864 2865 if (Ops.size() == 2) 2866 // C1*(C2+V) -> C1*C2 + C1*V 2867 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2868 // If any of Add's ops are Adds or Muls with a constant, apply this 2869 // transformation as well. 2870 // 2871 // TODO: There are some cases where this transformation is not 2872 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2873 // this transformation should be narrowed down. 2874 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2875 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2876 SCEV::FlagAnyWrap, Depth + 1), 2877 getMulExpr(LHSC, Add->getOperand(1), 2878 SCEV::FlagAnyWrap, Depth + 1), 2879 SCEV::FlagAnyWrap, Depth + 1); 2880 2881 ++Idx; 2882 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2883 // We found two constants, fold them together! 2884 ConstantInt *Fold = 2885 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2886 Ops[0] = getConstant(Fold); 2887 Ops.erase(Ops.begin()+1); // Erase the folded element 2888 if (Ops.size() == 1) return Ops[0]; 2889 LHSC = cast<SCEVConstant>(Ops[0]); 2890 } 2891 2892 // If we are left with a constant one being multiplied, strip it off. 2893 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2894 Ops.erase(Ops.begin()); 2895 --Idx; 2896 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2897 // If we have a multiply of zero, it will always be zero. 2898 return Ops[0]; 2899 } else if (Ops[0]->isAllOnesValue()) { 2900 // If we have a mul by -1 of an add, try distributing the -1 among the 2901 // add operands. 2902 if (Ops.size() == 2) { 2903 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2904 SmallVector<const SCEV *, 4> NewOps; 2905 bool AnyFolded = false; 2906 for (const SCEV *AddOp : Add->operands()) { 2907 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2908 Depth + 1); 2909 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2910 NewOps.push_back(Mul); 2911 } 2912 if (AnyFolded) 2913 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2914 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2915 // Negation preserves a recurrence's no self-wrap property. 2916 SmallVector<const SCEV *, 4> Operands; 2917 for (const SCEV *AddRecOp : AddRec->operands()) 2918 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2919 Depth + 1)); 2920 2921 return getAddRecExpr(Operands, AddRec->getLoop(), 2922 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2923 } 2924 } 2925 } 2926 2927 if (Ops.size() == 1) 2928 return Ops[0]; 2929 } 2930 2931 // Skip over the add expression until we get to a multiply. 2932 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2933 ++Idx; 2934 2935 // If there are mul operands inline them all into this expression. 2936 if (Idx < Ops.size()) { 2937 bool DeletedMul = false; 2938 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2939 if (Ops.size() > MulOpsInlineThreshold) 2940 break; 2941 // If we have an mul, expand the mul operands onto the end of the 2942 // operands list. 2943 Ops.erase(Ops.begin()+Idx); 2944 Ops.append(Mul->op_begin(), Mul->op_end()); 2945 DeletedMul = true; 2946 } 2947 2948 // If we deleted at least one mul, we added operands to the end of the 2949 // list, and they are not necessarily sorted. Recurse to resort and 2950 // resimplify any operands we just acquired. 2951 if (DeletedMul) 2952 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2953 } 2954 2955 // If there are any add recurrences in the operands list, see if any other 2956 // added values are loop invariant. If so, we can fold them into the 2957 // recurrence. 2958 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2959 ++Idx; 2960 2961 // Scan over all recurrences, trying to fold loop invariants into them. 2962 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2963 // Scan all of the other operands to this mul and add them to the vector 2964 // if they are loop invariant w.r.t. the recurrence. 2965 SmallVector<const SCEV *, 8> LIOps; 2966 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2967 const Loop *AddRecLoop = AddRec->getLoop(); 2968 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2969 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2970 LIOps.push_back(Ops[i]); 2971 Ops.erase(Ops.begin()+i); 2972 --i; --e; 2973 } 2974 2975 // If we found some loop invariants, fold them into the recurrence. 2976 if (!LIOps.empty()) { 2977 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2978 SmallVector<const SCEV *, 4> NewOps; 2979 NewOps.reserve(AddRec->getNumOperands()); 2980 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2981 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2982 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2983 SCEV::FlagAnyWrap, Depth + 1)); 2984 2985 // Build the new addrec. Propagate the NUW and NSW flags if both the 2986 // outer mul and the inner addrec are guaranteed to have no overflow. 2987 // 2988 // No self-wrap cannot be guaranteed after changing the step size, but 2989 // will be inferred if either NUW or NSW is true. 2990 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2991 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2992 2993 // If all of the other operands were loop invariant, we are done. 2994 if (Ops.size() == 1) return NewRec; 2995 2996 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2997 for (unsigned i = 0;; ++i) 2998 if (Ops[i] == AddRec) { 2999 Ops[i] = NewRec; 3000 break; 3001 } 3002 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3003 } 3004 3005 // Okay, if there weren't any loop invariants to be folded, check to see 3006 // if there are multiple AddRec's with the same loop induction variable 3007 // being multiplied together. If so, we can fold them. 3008 3009 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3010 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3011 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3012 // ]]],+,...up to x=2n}. 3013 // Note that the arguments to choose() are always integers with values 3014 // known at compile time, never SCEV objects. 3015 // 3016 // The implementation avoids pointless extra computations when the two 3017 // addrec's are of different length (mathematically, it's equivalent to 3018 // an infinite stream of zeros on the right). 3019 bool OpsModified = false; 3020 for (unsigned OtherIdx = Idx+1; 3021 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3022 ++OtherIdx) { 3023 const SCEVAddRecExpr *OtherAddRec = 3024 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3025 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3026 continue; 3027 3028 // Limit max number of arguments to avoid creation of unreasonably big 3029 // SCEVAddRecs with very complex operands. 3030 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3031 MaxAddRecSize) 3032 continue; 3033 3034 bool Overflow = false; 3035 Type *Ty = AddRec->getType(); 3036 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3037 SmallVector<const SCEV*, 7> AddRecOps; 3038 for (int x = 0, xe = AddRec->getNumOperands() + 3039 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3040 const SCEV *Term = getZero(Ty); 3041 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3042 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3043 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3044 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3045 z < ze && !Overflow; ++z) { 3046 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3047 uint64_t Coeff; 3048 if (LargerThan64Bits) 3049 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3050 else 3051 Coeff = Coeff1*Coeff2; 3052 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3053 const SCEV *Term1 = AddRec->getOperand(y-z); 3054 const SCEV *Term2 = OtherAddRec->getOperand(z); 3055 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 3056 SCEV::FlagAnyWrap, Depth + 1), 3057 SCEV::FlagAnyWrap, Depth + 1); 3058 } 3059 } 3060 AddRecOps.push_back(Term); 3061 } 3062 if (!Overflow) { 3063 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 3064 SCEV::FlagAnyWrap); 3065 if (Ops.size() == 2) return NewAddRec; 3066 Ops[Idx] = NewAddRec; 3067 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3068 OpsModified = true; 3069 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3070 if (!AddRec) 3071 break; 3072 } 3073 } 3074 if (OpsModified) 3075 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3076 3077 // Otherwise couldn't fold anything into this recurrence. Move onto the 3078 // next one. 3079 } 3080 3081 // Okay, it looks like we really DO need an mul expr. Check to see if we 3082 // already have one, otherwise create a new one. 3083 return getOrCreateMulExpr(Ops, Flags); 3084 } 3085 3086 /// Represents an unsigned remainder expression based on unsigned division. 3087 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3088 const SCEV *RHS) { 3089 assert(getEffectiveSCEVType(LHS->getType()) == 3090 getEffectiveSCEVType(RHS->getType()) && 3091 "SCEVURemExpr operand types don't match!"); 3092 3093 // Short-circuit easy cases 3094 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3095 // If constant is one, the result is trivial 3096 if (RHSC->getValue()->isOne()) 3097 return getZero(LHS->getType()); // X urem 1 --> 0 3098 3099 // If constant is a power of two, fold into a zext(trunc(LHS)). 3100 if (RHSC->getAPInt().isPowerOf2()) { 3101 Type *FullTy = LHS->getType(); 3102 Type *TruncTy = 3103 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3104 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3105 } 3106 } 3107 3108 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3109 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3110 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3111 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3112 } 3113 3114 /// Get a canonical unsigned division expression, or something simpler if 3115 /// possible. 3116 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3117 const SCEV *RHS) { 3118 assert(getEffectiveSCEVType(LHS->getType()) == 3119 getEffectiveSCEVType(RHS->getType()) && 3120 "SCEVUDivExpr operand types don't match!"); 3121 3122 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3123 if (RHSC->getValue()->isOne()) 3124 return LHS; // X udiv 1 --> x 3125 // If the denominator is zero, the result of the udiv is undefined. Don't 3126 // try to analyze it, because the resolution chosen here may differ from 3127 // the resolution chosen in other parts of the compiler. 3128 if (!RHSC->getValue()->isZero()) { 3129 // Determine if the division can be folded into the operands of 3130 // its operands. 3131 // TODO: Generalize this to non-constants by using known-bits information. 3132 Type *Ty = LHS->getType(); 3133 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3134 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3135 // For non-power-of-two values, effectively round the value up to the 3136 // nearest power of two. 3137 if (!RHSC->getAPInt().isPowerOf2()) 3138 ++MaxShiftAmt; 3139 IntegerType *ExtTy = 3140 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3141 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3142 if (const SCEVConstant *Step = 3143 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3144 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3145 const APInt &StepInt = Step->getAPInt(); 3146 const APInt &DivInt = RHSC->getAPInt(); 3147 if (!StepInt.urem(DivInt) && 3148 getZeroExtendExpr(AR, ExtTy) == 3149 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3150 getZeroExtendExpr(Step, ExtTy), 3151 AR->getLoop(), SCEV::FlagAnyWrap)) { 3152 SmallVector<const SCEV *, 4> Operands; 3153 for (const SCEV *Op : AR->operands()) 3154 Operands.push_back(getUDivExpr(Op, RHS)); 3155 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3156 } 3157 /// Get a canonical UDivExpr for a recurrence. 3158 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3159 // We can currently only fold X%N if X is constant. 3160 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3161 if (StartC && !DivInt.urem(StepInt) && 3162 getZeroExtendExpr(AR, ExtTy) == 3163 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3164 getZeroExtendExpr(Step, ExtTy), 3165 AR->getLoop(), SCEV::FlagAnyWrap)) { 3166 const APInt &StartInt = StartC->getAPInt(); 3167 const APInt &StartRem = StartInt.urem(StepInt); 3168 if (StartRem != 0) 3169 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3170 AR->getLoop(), SCEV::FlagNW); 3171 } 3172 } 3173 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3174 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3175 SmallVector<const SCEV *, 4> Operands; 3176 for (const SCEV *Op : M->operands()) 3177 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3178 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3179 // Find an operand that's safely divisible. 3180 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3181 const SCEV *Op = M->getOperand(i); 3182 const SCEV *Div = getUDivExpr(Op, RHSC); 3183 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3184 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3185 M->op_end()); 3186 Operands[i] = Div; 3187 return getMulExpr(Operands); 3188 } 3189 } 3190 } 3191 3192 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3193 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3194 if (auto *DivisorConstant = 3195 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3196 bool Overflow = false; 3197 APInt NewRHS = 3198 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3199 if (Overflow) { 3200 return getConstant(RHSC->getType(), 0, false); 3201 } 3202 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3203 } 3204 } 3205 3206 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3207 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3208 SmallVector<const SCEV *, 4> Operands; 3209 for (const SCEV *Op : A->operands()) 3210 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3211 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3212 Operands.clear(); 3213 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3214 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3215 if (isa<SCEVUDivExpr>(Op) || 3216 getMulExpr(Op, RHS) != A->getOperand(i)) 3217 break; 3218 Operands.push_back(Op); 3219 } 3220 if (Operands.size() == A->getNumOperands()) 3221 return getAddExpr(Operands); 3222 } 3223 } 3224 3225 // Fold if both operands are constant. 3226 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3227 Constant *LHSCV = LHSC->getValue(); 3228 Constant *RHSCV = RHSC->getValue(); 3229 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3230 RHSCV))); 3231 } 3232 } 3233 } 3234 3235 FoldingSetNodeID ID; 3236 ID.AddInteger(scUDivExpr); 3237 ID.AddPointer(LHS); 3238 ID.AddPointer(RHS); 3239 void *IP = nullptr; 3240 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3241 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3242 LHS, RHS); 3243 UniqueSCEVs.InsertNode(S, IP); 3244 addToLoopUseLists(S); 3245 return S; 3246 } 3247 3248 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3249 APInt A = C1->getAPInt().abs(); 3250 APInt B = C2->getAPInt().abs(); 3251 uint32_t ABW = A.getBitWidth(); 3252 uint32_t BBW = B.getBitWidth(); 3253 3254 if (ABW > BBW) 3255 B = B.zext(ABW); 3256 else if (ABW < BBW) 3257 A = A.zext(BBW); 3258 3259 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3260 } 3261 3262 /// Get a canonical unsigned division expression, or something simpler if 3263 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3264 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3265 /// it's not exact because the udiv may be clearing bits. 3266 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3267 const SCEV *RHS) { 3268 // TODO: we could try to find factors in all sorts of things, but for now we 3269 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3270 // end of this file for inspiration. 3271 3272 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3273 if (!Mul || !Mul->hasNoUnsignedWrap()) 3274 return getUDivExpr(LHS, RHS); 3275 3276 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3277 // If the mulexpr multiplies by a constant, then that constant must be the 3278 // first element of the mulexpr. 3279 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3280 if (LHSCst == RHSCst) { 3281 SmallVector<const SCEV *, 2> Operands; 3282 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3283 return getMulExpr(Operands); 3284 } 3285 3286 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3287 // that there's a factor provided by one of the other terms. We need to 3288 // check. 3289 APInt Factor = gcd(LHSCst, RHSCst); 3290 if (!Factor.isIntN(1)) { 3291 LHSCst = 3292 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3293 RHSCst = 3294 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3295 SmallVector<const SCEV *, 2> Operands; 3296 Operands.push_back(LHSCst); 3297 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3298 LHS = getMulExpr(Operands); 3299 RHS = RHSCst; 3300 Mul = dyn_cast<SCEVMulExpr>(LHS); 3301 if (!Mul) 3302 return getUDivExactExpr(LHS, RHS); 3303 } 3304 } 3305 } 3306 3307 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3308 if (Mul->getOperand(i) == RHS) { 3309 SmallVector<const SCEV *, 2> Operands; 3310 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3311 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3312 return getMulExpr(Operands); 3313 } 3314 } 3315 3316 return getUDivExpr(LHS, RHS); 3317 } 3318 3319 /// Get an add recurrence expression for the specified loop. Simplify the 3320 /// expression as much as possible. 3321 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3322 const Loop *L, 3323 SCEV::NoWrapFlags Flags) { 3324 SmallVector<const SCEV *, 4> Operands; 3325 Operands.push_back(Start); 3326 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3327 if (StepChrec->getLoop() == L) { 3328 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3329 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3330 } 3331 3332 Operands.push_back(Step); 3333 return getAddRecExpr(Operands, L, Flags); 3334 } 3335 3336 /// Get an add recurrence expression for the specified loop. Simplify the 3337 /// expression as much as possible. 3338 const SCEV * 3339 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3340 const Loop *L, SCEV::NoWrapFlags Flags) { 3341 if (Operands.size() == 1) return Operands[0]; 3342 #ifndef NDEBUG 3343 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3344 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3345 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3346 "SCEVAddRecExpr operand types don't match!"); 3347 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3348 assert(isLoopInvariant(Operands[i], L) && 3349 "SCEVAddRecExpr operand is not loop-invariant!"); 3350 #endif 3351 3352 if (Operands.back()->isZero()) { 3353 Operands.pop_back(); 3354 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3355 } 3356 3357 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3358 // use that information to infer NUW and NSW flags. However, computing a 3359 // BE count requires calling getAddRecExpr, so we may not yet have a 3360 // meaningful BE count at this point (and if we don't, we'd be stuck 3361 // with a SCEVCouldNotCompute as the cached BE count). 3362 3363 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3364 3365 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3366 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3367 const Loop *NestedLoop = NestedAR->getLoop(); 3368 if (L->contains(NestedLoop) 3369 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3370 : (!NestedLoop->contains(L) && 3371 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3372 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3373 NestedAR->op_end()); 3374 Operands[0] = NestedAR->getStart(); 3375 // AddRecs require their operands be loop-invariant with respect to their 3376 // loops. Don't perform this transformation if it would break this 3377 // requirement. 3378 bool AllInvariant = all_of( 3379 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3380 3381 if (AllInvariant) { 3382 // Create a recurrence for the outer loop with the same step size. 3383 // 3384 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3385 // inner recurrence has the same property. 3386 SCEV::NoWrapFlags OuterFlags = 3387 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3388 3389 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3390 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3391 return isLoopInvariant(Op, NestedLoop); 3392 }); 3393 3394 if (AllInvariant) { 3395 // Ok, both add recurrences are valid after the transformation. 3396 // 3397 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3398 // the outer recurrence has the same property. 3399 SCEV::NoWrapFlags InnerFlags = 3400 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3401 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3402 } 3403 } 3404 // Reset Operands to its original state. 3405 Operands[0] = NestedAR; 3406 } 3407 } 3408 3409 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3410 // already have one, otherwise create a new one. 3411 FoldingSetNodeID ID; 3412 ID.AddInteger(scAddRecExpr); 3413 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3414 ID.AddPointer(Operands[i]); 3415 ID.AddPointer(L); 3416 void *IP = nullptr; 3417 SCEVAddRecExpr *S = 3418 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3419 if (!S) { 3420 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3421 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3422 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3423 O, Operands.size(), L); 3424 UniqueSCEVs.InsertNode(S, IP); 3425 addToLoopUseLists(S); 3426 } 3427 S->setNoWrapFlags(Flags); 3428 return S; 3429 } 3430 3431 const SCEV * 3432 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3433 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3434 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3435 // getSCEV(Base)->getType() has the same address space as Base->getType() 3436 // because SCEV::getType() preserves the address space. 3437 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3438 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3439 // instruction to its SCEV, because the Instruction may be guarded by control 3440 // flow and the no-overflow bits may not be valid for the expression in any 3441 // context. This can be fixed similarly to how these flags are handled for 3442 // adds. 3443 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3444 : SCEV::FlagAnyWrap; 3445 3446 const SCEV *TotalOffset = getZero(IntPtrTy); 3447 // The array size is unimportant. The first thing we do on CurTy is getting 3448 // its element type. 3449 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3450 for (const SCEV *IndexExpr : IndexExprs) { 3451 // Compute the (potentially symbolic) offset in bytes for this index. 3452 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3453 // For a struct, add the member offset. 3454 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3455 unsigned FieldNo = Index->getZExtValue(); 3456 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3457 3458 // Add the field offset to the running total offset. 3459 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3460 3461 // Update CurTy to the type of the field at Index. 3462 CurTy = STy->getTypeAtIndex(Index); 3463 } else { 3464 // Update CurTy to its element type. 3465 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3466 // For an array, add the element offset, explicitly scaled. 3467 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3468 // Getelementptr indices are signed. 3469 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3470 3471 // Multiply the index by the element size to compute the element offset. 3472 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3473 3474 // Add the element offset to the running total offset. 3475 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3476 } 3477 } 3478 3479 // Add the total offset from all the GEP indices to the base. 3480 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3481 } 3482 3483 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3484 const SCEV *RHS) { 3485 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3486 return getSMaxExpr(Ops); 3487 } 3488 3489 const SCEV * 3490 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3491 assert(!Ops.empty() && "Cannot get empty smax!"); 3492 if (Ops.size() == 1) return Ops[0]; 3493 #ifndef NDEBUG 3494 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3495 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3496 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3497 "SCEVSMaxExpr operand types don't match!"); 3498 #endif 3499 3500 // Sort by complexity, this groups all similar expression types together. 3501 GroupByComplexity(Ops, &LI, DT); 3502 3503 // If there are any constants, fold them together. 3504 unsigned Idx = 0; 3505 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3506 ++Idx; 3507 assert(Idx < Ops.size()); 3508 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3509 // We found two constants, fold them together! 3510 ConstantInt *Fold = ConstantInt::get( 3511 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3512 Ops[0] = getConstant(Fold); 3513 Ops.erase(Ops.begin()+1); // Erase the folded element 3514 if (Ops.size() == 1) return Ops[0]; 3515 LHSC = cast<SCEVConstant>(Ops[0]); 3516 } 3517 3518 // If we are left with a constant minimum-int, strip it off. 3519 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3520 Ops.erase(Ops.begin()); 3521 --Idx; 3522 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3523 // If we have an smax with a constant maximum-int, it will always be 3524 // maximum-int. 3525 return Ops[0]; 3526 } 3527 3528 if (Ops.size() == 1) return Ops[0]; 3529 } 3530 3531 // Find the first SMax 3532 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3533 ++Idx; 3534 3535 // Check to see if one of the operands is an SMax. If so, expand its operands 3536 // onto our operand list, and recurse to simplify. 3537 if (Idx < Ops.size()) { 3538 bool DeletedSMax = false; 3539 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3540 Ops.erase(Ops.begin()+Idx); 3541 Ops.append(SMax->op_begin(), SMax->op_end()); 3542 DeletedSMax = true; 3543 } 3544 3545 if (DeletedSMax) 3546 return getSMaxExpr(Ops); 3547 } 3548 3549 // Okay, check to see if the same value occurs in the operand list twice. If 3550 // so, delete one. Since we sorted the list, these values are required to 3551 // be adjacent. 3552 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3553 // X smax Y smax Y --> X smax Y 3554 // X smax Y --> X, if X is always greater than Y 3555 if (Ops[i] == Ops[i+1] || 3556 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3557 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3558 --i; --e; 3559 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3560 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3561 --i; --e; 3562 } 3563 3564 if (Ops.size() == 1) return Ops[0]; 3565 3566 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3567 3568 // Okay, it looks like we really DO need an smax expr. Check to see if we 3569 // already have one, otherwise create a new one. 3570 FoldingSetNodeID ID; 3571 ID.AddInteger(scSMaxExpr); 3572 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3573 ID.AddPointer(Ops[i]); 3574 void *IP = nullptr; 3575 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3576 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3577 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3578 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3579 O, Ops.size()); 3580 UniqueSCEVs.InsertNode(S, IP); 3581 addToLoopUseLists(S); 3582 return S; 3583 } 3584 3585 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3586 const SCEV *RHS) { 3587 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3588 return getUMaxExpr(Ops); 3589 } 3590 3591 const SCEV * 3592 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3593 assert(!Ops.empty() && "Cannot get empty umax!"); 3594 if (Ops.size() == 1) return Ops[0]; 3595 #ifndef NDEBUG 3596 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3597 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3598 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3599 "SCEVUMaxExpr operand types don't match!"); 3600 #endif 3601 3602 // Sort by complexity, this groups all similar expression types together. 3603 GroupByComplexity(Ops, &LI, DT); 3604 3605 // If there are any constants, fold them together. 3606 unsigned Idx = 0; 3607 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3608 ++Idx; 3609 assert(Idx < Ops.size()); 3610 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3611 // We found two constants, fold them together! 3612 ConstantInt *Fold = ConstantInt::get( 3613 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3614 Ops[0] = getConstant(Fold); 3615 Ops.erase(Ops.begin()+1); // Erase the folded element 3616 if (Ops.size() == 1) return Ops[0]; 3617 LHSC = cast<SCEVConstant>(Ops[0]); 3618 } 3619 3620 // If we are left with a constant minimum-int, strip it off. 3621 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3622 Ops.erase(Ops.begin()); 3623 --Idx; 3624 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3625 // If we have an umax with a constant maximum-int, it will always be 3626 // maximum-int. 3627 return Ops[0]; 3628 } 3629 3630 if (Ops.size() == 1) return Ops[0]; 3631 } 3632 3633 // Find the first UMax 3634 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3635 ++Idx; 3636 3637 // Check to see if one of the operands is a UMax. If so, expand its operands 3638 // onto our operand list, and recurse to simplify. 3639 if (Idx < Ops.size()) { 3640 bool DeletedUMax = false; 3641 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3642 Ops.erase(Ops.begin()+Idx); 3643 Ops.append(UMax->op_begin(), UMax->op_end()); 3644 DeletedUMax = true; 3645 } 3646 3647 if (DeletedUMax) 3648 return getUMaxExpr(Ops); 3649 } 3650 3651 // Okay, check to see if the same value occurs in the operand list twice. If 3652 // so, delete one. Since we sorted the list, these values are required to 3653 // be adjacent. 3654 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3655 // X umax Y umax Y --> X umax Y 3656 // X umax Y --> X, if X is always greater than Y 3657 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning( 3658 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) { 3659 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3660 --i; --e; 3661 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i], 3662 Ops[i + 1])) { 3663 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3664 --i; --e; 3665 } 3666 3667 if (Ops.size() == 1) return Ops[0]; 3668 3669 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3670 3671 // Okay, it looks like we really DO need a umax expr. Check to see if we 3672 // already have one, otherwise create a new one. 3673 FoldingSetNodeID ID; 3674 ID.AddInteger(scUMaxExpr); 3675 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3676 ID.AddPointer(Ops[i]); 3677 void *IP = nullptr; 3678 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3679 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3680 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3681 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3682 O, Ops.size()); 3683 UniqueSCEVs.InsertNode(S, IP); 3684 addToLoopUseLists(S); 3685 return S; 3686 } 3687 3688 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3689 const SCEV *RHS) { 3690 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3691 return getSMinExpr(Ops); 3692 } 3693 3694 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3695 // ~smax(~x, ~y, ~z) == smin(x, y, z). 3696 SmallVector<const SCEV *, 2> NotOps; 3697 for (auto *S : Ops) 3698 NotOps.push_back(getNotSCEV(S)); 3699 return getNotSCEV(getSMaxExpr(NotOps)); 3700 } 3701 3702 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3703 const SCEV *RHS) { 3704 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3705 return getUMinExpr(Ops); 3706 } 3707 3708 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3709 assert(!Ops.empty() && "At least one operand must be!"); 3710 // Trivial case. 3711 if (Ops.size() == 1) 3712 return Ops[0]; 3713 3714 // ~umax(~x, ~y, ~z) == umin(x, y, z). 3715 SmallVector<const SCEV *, 2> NotOps; 3716 for (auto *S : Ops) 3717 NotOps.push_back(getNotSCEV(S)); 3718 return getNotSCEV(getUMaxExpr(NotOps)); 3719 } 3720 3721 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3722 // We can bypass creating a target-independent 3723 // constant expression and then folding it back into a ConstantInt. 3724 // This is just a compile-time optimization. 3725 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3726 } 3727 3728 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3729 StructType *STy, 3730 unsigned FieldNo) { 3731 // We can bypass creating a target-independent 3732 // constant expression and then folding it back into a ConstantInt. 3733 // This is just a compile-time optimization. 3734 return getConstant( 3735 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3736 } 3737 3738 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3739 // Don't attempt to do anything other than create a SCEVUnknown object 3740 // here. createSCEV only calls getUnknown after checking for all other 3741 // interesting possibilities, and any other code that calls getUnknown 3742 // is doing so in order to hide a value from SCEV canonicalization. 3743 3744 FoldingSetNodeID ID; 3745 ID.AddInteger(scUnknown); 3746 ID.AddPointer(V); 3747 void *IP = nullptr; 3748 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3749 assert(cast<SCEVUnknown>(S)->getValue() == V && 3750 "Stale SCEVUnknown in uniquing map!"); 3751 return S; 3752 } 3753 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3754 FirstUnknown); 3755 FirstUnknown = cast<SCEVUnknown>(S); 3756 UniqueSCEVs.InsertNode(S, IP); 3757 return S; 3758 } 3759 3760 //===----------------------------------------------------------------------===// 3761 // Basic SCEV Analysis and PHI Idiom Recognition Code 3762 // 3763 3764 /// Test if values of the given type are analyzable within the SCEV 3765 /// framework. This primarily includes integer types, and it can optionally 3766 /// include pointer types if the ScalarEvolution class has access to 3767 /// target-specific information. 3768 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3769 // Integers and pointers are always SCEVable. 3770 return Ty->isIntOrPtrTy(); 3771 } 3772 3773 /// Return the size in bits of the specified type, for which isSCEVable must 3774 /// return true. 3775 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3776 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3777 if (Ty->isPointerTy()) 3778 return getDataLayout().getIndexTypeSizeInBits(Ty); 3779 return getDataLayout().getTypeSizeInBits(Ty); 3780 } 3781 3782 /// Return a type with the same bitwidth as the given type and which represents 3783 /// how SCEV will treat the given type, for which isSCEVable must return 3784 /// true. For pointer types, this is the pointer-sized integer type. 3785 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3786 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3787 3788 if (Ty->isIntegerTy()) 3789 return Ty; 3790 3791 // The only other support type is pointer. 3792 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3793 return getDataLayout().getIntPtrType(Ty); 3794 } 3795 3796 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3797 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3798 } 3799 3800 const SCEV *ScalarEvolution::getCouldNotCompute() { 3801 return CouldNotCompute.get(); 3802 } 3803 3804 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3805 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3806 auto *SU = dyn_cast<SCEVUnknown>(S); 3807 return SU && SU->getValue() == nullptr; 3808 }); 3809 3810 return !ContainsNulls; 3811 } 3812 3813 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3814 HasRecMapType::iterator I = HasRecMap.find(S); 3815 if (I != HasRecMap.end()) 3816 return I->second; 3817 3818 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3819 HasRecMap.insert({S, FoundAddRec}); 3820 return FoundAddRec; 3821 } 3822 3823 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3824 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3825 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3826 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3827 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3828 if (!Add) 3829 return {S, nullptr}; 3830 3831 if (Add->getNumOperands() != 2) 3832 return {S, nullptr}; 3833 3834 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3835 if (!ConstOp) 3836 return {S, nullptr}; 3837 3838 return {Add->getOperand(1), ConstOp->getValue()}; 3839 } 3840 3841 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3842 /// by the value and offset from any ValueOffsetPair in the set. 3843 SetVector<ScalarEvolution::ValueOffsetPair> * 3844 ScalarEvolution::getSCEVValues(const SCEV *S) { 3845 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3846 if (SI == ExprValueMap.end()) 3847 return nullptr; 3848 #ifndef NDEBUG 3849 if (VerifySCEVMap) { 3850 // Check there is no dangling Value in the set returned. 3851 for (const auto &VE : SI->second) 3852 assert(ValueExprMap.count(VE.first)); 3853 } 3854 #endif 3855 return &SI->second; 3856 } 3857 3858 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3859 /// cannot be used separately. eraseValueFromMap should be used to remove 3860 /// V from ValueExprMap and ExprValueMap at the same time. 3861 void ScalarEvolution::eraseValueFromMap(Value *V) { 3862 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3863 if (I != ValueExprMap.end()) { 3864 const SCEV *S = I->second; 3865 // Remove {V, 0} from the set of ExprValueMap[S] 3866 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3867 SV->remove({V, nullptr}); 3868 3869 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3870 const SCEV *Stripped; 3871 ConstantInt *Offset; 3872 std::tie(Stripped, Offset) = splitAddExpr(S); 3873 if (Offset != nullptr) { 3874 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3875 SV->remove({V, Offset}); 3876 } 3877 ValueExprMap.erase(V); 3878 } 3879 } 3880 3881 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3882 /// TODO: In reality it is better to check the poison recursevely 3883 /// but this is better than nothing. 3884 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3885 if (auto *I = dyn_cast<Instruction>(V)) { 3886 if (isa<OverflowingBinaryOperator>(I)) { 3887 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3888 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3889 return true; 3890 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3891 return true; 3892 } 3893 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3894 return true; 3895 } 3896 return false; 3897 } 3898 3899 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3900 /// create a new one. 3901 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3902 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3903 3904 const SCEV *S = getExistingSCEV(V); 3905 if (S == nullptr) { 3906 S = createSCEV(V); 3907 // During PHI resolution, it is possible to create two SCEVs for the same 3908 // V, so it is needed to double check whether V->S is inserted into 3909 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3910 std::pair<ValueExprMapType::iterator, bool> Pair = 3911 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3912 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3913 ExprValueMap[S].insert({V, nullptr}); 3914 3915 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3916 // ExprValueMap. 3917 const SCEV *Stripped = S; 3918 ConstantInt *Offset = nullptr; 3919 std::tie(Stripped, Offset) = splitAddExpr(S); 3920 // If stripped is SCEVUnknown, don't bother to save 3921 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3922 // increase the complexity of the expansion code. 3923 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3924 // because it may generate add/sub instead of GEP in SCEV expansion. 3925 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3926 !isa<GetElementPtrInst>(V)) 3927 ExprValueMap[Stripped].insert({V, Offset}); 3928 } 3929 } 3930 return S; 3931 } 3932 3933 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3934 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3935 3936 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3937 if (I != ValueExprMap.end()) { 3938 const SCEV *S = I->second; 3939 if (checkValidity(S)) 3940 return S; 3941 eraseValueFromMap(V); 3942 forgetMemoizedResults(S); 3943 } 3944 return nullptr; 3945 } 3946 3947 /// Return a SCEV corresponding to -V = -1*V 3948 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3949 SCEV::NoWrapFlags Flags) { 3950 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3951 return getConstant( 3952 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3953 3954 Type *Ty = V->getType(); 3955 Ty = getEffectiveSCEVType(Ty); 3956 return getMulExpr( 3957 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3958 } 3959 3960 /// Return a SCEV corresponding to ~V = -1-V 3961 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3962 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3963 return getConstant( 3964 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3965 3966 Type *Ty = V->getType(); 3967 Ty = getEffectiveSCEVType(Ty); 3968 const SCEV *AllOnes = 3969 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3970 return getMinusSCEV(AllOnes, V); 3971 } 3972 3973 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3974 SCEV::NoWrapFlags Flags, 3975 unsigned Depth) { 3976 // Fast path: X - X --> 0. 3977 if (LHS == RHS) 3978 return getZero(LHS->getType()); 3979 3980 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3981 // makes it so that we cannot make much use of NUW. 3982 auto AddFlags = SCEV::FlagAnyWrap; 3983 const bool RHSIsNotMinSigned = 3984 !getSignedRangeMin(RHS).isMinSignedValue(); 3985 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3986 // Let M be the minimum representable signed value. Then (-1)*RHS 3987 // signed-wraps if and only if RHS is M. That can happen even for 3988 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3989 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3990 // (-1)*RHS, we need to prove that RHS != M. 3991 // 3992 // If LHS is non-negative and we know that LHS - RHS does not 3993 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3994 // either by proving that RHS > M or that LHS >= 0. 3995 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3996 AddFlags = SCEV::FlagNSW; 3997 } 3998 } 3999 4000 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4001 // RHS is NSW and LHS >= 0. 4002 // 4003 // The difficulty here is that the NSW flag may have been proven 4004 // relative to a loop that is to be found in a recurrence in LHS and 4005 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4006 // larger scope than intended. 4007 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4008 4009 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4010 } 4011 4012 const SCEV * 4013 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 4014 Type *SrcTy = V->getType(); 4015 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4016 "Cannot truncate or zero extend with non-integer arguments!"); 4017 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4018 return V; // No conversion 4019 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4020 return getTruncateExpr(V, Ty); 4021 return getZeroExtendExpr(V, Ty); 4022 } 4023 4024 const SCEV * 4025 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 4026 Type *Ty) { 4027 Type *SrcTy = V->getType(); 4028 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4029 "Cannot truncate or zero extend with non-integer arguments!"); 4030 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4031 return V; // No conversion 4032 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4033 return getTruncateExpr(V, Ty); 4034 return getSignExtendExpr(V, Ty); 4035 } 4036 4037 const SCEV * 4038 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4039 Type *SrcTy = V->getType(); 4040 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4041 "Cannot noop or zero extend with non-integer arguments!"); 4042 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4043 "getNoopOrZeroExtend cannot truncate!"); 4044 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4045 return V; // No conversion 4046 return getZeroExtendExpr(V, Ty); 4047 } 4048 4049 const SCEV * 4050 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4051 Type *SrcTy = V->getType(); 4052 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4053 "Cannot noop or sign extend with non-integer arguments!"); 4054 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4055 "getNoopOrSignExtend cannot truncate!"); 4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4057 return V; // No conversion 4058 return getSignExtendExpr(V, Ty); 4059 } 4060 4061 const SCEV * 4062 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4063 Type *SrcTy = V->getType(); 4064 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4065 "Cannot noop or any extend with non-integer arguments!"); 4066 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4067 "getNoopOrAnyExtend cannot truncate!"); 4068 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4069 return V; // No conversion 4070 return getAnyExtendExpr(V, Ty); 4071 } 4072 4073 const SCEV * 4074 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4075 Type *SrcTy = V->getType(); 4076 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4077 "Cannot truncate or noop with non-integer arguments!"); 4078 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4079 "getTruncateOrNoop cannot extend!"); 4080 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4081 return V; // No conversion 4082 return getTruncateExpr(V, Ty); 4083 } 4084 4085 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4086 const SCEV *RHS) { 4087 const SCEV *PromotedLHS = LHS; 4088 const SCEV *PromotedRHS = RHS; 4089 4090 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4091 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4092 else 4093 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4094 4095 return getUMaxExpr(PromotedLHS, PromotedRHS); 4096 } 4097 4098 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4099 const SCEV *RHS) { 4100 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4101 return getUMinFromMismatchedTypes(Ops); 4102 } 4103 4104 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4105 SmallVectorImpl<const SCEV *> &Ops) { 4106 assert(!Ops.empty() && "At least one operand must be!"); 4107 // Trivial case. 4108 if (Ops.size() == 1) 4109 return Ops[0]; 4110 4111 // Find the max type first. 4112 Type *MaxType = nullptr; 4113 for (auto *S : Ops) 4114 if (MaxType) 4115 MaxType = getWiderType(MaxType, S->getType()); 4116 else 4117 MaxType = S->getType(); 4118 4119 // Extend all ops to max type. 4120 SmallVector<const SCEV *, 2> PromotedOps; 4121 for (auto *S : Ops) 4122 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4123 4124 // Generate umin. 4125 return getUMinExpr(PromotedOps); 4126 } 4127 4128 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4129 // A pointer operand may evaluate to a nonpointer expression, such as null. 4130 if (!V->getType()->isPointerTy()) 4131 return V; 4132 4133 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4134 return getPointerBase(Cast->getOperand()); 4135 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4136 const SCEV *PtrOp = nullptr; 4137 for (const SCEV *NAryOp : NAry->operands()) { 4138 if (NAryOp->getType()->isPointerTy()) { 4139 // Cannot find the base of an expression with multiple pointer operands. 4140 if (PtrOp) 4141 return V; 4142 PtrOp = NAryOp; 4143 } 4144 } 4145 if (!PtrOp) 4146 return V; 4147 return getPointerBase(PtrOp); 4148 } 4149 return V; 4150 } 4151 4152 /// Push users of the given Instruction onto the given Worklist. 4153 static void 4154 PushDefUseChildren(Instruction *I, 4155 SmallVectorImpl<Instruction *> &Worklist) { 4156 // Push the def-use children onto the Worklist stack. 4157 for (User *U : I->users()) 4158 Worklist.push_back(cast<Instruction>(U)); 4159 } 4160 4161 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4162 SmallVector<Instruction *, 16> Worklist; 4163 PushDefUseChildren(PN, Worklist); 4164 4165 SmallPtrSet<Instruction *, 8> Visited; 4166 Visited.insert(PN); 4167 while (!Worklist.empty()) { 4168 Instruction *I = Worklist.pop_back_val(); 4169 if (!Visited.insert(I).second) 4170 continue; 4171 4172 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4173 if (It != ValueExprMap.end()) { 4174 const SCEV *Old = It->second; 4175 4176 // Short-circuit the def-use traversal if the symbolic name 4177 // ceases to appear in expressions. 4178 if (Old != SymName && !hasOperand(Old, SymName)) 4179 continue; 4180 4181 // SCEVUnknown for a PHI either means that it has an unrecognized 4182 // structure, it's a PHI that's in the progress of being computed 4183 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4184 // additional loop trip count information isn't going to change anything. 4185 // In the second case, createNodeForPHI will perform the necessary 4186 // updates on its own when it gets to that point. In the third, we do 4187 // want to forget the SCEVUnknown. 4188 if (!isa<PHINode>(I) || 4189 !isa<SCEVUnknown>(Old) || 4190 (I != PN && Old == SymName)) { 4191 eraseValueFromMap(It->first); 4192 forgetMemoizedResults(Old); 4193 } 4194 } 4195 4196 PushDefUseChildren(I, Worklist); 4197 } 4198 } 4199 4200 namespace { 4201 4202 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4203 /// expression in case its Loop is L. If it is not L then 4204 /// if IgnoreOtherLoops is true then use AddRec itself 4205 /// otherwise rewrite cannot be done. 4206 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4207 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4208 public: 4209 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4210 bool IgnoreOtherLoops = true) { 4211 SCEVInitRewriter Rewriter(L, SE); 4212 const SCEV *Result = Rewriter.visit(S); 4213 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4214 return SE.getCouldNotCompute(); 4215 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4216 ? SE.getCouldNotCompute() 4217 : Result; 4218 } 4219 4220 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4221 if (!SE.isLoopInvariant(Expr, L)) 4222 SeenLoopVariantSCEVUnknown = true; 4223 return Expr; 4224 } 4225 4226 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4227 // Only re-write AddRecExprs for this loop. 4228 if (Expr->getLoop() == L) 4229 return Expr->getStart(); 4230 SeenOtherLoops = true; 4231 return Expr; 4232 } 4233 4234 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4235 4236 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4237 4238 private: 4239 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4240 : SCEVRewriteVisitor(SE), L(L) {} 4241 4242 const Loop *L; 4243 bool SeenLoopVariantSCEVUnknown = false; 4244 bool SeenOtherLoops = false; 4245 }; 4246 4247 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4248 /// increment expression in case its Loop is L. If it is not L then 4249 /// use AddRec itself. 4250 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4251 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4252 public: 4253 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4254 SCEVPostIncRewriter Rewriter(L, SE); 4255 const SCEV *Result = Rewriter.visit(S); 4256 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4257 ? SE.getCouldNotCompute() 4258 : Result; 4259 } 4260 4261 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4262 if (!SE.isLoopInvariant(Expr, L)) 4263 SeenLoopVariantSCEVUnknown = true; 4264 return Expr; 4265 } 4266 4267 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4268 // Only re-write AddRecExprs for this loop. 4269 if (Expr->getLoop() == L) 4270 return Expr->getPostIncExpr(SE); 4271 SeenOtherLoops = true; 4272 return Expr; 4273 } 4274 4275 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4276 4277 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4278 4279 private: 4280 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4281 : SCEVRewriteVisitor(SE), L(L) {} 4282 4283 const Loop *L; 4284 bool SeenLoopVariantSCEVUnknown = false; 4285 bool SeenOtherLoops = false; 4286 }; 4287 4288 /// This class evaluates the compare condition by matching it against the 4289 /// condition of loop latch. If there is a match we assume a true value 4290 /// for the condition while building SCEV nodes. 4291 class SCEVBackedgeConditionFolder 4292 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4293 public: 4294 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4295 ScalarEvolution &SE) { 4296 bool IsPosBECond = false; 4297 Value *BECond = nullptr; 4298 if (BasicBlock *Latch = L->getLoopLatch()) { 4299 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4300 if (BI && BI->isConditional()) { 4301 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4302 "Both outgoing branches should not target same header!"); 4303 BECond = BI->getCondition(); 4304 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4305 } else { 4306 return S; 4307 } 4308 } 4309 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4310 return Rewriter.visit(S); 4311 } 4312 4313 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4314 const SCEV *Result = Expr; 4315 bool InvariantF = SE.isLoopInvariant(Expr, L); 4316 4317 if (!InvariantF) { 4318 Instruction *I = cast<Instruction>(Expr->getValue()); 4319 switch (I->getOpcode()) { 4320 case Instruction::Select: { 4321 SelectInst *SI = cast<SelectInst>(I); 4322 Optional<const SCEV *> Res = 4323 compareWithBackedgeCondition(SI->getCondition()); 4324 if (Res.hasValue()) { 4325 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4326 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4327 } 4328 break; 4329 } 4330 default: { 4331 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4332 if (Res.hasValue()) 4333 Result = Res.getValue(); 4334 break; 4335 } 4336 } 4337 } 4338 return Result; 4339 } 4340 4341 private: 4342 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4343 bool IsPosBECond, ScalarEvolution &SE) 4344 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4345 IsPositiveBECond(IsPosBECond) {} 4346 4347 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4348 4349 const Loop *L; 4350 /// Loop back condition. 4351 Value *BackedgeCond = nullptr; 4352 /// Set to true if loop back is on positive branch condition. 4353 bool IsPositiveBECond; 4354 }; 4355 4356 Optional<const SCEV *> 4357 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4358 4359 // If value matches the backedge condition for loop latch, 4360 // then return a constant evolution node based on loopback 4361 // branch taken. 4362 if (BackedgeCond == IC) 4363 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4364 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4365 return None; 4366 } 4367 4368 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4369 public: 4370 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4371 ScalarEvolution &SE) { 4372 SCEVShiftRewriter Rewriter(L, SE); 4373 const SCEV *Result = Rewriter.visit(S); 4374 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4375 } 4376 4377 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4378 // Only allow AddRecExprs for this loop. 4379 if (!SE.isLoopInvariant(Expr, L)) 4380 Valid = false; 4381 return Expr; 4382 } 4383 4384 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4385 if (Expr->getLoop() == L && Expr->isAffine()) 4386 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4387 Valid = false; 4388 return Expr; 4389 } 4390 4391 bool isValid() { return Valid; } 4392 4393 private: 4394 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4395 : SCEVRewriteVisitor(SE), L(L) {} 4396 4397 const Loop *L; 4398 bool Valid = true; 4399 }; 4400 4401 } // end anonymous namespace 4402 4403 SCEV::NoWrapFlags 4404 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4405 if (!AR->isAffine()) 4406 return SCEV::FlagAnyWrap; 4407 4408 using OBO = OverflowingBinaryOperator; 4409 4410 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4411 4412 if (!AR->hasNoSignedWrap()) { 4413 ConstantRange AddRecRange = getSignedRange(AR); 4414 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4415 4416 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4417 Instruction::Add, IncRange, OBO::NoSignedWrap); 4418 if (NSWRegion.contains(AddRecRange)) 4419 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4420 } 4421 4422 if (!AR->hasNoUnsignedWrap()) { 4423 ConstantRange AddRecRange = getUnsignedRange(AR); 4424 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4425 4426 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4427 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4428 if (NUWRegion.contains(AddRecRange)) 4429 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4430 } 4431 4432 return Result; 4433 } 4434 4435 namespace { 4436 4437 /// Represents an abstract binary operation. This may exist as a 4438 /// normal instruction or constant expression, or may have been 4439 /// derived from an expression tree. 4440 struct BinaryOp { 4441 unsigned Opcode; 4442 Value *LHS; 4443 Value *RHS; 4444 bool IsNSW = false; 4445 bool IsNUW = false; 4446 4447 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4448 /// constant expression. 4449 Operator *Op = nullptr; 4450 4451 explicit BinaryOp(Operator *Op) 4452 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4453 Op(Op) { 4454 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4455 IsNSW = OBO->hasNoSignedWrap(); 4456 IsNUW = OBO->hasNoUnsignedWrap(); 4457 } 4458 } 4459 4460 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4461 bool IsNUW = false) 4462 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4463 }; 4464 4465 } // end anonymous namespace 4466 4467 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4468 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4469 auto *Op = dyn_cast<Operator>(V); 4470 if (!Op) 4471 return None; 4472 4473 // Implementation detail: all the cleverness here should happen without 4474 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4475 // SCEV expressions when possible, and we should not break that. 4476 4477 switch (Op->getOpcode()) { 4478 case Instruction::Add: 4479 case Instruction::Sub: 4480 case Instruction::Mul: 4481 case Instruction::UDiv: 4482 case Instruction::URem: 4483 case Instruction::And: 4484 case Instruction::Or: 4485 case Instruction::AShr: 4486 case Instruction::Shl: 4487 return BinaryOp(Op); 4488 4489 case Instruction::Xor: 4490 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4491 // If the RHS of the xor is a signmask, then this is just an add. 4492 // Instcombine turns add of signmask into xor as a strength reduction step. 4493 if (RHSC->getValue().isSignMask()) 4494 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4495 return BinaryOp(Op); 4496 4497 case Instruction::LShr: 4498 // Turn logical shift right of a constant into a unsigned divide. 4499 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4500 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4501 4502 // If the shift count is not less than the bitwidth, the result of 4503 // the shift is undefined. Don't try to analyze it, because the 4504 // resolution chosen here may differ from the resolution chosen in 4505 // other parts of the compiler. 4506 if (SA->getValue().ult(BitWidth)) { 4507 Constant *X = 4508 ConstantInt::get(SA->getContext(), 4509 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4510 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4511 } 4512 } 4513 return BinaryOp(Op); 4514 4515 case Instruction::ExtractValue: { 4516 auto *EVI = cast<ExtractValueInst>(Op); 4517 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4518 break; 4519 4520 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4521 if (!CI) 4522 break; 4523 4524 if (auto *F = CI->getCalledFunction()) 4525 switch (F->getIntrinsicID()) { 4526 case Intrinsic::sadd_with_overflow: 4527 case Intrinsic::uadd_with_overflow: 4528 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4529 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4530 CI->getArgOperand(1)); 4531 4532 // Now that we know that all uses of the arithmetic-result component of 4533 // CI are guarded by the overflow check, we can go ahead and pretend 4534 // that the arithmetic is non-overflowing. 4535 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4536 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4537 CI->getArgOperand(1), /* IsNSW = */ true, 4538 /* IsNUW = */ false); 4539 else 4540 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4541 CI->getArgOperand(1), /* IsNSW = */ false, 4542 /* IsNUW*/ true); 4543 case Intrinsic::ssub_with_overflow: 4544 case Intrinsic::usub_with_overflow: 4545 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4546 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4547 CI->getArgOperand(1)); 4548 4549 // The same reasoning as sadd/uadd above. 4550 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4551 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4552 CI->getArgOperand(1), /* IsNSW = */ true, 4553 /* IsNUW = */ false); 4554 else 4555 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4556 CI->getArgOperand(1), /* IsNSW = */ false, 4557 /* IsNUW = */ true); 4558 case Intrinsic::smul_with_overflow: 4559 case Intrinsic::umul_with_overflow: 4560 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4561 CI->getArgOperand(1)); 4562 default: 4563 break; 4564 } 4565 break; 4566 } 4567 4568 default: 4569 break; 4570 } 4571 4572 return None; 4573 } 4574 4575 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4576 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4577 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4578 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4579 /// follows one of the following patterns: 4580 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4581 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4582 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4583 /// we return the type of the truncation operation, and indicate whether the 4584 /// truncated type should be treated as signed/unsigned by setting 4585 /// \p Signed to true/false, respectively. 4586 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4587 bool &Signed, ScalarEvolution &SE) { 4588 // The case where Op == SymbolicPHI (that is, with no type conversions on 4589 // the way) is handled by the regular add recurrence creating logic and 4590 // would have already been triggered in createAddRecForPHI. Reaching it here 4591 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4592 // because one of the other operands of the SCEVAddExpr updating this PHI is 4593 // not invariant). 4594 // 4595 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4596 // this case predicates that allow us to prove that Op == SymbolicPHI will 4597 // be added. 4598 if (Op == SymbolicPHI) 4599 return nullptr; 4600 4601 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4602 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4603 if (SourceBits != NewBits) 4604 return nullptr; 4605 4606 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4607 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4608 if (!SExt && !ZExt) 4609 return nullptr; 4610 const SCEVTruncateExpr *Trunc = 4611 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4612 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4613 if (!Trunc) 4614 return nullptr; 4615 const SCEV *X = Trunc->getOperand(); 4616 if (X != SymbolicPHI) 4617 return nullptr; 4618 Signed = SExt != nullptr; 4619 return Trunc->getType(); 4620 } 4621 4622 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4623 if (!PN->getType()->isIntegerTy()) 4624 return nullptr; 4625 const Loop *L = LI.getLoopFor(PN->getParent()); 4626 if (!L || L->getHeader() != PN->getParent()) 4627 return nullptr; 4628 return L; 4629 } 4630 4631 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4632 // computation that updates the phi follows the following pattern: 4633 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4634 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4635 // If so, try to see if it can be rewritten as an AddRecExpr under some 4636 // Predicates. If successful, return them as a pair. Also cache the results 4637 // of the analysis. 4638 // 4639 // Example usage scenario: 4640 // Say the Rewriter is called for the following SCEV: 4641 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4642 // where: 4643 // %X = phi i64 (%Start, %BEValue) 4644 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4645 // and call this function with %SymbolicPHI = %X. 4646 // 4647 // The analysis will find that the value coming around the backedge has 4648 // the following SCEV: 4649 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4650 // Upon concluding that this matches the desired pattern, the function 4651 // will return the pair {NewAddRec, SmallPredsVec} where: 4652 // NewAddRec = {%Start,+,%Step} 4653 // SmallPredsVec = {P1, P2, P3} as follows: 4654 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4655 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4656 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4657 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4658 // under the predicates {P1,P2,P3}. 4659 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4660 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4661 // 4662 // TODO's: 4663 // 4664 // 1) Extend the Induction descriptor to also support inductions that involve 4665 // casts: When needed (namely, when we are called in the context of the 4666 // vectorizer induction analysis), a Set of cast instructions will be 4667 // populated by this method, and provided back to isInductionPHI. This is 4668 // needed to allow the vectorizer to properly record them to be ignored by 4669 // the cost model and to avoid vectorizing them (otherwise these casts, 4670 // which are redundant under the runtime overflow checks, will be 4671 // vectorized, which can be costly). 4672 // 4673 // 2) Support additional induction/PHISCEV patterns: We also want to support 4674 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4675 // after the induction update operation (the induction increment): 4676 // 4677 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4678 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4679 // 4680 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4681 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4682 // 4683 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4684 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4685 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4686 SmallVector<const SCEVPredicate *, 3> Predicates; 4687 4688 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4689 // return an AddRec expression under some predicate. 4690 4691 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4692 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4693 assert(L && "Expecting an integer loop header phi"); 4694 4695 // The loop may have multiple entrances or multiple exits; we can analyze 4696 // this phi as an addrec if it has a unique entry value and a unique 4697 // backedge value. 4698 Value *BEValueV = nullptr, *StartValueV = nullptr; 4699 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4700 Value *V = PN->getIncomingValue(i); 4701 if (L->contains(PN->getIncomingBlock(i))) { 4702 if (!BEValueV) { 4703 BEValueV = V; 4704 } else if (BEValueV != V) { 4705 BEValueV = nullptr; 4706 break; 4707 } 4708 } else if (!StartValueV) { 4709 StartValueV = V; 4710 } else if (StartValueV != V) { 4711 StartValueV = nullptr; 4712 break; 4713 } 4714 } 4715 if (!BEValueV || !StartValueV) 4716 return None; 4717 4718 const SCEV *BEValue = getSCEV(BEValueV); 4719 4720 // If the value coming around the backedge is an add with the symbolic 4721 // value we just inserted, possibly with casts that we can ignore under 4722 // an appropriate runtime guard, then we found a simple induction variable! 4723 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4724 if (!Add) 4725 return None; 4726 4727 // If there is a single occurrence of the symbolic value, possibly 4728 // casted, replace it with a recurrence. 4729 unsigned FoundIndex = Add->getNumOperands(); 4730 Type *TruncTy = nullptr; 4731 bool Signed; 4732 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4733 if ((TruncTy = 4734 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4735 if (FoundIndex == e) { 4736 FoundIndex = i; 4737 break; 4738 } 4739 4740 if (FoundIndex == Add->getNumOperands()) 4741 return None; 4742 4743 // Create an add with everything but the specified operand. 4744 SmallVector<const SCEV *, 8> Ops; 4745 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4746 if (i != FoundIndex) 4747 Ops.push_back(Add->getOperand(i)); 4748 const SCEV *Accum = getAddExpr(Ops); 4749 4750 // The runtime checks will not be valid if the step amount is 4751 // varying inside the loop. 4752 if (!isLoopInvariant(Accum, L)) 4753 return None; 4754 4755 // *** Part2: Create the predicates 4756 4757 // Analysis was successful: we have a phi-with-cast pattern for which we 4758 // can return an AddRec expression under the following predicates: 4759 // 4760 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4761 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4762 // P2: An Equal predicate that guarantees that 4763 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4764 // P3: An Equal predicate that guarantees that 4765 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4766 // 4767 // As we next prove, the above predicates guarantee that: 4768 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4769 // 4770 // 4771 // More formally, we want to prove that: 4772 // Expr(i+1) = Start + (i+1) * Accum 4773 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4774 // 4775 // Given that: 4776 // 1) Expr(0) = Start 4777 // 2) Expr(1) = Start + Accum 4778 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4779 // 3) Induction hypothesis (step i): 4780 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4781 // 4782 // Proof: 4783 // Expr(i+1) = 4784 // = Start + (i+1)*Accum 4785 // = (Start + i*Accum) + Accum 4786 // = Expr(i) + Accum 4787 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4788 // :: from step i 4789 // 4790 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4791 // 4792 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4793 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4794 // + Accum :: from P3 4795 // 4796 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4797 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4798 // 4799 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4800 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4801 // 4802 // By induction, the same applies to all iterations 1<=i<n: 4803 // 4804 4805 // Create a truncated addrec for which we will add a no overflow check (P1). 4806 const SCEV *StartVal = getSCEV(StartValueV); 4807 const SCEV *PHISCEV = 4808 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4809 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4810 4811 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4812 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4813 // will be constant. 4814 // 4815 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4816 // add P1. 4817 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4818 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4819 Signed ? SCEVWrapPredicate::IncrementNSSW 4820 : SCEVWrapPredicate::IncrementNUSW; 4821 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4822 Predicates.push_back(AddRecPred); 4823 } 4824 4825 // Create the Equal Predicates P2,P3: 4826 4827 // It is possible that the predicates P2 and/or P3 are computable at 4828 // compile time due to StartVal and/or Accum being constants. 4829 // If either one is, then we can check that now and escape if either P2 4830 // or P3 is false. 4831 4832 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4833 // for each of StartVal and Accum 4834 auto getExtendedExpr = [&](const SCEV *Expr, 4835 bool CreateSignExtend) -> const SCEV * { 4836 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4837 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4838 const SCEV *ExtendedExpr = 4839 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4840 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4841 return ExtendedExpr; 4842 }; 4843 4844 // Given: 4845 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4846 // = getExtendedExpr(Expr) 4847 // Determine whether the predicate P: Expr == ExtendedExpr 4848 // is known to be false at compile time 4849 auto PredIsKnownFalse = [&](const SCEV *Expr, 4850 const SCEV *ExtendedExpr) -> bool { 4851 return Expr != ExtendedExpr && 4852 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4853 }; 4854 4855 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4856 if (PredIsKnownFalse(StartVal, StartExtended)) { 4857 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4858 return None; 4859 } 4860 4861 // The Step is always Signed (because the overflow checks are either 4862 // NSSW or NUSW) 4863 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4864 if (PredIsKnownFalse(Accum, AccumExtended)) { 4865 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4866 return None; 4867 } 4868 4869 auto AppendPredicate = [&](const SCEV *Expr, 4870 const SCEV *ExtendedExpr) -> void { 4871 if (Expr != ExtendedExpr && 4872 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4873 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4874 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4875 Predicates.push_back(Pred); 4876 } 4877 }; 4878 4879 AppendPredicate(StartVal, StartExtended); 4880 AppendPredicate(Accum, AccumExtended); 4881 4882 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4883 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4884 // into NewAR if it will also add the runtime overflow checks specified in 4885 // Predicates. 4886 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4887 4888 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4889 std::make_pair(NewAR, Predicates); 4890 // Remember the result of the analysis for this SCEV at this locayyytion. 4891 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4892 return PredRewrite; 4893 } 4894 4895 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4896 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4897 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4898 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4899 if (!L) 4900 return None; 4901 4902 // Check to see if we already analyzed this PHI. 4903 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4904 if (I != PredicatedSCEVRewrites.end()) { 4905 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4906 I->second; 4907 // Analysis was done before and failed to create an AddRec: 4908 if (Rewrite.first == SymbolicPHI) 4909 return None; 4910 // Analysis was done before and succeeded to create an AddRec under 4911 // a predicate: 4912 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4913 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4914 return Rewrite; 4915 } 4916 4917 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4918 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4919 4920 // Record in the cache that the analysis failed 4921 if (!Rewrite) { 4922 SmallVector<const SCEVPredicate *, 3> Predicates; 4923 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4924 return None; 4925 } 4926 4927 return Rewrite; 4928 } 4929 4930 // FIXME: This utility is currently required because the Rewriter currently 4931 // does not rewrite this expression: 4932 // {0, +, (sext ix (trunc iy to ix) to iy)} 4933 // into {0, +, %step}, 4934 // even when the following Equal predicate exists: 4935 // "%step == (sext ix (trunc iy to ix) to iy)". 4936 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4937 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4938 if (AR1 == AR2) 4939 return true; 4940 4941 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4942 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4943 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4944 return false; 4945 return true; 4946 }; 4947 4948 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4949 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4950 return false; 4951 return true; 4952 } 4953 4954 /// A helper function for createAddRecFromPHI to handle simple cases. 4955 /// 4956 /// This function tries to find an AddRec expression for the simplest (yet most 4957 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4958 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4959 /// technique for finding the AddRec expression. 4960 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4961 Value *BEValueV, 4962 Value *StartValueV) { 4963 const Loop *L = LI.getLoopFor(PN->getParent()); 4964 assert(L && L->getHeader() == PN->getParent()); 4965 assert(BEValueV && StartValueV); 4966 4967 auto BO = MatchBinaryOp(BEValueV, DT); 4968 if (!BO) 4969 return nullptr; 4970 4971 if (BO->Opcode != Instruction::Add) 4972 return nullptr; 4973 4974 const SCEV *Accum = nullptr; 4975 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4976 Accum = getSCEV(BO->RHS); 4977 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4978 Accum = getSCEV(BO->LHS); 4979 4980 if (!Accum) 4981 return nullptr; 4982 4983 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4984 if (BO->IsNUW) 4985 Flags = setFlags(Flags, SCEV::FlagNUW); 4986 if (BO->IsNSW) 4987 Flags = setFlags(Flags, SCEV::FlagNSW); 4988 4989 const SCEV *StartVal = getSCEV(StartValueV); 4990 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4991 4992 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4993 4994 // We can add Flags to the post-inc expression only if we 4995 // know that it is *undefined behavior* for BEValueV to 4996 // overflow. 4997 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4998 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4999 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5000 5001 return PHISCEV; 5002 } 5003 5004 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5005 const Loop *L = LI.getLoopFor(PN->getParent()); 5006 if (!L || L->getHeader() != PN->getParent()) 5007 return nullptr; 5008 5009 // The loop may have multiple entrances or multiple exits; we can analyze 5010 // this phi as an addrec if it has a unique entry value and a unique 5011 // backedge value. 5012 Value *BEValueV = nullptr, *StartValueV = nullptr; 5013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5014 Value *V = PN->getIncomingValue(i); 5015 if (L->contains(PN->getIncomingBlock(i))) { 5016 if (!BEValueV) { 5017 BEValueV = V; 5018 } else if (BEValueV != V) { 5019 BEValueV = nullptr; 5020 break; 5021 } 5022 } else if (!StartValueV) { 5023 StartValueV = V; 5024 } else if (StartValueV != V) { 5025 StartValueV = nullptr; 5026 break; 5027 } 5028 } 5029 if (!BEValueV || !StartValueV) 5030 return nullptr; 5031 5032 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5033 "PHI node already processed?"); 5034 5035 // First, try to find AddRec expression without creating a fictituos symbolic 5036 // value for PN. 5037 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5038 return S; 5039 5040 // Handle PHI node value symbolically. 5041 const SCEV *SymbolicName = getUnknown(PN); 5042 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5043 5044 // Using this symbolic name for the PHI, analyze the value coming around 5045 // the back-edge. 5046 const SCEV *BEValue = getSCEV(BEValueV); 5047 5048 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5049 // has a special value for the first iteration of the loop. 5050 5051 // If the value coming around the backedge is an add with the symbolic 5052 // value we just inserted, then we found a simple induction variable! 5053 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5054 // If there is a single occurrence of the symbolic value, replace it 5055 // with a recurrence. 5056 unsigned FoundIndex = Add->getNumOperands(); 5057 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5058 if (Add->getOperand(i) == SymbolicName) 5059 if (FoundIndex == e) { 5060 FoundIndex = i; 5061 break; 5062 } 5063 5064 if (FoundIndex != Add->getNumOperands()) { 5065 // Create an add with everything but the specified operand. 5066 SmallVector<const SCEV *, 8> Ops; 5067 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5068 if (i != FoundIndex) 5069 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5070 L, *this)); 5071 const SCEV *Accum = getAddExpr(Ops); 5072 5073 // This is not a valid addrec if the step amount is varying each 5074 // loop iteration, but is not itself an addrec in this loop. 5075 if (isLoopInvariant(Accum, L) || 5076 (isa<SCEVAddRecExpr>(Accum) && 5077 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5078 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5079 5080 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5081 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5082 if (BO->IsNUW) 5083 Flags = setFlags(Flags, SCEV::FlagNUW); 5084 if (BO->IsNSW) 5085 Flags = setFlags(Flags, SCEV::FlagNSW); 5086 } 5087 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5088 // If the increment is an inbounds GEP, then we know the address 5089 // space cannot be wrapped around. We cannot make any guarantee 5090 // about signed or unsigned overflow because pointers are 5091 // unsigned but we may have a negative index from the base 5092 // pointer. We can guarantee that no unsigned wrap occurs if the 5093 // indices form a positive value. 5094 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5095 Flags = setFlags(Flags, SCEV::FlagNW); 5096 5097 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5098 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5099 Flags = setFlags(Flags, SCEV::FlagNUW); 5100 } 5101 5102 // We cannot transfer nuw and nsw flags from subtraction 5103 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5104 // for instance. 5105 } 5106 5107 const SCEV *StartVal = getSCEV(StartValueV); 5108 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5109 5110 // Okay, for the entire analysis of this edge we assumed the PHI 5111 // to be symbolic. We now need to go back and purge all of the 5112 // entries for the scalars that use the symbolic expression. 5113 forgetSymbolicName(PN, SymbolicName); 5114 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5115 5116 // We can add Flags to the post-inc expression only if we 5117 // know that it is *undefined behavior* for BEValueV to 5118 // overflow. 5119 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5120 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5121 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5122 5123 return PHISCEV; 5124 } 5125 } 5126 } else { 5127 // Otherwise, this could be a loop like this: 5128 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5129 // In this case, j = {1,+,1} and BEValue is j. 5130 // Because the other in-value of i (0) fits the evolution of BEValue 5131 // i really is an addrec evolution. 5132 // 5133 // We can generalize this saying that i is the shifted value of BEValue 5134 // by one iteration: 5135 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5136 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5137 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5138 if (Shifted != getCouldNotCompute() && 5139 Start != getCouldNotCompute()) { 5140 const SCEV *StartVal = getSCEV(StartValueV); 5141 if (Start == StartVal) { 5142 // Okay, for the entire analysis of this edge we assumed the PHI 5143 // to be symbolic. We now need to go back and purge all of the 5144 // entries for the scalars that use the symbolic expression. 5145 forgetSymbolicName(PN, SymbolicName); 5146 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5147 return Shifted; 5148 } 5149 } 5150 } 5151 5152 // Remove the temporary PHI node SCEV that has been inserted while intending 5153 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5154 // as it will prevent later (possibly simpler) SCEV expressions to be added 5155 // to the ValueExprMap. 5156 eraseValueFromMap(PN); 5157 5158 return nullptr; 5159 } 5160 5161 // Checks if the SCEV S is available at BB. S is considered available at BB 5162 // if S can be materialized at BB without introducing a fault. 5163 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5164 BasicBlock *BB) { 5165 struct CheckAvailable { 5166 bool TraversalDone = false; 5167 bool Available = true; 5168 5169 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5170 BasicBlock *BB = nullptr; 5171 DominatorTree &DT; 5172 5173 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5174 : L(L), BB(BB), DT(DT) {} 5175 5176 bool setUnavailable() { 5177 TraversalDone = true; 5178 Available = false; 5179 return false; 5180 } 5181 5182 bool follow(const SCEV *S) { 5183 switch (S->getSCEVType()) { 5184 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5185 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5186 // These expressions are available if their operand(s) is/are. 5187 return true; 5188 5189 case scAddRecExpr: { 5190 // We allow add recurrences that are on the loop BB is in, or some 5191 // outer loop. This guarantees availability because the value of the 5192 // add recurrence at BB is simply the "current" value of the induction 5193 // variable. We can relax this in the future; for instance an add 5194 // recurrence on a sibling dominating loop is also available at BB. 5195 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5196 if (L && (ARLoop == L || ARLoop->contains(L))) 5197 return true; 5198 5199 return setUnavailable(); 5200 } 5201 5202 case scUnknown: { 5203 // For SCEVUnknown, we check for simple dominance. 5204 const auto *SU = cast<SCEVUnknown>(S); 5205 Value *V = SU->getValue(); 5206 5207 if (isa<Argument>(V)) 5208 return false; 5209 5210 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5211 return false; 5212 5213 return setUnavailable(); 5214 } 5215 5216 case scUDivExpr: 5217 case scCouldNotCompute: 5218 // We do not try to smart about these at all. 5219 return setUnavailable(); 5220 } 5221 llvm_unreachable("switch should be fully covered!"); 5222 } 5223 5224 bool isDone() { return TraversalDone; } 5225 }; 5226 5227 CheckAvailable CA(L, BB, DT); 5228 SCEVTraversal<CheckAvailable> ST(CA); 5229 5230 ST.visitAll(S); 5231 return CA.Available; 5232 } 5233 5234 // Try to match a control flow sequence that branches out at BI and merges back 5235 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5236 // match. 5237 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5238 Value *&C, Value *&LHS, Value *&RHS) { 5239 C = BI->getCondition(); 5240 5241 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5242 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5243 5244 if (!LeftEdge.isSingleEdge()) 5245 return false; 5246 5247 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5248 5249 Use &LeftUse = Merge->getOperandUse(0); 5250 Use &RightUse = Merge->getOperandUse(1); 5251 5252 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5253 LHS = LeftUse; 5254 RHS = RightUse; 5255 return true; 5256 } 5257 5258 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5259 LHS = RightUse; 5260 RHS = LeftUse; 5261 return true; 5262 } 5263 5264 return false; 5265 } 5266 5267 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5268 auto IsReachable = 5269 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5270 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5271 const Loop *L = LI.getLoopFor(PN->getParent()); 5272 5273 // We don't want to break LCSSA, even in a SCEV expression tree. 5274 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5275 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5276 return nullptr; 5277 5278 // Try to match 5279 // 5280 // br %cond, label %left, label %right 5281 // left: 5282 // br label %merge 5283 // right: 5284 // br label %merge 5285 // merge: 5286 // V = phi [ %x, %left ], [ %y, %right ] 5287 // 5288 // as "select %cond, %x, %y" 5289 5290 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5291 assert(IDom && "At least the entry block should dominate PN"); 5292 5293 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5294 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5295 5296 if (BI && BI->isConditional() && 5297 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5298 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5299 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5300 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5301 } 5302 5303 return nullptr; 5304 } 5305 5306 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5307 if (const SCEV *S = createAddRecFromPHI(PN)) 5308 return S; 5309 5310 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5311 return S; 5312 5313 // If the PHI has a single incoming value, follow that value, unless the 5314 // PHI's incoming blocks are in a different loop, in which case doing so 5315 // risks breaking LCSSA form. Instcombine would normally zap these, but 5316 // it doesn't have DominatorTree information, so it may miss cases. 5317 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5318 if (LI.replacementPreservesLCSSAForm(PN, V)) 5319 return getSCEV(V); 5320 5321 // If it's not a loop phi, we can't handle it yet. 5322 return getUnknown(PN); 5323 } 5324 5325 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5326 Value *Cond, 5327 Value *TrueVal, 5328 Value *FalseVal) { 5329 // Handle "constant" branch or select. This can occur for instance when a 5330 // loop pass transforms an inner loop and moves on to process the outer loop. 5331 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5332 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5333 5334 // Try to match some simple smax or umax patterns. 5335 auto *ICI = dyn_cast<ICmpInst>(Cond); 5336 if (!ICI) 5337 return getUnknown(I); 5338 5339 Value *LHS = ICI->getOperand(0); 5340 Value *RHS = ICI->getOperand(1); 5341 5342 switch (ICI->getPredicate()) { 5343 case ICmpInst::ICMP_SLT: 5344 case ICmpInst::ICMP_SLE: 5345 std::swap(LHS, RHS); 5346 LLVM_FALLTHROUGH; 5347 case ICmpInst::ICMP_SGT: 5348 case ICmpInst::ICMP_SGE: 5349 // a >s b ? a+x : b+x -> smax(a, b)+x 5350 // a >s b ? b+x : a+x -> smin(a, b)+x 5351 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5352 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5353 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5354 const SCEV *LA = getSCEV(TrueVal); 5355 const SCEV *RA = getSCEV(FalseVal); 5356 const SCEV *LDiff = getMinusSCEV(LA, LS); 5357 const SCEV *RDiff = getMinusSCEV(RA, RS); 5358 if (LDiff == RDiff) 5359 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5360 LDiff = getMinusSCEV(LA, RS); 5361 RDiff = getMinusSCEV(RA, LS); 5362 if (LDiff == RDiff) 5363 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5364 } 5365 break; 5366 case ICmpInst::ICMP_ULT: 5367 case ICmpInst::ICMP_ULE: 5368 std::swap(LHS, RHS); 5369 LLVM_FALLTHROUGH; 5370 case ICmpInst::ICMP_UGT: 5371 case ICmpInst::ICMP_UGE: 5372 // a >u b ? a+x : b+x -> umax(a, b)+x 5373 // a >u b ? b+x : a+x -> umin(a, b)+x 5374 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5375 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5376 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5377 const SCEV *LA = getSCEV(TrueVal); 5378 const SCEV *RA = getSCEV(FalseVal); 5379 const SCEV *LDiff = getMinusSCEV(LA, LS); 5380 const SCEV *RDiff = getMinusSCEV(RA, RS); 5381 if (LDiff == RDiff) 5382 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5383 LDiff = getMinusSCEV(LA, RS); 5384 RDiff = getMinusSCEV(RA, LS); 5385 if (LDiff == RDiff) 5386 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5387 } 5388 break; 5389 case ICmpInst::ICMP_NE: 5390 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5391 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5392 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5393 const SCEV *One = getOne(I->getType()); 5394 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5395 const SCEV *LA = getSCEV(TrueVal); 5396 const SCEV *RA = getSCEV(FalseVal); 5397 const SCEV *LDiff = getMinusSCEV(LA, LS); 5398 const SCEV *RDiff = getMinusSCEV(RA, One); 5399 if (LDiff == RDiff) 5400 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5401 } 5402 break; 5403 case ICmpInst::ICMP_EQ: 5404 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5405 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5406 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5407 const SCEV *One = getOne(I->getType()); 5408 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5409 const SCEV *LA = getSCEV(TrueVal); 5410 const SCEV *RA = getSCEV(FalseVal); 5411 const SCEV *LDiff = getMinusSCEV(LA, One); 5412 const SCEV *RDiff = getMinusSCEV(RA, LS); 5413 if (LDiff == RDiff) 5414 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5415 } 5416 break; 5417 default: 5418 break; 5419 } 5420 5421 return getUnknown(I); 5422 } 5423 5424 /// Expand GEP instructions into add and multiply operations. This allows them 5425 /// to be analyzed by regular SCEV code. 5426 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5427 // Don't attempt to analyze GEPs over unsized objects. 5428 if (!GEP->getSourceElementType()->isSized()) 5429 return getUnknown(GEP); 5430 5431 SmallVector<const SCEV *, 4> IndexExprs; 5432 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5433 IndexExprs.push_back(getSCEV(*Index)); 5434 return getGEPExpr(GEP, IndexExprs); 5435 } 5436 5437 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5438 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5439 return C->getAPInt().countTrailingZeros(); 5440 5441 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5442 return std::min(GetMinTrailingZeros(T->getOperand()), 5443 (uint32_t)getTypeSizeInBits(T->getType())); 5444 5445 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5446 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5447 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5448 ? getTypeSizeInBits(E->getType()) 5449 : OpRes; 5450 } 5451 5452 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5453 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5454 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5455 ? getTypeSizeInBits(E->getType()) 5456 : OpRes; 5457 } 5458 5459 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5460 // The result is the min of all operands results. 5461 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5462 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5463 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5464 return MinOpRes; 5465 } 5466 5467 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5468 // The result is the sum of all operands results. 5469 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5470 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5471 for (unsigned i = 1, e = M->getNumOperands(); 5472 SumOpRes != BitWidth && i != e; ++i) 5473 SumOpRes = 5474 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5475 return SumOpRes; 5476 } 5477 5478 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5479 // The result is the min of all operands results. 5480 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5481 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5482 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5483 return MinOpRes; 5484 } 5485 5486 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5487 // The result is the min of all operands results. 5488 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5489 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5491 return MinOpRes; 5492 } 5493 5494 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5495 // The result is the min of all operands results. 5496 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5497 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5499 return MinOpRes; 5500 } 5501 5502 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5503 // For a SCEVUnknown, ask ValueTracking. 5504 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5505 return Known.countMinTrailingZeros(); 5506 } 5507 5508 // SCEVUDivExpr 5509 return 0; 5510 } 5511 5512 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5513 auto I = MinTrailingZerosCache.find(S); 5514 if (I != MinTrailingZerosCache.end()) 5515 return I->second; 5516 5517 uint32_t Result = GetMinTrailingZerosImpl(S); 5518 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5519 assert(InsertPair.second && "Should insert a new key"); 5520 return InsertPair.first->second; 5521 } 5522 5523 /// Helper method to assign a range to V from metadata present in the IR. 5524 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5525 if (Instruction *I = dyn_cast<Instruction>(V)) 5526 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5527 return getConstantRangeFromMetadata(*MD); 5528 5529 return None; 5530 } 5531 5532 /// Determine the range for a particular SCEV. If SignHint is 5533 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5534 /// with a "cleaner" unsigned (resp. signed) representation. 5535 const ConstantRange & 5536 ScalarEvolution::getRangeRef(const SCEV *S, 5537 ScalarEvolution::RangeSignHint SignHint) { 5538 DenseMap<const SCEV *, ConstantRange> &Cache = 5539 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5540 : SignedRanges; 5541 5542 // See if we've computed this range already. 5543 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5544 if (I != Cache.end()) 5545 return I->second; 5546 5547 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5548 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5549 5550 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5551 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5552 5553 // If the value has known zeros, the maximum value will have those known zeros 5554 // as well. 5555 uint32_t TZ = GetMinTrailingZeros(S); 5556 if (TZ != 0) { 5557 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5558 ConservativeResult = 5559 ConstantRange(APInt::getMinValue(BitWidth), 5560 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5561 else 5562 ConservativeResult = ConstantRange( 5563 APInt::getSignedMinValue(BitWidth), 5564 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5565 } 5566 5567 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5568 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5569 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5570 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5571 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5572 } 5573 5574 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5575 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5576 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5577 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5578 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5579 } 5580 5581 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5582 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5583 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5584 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5585 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5586 } 5587 5588 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5589 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5590 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5591 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5592 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5593 } 5594 5595 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5596 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5597 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5598 return setRange(UDiv, SignHint, 5599 ConservativeResult.intersectWith(X.udiv(Y))); 5600 } 5601 5602 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5603 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5604 return setRange(ZExt, SignHint, 5605 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5606 } 5607 5608 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5609 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5610 return setRange(SExt, SignHint, 5611 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5612 } 5613 5614 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5615 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5616 return setRange(Trunc, SignHint, 5617 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5618 } 5619 5620 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5621 // If there's no unsigned wrap, the value will never be less than its 5622 // initial value. 5623 if (AddRec->hasNoUnsignedWrap()) 5624 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5625 if (!C->getValue()->isZero()) 5626 ConservativeResult = ConservativeResult.intersectWith( 5627 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5628 5629 // If there's no signed wrap, and all the operands have the same sign or 5630 // zero, the value won't ever change sign. 5631 if (AddRec->hasNoSignedWrap()) { 5632 bool AllNonNeg = true; 5633 bool AllNonPos = true; 5634 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5635 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5636 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5637 } 5638 if (AllNonNeg) 5639 ConservativeResult = ConservativeResult.intersectWith( 5640 ConstantRange(APInt(BitWidth, 0), 5641 APInt::getSignedMinValue(BitWidth))); 5642 else if (AllNonPos) 5643 ConservativeResult = ConservativeResult.intersectWith( 5644 ConstantRange(APInt::getSignedMinValue(BitWidth), 5645 APInt(BitWidth, 1))); 5646 } 5647 5648 // TODO: non-affine addrec 5649 if (AddRec->isAffine()) { 5650 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5651 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5652 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5653 auto RangeFromAffine = getRangeForAffineAR( 5654 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5655 BitWidth); 5656 if (!RangeFromAffine.isFullSet()) 5657 ConservativeResult = 5658 ConservativeResult.intersectWith(RangeFromAffine); 5659 5660 auto RangeFromFactoring = getRangeViaFactoring( 5661 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5662 BitWidth); 5663 if (!RangeFromFactoring.isFullSet()) 5664 ConservativeResult = 5665 ConservativeResult.intersectWith(RangeFromFactoring); 5666 } 5667 } 5668 5669 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5670 } 5671 5672 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5673 // Check if the IR explicitly contains !range metadata. 5674 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5675 if (MDRange.hasValue()) 5676 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5677 5678 // Split here to avoid paying the compile-time cost of calling both 5679 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5680 // if needed. 5681 const DataLayout &DL = getDataLayout(); 5682 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5683 // For a SCEVUnknown, ask ValueTracking. 5684 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5685 if (Known.One != ~Known.Zero + 1) 5686 ConservativeResult = 5687 ConservativeResult.intersectWith(ConstantRange(Known.One, 5688 ~Known.Zero + 1)); 5689 } else { 5690 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5691 "generalize as needed!"); 5692 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5693 if (NS > 1) 5694 ConservativeResult = ConservativeResult.intersectWith( 5695 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5696 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5697 } 5698 5699 // A range of Phi is a subset of union of all ranges of its input. 5700 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5701 // Make sure that we do not run over cycled Phis. 5702 if (PendingPhiRanges.insert(Phi).second) { 5703 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5704 for (auto &Op : Phi->operands()) { 5705 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5706 RangeFromOps = RangeFromOps.unionWith(OpRange); 5707 // No point to continue if we already have a full set. 5708 if (RangeFromOps.isFullSet()) 5709 break; 5710 } 5711 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5712 bool Erased = PendingPhiRanges.erase(Phi); 5713 assert(Erased && "Failed to erase Phi properly?"); 5714 (void) Erased; 5715 } 5716 } 5717 5718 return setRange(U, SignHint, std::move(ConservativeResult)); 5719 } 5720 5721 return setRange(S, SignHint, std::move(ConservativeResult)); 5722 } 5723 5724 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5725 // values that the expression can take. Initially, the expression has a value 5726 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5727 // argument defines if we treat Step as signed or unsigned. 5728 static ConstantRange getRangeForAffineARHelper(APInt Step, 5729 const ConstantRange &StartRange, 5730 const APInt &MaxBECount, 5731 unsigned BitWidth, bool Signed) { 5732 // If either Step or MaxBECount is 0, then the expression won't change, and we 5733 // just need to return the initial range. 5734 if (Step == 0 || MaxBECount == 0) 5735 return StartRange; 5736 5737 // If we don't know anything about the initial value (i.e. StartRange is 5738 // FullRange), then we don't know anything about the final range either. 5739 // Return FullRange. 5740 if (StartRange.isFullSet()) 5741 return ConstantRange(BitWidth, /* isFullSet = */ true); 5742 5743 // If Step is signed and negative, then we use its absolute value, but we also 5744 // note that we're moving in the opposite direction. 5745 bool Descending = Signed && Step.isNegative(); 5746 5747 if (Signed) 5748 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5749 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5750 // This equations hold true due to the well-defined wrap-around behavior of 5751 // APInt. 5752 Step = Step.abs(); 5753 5754 // Check if Offset is more than full span of BitWidth. If it is, the 5755 // expression is guaranteed to overflow. 5756 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5757 return ConstantRange(BitWidth, /* isFullSet = */ true); 5758 5759 // Offset is by how much the expression can change. Checks above guarantee no 5760 // overflow here. 5761 APInt Offset = Step * MaxBECount; 5762 5763 // Minimum value of the final range will match the minimal value of StartRange 5764 // if the expression is increasing and will be decreased by Offset otherwise. 5765 // Maximum value of the final range will match the maximal value of StartRange 5766 // if the expression is decreasing and will be increased by Offset otherwise. 5767 APInt StartLower = StartRange.getLower(); 5768 APInt StartUpper = StartRange.getUpper() - 1; 5769 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5770 : (StartUpper + std::move(Offset)); 5771 5772 // It's possible that the new minimum/maximum value will fall into the initial 5773 // range (due to wrap around). This means that the expression can take any 5774 // value in this bitwidth, and we have to return full range. 5775 if (StartRange.contains(MovedBoundary)) 5776 return ConstantRange(BitWidth, /* isFullSet = */ true); 5777 5778 APInt NewLower = 5779 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5780 APInt NewUpper = 5781 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5782 NewUpper += 1; 5783 5784 // If we end up with full range, return a proper full range. 5785 if (NewLower == NewUpper) 5786 return ConstantRange(BitWidth, /* isFullSet = */ true); 5787 5788 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5789 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5790 } 5791 5792 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5793 const SCEV *Step, 5794 const SCEV *MaxBECount, 5795 unsigned BitWidth) { 5796 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5797 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5798 "Precondition!"); 5799 5800 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5801 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5802 5803 // First, consider step signed. 5804 ConstantRange StartSRange = getSignedRange(Start); 5805 ConstantRange StepSRange = getSignedRange(Step); 5806 5807 // If Step can be both positive and negative, we need to find ranges for the 5808 // maximum absolute step values in both directions and union them. 5809 ConstantRange SR = 5810 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5811 MaxBECountValue, BitWidth, /* Signed = */ true); 5812 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5813 StartSRange, MaxBECountValue, 5814 BitWidth, /* Signed = */ true)); 5815 5816 // Next, consider step unsigned. 5817 ConstantRange UR = getRangeForAffineARHelper( 5818 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5819 MaxBECountValue, BitWidth, /* Signed = */ false); 5820 5821 // Finally, intersect signed and unsigned ranges. 5822 return SR.intersectWith(UR); 5823 } 5824 5825 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5826 const SCEV *Step, 5827 const SCEV *MaxBECount, 5828 unsigned BitWidth) { 5829 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5830 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5831 5832 struct SelectPattern { 5833 Value *Condition = nullptr; 5834 APInt TrueValue; 5835 APInt FalseValue; 5836 5837 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5838 const SCEV *S) { 5839 Optional<unsigned> CastOp; 5840 APInt Offset(BitWidth, 0); 5841 5842 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5843 "Should be!"); 5844 5845 // Peel off a constant offset: 5846 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5847 // In the future we could consider being smarter here and handle 5848 // {Start+Step,+,Step} too. 5849 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5850 return; 5851 5852 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5853 S = SA->getOperand(1); 5854 } 5855 5856 // Peel off a cast operation 5857 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5858 CastOp = SCast->getSCEVType(); 5859 S = SCast->getOperand(); 5860 } 5861 5862 using namespace llvm::PatternMatch; 5863 5864 auto *SU = dyn_cast<SCEVUnknown>(S); 5865 const APInt *TrueVal, *FalseVal; 5866 if (!SU || 5867 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5868 m_APInt(FalseVal)))) { 5869 Condition = nullptr; 5870 return; 5871 } 5872 5873 TrueValue = *TrueVal; 5874 FalseValue = *FalseVal; 5875 5876 // Re-apply the cast we peeled off earlier 5877 if (CastOp.hasValue()) 5878 switch (*CastOp) { 5879 default: 5880 llvm_unreachable("Unknown SCEV cast type!"); 5881 5882 case scTruncate: 5883 TrueValue = TrueValue.trunc(BitWidth); 5884 FalseValue = FalseValue.trunc(BitWidth); 5885 break; 5886 case scZeroExtend: 5887 TrueValue = TrueValue.zext(BitWidth); 5888 FalseValue = FalseValue.zext(BitWidth); 5889 break; 5890 case scSignExtend: 5891 TrueValue = TrueValue.sext(BitWidth); 5892 FalseValue = FalseValue.sext(BitWidth); 5893 break; 5894 } 5895 5896 // Re-apply the constant offset we peeled off earlier 5897 TrueValue += Offset; 5898 FalseValue += Offset; 5899 } 5900 5901 bool isRecognized() { return Condition != nullptr; } 5902 }; 5903 5904 SelectPattern StartPattern(*this, BitWidth, Start); 5905 if (!StartPattern.isRecognized()) 5906 return ConstantRange(BitWidth, /* isFullSet = */ true); 5907 5908 SelectPattern StepPattern(*this, BitWidth, Step); 5909 if (!StepPattern.isRecognized()) 5910 return ConstantRange(BitWidth, /* isFullSet = */ true); 5911 5912 if (StartPattern.Condition != StepPattern.Condition) { 5913 // We don't handle this case today; but we could, by considering four 5914 // possibilities below instead of two. I'm not sure if there are cases where 5915 // that will help over what getRange already does, though. 5916 return ConstantRange(BitWidth, /* isFullSet = */ true); 5917 } 5918 5919 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5920 // construct arbitrary general SCEV expressions here. This function is called 5921 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5922 // say) can end up caching a suboptimal value. 5923 5924 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5925 // C2352 and C2512 (otherwise it isn't needed). 5926 5927 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5928 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5929 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5930 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5931 5932 ConstantRange TrueRange = 5933 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5934 ConstantRange FalseRange = 5935 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5936 5937 return TrueRange.unionWith(FalseRange); 5938 } 5939 5940 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5941 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5942 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5943 5944 // Return early if there are no flags to propagate to the SCEV. 5945 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5946 if (BinOp->hasNoUnsignedWrap()) 5947 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5948 if (BinOp->hasNoSignedWrap()) 5949 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5950 if (Flags == SCEV::FlagAnyWrap) 5951 return SCEV::FlagAnyWrap; 5952 5953 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5954 } 5955 5956 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5957 // Here we check that I is in the header of the innermost loop containing I, 5958 // since we only deal with instructions in the loop header. The actual loop we 5959 // need to check later will come from an add recurrence, but getting that 5960 // requires computing the SCEV of the operands, which can be expensive. This 5961 // check we can do cheaply to rule out some cases early. 5962 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5963 if (InnermostContainingLoop == nullptr || 5964 InnermostContainingLoop->getHeader() != I->getParent()) 5965 return false; 5966 5967 // Only proceed if we can prove that I does not yield poison. 5968 if (!programUndefinedIfFullPoison(I)) 5969 return false; 5970 5971 // At this point we know that if I is executed, then it does not wrap 5972 // according to at least one of NSW or NUW. If I is not executed, then we do 5973 // not know if the calculation that I represents would wrap. Multiple 5974 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5975 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5976 // derived from other instructions that map to the same SCEV. We cannot make 5977 // that guarantee for cases where I is not executed. So we need to find the 5978 // loop that I is considered in relation to and prove that I is executed for 5979 // every iteration of that loop. That implies that the value that I 5980 // calculates does not wrap anywhere in the loop, so then we can apply the 5981 // flags to the SCEV. 5982 // 5983 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5984 // from different loops, so that we know which loop to prove that I is 5985 // executed in. 5986 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5987 // I could be an extractvalue from a call to an overflow intrinsic. 5988 // TODO: We can do better here in some cases. 5989 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5990 return false; 5991 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5992 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5993 bool AllOtherOpsLoopInvariant = true; 5994 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5995 ++OtherOpIndex) { 5996 if (OtherOpIndex != OpIndex) { 5997 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5998 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5999 AllOtherOpsLoopInvariant = false; 6000 break; 6001 } 6002 } 6003 } 6004 if (AllOtherOpsLoopInvariant && 6005 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6006 return true; 6007 } 6008 } 6009 return false; 6010 } 6011 6012 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6013 // If we know that \c I can never be poison period, then that's enough. 6014 if (isSCEVExprNeverPoison(I)) 6015 return true; 6016 6017 // For an add recurrence specifically, we assume that infinite loops without 6018 // side effects are undefined behavior, and then reason as follows: 6019 // 6020 // If the add recurrence is poison in any iteration, it is poison on all 6021 // future iterations (since incrementing poison yields poison). If the result 6022 // of the add recurrence is fed into the loop latch condition and the loop 6023 // does not contain any throws or exiting blocks other than the latch, we now 6024 // have the ability to "choose" whether the backedge is taken or not (by 6025 // choosing a sufficiently evil value for the poison feeding into the branch) 6026 // for every iteration including and after the one in which \p I first became 6027 // poison. There are two possibilities (let's call the iteration in which \p 6028 // I first became poison as K): 6029 // 6030 // 1. In the set of iterations including and after K, the loop body executes 6031 // no side effects. In this case executing the backege an infinte number 6032 // of times will yield undefined behavior. 6033 // 6034 // 2. In the set of iterations including and after K, the loop body executes 6035 // at least one side effect. In this case, that specific instance of side 6036 // effect is control dependent on poison, which also yields undefined 6037 // behavior. 6038 6039 auto *ExitingBB = L->getExitingBlock(); 6040 auto *LatchBB = L->getLoopLatch(); 6041 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6042 return false; 6043 6044 SmallPtrSet<const Instruction *, 16> Pushed; 6045 SmallVector<const Instruction *, 8> PoisonStack; 6046 6047 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6048 // things that are known to be fully poison under that assumption go on the 6049 // PoisonStack. 6050 Pushed.insert(I); 6051 PoisonStack.push_back(I); 6052 6053 bool LatchControlDependentOnPoison = false; 6054 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6055 const Instruction *Poison = PoisonStack.pop_back_val(); 6056 6057 for (auto *PoisonUser : Poison->users()) { 6058 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6059 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6060 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6061 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6062 assert(BI->isConditional() && "Only possibility!"); 6063 if (BI->getParent() == LatchBB) { 6064 LatchControlDependentOnPoison = true; 6065 break; 6066 } 6067 } 6068 } 6069 } 6070 6071 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6072 } 6073 6074 ScalarEvolution::LoopProperties 6075 ScalarEvolution::getLoopProperties(const Loop *L) { 6076 using LoopProperties = ScalarEvolution::LoopProperties; 6077 6078 auto Itr = LoopPropertiesCache.find(L); 6079 if (Itr == LoopPropertiesCache.end()) { 6080 auto HasSideEffects = [](Instruction *I) { 6081 if (auto *SI = dyn_cast<StoreInst>(I)) 6082 return !SI->isSimple(); 6083 6084 return I->mayHaveSideEffects(); 6085 }; 6086 6087 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6088 /*HasNoSideEffects*/ true}; 6089 6090 for (auto *BB : L->getBlocks()) 6091 for (auto &I : *BB) { 6092 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6093 LP.HasNoAbnormalExits = false; 6094 if (HasSideEffects(&I)) 6095 LP.HasNoSideEffects = false; 6096 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6097 break; // We're already as pessimistic as we can get. 6098 } 6099 6100 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6101 assert(InsertPair.second && "We just checked!"); 6102 Itr = InsertPair.first; 6103 } 6104 6105 return Itr->second; 6106 } 6107 6108 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6109 if (!isSCEVable(V->getType())) 6110 return getUnknown(V); 6111 6112 if (Instruction *I = dyn_cast<Instruction>(V)) { 6113 // Don't attempt to analyze instructions in blocks that aren't 6114 // reachable. Such instructions don't matter, and they aren't required 6115 // to obey basic rules for definitions dominating uses which this 6116 // analysis depends on. 6117 if (!DT.isReachableFromEntry(I->getParent())) 6118 return getUnknown(V); 6119 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6120 return getConstant(CI); 6121 else if (isa<ConstantPointerNull>(V)) 6122 return getZero(V->getType()); 6123 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6124 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6125 else if (!isa<ConstantExpr>(V)) 6126 return getUnknown(V); 6127 6128 Operator *U = cast<Operator>(V); 6129 if (auto BO = MatchBinaryOp(U, DT)) { 6130 switch (BO->Opcode) { 6131 case Instruction::Add: { 6132 // The simple thing to do would be to just call getSCEV on both operands 6133 // and call getAddExpr with the result. However if we're looking at a 6134 // bunch of things all added together, this can be quite inefficient, 6135 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6136 // Instead, gather up all the operands and make a single getAddExpr call. 6137 // LLVM IR canonical form means we need only traverse the left operands. 6138 SmallVector<const SCEV *, 4> AddOps; 6139 do { 6140 if (BO->Op) { 6141 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6142 AddOps.push_back(OpSCEV); 6143 break; 6144 } 6145 6146 // If a NUW or NSW flag can be applied to the SCEV for this 6147 // addition, then compute the SCEV for this addition by itself 6148 // with a separate call to getAddExpr. We need to do that 6149 // instead of pushing the operands of the addition onto AddOps, 6150 // since the flags are only known to apply to this particular 6151 // addition - they may not apply to other additions that can be 6152 // formed with operands from AddOps. 6153 const SCEV *RHS = getSCEV(BO->RHS); 6154 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6155 if (Flags != SCEV::FlagAnyWrap) { 6156 const SCEV *LHS = getSCEV(BO->LHS); 6157 if (BO->Opcode == Instruction::Sub) 6158 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6159 else 6160 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6161 break; 6162 } 6163 } 6164 6165 if (BO->Opcode == Instruction::Sub) 6166 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6167 else 6168 AddOps.push_back(getSCEV(BO->RHS)); 6169 6170 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6171 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6172 NewBO->Opcode != Instruction::Sub)) { 6173 AddOps.push_back(getSCEV(BO->LHS)); 6174 break; 6175 } 6176 BO = NewBO; 6177 } while (true); 6178 6179 return getAddExpr(AddOps); 6180 } 6181 6182 case Instruction::Mul: { 6183 SmallVector<const SCEV *, 4> MulOps; 6184 do { 6185 if (BO->Op) { 6186 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6187 MulOps.push_back(OpSCEV); 6188 break; 6189 } 6190 6191 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6192 if (Flags != SCEV::FlagAnyWrap) { 6193 MulOps.push_back( 6194 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6195 break; 6196 } 6197 } 6198 6199 MulOps.push_back(getSCEV(BO->RHS)); 6200 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6201 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6202 MulOps.push_back(getSCEV(BO->LHS)); 6203 break; 6204 } 6205 BO = NewBO; 6206 } while (true); 6207 6208 return getMulExpr(MulOps); 6209 } 6210 case Instruction::UDiv: 6211 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6212 case Instruction::URem: 6213 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6214 case Instruction::Sub: { 6215 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6216 if (BO->Op) 6217 Flags = getNoWrapFlagsFromUB(BO->Op); 6218 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6219 } 6220 case Instruction::And: 6221 // For an expression like x&255 that merely masks off the high bits, 6222 // use zext(trunc(x)) as the SCEV expression. 6223 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6224 if (CI->isZero()) 6225 return getSCEV(BO->RHS); 6226 if (CI->isMinusOne()) 6227 return getSCEV(BO->LHS); 6228 const APInt &A = CI->getValue(); 6229 6230 // Instcombine's ShrinkDemandedConstant may strip bits out of 6231 // constants, obscuring what would otherwise be a low-bits mask. 6232 // Use computeKnownBits to compute what ShrinkDemandedConstant 6233 // knew about to reconstruct a low-bits mask value. 6234 unsigned LZ = A.countLeadingZeros(); 6235 unsigned TZ = A.countTrailingZeros(); 6236 unsigned BitWidth = A.getBitWidth(); 6237 KnownBits Known(BitWidth); 6238 computeKnownBits(BO->LHS, Known, getDataLayout(), 6239 0, &AC, nullptr, &DT); 6240 6241 APInt EffectiveMask = 6242 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6243 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6244 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6245 const SCEV *LHS = getSCEV(BO->LHS); 6246 const SCEV *ShiftedLHS = nullptr; 6247 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6248 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6249 // For an expression like (x * 8) & 8, simplify the multiply. 6250 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6251 unsigned GCD = std::min(MulZeros, TZ); 6252 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6253 SmallVector<const SCEV*, 4> MulOps; 6254 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6255 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6256 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6257 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6258 } 6259 } 6260 if (!ShiftedLHS) 6261 ShiftedLHS = getUDivExpr(LHS, MulCount); 6262 return getMulExpr( 6263 getZeroExtendExpr( 6264 getTruncateExpr(ShiftedLHS, 6265 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6266 BO->LHS->getType()), 6267 MulCount); 6268 } 6269 } 6270 break; 6271 6272 case Instruction::Or: 6273 // If the RHS of the Or is a constant, we may have something like: 6274 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6275 // optimizations will transparently handle this case. 6276 // 6277 // In order for this transformation to be safe, the LHS must be of the 6278 // form X*(2^n) and the Or constant must be less than 2^n. 6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6280 const SCEV *LHS = getSCEV(BO->LHS); 6281 const APInt &CIVal = CI->getValue(); 6282 if (GetMinTrailingZeros(LHS) >= 6283 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6284 // Build a plain add SCEV. 6285 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6286 // If the LHS of the add was an addrec and it has no-wrap flags, 6287 // transfer the no-wrap flags, since an or won't introduce a wrap. 6288 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6289 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6290 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6291 OldAR->getNoWrapFlags()); 6292 } 6293 return S; 6294 } 6295 } 6296 break; 6297 6298 case Instruction::Xor: 6299 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6300 // If the RHS of xor is -1, then this is a not operation. 6301 if (CI->isMinusOne()) 6302 return getNotSCEV(getSCEV(BO->LHS)); 6303 6304 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6305 // This is a variant of the check for xor with -1, and it handles 6306 // the case where instcombine has trimmed non-demanded bits out 6307 // of an xor with -1. 6308 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6309 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6310 if (LBO->getOpcode() == Instruction::And && 6311 LCI->getValue() == CI->getValue()) 6312 if (const SCEVZeroExtendExpr *Z = 6313 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6314 Type *UTy = BO->LHS->getType(); 6315 const SCEV *Z0 = Z->getOperand(); 6316 Type *Z0Ty = Z0->getType(); 6317 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6318 6319 // If C is a low-bits mask, the zero extend is serving to 6320 // mask off the high bits. Complement the operand and 6321 // re-apply the zext. 6322 if (CI->getValue().isMask(Z0TySize)) 6323 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6324 6325 // If C is a single bit, it may be in the sign-bit position 6326 // before the zero-extend. In this case, represent the xor 6327 // using an add, which is equivalent, and re-apply the zext. 6328 APInt Trunc = CI->getValue().trunc(Z0TySize); 6329 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6330 Trunc.isSignMask()) 6331 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6332 UTy); 6333 } 6334 } 6335 break; 6336 6337 case Instruction::Shl: 6338 // Turn shift left of a constant amount into a multiply. 6339 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6340 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6341 6342 // If the shift count is not less than the bitwidth, the result of 6343 // the shift is undefined. Don't try to analyze it, because the 6344 // resolution chosen here may differ from the resolution chosen in 6345 // other parts of the compiler. 6346 if (SA->getValue().uge(BitWidth)) 6347 break; 6348 6349 // It is currently not resolved how to interpret NSW for left 6350 // shift by BitWidth - 1, so we avoid applying flags in that 6351 // case. Remove this check (or this comment) once the situation 6352 // is resolved. See 6353 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6354 // and http://reviews.llvm.org/D8890 . 6355 auto Flags = SCEV::FlagAnyWrap; 6356 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6357 Flags = getNoWrapFlagsFromUB(BO->Op); 6358 6359 Constant *X = ConstantInt::get( 6360 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6361 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6362 } 6363 break; 6364 6365 case Instruction::AShr: { 6366 // AShr X, C, where C is a constant. 6367 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6368 if (!CI) 6369 break; 6370 6371 Type *OuterTy = BO->LHS->getType(); 6372 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6373 // If the shift count is not less than the bitwidth, the result of 6374 // the shift is undefined. Don't try to analyze it, because the 6375 // resolution chosen here may differ from the resolution chosen in 6376 // other parts of the compiler. 6377 if (CI->getValue().uge(BitWidth)) 6378 break; 6379 6380 if (CI->isZero()) 6381 return getSCEV(BO->LHS); // shift by zero --> noop 6382 6383 uint64_t AShrAmt = CI->getZExtValue(); 6384 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6385 6386 Operator *L = dyn_cast<Operator>(BO->LHS); 6387 if (L && L->getOpcode() == Instruction::Shl) { 6388 // X = Shl A, n 6389 // Y = AShr X, m 6390 // Both n and m are constant. 6391 6392 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6393 if (L->getOperand(1) == BO->RHS) 6394 // For a two-shift sext-inreg, i.e. n = m, 6395 // use sext(trunc(x)) as the SCEV expression. 6396 return getSignExtendExpr( 6397 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6398 6399 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6400 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6401 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6402 if (ShlAmt > AShrAmt) { 6403 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6404 // expression. We already checked that ShlAmt < BitWidth, so 6405 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6406 // ShlAmt - AShrAmt < Amt. 6407 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6408 ShlAmt - AShrAmt); 6409 return getSignExtendExpr( 6410 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6411 getConstant(Mul)), OuterTy); 6412 } 6413 } 6414 } 6415 break; 6416 } 6417 } 6418 } 6419 6420 switch (U->getOpcode()) { 6421 case Instruction::Trunc: 6422 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6423 6424 case Instruction::ZExt: 6425 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6426 6427 case Instruction::SExt: 6428 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6429 // The NSW flag of a subtract does not always survive the conversion to 6430 // A + (-1)*B. By pushing sign extension onto its operands we are much 6431 // more likely to preserve NSW and allow later AddRec optimisations. 6432 // 6433 // NOTE: This is effectively duplicating this logic from getSignExtend: 6434 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6435 // but by that point the NSW information has potentially been lost. 6436 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6437 Type *Ty = U->getType(); 6438 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6439 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6440 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6441 } 6442 } 6443 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6444 6445 case Instruction::BitCast: 6446 // BitCasts are no-op casts so we just eliminate the cast. 6447 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6448 return getSCEV(U->getOperand(0)); 6449 break; 6450 6451 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6452 // lead to pointer expressions which cannot safely be expanded to GEPs, 6453 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6454 // simplifying integer expressions. 6455 6456 case Instruction::GetElementPtr: 6457 return createNodeForGEP(cast<GEPOperator>(U)); 6458 6459 case Instruction::PHI: 6460 return createNodeForPHI(cast<PHINode>(U)); 6461 6462 case Instruction::Select: 6463 // U can also be a select constant expr, which let fall through. Since 6464 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6465 // constant expressions cannot have instructions as operands, we'd have 6466 // returned getUnknown for a select constant expressions anyway. 6467 if (isa<Instruction>(U)) 6468 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6469 U->getOperand(1), U->getOperand(2)); 6470 break; 6471 6472 case Instruction::Call: 6473 case Instruction::Invoke: 6474 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6475 return getSCEV(RV); 6476 break; 6477 } 6478 6479 return getUnknown(V); 6480 } 6481 6482 //===----------------------------------------------------------------------===// 6483 // Iteration Count Computation Code 6484 // 6485 6486 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6487 if (!ExitCount) 6488 return 0; 6489 6490 ConstantInt *ExitConst = ExitCount->getValue(); 6491 6492 // Guard against huge trip counts. 6493 if (ExitConst->getValue().getActiveBits() > 32) 6494 return 0; 6495 6496 // In case of integer overflow, this returns 0, which is correct. 6497 return ((unsigned)ExitConst->getZExtValue()) + 1; 6498 } 6499 6500 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6501 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6502 return getSmallConstantTripCount(L, ExitingBB); 6503 6504 // No trip count information for multiple exits. 6505 return 0; 6506 } 6507 6508 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6509 BasicBlock *ExitingBlock) { 6510 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6511 assert(L->isLoopExiting(ExitingBlock) && 6512 "Exiting block must actually branch out of the loop!"); 6513 const SCEVConstant *ExitCount = 6514 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6515 return getConstantTripCount(ExitCount); 6516 } 6517 6518 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6519 const auto *MaxExitCount = 6520 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6521 return getConstantTripCount(MaxExitCount); 6522 } 6523 6524 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6525 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6526 return getSmallConstantTripMultiple(L, ExitingBB); 6527 6528 // No trip multiple information for multiple exits. 6529 return 0; 6530 } 6531 6532 /// Returns the largest constant divisor of the trip count of this loop as a 6533 /// normal unsigned value, if possible. This means that the actual trip count is 6534 /// always a multiple of the returned value (don't forget the trip count could 6535 /// very well be zero as well!). 6536 /// 6537 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6538 /// multiple of a constant (which is also the case if the trip count is simply 6539 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6540 /// if the trip count is very large (>= 2^32). 6541 /// 6542 /// As explained in the comments for getSmallConstantTripCount, this assumes 6543 /// that control exits the loop via ExitingBlock. 6544 unsigned 6545 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6546 BasicBlock *ExitingBlock) { 6547 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6548 assert(L->isLoopExiting(ExitingBlock) && 6549 "Exiting block must actually branch out of the loop!"); 6550 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6551 if (ExitCount == getCouldNotCompute()) 6552 return 1; 6553 6554 // Get the trip count from the BE count by adding 1. 6555 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6556 6557 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6558 if (!TC) 6559 // Attempt to factor more general cases. Returns the greatest power of 6560 // two divisor. If overflow happens, the trip count expression is still 6561 // divisible by the greatest power of 2 divisor returned. 6562 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6563 6564 ConstantInt *Result = TC->getValue(); 6565 6566 // Guard against huge trip counts (this requires checking 6567 // for zero to handle the case where the trip count == -1 and the 6568 // addition wraps). 6569 if (!Result || Result->getValue().getActiveBits() > 32 || 6570 Result->getValue().getActiveBits() == 0) 6571 return 1; 6572 6573 return (unsigned)Result->getZExtValue(); 6574 } 6575 6576 /// Get the expression for the number of loop iterations for which this loop is 6577 /// guaranteed not to exit via ExitingBlock. Otherwise return 6578 /// SCEVCouldNotCompute. 6579 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6580 BasicBlock *ExitingBlock) { 6581 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6582 } 6583 6584 const SCEV * 6585 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6586 SCEVUnionPredicate &Preds) { 6587 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6588 } 6589 6590 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6591 return getBackedgeTakenInfo(L).getExact(L, this); 6592 } 6593 6594 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6595 /// known never to be less than the actual backedge taken count. 6596 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6597 return getBackedgeTakenInfo(L).getMax(this); 6598 } 6599 6600 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6601 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6602 } 6603 6604 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6605 static void 6606 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6607 BasicBlock *Header = L->getHeader(); 6608 6609 // Push all Loop-header PHIs onto the Worklist stack. 6610 for (PHINode &PN : Header->phis()) 6611 Worklist.push_back(&PN); 6612 } 6613 6614 const ScalarEvolution::BackedgeTakenInfo & 6615 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6616 auto &BTI = getBackedgeTakenInfo(L); 6617 if (BTI.hasFullInfo()) 6618 return BTI; 6619 6620 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6621 6622 if (!Pair.second) 6623 return Pair.first->second; 6624 6625 BackedgeTakenInfo Result = 6626 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6627 6628 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6629 } 6630 6631 const ScalarEvolution::BackedgeTakenInfo & 6632 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6633 // Initially insert an invalid entry for this loop. If the insertion 6634 // succeeds, proceed to actually compute a backedge-taken count and 6635 // update the value. The temporary CouldNotCompute value tells SCEV 6636 // code elsewhere that it shouldn't attempt to request a new 6637 // backedge-taken count, which could result in infinite recursion. 6638 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6639 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6640 if (!Pair.second) 6641 return Pair.first->second; 6642 6643 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6644 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6645 // must be cleared in this scope. 6646 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6647 6648 // In product build, there are no usage of statistic. 6649 (void)NumTripCountsComputed; 6650 (void)NumTripCountsNotComputed; 6651 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6652 const SCEV *BEExact = Result.getExact(L, this); 6653 if (BEExact != getCouldNotCompute()) { 6654 assert(isLoopInvariant(BEExact, L) && 6655 isLoopInvariant(Result.getMax(this), L) && 6656 "Computed backedge-taken count isn't loop invariant for loop!"); 6657 ++NumTripCountsComputed; 6658 } 6659 else if (Result.getMax(this) == getCouldNotCompute() && 6660 isa<PHINode>(L->getHeader()->begin())) { 6661 // Only count loops that have phi nodes as not being computable. 6662 ++NumTripCountsNotComputed; 6663 } 6664 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6665 6666 // Now that we know more about the trip count for this loop, forget any 6667 // existing SCEV values for PHI nodes in this loop since they are only 6668 // conservative estimates made without the benefit of trip count 6669 // information. This is similar to the code in forgetLoop, except that 6670 // it handles SCEVUnknown PHI nodes specially. 6671 if (Result.hasAnyInfo()) { 6672 SmallVector<Instruction *, 16> Worklist; 6673 PushLoopPHIs(L, Worklist); 6674 6675 SmallPtrSet<Instruction *, 8> Discovered; 6676 while (!Worklist.empty()) { 6677 Instruction *I = Worklist.pop_back_val(); 6678 6679 ValueExprMapType::iterator It = 6680 ValueExprMap.find_as(static_cast<Value *>(I)); 6681 if (It != ValueExprMap.end()) { 6682 const SCEV *Old = It->second; 6683 6684 // SCEVUnknown for a PHI either means that it has an unrecognized 6685 // structure, or it's a PHI that's in the progress of being computed 6686 // by createNodeForPHI. In the former case, additional loop trip 6687 // count information isn't going to change anything. In the later 6688 // case, createNodeForPHI will perform the necessary updates on its 6689 // own when it gets to that point. 6690 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6691 eraseValueFromMap(It->first); 6692 forgetMemoizedResults(Old); 6693 } 6694 if (PHINode *PN = dyn_cast<PHINode>(I)) 6695 ConstantEvolutionLoopExitValue.erase(PN); 6696 } 6697 6698 // Since we don't need to invalidate anything for correctness and we're 6699 // only invalidating to make SCEV's results more precise, we get to stop 6700 // early to avoid invalidating too much. This is especially important in 6701 // cases like: 6702 // 6703 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6704 // loop0: 6705 // %pn0 = phi 6706 // ... 6707 // loop1: 6708 // %pn1 = phi 6709 // ... 6710 // 6711 // where both loop0 and loop1's backedge taken count uses the SCEV 6712 // expression for %v. If we don't have the early stop below then in cases 6713 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6714 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6715 // count for loop1, effectively nullifying SCEV's trip count cache. 6716 for (auto *U : I->users()) 6717 if (auto *I = dyn_cast<Instruction>(U)) { 6718 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6719 if (LoopForUser && L->contains(LoopForUser) && 6720 Discovered.insert(I).second) 6721 Worklist.push_back(I); 6722 } 6723 } 6724 } 6725 6726 // Re-lookup the insert position, since the call to 6727 // computeBackedgeTakenCount above could result in a 6728 // recusive call to getBackedgeTakenInfo (on a different 6729 // loop), which would invalidate the iterator computed 6730 // earlier. 6731 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6732 } 6733 6734 void ScalarEvolution::forgetLoop(const Loop *L) { 6735 // Drop any stored trip count value. 6736 auto RemoveLoopFromBackedgeMap = 6737 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6738 auto BTCPos = Map.find(L); 6739 if (BTCPos != Map.end()) { 6740 BTCPos->second.clear(); 6741 Map.erase(BTCPos); 6742 } 6743 }; 6744 6745 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6746 SmallVector<Instruction *, 32> Worklist; 6747 SmallPtrSet<Instruction *, 16> Visited; 6748 6749 // Iterate over all the loops and sub-loops to drop SCEV information. 6750 while (!LoopWorklist.empty()) { 6751 auto *CurrL = LoopWorklist.pop_back_val(); 6752 6753 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6754 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6755 6756 // Drop information about predicated SCEV rewrites for this loop. 6757 for (auto I = PredicatedSCEVRewrites.begin(); 6758 I != PredicatedSCEVRewrites.end();) { 6759 std::pair<const SCEV *, const Loop *> Entry = I->first; 6760 if (Entry.second == CurrL) 6761 PredicatedSCEVRewrites.erase(I++); 6762 else 6763 ++I; 6764 } 6765 6766 auto LoopUsersItr = LoopUsers.find(CurrL); 6767 if (LoopUsersItr != LoopUsers.end()) { 6768 for (auto *S : LoopUsersItr->second) 6769 forgetMemoizedResults(S); 6770 LoopUsers.erase(LoopUsersItr); 6771 } 6772 6773 // Drop information about expressions based on loop-header PHIs. 6774 PushLoopPHIs(CurrL, Worklist); 6775 6776 while (!Worklist.empty()) { 6777 Instruction *I = Worklist.pop_back_val(); 6778 if (!Visited.insert(I).second) 6779 continue; 6780 6781 ValueExprMapType::iterator It = 6782 ValueExprMap.find_as(static_cast<Value *>(I)); 6783 if (It != ValueExprMap.end()) { 6784 eraseValueFromMap(It->first); 6785 forgetMemoizedResults(It->second); 6786 if (PHINode *PN = dyn_cast<PHINode>(I)) 6787 ConstantEvolutionLoopExitValue.erase(PN); 6788 } 6789 6790 PushDefUseChildren(I, Worklist); 6791 } 6792 6793 LoopPropertiesCache.erase(CurrL); 6794 // Forget all contained loops too, to avoid dangling entries in the 6795 // ValuesAtScopes map. 6796 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6797 } 6798 } 6799 6800 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6801 while (Loop *Parent = L->getParentLoop()) 6802 L = Parent; 6803 forgetLoop(L); 6804 } 6805 6806 void ScalarEvolution::forgetValue(Value *V) { 6807 Instruction *I = dyn_cast<Instruction>(V); 6808 if (!I) return; 6809 6810 // Drop information about expressions based on loop-header PHIs. 6811 SmallVector<Instruction *, 16> Worklist; 6812 Worklist.push_back(I); 6813 6814 SmallPtrSet<Instruction *, 8> Visited; 6815 while (!Worklist.empty()) { 6816 I = Worklist.pop_back_val(); 6817 if (!Visited.insert(I).second) 6818 continue; 6819 6820 ValueExprMapType::iterator It = 6821 ValueExprMap.find_as(static_cast<Value *>(I)); 6822 if (It != ValueExprMap.end()) { 6823 eraseValueFromMap(It->first); 6824 forgetMemoizedResults(It->second); 6825 if (PHINode *PN = dyn_cast<PHINode>(I)) 6826 ConstantEvolutionLoopExitValue.erase(PN); 6827 } 6828 6829 PushDefUseChildren(I, Worklist); 6830 } 6831 } 6832 6833 /// Get the exact loop backedge taken count considering all loop exits. A 6834 /// computable result can only be returned for loops with all exiting blocks 6835 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6836 /// is never skipped. This is a valid assumption as long as the loop exits via 6837 /// that test. For precise results, it is the caller's responsibility to specify 6838 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6839 const SCEV * 6840 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6841 SCEVUnionPredicate *Preds) const { 6842 // If any exits were not computable, the loop is not computable. 6843 if (!isComplete() || ExitNotTaken.empty()) 6844 return SE->getCouldNotCompute(); 6845 6846 const BasicBlock *Latch = L->getLoopLatch(); 6847 // All exiting blocks we have collected must dominate the only backedge. 6848 if (!Latch) 6849 return SE->getCouldNotCompute(); 6850 6851 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6852 // count is simply a minimum out of all these calculated exit counts. 6853 SmallVector<const SCEV *, 2> Ops; 6854 for (auto &ENT : ExitNotTaken) { 6855 const SCEV *BECount = ENT.ExactNotTaken; 6856 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6857 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6858 "We should only have known counts for exiting blocks that dominate " 6859 "latch!"); 6860 6861 Ops.push_back(BECount); 6862 6863 if (Preds && !ENT.hasAlwaysTruePredicate()) 6864 Preds->add(ENT.Predicate.get()); 6865 6866 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6867 "Predicate should be always true!"); 6868 } 6869 6870 return SE->getUMinFromMismatchedTypes(Ops); 6871 } 6872 6873 /// Get the exact not taken count for this loop exit. 6874 const SCEV * 6875 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6876 ScalarEvolution *SE) const { 6877 for (auto &ENT : ExitNotTaken) 6878 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6879 return ENT.ExactNotTaken; 6880 6881 return SE->getCouldNotCompute(); 6882 } 6883 6884 /// getMax - Get the max backedge taken count for the loop. 6885 const SCEV * 6886 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6887 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6888 return !ENT.hasAlwaysTruePredicate(); 6889 }; 6890 6891 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6892 return SE->getCouldNotCompute(); 6893 6894 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6895 "No point in having a non-constant max backedge taken count!"); 6896 return getMax(); 6897 } 6898 6899 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6900 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6901 return !ENT.hasAlwaysTruePredicate(); 6902 }; 6903 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6904 } 6905 6906 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6907 ScalarEvolution *SE) const { 6908 if (getMax() && getMax() != SE->getCouldNotCompute() && 6909 SE->hasOperand(getMax(), S)) 6910 return true; 6911 6912 for (auto &ENT : ExitNotTaken) 6913 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6914 SE->hasOperand(ENT.ExactNotTaken, S)) 6915 return true; 6916 6917 return false; 6918 } 6919 6920 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6921 : ExactNotTaken(E), MaxNotTaken(E) { 6922 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6923 isa<SCEVConstant>(MaxNotTaken)) && 6924 "No point in having a non-constant max backedge taken count!"); 6925 } 6926 6927 ScalarEvolution::ExitLimit::ExitLimit( 6928 const SCEV *E, const SCEV *M, bool MaxOrZero, 6929 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6930 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6931 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6932 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6933 "Exact is not allowed to be less precise than Max"); 6934 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6935 isa<SCEVConstant>(MaxNotTaken)) && 6936 "No point in having a non-constant max backedge taken count!"); 6937 for (auto *PredSet : PredSetList) 6938 for (auto *P : *PredSet) 6939 addPredicate(P); 6940 } 6941 6942 ScalarEvolution::ExitLimit::ExitLimit( 6943 const SCEV *E, const SCEV *M, bool MaxOrZero, 6944 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6945 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6946 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6947 isa<SCEVConstant>(MaxNotTaken)) && 6948 "No point in having a non-constant max backedge taken count!"); 6949 } 6950 6951 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6952 bool MaxOrZero) 6953 : ExitLimit(E, M, MaxOrZero, None) { 6954 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6955 isa<SCEVConstant>(MaxNotTaken)) && 6956 "No point in having a non-constant max backedge taken count!"); 6957 } 6958 6959 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6960 /// computable exit into a persistent ExitNotTakenInfo array. 6961 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6962 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6963 &&ExitCounts, 6964 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6965 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6966 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6967 6968 ExitNotTaken.reserve(ExitCounts.size()); 6969 std::transform( 6970 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6971 [&](const EdgeExitInfo &EEI) { 6972 BasicBlock *ExitBB = EEI.first; 6973 const ExitLimit &EL = EEI.second; 6974 if (EL.Predicates.empty()) 6975 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6976 6977 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6978 for (auto *Pred : EL.Predicates) 6979 Predicate->add(Pred); 6980 6981 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6982 }); 6983 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6984 "No point in having a non-constant max backedge taken count!"); 6985 } 6986 6987 /// Invalidate this result and free the ExitNotTakenInfo array. 6988 void ScalarEvolution::BackedgeTakenInfo::clear() { 6989 ExitNotTaken.clear(); 6990 } 6991 6992 /// Compute the number of times the backedge of the specified loop will execute. 6993 ScalarEvolution::BackedgeTakenInfo 6994 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6995 bool AllowPredicates) { 6996 SmallVector<BasicBlock *, 8> ExitingBlocks; 6997 L->getExitingBlocks(ExitingBlocks); 6998 6999 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7000 7001 SmallVector<EdgeExitInfo, 4> ExitCounts; 7002 bool CouldComputeBECount = true; 7003 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7004 const SCEV *MustExitMaxBECount = nullptr; 7005 const SCEV *MayExitMaxBECount = nullptr; 7006 bool MustExitMaxOrZero = false; 7007 7008 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7009 // and compute maxBECount. 7010 // Do a union of all the predicates here. 7011 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7012 BasicBlock *ExitBB = ExitingBlocks[i]; 7013 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7014 7015 assert((AllowPredicates || EL.Predicates.empty()) && 7016 "Predicated exit limit when predicates are not allowed!"); 7017 7018 // 1. For each exit that can be computed, add an entry to ExitCounts. 7019 // CouldComputeBECount is true only if all exits can be computed. 7020 if (EL.ExactNotTaken == getCouldNotCompute()) 7021 // We couldn't compute an exact value for this exit, so 7022 // we won't be able to compute an exact value for the loop. 7023 CouldComputeBECount = false; 7024 else 7025 ExitCounts.emplace_back(ExitBB, EL); 7026 7027 // 2. Derive the loop's MaxBECount from each exit's max number of 7028 // non-exiting iterations. Partition the loop exits into two kinds: 7029 // LoopMustExits and LoopMayExits. 7030 // 7031 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7032 // is a LoopMayExit. If any computable LoopMustExit is found, then 7033 // MaxBECount is the minimum EL.MaxNotTaken of computable 7034 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7035 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7036 // computable EL.MaxNotTaken. 7037 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7038 DT.dominates(ExitBB, Latch)) { 7039 if (!MustExitMaxBECount) { 7040 MustExitMaxBECount = EL.MaxNotTaken; 7041 MustExitMaxOrZero = EL.MaxOrZero; 7042 } else { 7043 MustExitMaxBECount = 7044 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7045 } 7046 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7047 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7048 MayExitMaxBECount = EL.MaxNotTaken; 7049 else { 7050 MayExitMaxBECount = 7051 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7052 } 7053 } 7054 } 7055 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7056 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7057 // The loop backedge will be taken the maximum or zero times if there's 7058 // a single exit that must be taken the maximum or zero times. 7059 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7060 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7061 MaxBECount, MaxOrZero); 7062 } 7063 7064 ScalarEvolution::ExitLimit 7065 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7066 bool AllowPredicates) { 7067 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7068 // If our exiting block does not dominate the latch, then its connection with 7069 // loop's exit limit may be far from trivial. 7070 const BasicBlock *Latch = L->getLoopLatch(); 7071 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7072 return getCouldNotCompute(); 7073 7074 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7075 TerminatorInst *Term = ExitingBlock->getTerminator(); 7076 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7077 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7078 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7079 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7080 "It should have one successor in loop and one exit block!"); 7081 // Proceed to the next level to examine the exit condition expression. 7082 return computeExitLimitFromCond( 7083 L, BI->getCondition(), ExitIfTrue, 7084 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7085 } 7086 7087 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7088 // For switch, make sure that there is a single exit from the loop. 7089 BasicBlock *Exit = nullptr; 7090 for (auto *SBB : successors(ExitingBlock)) 7091 if (!L->contains(SBB)) { 7092 if (Exit) // Multiple exit successors. 7093 return getCouldNotCompute(); 7094 Exit = SBB; 7095 } 7096 assert(Exit && "Exiting block must have at least one exit"); 7097 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7098 /*ControlsExit=*/IsOnlyExit); 7099 } 7100 7101 return getCouldNotCompute(); 7102 } 7103 7104 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7105 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7106 bool ControlsExit, bool AllowPredicates) { 7107 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7108 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7109 ControlsExit, AllowPredicates); 7110 } 7111 7112 Optional<ScalarEvolution::ExitLimit> 7113 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7114 bool ExitIfTrue, bool ControlsExit, 7115 bool AllowPredicates) { 7116 (void)this->L; 7117 (void)this->ExitIfTrue; 7118 (void)this->AllowPredicates; 7119 7120 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7121 this->AllowPredicates == AllowPredicates && 7122 "Variance in assumed invariant key components!"); 7123 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7124 if (Itr == TripCountMap.end()) 7125 return None; 7126 return Itr->second; 7127 } 7128 7129 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7130 bool ExitIfTrue, 7131 bool ControlsExit, 7132 bool AllowPredicates, 7133 const ExitLimit &EL) { 7134 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7135 this->AllowPredicates == AllowPredicates && 7136 "Variance in assumed invariant key components!"); 7137 7138 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7139 assert(InsertResult.second && "Expected successful insertion!"); 7140 (void)InsertResult; 7141 (void)ExitIfTrue; 7142 } 7143 7144 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7145 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7146 bool ControlsExit, bool AllowPredicates) { 7147 7148 if (auto MaybeEL = 7149 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7150 return *MaybeEL; 7151 7152 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7153 ControlsExit, AllowPredicates); 7154 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7155 return EL; 7156 } 7157 7158 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7159 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7160 bool ControlsExit, bool AllowPredicates) { 7161 // Check if the controlling expression for this loop is an And or Or. 7162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7163 if (BO->getOpcode() == Instruction::And) { 7164 // Recurse on the operands of the and. 7165 bool EitherMayExit = !ExitIfTrue; 7166 ExitLimit EL0 = computeExitLimitFromCondCached( 7167 Cache, L, BO->getOperand(0), ExitIfTrue, 7168 ControlsExit && !EitherMayExit, AllowPredicates); 7169 ExitLimit EL1 = computeExitLimitFromCondCached( 7170 Cache, L, BO->getOperand(1), ExitIfTrue, 7171 ControlsExit && !EitherMayExit, AllowPredicates); 7172 const SCEV *BECount = getCouldNotCompute(); 7173 const SCEV *MaxBECount = getCouldNotCompute(); 7174 if (EitherMayExit) { 7175 // Both conditions must be true for the loop to continue executing. 7176 // Choose the less conservative count. 7177 if (EL0.ExactNotTaken == getCouldNotCompute() || 7178 EL1.ExactNotTaken == getCouldNotCompute()) 7179 BECount = getCouldNotCompute(); 7180 else 7181 BECount = 7182 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7183 if (EL0.MaxNotTaken == getCouldNotCompute()) 7184 MaxBECount = EL1.MaxNotTaken; 7185 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7186 MaxBECount = EL0.MaxNotTaken; 7187 else 7188 MaxBECount = 7189 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7190 } else { 7191 // Both conditions must be true at the same time for the loop to exit. 7192 // For now, be conservative. 7193 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7194 MaxBECount = EL0.MaxNotTaken; 7195 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7196 BECount = EL0.ExactNotTaken; 7197 } 7198 7199 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7200 // to be more aggressive when computing BECount than when computing 7201 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7202 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7203 // to not. 7204 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7205 !isa<SCEVCouldNotCompute>(BECount)) 7206 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7207 7208 return ExitLimit(BECount, MaxBECount, false, 7209 {&EL0.Predicates, &EL1.Predicates}); 7210 } 7211 if (BO->getOpcode() == Instruction::Or) { 7212 // Recurse on the operands of the or. 7213 bool EitherMayExit = ExitIfTrue; 7214 ExitLimit EL0 = computeExitLimitFromCondCached( 7215 Cache, L, BO->getOperand(0), ExitIfTrue, 7216 ControlsExit && !EitherMayExit, AllowPredicates); 7217 ExitLimit EL1 = computeExitLimitFromCondCached( 7218 Cache, L, BO->getOperand(1), ExitIfTrue, 7219 ControlsExit && !EitherMayExit, AllowPredicates); 7220 const SCEV *BECount = getCouldNotCompute(); 7221 const SCEV *MaxBECount = getCouldNotCompute(); 7222 if (EitherMayExit) { 7223 // Both conditions must be false for the loop to continue executing. 7224 // Choose the less conservative count. 7225 if (EL0.ExactNotTaken == getCouldNotCompute() || 7226 EL1.ExactNotTaken == getCouldNotCompute()) 7227 BECount = getCouldNotCompute(); 7228 else 7229 BECount = 7230 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7231 if (EL0.MaxNotTaken == getCouldNotCompute()) 7232 MaxBECount = EL1.MaxNotTaken; 7233 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7234 MaxBECount = EL0.MaxNotTaken; 7235 else 7236 MaxBECount = 7237 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7238 } else { 7239 // Both conditions must be false at the same time for the loop to exit. 7240 // For now, be conservative. 7241 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7242 MaxBECount = EL0.MaxNotTaken; 7243 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7244 BECount = EL0.ExactNotTaken; 7245 } 7246 7247 return ExitLimit(BECount, MaxBECount, false, 7248 {&EL0.Predicates, &EL1.Predicates}); 7249 } 7250 } 7251 7252 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7253 // Proceed to the next level to examine the icmp. 7254 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7255 ExitLimit EL = 7256 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7257 if (EL.hasFullInfo() || !AllowPredicates) 7258 return EL; 7259 7260 // Try again, but use SCEV predicates this time. 7261 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7262 /*AllowPredicates=*/true); 7263 } 7264 7265 // Check for a constant condition. These are normally stripped out by 7266 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7267 // preserve the CFG and is temporarily leaving constant conditions 7268 // in place. 7269 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7270 if (ExitIfTrue == !CI->getZExtValue()) 7271 // The backedge is always taken. 7272 return getCouldNotCompute(); 7273 else 7274 // The backedge is never taken. 7275 return getZero(CI->getType()); 7276 } 7277 7278 // If it's not an integer or pointer comparison then compute it the hard way. 7279 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7280 } 7281 7282 ScalarEvolution::ExitLimit 7283 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7284 ICmpInst *ExitCond, 7285 bool ExitIfTrue, 7286 bool ControlsExit, 7287 bool AllowPredicates) { 7288 // If the condition was exit on true, convert the condition to exit on false 7289 ICmpInst::Predicate Pred; 7290 if (!ExitIfTrue) 7291 Pred = ExitCond->getPredicate(); 7292 else 7293 Pred = ExitCond->getInversePredicate(); 7294 const ICmpInst::Predicate OriginalPred = Pred; 7295 7296 // Handle common loops like: for (X = "string"; *X; ++X) 7297 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7298 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7299 ExitLimit ItCnt = 7300 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7301 if (ItCnt.hasAnyInfo()) 7302 return ItCnt; 7303 } 7304 7305 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7306 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7307 7308 // Try to evaluate any dependencies out of the loop. 7309 LHS = getSCEVAtScope(LHS, L); 7310 RHS = getSCEVAtScope(RHS, L); 7311 7312 // At this point, we would like to compute how many iterations of the 7313 // loop the predicate will return true for these inputs. 7314 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7315 // If there is a loop-invariant, force it into the RHS. 7316 std::swap(LHS, RHS); 7317 Pred = ICmpInst::getSwappedPredicate(Pred); 7318 } 7319 7320 // Simplify the operands before analyzing them. 7321 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7322 7323 // If we have a comparison of a chrec against a constant, try to use value 7324 // ranges to answer this query. 7325 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7326 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7327 if (AddRec->getLoop() == L) { 7328 // Form the constant range. 7329 ConstantRange CompRange = 7330 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7331 7332 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7333 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7334 } 7335 7336 switch (Pred) { 7337 case ICmpInst::ICMP_NE: { // while (X != Y) 7338 // Convert to: while (X-Y != 0) 7339 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7340 AllowPredicates); 7341 if (EL.hasAnyInfo()) return EL; 7342 break; 7343 } 7344 case ICmpInst::ICMP_EQ: { // while (X == Y) 7345 // Convert to: while (X-Y == 0) 7346 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7347 if (EL.hasAnyInfo()) return EL; 7348 break; 7349 } 7350 case ICmpInst::ICMP_SLT: 7351 case ICmpInst::ICMP_ULT: { // while (X < Y) 7352 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7353 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7354 AllowPredicates); 7355 if (EL.hasAnyInfo()) return EL; 7356 break; 7357 } 7358 case ICmpInst::ICMP_SGT: 7359 case ICmpInst::ICMP_UGT: { // while (X > Y) 7360 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7361 ExitLimit EL = 7362 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7363 AllowPredicates); 7364 if (EL.hasAnyInfo()) return EL; 7365 break; 7366 } 7367 default: 7368 break; 7369 } 7370 7371 auto *ExhaustiveCount = 7372 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7373 7374 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7375 return ExhaustiveCount; 7376 7377 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7378 ExitCond->getOperand(1), L, OriginalPred); 7379 } 7380 7381 ScalarEvolution::ExitLimit 7382 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7383 SwitchInst *Switch, 7384 BasicBlock *ExitingBlock, 7385 bool ControlsExit) { 7386 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7387 7388 // Give up if the exit is the default dest of a switch. 7389 if (Switch->getDefaultDest() == ExitingBlock) 7390 return getCouldNotCompute(); 7391 7392 assert(L->contains(Switch->getDefaultDest()) && 7393 "Default case must not exit the loop!"); 7394 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7395 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7396 7397 // while (X != Y) --> while (X-Y != 0) 7398 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7399 if (EL.hasAnyInfo()) 7400 return EL; 7401 7402 return getCouldNotCompute(); 7403 } 7404 7405 static ConstantInt * 7406 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7407 ScalarEvolution &SE) { 7408 const SCEV *InVal = SE.getConstant(C); 7409 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7410 assert(isa<SCEVConstant>(Val) && 7411 "Evaluation of SCEV at constant didn't fold correctly?"); 7412 return cast<SCEVConstant>(Val)->getValue(); 7413 } 7414 7415 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7416 /// compute the backedge execution count. 7417 ScalarEvolution::ExitLimit 7418 ScalarEvolution::computeLoadConstantCompareExitLimit( 7419 LoadInst *LI, 7420 Constant *RHS, 7421 const Loop *L, 7422 ICmpInst::Predicate predicate) { 7423 if (LI->isVolatile()) return getCouldNotCompute(); 7424 7425 // Check to see if the loaded pointer is a getelementptr of a global. 7426 // TODO: Use SCEV instead of manually grubbing with GEPs. 7427 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7428 if (!GEP) return getCouldNotCompute(); 7429 7430 // Make sure that it is really a constant global we are gepping, with an 7431 // initializer, and make sure the first IDX is really 0. 7432 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7433 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7434 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7435 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7436 return getCouldNotCompute(); 7437 7438 // Okay, we allow one non-constant index into the GEP instruction. 7439 Value *VarIdx = nullptr; 7440 std::vector<Constant*> Indexes; 7441 unsigned VarIdxNum = 0; 7442 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7443 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7444 Indexes.push_back(CI); 7445 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7446 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7447 VarIdx = GEP->getOperand(i); 7448 VarIdxNum = i-2; 7449 Indexes.push_back(nullptr); 7450 } 7451 7452 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7453 if (!VarIdx) 7454 return getCouldNotCompute(); 7455 7456 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7457 // Check to see if X is a loop variant variable value now. 7458 const SCEV *Idx = getSCEV(VarIdx); 7459 Idx = getSCEVAtScope(Idx, L); 7460 7461 // We can only recognize very limited forms of loop index expressions, in 7462 // particular, only affine AddRec's like {C1,+,C2}. 7463 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7464 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7465 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7466 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7467 return getCouldNotCompute(); 7468 7469 unsigned MaxSteps = MaxBruteForceIterations; 7470 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7471 ConstantInt *ItCst = ConstantInt::get( 7472 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7473 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7474 7475 // Form the GEP offset. 7476 Indexes[VarIdxNum] = Val; 7477 7478 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7479 Indexes); 7480 if (!Result) break; // Cannot compute! 7481 7482 // Evaluate the condition for this iteration. 7483 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7484 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7485 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7486 ++NumArrayLenItCounts; 7487 return getConstant(ItCst); // Found terminating iteration! 7488 } 7489 } 7490 return getCouldNotCompute(); 7491 } 7492 7493 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7494 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7495 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7496 if (!RHS) 7497 return getCouldNotCompute(); 7498 7499 const BasicBlock *Latch = L->getLoopLatch(); 7500 if (!Latch) 7501 return getCouldNotCompute(); 7502 7503 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7504 if (!Predecessor) 7505 return getCouldNotCompute(); 7506 7507 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7508 // Return LHS in OutLHS and shift_opt in OutOpCode. 7509 auto MatchPositiveShift = 7510 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7511 7512 using namespace PatternMatch; 7513 7514 ConstantInt *ShiftAmt; 7515 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7516 OutOpCode = Instruction::LShr; 7517 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7518 OutOpCode = Instruction::AShr; 7519 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7520 OutOpCode = Instruction::Shl; 7521 else 7522 return false; 7523 7524 return ShiftAmt->getValue().isStrictlyPositive(); 7525 }; 7526 7527 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7528 // 7529 // loop: 7530 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7531 // %iv.shifted = lshr i32 %iv, <positive constant> 7532 // 7533 // Return true on a successful match. Return the corresponding PHI node (%iv 7534 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7535 auto MatchShiftRecurrence = 7536 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7537 Optional<Instruction::BinaryOps> PostShiftOpCode; 7538 7539 { 7540 Instruction::BinaryOps OpC; 7541 Value *V; 7542 7543 // If we encounter a shift instruction, "peel off" the shift operation, 7544 // and remember that we did so. Later when we inspect %iv's backedge 7545 // value, we will make sure that the backedge value uses the same 7546 // operation. 7547 // 7548 // Note: the peeled shift operation does not have to be the same 7549 // instruction as the one feeding into the PHI's backedge value. We only 7550 // really care about it being the same *kind* of shift instruction -- 7551 // that's all that is required for our later inferences to hold. 7552 if (MatchPositiveShift(LHS, V, OpC)) { 7553 PostShiftOpCode = OpC; 7554 LHS = V; 7555 } 7556 } 7557 7558 PNOut = dyn_cast<PHINode>(LHS); 7559 if (!PNOut || PNOut->getParent() != L->getHeader()) 7560 return false; 7561 7562 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7563 Value *OpLHS; 7564 7565 return 7566 // The backedge value for the PHI node must be a shift by a positive 7567 // amount 7568 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7569 7570 // of the PHI node itself 7571 OpLHS == PNOut && 7572 7573 // and the kind of shift should be match the kind of shift we peeled 7574 // off, if any. 7575 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7576 }; 7577 7578 PHINode *PN; 7579 Instruction::BinaryOps OpCode; 7580 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7581 return getCouldNotCompute(); 7582 7583 const DataLayout &DL = getDataLayout(); 7584 7585 // The key rationale for this optimization is that for some kinds of shift 7586 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7587 // within a finite number of iterations. If the condition guarding the 7588 // backedge (in the sense that the backedge is taken if the condition is true) 7589 // is false for the value the shift recurrence stabilizes to, then we know 7590 // that the backedge is taken only a finite number of times. 7591 7592 ConstantInt *StableValue = nullptr; 7593 switch (OpCode) { 7594 default: 7595 llvm_unreachable("Impossible case!"); 7596 7597 case Instruction::AShr: { 7598 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7599 // bitwidth(K) iterations. 7600 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7601 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7602 Predecessor->getTerminator(), &DT); 7603 auto *Ty = cast<IntegerType>(RHS->getType()); 7604 if (Known.isNonNegative()) 7605 StableValue = ConstantInt::get(Ty, 0); 7606 else if (Known.isNegative()) 7607 StableValue = ConstantInt::get(Ty, -1, true); 7608 else 7609 return getCouldNotCompute(); 7610 7611 break; 7612 } 7613 case Instruction::LShr: 7614 case Instruction::Shl: 7615 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7616 // stabilize to 0 in at most bitwidth(K) iterations. 7617 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7618 break; 7619 } 7620 7621 auto *Result = 7622 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7623 assert(Result->getType()->isIntegerTy(1) && 7624 "Otherwise cannot be an operand to a branch instruction"); 7625 7626 if (Result->isZeroValue()) { 7627 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7628 const SCEV *UpperBound = 7629 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7630 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7631 } 7632 7633 return getCouldNotCompute(); 7634 } 7635 7636 /// Return true if we can constant fold an instruction of the specified type, 7637 /// assuming that all operands were constants. 7638 static bool CanConstantFold(const Instruction *I) { 7639 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7640 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7641 isa<LoadInst>(I)) 7642 return true; 7643 7644 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7645 if (const Function *F = CI->getCalledFunction()) 7646 return canConstantFoldCallTo(CI, F); 7647 return false; 7648 } 7649 7650 /// Determine whether this instruction can constant evolve within this loop 7651 /// assuming its operands can all constant evolve. 7652 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7653 // An instruction outside of the loop can't be derived from a loop PHI. 7654 if (!L->contains(I)) return false; 7655 7656 if (isa<PHINode>(I)) { 7657 // We don't currently keep track of the control flow needed to evaluate 7658 // PHIs, so we cannot handle PHIs inside of loops. 7659 return L->getHeader() == I->getParent(); 7660 } 7661 7662 // If we won't be able to constant fold this expression even if the operands 7663 // are constants, bail early. 7664 return CanConstantFold(I); 7665 } 7666 7667 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7668 /// recursing through each instruction operand until reaching a loop header phi. 7669 static PHINode * 7670 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7671 DenseMap<Instruction *, PHINode *> &PHIMap, 7672 unsigned Depth) { 7673 if (Depth > MaxConstantEvolvingDepth) 7674 return nullptr; 7675 7676 // Otherwise, we can evaluate this instruction if all of its operands are 7677 // constant or derived from a PHI node themselves. 7678 PHINode *PHI = nullptr; 7679 for (Value *Op : UseInst->operands()) { 7680 if (isa<Constant>(Op)) continue; 7681 7682 Instruction *OpInst = dyn_cast<Instruction>(Op); 7683 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7684 7685 PHINode *P = dyn_cast<PHINode>(OpInst); 7686 if (!P) 7687 // If this operand is already visited, reuse the prior result. 7688 // We may have P != PHI if this is the deepest point at which the 7689 // inconsistent paths meet. 7690 P = PHIMap.lookup(OpInst); 7691 if (!P) { 7692 // Recurse and memoize the results, whether a phi is found or not. 7693 // This recursive call invalidates pointers into PHIMap. 7694 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7695 PHIMap[OpInst] = P; 7696 } 7697 if (!P) 7698 return nullptr; // Not evolving from PHI 7699 if (PHI && PHI != P) 7700 return nullptr; // Evolving from multiple different PHIs. 7701 PHI = P; 7702 } 7703 // This is a expression evolving from a constant PHI! 7704 return PHI; 7705 } 7706 7707 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7708 /// in the loop that V is derived from. We allow arbitrary operations along the 7709 /// way, but the operands of an operation must either be constants or a value 7710 /// derived from a constant PHI. If this expression does not fit with these 7711 /// constraints, return null. 7712 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7713 Instruction *I = dyn_cast<Instruction>(V); 7714 if (!I || !canConstantEvolve(I, L)) return nullptr; 7715 7716 if (PHINode *PN = dyn_cast<PHINode>(I)) 7717 return PN; 7718 7719 // Record non-constant instructions contained by the loop. 7720 DenseMap<Instruction *, PHINode *> PHIMap; 7721 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7722 } 7723 7724 /// EvaluateExpression - Given an expression that passes the 7725 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7726 /// in the loop has the value PHIVal. If we can't fold this expression for some 7727 /// reason, return null. 7728 static Constant *EvaluateExpression(Value *V, const Loop *L, 7729 DenseMap<Instruction *, Constant *> &Vals, 7730 const DataLayout &DL, 7731 const TargetLibraryInfo *TLI) { 7732 // Convenient constant check, but redundant for recursive calls. 7733 if (Constant *C = dyn_cast<Constant>(V)) return C; 7734 Instruction *I = dyn_cast<Instruction>(V); 7735 if (!I) return nullptr; 7736 7737 if (Constant *C = Vals.lookup(I)) return C; 7738 7739 // An instruction inside the loop depends on a value outside the loop that we 7740 // weren't given a mapping for, or a value such as a call inside the loop. 7741 if (!canConstantEvolve(I, L)) return nullptr; 7742 7743 // An unmapped PHI can be due to a branch or another loop inside this loop, 7744 // or due to this not being the initial iteration through a loop where we 7745 // couldn't compute the evolution of this particular PHI last time. 7746 if (isa<PHINode>(I)) return nullptr; 7747 7748 std::vector<Constant*> Operands(I->getNumOperands()); 7749 7750 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7751 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7752 if (!Operand) { 7753 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7754 if (!Operands[i]) return nullptr; 7755 continue; 7756 } 7757 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7758 Vals[Operand] = C; 7759 if (!C) return nullptr; 7760 Operands[i] = C; 7761 } 7762 7763 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7764 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7765 Operands[1], DL, TLI); 7766 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7767 if (!LI->isVolatile()) 7768 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7769 } 7770 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7771 } 7772 7773 7774 // If every incoming value to PN except the one for BB is a specific Constant, 7775 // return that, else return nullptr. 7776 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7777 Constant *IncomingVal = nullptr; 7778 7779 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7780 if (PN->getIncomingBlock(i) == BB) 7781 continue; 7782 7783 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7784 if (!CurrentVal) 7785 return nullptr; 7786 7787 if (IncomingVal != CurrentVal) { 7788 if (IncomingVal) 7789 return nullptr; 7790 IncomingVal = CurrentVal; 7791 } 7792 } 7793 7794 return IncomingVal; 7795 } 7796 7797 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7798 /// in the header of its containing loop, we know the loop executes a 7799 /// constant number of times, and the PHI node is just a recurrence 7800 /// involving constants, fold it. 7801 Constant * 7802 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7803 const APInt &BEs, 7804 const Loop *L) { 7805 auto I = ConstantEvolutionLoopExitValue.find(PN); 7806 if (I != ConstantEvolutionLoopExitValue.end()) 7807 return I->second; 7808 7809 if (BEs.ugt(MaxBruteForceIterations)) 7810 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7811 7812 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7813 7814 DenseMap<Instruction *, Constant *> CurrentIterVals; 7815 BasicBlock *Header = L->getHeader(); 7816 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7817 7818 BasicBlock *Latch = L->getLoopLatch(); 7819 if (!Latch) 7820 return nullptr; 7821 7822 for (PHINode &PHI : Header->phis()) { 7823 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7824 CurrentIterVals[&PHI] = StartCST; 7825 } 7826 if (!CurrentIterVals.count(PN)) 7827 return RetVal = nullptr; 7828 7829 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7830 7831 // Execute the loop symbolically to determine the exit value. 7832 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7833 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7834 7835 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7836 unsigned IterationNum = 0; 7837 const DataLayout &DL = getDataLayout(); 7838 for (; ; ++IterationNum) { 7839 if (IterationNum == NumIterations) 7840 return RetVal = CurrentIterVals[PN]; // Got exit value! 7841 7842 // Compute the value of the PHIs for the next iteration. 7843 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7844 DenseMap<Instruction *, Constant *> NextIterVals; 7845 Constant *NextPHI = 7846 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7847 if (!NextPHI) 7848 return nullptr; // Couldn't evaluate! 7849 NextIterVals[PN] = NextPHI; 7850 7851 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7852 7853 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7854 // cease to be able to evaluate one of them or if they stop evolving, 7855 // because that doesn't necessarily prevent us from computing PN. 7856 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7857 for (const auto &I : CurrentIterVals) { 7858 PHINode *PHI = dyn_cast<PHINode>(I.first); 7859 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7860 PHIsToCompute.emplace_back(PHI, I.second); 7861 } 7862 // We use two distinct loops because EvaluateExpression may invalidate any 7863 // iterators into CurrentIterVals. 7864 for (const auto &I : PHIsToCompute) { 7865 PHINode *PHI = I.first; 7866 Constant *&NextPHI = NextIterVals[PHI]; 7867 if (!NextPHI) { // Not already computed. 7868 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7869 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7870 } 7871 if (NextPHI != I.second) 7872 StoppedEvolving = false; 7873 } 7874 7875 // If all entries in CurrentIterVals == NextIterVals then we can stop 7876 // iterating, the loop can't continue to change. 7877 if (StoppedEvolving) 7878 return RetVal = CurrentIterVals[PN]; 7879 7880 CurrentIterVals.swap(NextIterVals); 7881 } 7882 } 7883 7884 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7885 Value *Cond, 7886 bool ExitWhen) { 7887 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7888 if (!PN) return getCouldNotCompute(); 7889 7890 // If the loop is canonicalized, the PHI will have exactly two entries. 7891 // That's the only form we support here. 7892 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7893 7894 DenseMap<Instruction *, Constant *> CurrentIterVals; 7895 BasicBlock *Header = L->getHeader(); 7896 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7897 7898 BasicBlock *Latch = L->getLoopLatch(); 7899 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7900 7901 for (PHINode &PHI : Header->phis()) { 7902 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7903 CurrentIterVals[&PHI] = StartCST; 7904 } 7905 if (!CurrentIterVals.count(PN)) 7906 return getCouldNotCompute(); 7907 7908 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7909 // the loop symbolically to determine when the condition gets a value of 7910 // "ExitWhen". 7911 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7912 const DataLayout &DL = getDataLayout(); 7913 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7914 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7915 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7916 7917 // Couldn't symbolically evaluate. 7918 if (!CondVal) return getCouldNotCompute(); 7919 7920 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7921 ++NumBruteForceTripCountsComputed; 7922 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7923 } 7924 7925 // Update all the PHI nodes for the next iteration. 7926 DenseMap<Instruction *, Constant *> NextIterVals; 7927 7928 // Create a list of which PHIs we need to compute. We want to do this before 7929 // calling EvaluateExpression on them because that may invalidate iterators 7930 // into CurrentIterVals. 7931 SmallVector<PHINode *, 8> PHIsToCompute; 7932 for (const auto &I : CurrentIterVals) { 7933 PHINode *PHI = dyn_cast<PHINode>(I.first); 7934 if (!PHI || PHI->getParent() != Header) continue; 7935 PHIsToCompute.push_back(PHI); 7936 } 7937 for (PHINode *PHI : PHIsToCompute) { 7938 Constant *&NextPHI = NextIterVals[PHI]; 7939 if (NextPHI) continue; // Already computed! 7940 7941 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7942 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7943 } 7944 CurrentIterVals.swap(NextIterVals); 7945 } 7946 7947 // Too many iterations were needed to evaluate. 7948 return getCouldNotCompute(); 7949 } 7950 7951 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7952 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7953 ValuesAtScopes[V]; 7954 // Check to see if we've folded this expression at this loop before. 7955 for (auto &LS : Values) 7956 if (LS.first == L) 7957 return LS.second ? LS.second : V; 7958 7959 Values.emplace_back(L, nullptr); 7960 7961 // Otherwise compute it. 7962 const SCEV *C = computeSCEVAtScope(V, L); 7963 for (auto &LS : reverse(ValuesAtScopes[V])) 7964 if (LS.first == L) { 7965 LS.second = C; 7966 break; 7967 } 7968 return C; 7969 } 7970 7971 /// This builds up a Constant using the ConstantExpr interface. That way, we 7972 /// will return Constants for objects which aren't represented by a 7973 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7974 /// Returns NULL if the SCEV isn't representable as a Constant. 7975 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7976 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7977 case scCouldNotCompute: 7978 case scAddRecExpr: 7979 break; 7980 case scConstant: 7981 return cast<SCEVConstant>(V)->getValue(); 7982 case scUnknown: 7983 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7984 case scSignExtend: { 7985 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7986 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7987 return ConstantExpr::getSExt(CastOp, SS->getType()); 7988 break; 7989 } 7990 case scZeroExtend: { 7991 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7992 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7993 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7994 break; 7995 } 7996 case scTruncate: { 7997 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7998 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7999 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8000 break; 8001 } 8002 case scAddExpr: { 8003 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8004 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8005 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8006 unsigned AS = PTy->getAddressSpace(); 8007 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8008 C = ConstantExpr::getBitCast(C, DestPtrTy); 8009 } 8010 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8011 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8012 if (!C2) return nullptr; 8013 8014 // First pointer! 8015 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8016 unsigned AS = C2->getType()->getPointerAddressSpace(); 8017 std::swap(C, C2); 8018 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8019 // The offsets have been converted to bytes. We can add bytes to an 8020 // i8* by GEP with the byte count in the first index. 8021 C = ConstantExpr::getBitCast(C, DestPtrTy); 8022 } 8023 8024 // Don't bother trying to sum two pointers. We probably can't 8025 // statically compute a load that results from it anyway. 8026 if (C2->getType()->isPointerTy()) 8027 return nullptr; 8028 8029 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8030 if (PTy->getElementType()->isStructTy()) 8031 C2 = ConstantExpr::getIntegerCast( 8032 C2, Type::getInt32Ty(C->getContext()), true); 8033 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8034 } else 8035 C = ConstantExpr::getAdd(C, C2); 8036 } 8037 return C; 8038 } 8039 break; 8040 } 8041 case scMulExpr: { 8042 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8043 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8044 // Don't bother with pointers at all. 8045 if (C->getType()->isPointerTy()) return nullptr; 8046 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8047 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8048 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8049 C = ConstantExpr::getMul(C, C2); 8050 } 8051 return C; 8052 } 8053 break; 8054 } 8055 case scUDivExpr: { 8056 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8057 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8058 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8059 if (LHS->getType() == RHS->getType()) 8060 return ConstantExpr::getUDiv(LHS, RHS); 8061 break; 8062 } 8063 case scSMaxExpr: 8064 case scUMaxExpr: 8065 break; // TODO: smax, umax. 8066 } 8067 return nullptr; 8068 } 8069 8070 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8071 if (isa<SCEVConstant>(V)) return V; 8072 8073 // If this instruction is evolved from a constant-evolving PHI, compute the 8074 // exit value from the loop without using SCEVs. 8075 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8076 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8077 const Loop *LI = this->LI[I->getParent()]; 8078 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 8079 if (PHINode *PN = dyn_cast<PHINode>(I)) 8080 if (PN->getParent() == LI->getHeader()) { 8081 // Okay, there is no closed form solution for the PHI node. Check 8082 // to see if the loop that contains it has a known backedge-taken 8083 // count. If so, we may be able to force computation of the exit 8084 // value. 8085 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8086 if (const SCEVConstant *BTCC = 8087 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8088 8089 // This trivial case can show up in some degenerate cases where 8090 // the incoming IR has not yet been fully simplified. 8091 if (BTCC->getValue()->isZero()) { 8092 Value *InitValue = nullptr; 8093 bool MultipleInitValues = false; 8094 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8095 if (!LI->contains(PN->getIncomingBlock(i))) { 8096 if (!InitValue) 8097 InitValue = PN->getIncomingValue(i); 8098 else if (InitValue != PN->getIncomingValue(i)) { 8099 MultipleInitValues = true; 8100 break; 8101 } 8102 } 8103 if (!MultipleInitValues && InitValue) 8104 return getSCEV(InitValue); 8105 } 8106 } 8107 // Okay, we know how many times the containing loop executes. If 8108 // this is a constant evolving PHI node, get the final value at 8109 // the specified iteration number. 8110 Constant *RV = 8111 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8112 if (RV) return getSCEV(RV); 8113 } 8114 } 8115 8116 // Okay, this is an expression that we cannot symbolically evaluate 8117 // into a SCEV. Check to see if it's possible to symbolically evaluate 8118 // the arguments into constants, and if so, try to constant propagate the 8119 // result. This is particularly useful for computing loop exit values. 8120 if (CanConstantFold(I)) { 8121 SmallVector<Constant *, 4> Operands; 8122 bool MadeImprovement = false; 8123 for (Value *Op : I->operands()) { 8124 if (Constant *C = dyn_cast<Constant>(Op)) { 8125 Operands.push_back(C); 8126 continue; 8127 } 8128 8129 // If any of the operands is non-constant and if they are 8130 // non-integer and non-pointer, don't even try to analyze them 8131 // with scev techniques. 8132 if (!isSCEVable(Op->getType())) 8133 return V; 8134 8135 const SCEV *OrigV = getSCEV(Op); 8136 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8137 MadeImprovement |= OrigV != OpV; 8138 8139 Constant *C = BuildConstantFromSCEV(OpV); 8140 if (!C) return V; 8141 if (C->getType() != Op->getType()) 8142 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8143 Op->getType(), 8144 false), 8145 C, Op->getType()); 8146 Operands.push_back(C); 8147 } 8148 8149 // Check to see if getSCEVAtScope actually made an improvement. 8150 if (MadeImprovement) { 8151 Constant *C = nullptr; 8152 const DataLayout &DL = getDataLayout(); 8153 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8154 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8155 Operands[1], DL, &TLI); 8156 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8157 if (!LI->isVolatile()) 8158 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8159 } else 8160 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8161 if (!C) return V; 8162 return getSCEV(C); 8163 } 8164 } 8165 } 8166 8167 // This is some other type of SCEVUnknown, just return it. 8168 return V; 8169 } 8170 8171 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8172 // Avoid performing the look-up in the common case where the specified 8173 // expression has no loop-variant portions. 8174 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8175 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8176 if (OpAtScope != Comm->getOperand(i)) { 8177 // Okay, at least one of these operands is loop variant but might be 8178 // foldable. Build a new instance of the folded commutative expression. 8179 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8180 Comm->op_begin()+i); 8181 NewOps.push_back(OpAtScope); 8182 8183 for (++i; i != e; ++i) { 8184 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8185 NewOps.push_back(OpAtScope); 8186 } 8187 if (isa<SCEVAddExpr>(Comm)) 8188 return getAddExpr(NewOps); 8189 if (isa<SCEVMulExpr>(Comm)) 8190 return getMulExpr(NewOps); 8191 if (isa<SCEVSMaxExpr>(Comm)) 8192 return getSMaxExpr(NewOps); 8193 if (isa<SCEVUMaxExpr>(Comm)) 8194 return getUMaxExpr(NewOps); 8195 llvm_unreachable("Unknown commutative SCEV type!"); 8196 } 8197 } 8198 // If we got here, all operands are loop invariant. 8199 return Comm; 8200 } 8201 8202 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8203 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8204 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8205 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8206 return Div; // must be loop invariant 8207 return getUDivExpr(LHS, RHS); 8208 } 8209 8210 // If this is a loop recurrence for a loop that does not contain L, then we 8211 // are dealing with the final value computed by the loop. 8212 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8213 // First, attempt to evaluate each operand. 8214 // Avoid performing the look-up in the common case where the specified 8215 // expression has no loop-variant portions. 8216 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8217 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8218 if (OpAtScope == AddRec->getOperand(i)) 8219 continue; 8220 8221 // Okay, at least one of these operands is loop variant but might be 8222 // foldable. Build a new instance of the folded commutative expression. 8223 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8224 AddRec->op_begin()+i); 8225 NewOps.push_back(OpAtScope); 8226 for (++i; i != e; ++i) 8227 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8228 8229 const SCEV *FoldedRec = 8230 getAddRecExpr(NewOps, AddRec->getLoop(), 8231 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8232 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8233 // The addrec may be folded to a nonrecurrence, for example, if the 8234 // induction variable is multiplied by zero after constant folding. Go 8235 // ahead and return the folded value. 8236 if (!AddRec) 8237 return FoldedRec; 8238 break; 8239 } 8240 8241 // If the scope is outside the addrec's loop, evaluate it by using the 8242 // loop exit value of the addrec. 8243 if (!AddRec->getLoop()->contains(L)) { 8244 // To evaluate this recurrence, we need to know how many times the AddRec 8245 // loop iterates. Compute this now. 8246 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8247 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8248 8249 // Then, evaluate the AddRec. 8250 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8251 } 8252 8253 return AddRec; 8254 } 8255 8256 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8257 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8258 if (Op == Cast->getOperand()) 8259 return Cast; // must be loop invariant 8260 return getZeroExtendExpr(Op, Cast->getType()); 8261 } 8262 8263 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8264 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8265 if (Op == Cast->getOperand()) 8266 return Cast; // must be loop invariant 8267 return getSignExtendExpr(Op, Cast->getType()); 8268 } 8269 8270 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8271 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8272 if (Op == Cast->getOperand()) 8273 return Cast; // must be loop invariant 8274 return getTruncateExpr(Op, Cast->getType()); 8275 } 8276 8277 llvm_unreachable("Unknown SCEV type!"); 8278 } 8279 8280 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8281 return getSCEVAtScope(getSCEV(V), L); 8282 } 8283 8284 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8285 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8286 return stripInjectiveFunctions(ZExt->getOperand()); 8287 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8288 return stripInjectiveFunctions(SExt->getOperand()); 8289 return S; 8290 } 8291 8292 /// Finds the minimum unsigned root of the following equation: 8293 /// 8294 /// A * X = B (mod N) 8295 /// 8296 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8297 /// A and B isn't important. 8298 /// 8299 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8300 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8301 ScalarEvolution &SE) { 8302 uint32_t BW = A.getBitWidth(); 8303 assert(BW == SE.getTypeSizeInBits(B->getType())); 8304 assert(A != 0 && "A must be non-zero."); 8305 8306 // 1. D = gcd(A, N) 8307 // 8308 // The gcd of A and N may have only one prime factor: 2. The number of 8309 // trailing zeros in A is its multiplicity 8310 uint32_t Mult2 = A.countTrailingZeros(); 8311 // D = 2^Mult2 8312 8313 // 2. Check if B is divisible by D. 8314 // 8315 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8316 // is not less than multiplicity of this prime factor for D. 8317 if (SE.GetMinTrailingZeros(B) < Mult2) 8318 return SE.getCouldNotCompute(); 8319 8320 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8321 // modulo (N / D). 8322 // 8323 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8324 // (N / D) in general. The inverse itself always fits into BW bits, though, 8325 // so we immediately truncate it. 8326 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8327 APInt Mod(BW + 1, 0); 8328 Mod.setBit(BW - Mult2); // Mod = N / D 8329 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8330 8331 // 4. Compute the minimum unsigned root of the equation: 8332 // I * (B / D) mod (N / D) 8333 // To simplify the computation, we factor out the divide by D: 8334 // (I * B mod N) / D 8335 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8336 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8337 } 8338 8339 /// For a given quadratic addrec, generate coefficients of the corresponding 8340 /// quadratic equation, multiplied by a common value to ensure that they are 8341 /// integers. 8342 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8343 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8344 /// were multiplied by, and BitWidth is the bit width of the original addrec 8345 /// coefficients. 8346 /// This function returns None if the addrec coefficients are not compile- 8347 /// time constants. 8348 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8349 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8350 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8351 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8352 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8353 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8354 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8355 << *AddRec << '\n'); 8356 8357 // We currently can only solve this if the coefficients are constants. 8358 if (!LC || !MC || !NC) { 8359 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8360 return None; 8361 } 8362 8363 APInt L = LC->getAPInt(); 8364 APInt M = MC->getAPInt(); 8365 APInt N = NC->getAPInt(); 8366 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8367 8368 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8369 unsigned NewWidth = BitWidth + 1; 8370 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8371 << BitWidth << '\n'); 8372 // The sign-extension (as opposed to a zero-extension) here matches the 8373 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8374 N = N.sext(NewWidth); 8375 M = M.sext(NewWidth); 8376 L = L.sext(NewWidth); 8377 8378 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8379 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8380 // L+M, L+2M+N, L+3M+3N, ... 8381 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8382 // 8383 // The equation Acc = 0 is then 8384 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8385 // In a quadratic form it becomes: 8386 // N n^2 + (2M-N) n + 2L = 0. 8387 8388 APInt A = N; 8389 APInt B = 2 * M - A; 8390 APInt C = 2 * L; 8391 APInt T = APInt(NewWidth, 2); 8392 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8393 << "x + " << C << ", coeff bw: " << NewWidth 8394 << ", multiplied by " << T << '\n'); 8395 return std::make_tuple(A, B, C, T, BitWidth); 8396 } 8397 8398 /// Helper function to compare optional APInts: 8399 /// (a) if X and Y both exist, return min(X, Y), 8400 /// (b) if neither X nor Y exist, return None, 8401 /// (c) if exactly one of X and Y exists, return that value. 8402 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8403 if (X.hasValue() && Y.hasValue()) { 8404 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8405 APInt XW = X->sextOrSelf(W); 8406 APInt YW = Y->sextOrSelf(W); 8407 return XW.slt(YW) ? *X : *Y; 8408 } 8409 if (!X.hasValue() && !Y.hasValue()) 8410 return None; 8411 return X.hasValue() ? *X : *Y; 8412 } 8413 8414 /// Helper function to truncate an optional APInt to a given BitWidth. 8415 /// When solving addrec-related equations, it is preferable to return a value 8416 /// that has the same bit width as the original addrec's coefficients. If the 8417 /// solution fits in the original bit width, truncate it (except for i1). 8418 /// Returning a value of a different bit width may inhibit some optimizations. 8419 /// 8420 /// In general, a solution to a quadratic equation generated from an addrec 8421 /// may require BW+1 bits, where BW is the bit width of the addrec's 8422 /// coefficients. The reason is that the coefficients of the quadratic 8423 /// equation are BW+1 bits wide (to avoid truncation when converting from 8424 /// the addrec to the equation). 8425 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8426 if (!X.hasValue()) 8427 return None; 8428 unsigned W = X->getBitWidth(); 8429 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8430 return X->trunc(BitWidth); 8431 return X; 8432 } 8433 8434 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8435 /// iterations. The values L, M, N are assumed to be signed, and they 8436 /// should all have the same bit widths. 8437 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8438 /// where BW is the bit width of the addrec's coefficients. 8439 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8440 /// returned as such, otherwise the bit width of the returned value may 8441 /// be greater than BW. 8442 /// 8443 /// This function returns None if 8444 /// (a) the addrec coefficients are not constant, or 8445 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8446 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8447 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8448 static Optional<APInt> 8449 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8450 APInt A, B, C, M; 8451 unsigned BitWidth; 8452 auto T = GetQuadraticEquation(AddRec); 8453 if (!T.hasValue()) 8454 return None; 8455 8456 std::tie(A, B, C, M, BitWidth) = *T; 8457 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8458 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8459 if (!X.hasValue()) 8460 return None; 8461 8462 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8463 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8464 if (!V->isZero()) 8465 return None; 8466 8467 return TruncIfPossible(X, BitWidth); 8468 } 8469 8470 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8471 /// iterations. The values M, N are assumed to be signed, and they 8472 /// should all have the same bit widths. 8473 /// Find the least n such that c(n) does not belong to the given range, 8474 /// while c(n-1) does. 8475 /// 8476 /// This function returns None if 8477 /// (a) the addrec coefficients are not constant, or 8478 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8479 /// bounds of the range. 8480 static Optional<APInt> 8481 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8482 const ConstantRange &Range, ScalarEvolution &SE) { 8483 assert(AddRec->getOperand(0)->isZero() && 8484 "Starting value of addrec should be 0"); 8485 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8486 << Range << ", addrec " << *AddRec << '\n'); 8487 // This case is handled in getNumIterationsInRange. Here we can assume that 8488 // we start in the range. 8489 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8490 "Addrec's initial value should be in range"); 8491 8492 APInt A, B, C, M; 8493 unsigned BitWidth; 8494 auto T = GetQuadraticEquation(AddRec); 8495 if (!T.hasValue()) 8496 return None; 8497 8498 // Be careful about the return value: there can be two reasons for not 8499 // returning an actual number. First, if no solutions to the equations 8500 // were found, and second, if the solutions don't leave the given range. 8501 // The first case means that the actual solution is "unknown", the second 8502 // means that it's known, but not valid. If the solution is unknown, we 8503 // cannot make any conclusions. 8504 // Return a pair: the optional solution and a flag indicating if the 8505 // solution was found. 8506 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8507 // Solve for signed overflow and unsigned overflow, pick the lower 8508 // solution. 8509 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8510 << Bound << " (before multiplying by " << M << ")\n"); 8511 Bound *= M; // The quadratic equation multiplier. 8512 8513 Optional<APInt> SO = None; 8514 if (BitWidth > 1) { 8515 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8516 "signed overflow\n"); 8517 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8518 } 8519 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8520 "unsigned overflow\n"); 8521 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8522 BitWidth+1); 8523 8524 auto LeavesRange = [&] (const APInt &X) { 8525 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8526 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8527 if (Range.contains(V0->getValue())) 8528 return false; 8529 // X should be at least 1, so X-1 is non-negative. 8530 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8531 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8532 if (Range.contains(V1->getValue())) 8533 return true; 8534 return false; 8535 }; 8536 8537 // If SolveQuadraticEquationWrap returns None, it means that there can 8538 // be a solution, but the function failed to find it. We cannot treat it 8539 // as "no solution". 8540 if (!SO.hasValue() || !UO.hasValue()) 8541 return { None, false }; 8542 8543 // Check the smaller value first to see if it leaves the range. 8544 // At this point, both SO and UO must have values. 8545 Optional<APInt> Min = MinOptional(SO, UO); 8546 if (LeavesRange(*Min)) 8547 return { Min, true }; 8548 Optional<APInt> Max = Min == SO ? UO : SO; 8549 if (LeavesRange(*Max)) 8550 return { Max, true }; 8551 8552 // Solutions were found, but were eliminated, hence the "true". 8553 return { None, true }; 8554 }; 8555 8556 std::tie(A, B, C, M, BitWidth) = *T; 8557 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8558 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8559 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8560 auto SL = SolveForBoundary(Lower); 8561 auto SU = SolveForBoundary(Upper); 8562 // If any of the solutions was unknown, no meaninigful conclusions can 8563 // be made. 8564 if (!SL.second || !SU.second) 8565 return None; 8566 8567 // Claim: The correct solution is not some value between Min and Max. 8568 // 8569 // Justification: Assuming that Min and Max are different values, one of 8570 // them is when the first signed overflow happens, the other is when the 8571 // first unsigned overflow happens. Crossing the range boundary is only 8572 // possible via an overflow (treating 0 as a special case of it, modeling 8573 // an overflow as crossing k*2^W for some k). 8574 // 8575 // The interesting case here is when Min was eliminated as an invalid 8576 // solution, but Max was not. The argument is that if there was another 8577 // overflow between Min and Max, it would also have been eliminated if 8578 // it was considered. 8579 // 8580 // For a given boundary, it is possible to have two overflows of the same 8581 // type (signed/unsigned) without having the other type in between: this 8582 // can happen when the vertex of the parabola is between the iterations 8583 // corresponding to the overflows. This is only possible when the two 8584 // overflows cross k*2^W for the same k. In such case, if the second one 8585 // left the range (and was the first one to do so), the first overflow 8586 // would have to enter the range, which would mean that either we had left 8587 // the range before or that we started outside of it. Both of these cases 8588 // are contradictions. 8589 // 8590 // Claim: In the case where SolveForBoundary returns None, the correct 8591 // solution is not some value between the Max for this boundary and the 8592 // Min of the other boundary. 8593 // 8594 // Justification: Assume that we had such Max_A and Min_B corresponding 8595 // to range boundaries A and B and such that Max_A < Min_B. If there was 8596 // a solution between Max_A and Min_B, it would have to be caused by an 8597 // overflow corresponding to either A or B. It cannot correspond to B, 8598 // since Min_B is the first occurrence of such an overflow. If it 8599 // corresponded to A, it would have to be either a signed or an unsigned 8600 // overflow that is larger than both eliminated overflows for A. But 8601 // between the eliminated overflows and this overflow, the values would 8602 // cover the entire value space, thus crossing the other boundary, which 8603 // is a contradiction. 8604 8605 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8606 } 8607 8608 ScalarEvolution::ExitLimit 8609 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8610 bool AllowPredicates) { 8611 8612 // This is only used for loops with a "x != y" exit test. The exit condition 8613 // is now expressed as a single expression, V = x-y. So the exit test is 8614 // effectively V != 0. We know and take advantage of the fact that this 8615 // expression only being used in a comparison by zero context. 8616 8617 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8618 // If the value is a constant 8619 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8620 // If the value is already zero, the branch will execute zero times. 8621 if (C->getValue()->isZero()) return C; 8622 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8623 } 8624 8625 const SCEVAddRecExpr *AddRec = 8626 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8627 8628 if (!AddRec && AllowPredicates) 8629 // Try to make this an AddRec using runtime tests, in the first X 8630 // iterations of this loop, where X is the SCEV expression found by the 8631 // algorithm below. 8632 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8633 8634 if (!AddRec || AddRec->getLoop() != L) 8635 return getCouldNotCompute(); 8636 8637 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8638 // the quadratic equation to solve it. 8639 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8640 // We can only use this value if the chrec ends up with an exact zero 8641 // value at this index. When solving for "X*X != 5", for example, we 8642 // should not accept a root of 2. 8643 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8644 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8645 return ExitLimit(R, R, false, Predicates); 8646 } 8647 return getCouldNotCompute(); 8648 } 8649 8650 // Otherwise we can only handle this if it is affine. 8651 if (!AddRec->isAffine()) 8652 return getCouldNotCompute(); 8653 8654 // If this is an affine expression, the execution count of this branch is 8655 // the minimum unsigned root of the following equation: 8656 // 8657 // Start + Step*N = 0 (mod 2^BW) 8658 // 8659 // equivalent to: 8660 // 8661 // Step*N = -Start (mod 2^BW) 8662 // 8663 // where BW is the common bit width of Start and Step. 8664 8665 // Get the initial value for the loop. 8666 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8667 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8668 8669 // For now we handle only constant steps. 8670 // 8671 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8672 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8673 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8674 // We have not yet seen any such cases. 8675 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8676 if (!StepC || StepC->getValue()->isZero()) 8677 return getCouldNotCompute(); 8678 8679 // For positive steps (counting up until unsigned overflow): 8680 // N = -Start/Step (as unsigned) 8681 // For negative steps (counting down to zero): 8682 // N = Start/-Step 8683 // First compute the unsigned distance from zero in the direction of Step. 8684 bool CountDown = StepC->getAPInt().isNegative(); 8685 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8686 8687 // Handle unitary steps, which cannot wraparound. 8688 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8689 // N = Distance (as unsigned) 8690 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8691 APInt MaxBECount = getUnsignedRangeMax(Distance); 8692 8693 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8694 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8695 // case, and see if we can improve the bound. 8696 // 8697 // Explicitly handling this here is necessary because getUnsignedRange 8698 // isn't context-sensitive; it doesn't know that we only care about the 8699 // range inside the loop. 8700 const SCEV *Zero = getZero(Distance->getType()); 8701 const SCEV *One = getOne(Distance->getType()); 8702 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8703 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8704 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8705 // as "unsigned_max(Distance + 1) - 1". 8706 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8707 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8708 } 8709 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8710 } 8711 8712 // If the condition controls loop exit (the loop exits only if the expression 8713 // is true) and the addition is no-wrap we can use unsigned divide to 8714 // compute the backedge count. In this case, the step may not divide the 8715 // distance, but we don't care because if the condition is "missed" the loop 8716 // will have undefined behavior due to wrapping. 8717 if (ControlsExit && AddRec->hasNoSelfWrap() && 8718 loopHasNoAbnormalExits(AddRec->getLoop())) { 8719 const SCEV *Exact = 8720 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8721 const SCEV *Max = 8722 Exact == getCouldNotCompute() 8723 ? Exact 8724 : getConstant(getUnsignedRangeMax(Exact)); 8725 return ExitLimit(Exact, Max, false, Predicates); 8726 } 8727 8728 // Solve the general equation. 8729 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8730 getNegativeSCEV(Start), *this); 8731 const SCEV *M = E == getCouldNotCompute() 8732 ? E 8733 : getConstant(getUnsignedRangeMax(E)); 8734 return ExitLimit(E, M, false, Predicates); 8735 } 8736 8737 ScalarEvolution::ExitLimit 8738 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8739 // Loops that look like: while (X == 0) are very strange indeed. We don't 8740 // handle them yet except for the trivial case. This could be expanded in the 8741 // future as needed. 8742 8743 // If the value is a constant, check to see if it is known to be non-zero 8744 // already. If so, the backedge will execute zero times. 8745 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8746 if (!C->getValue()->isZero()) 8747 return getZero(C->getType()); 8748 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8749 } 8750 8751 // We could implement others, but I really doubt anyone writes loops like 8752 // this, and if they did, they would already be constant folded. 8753 return getCouldNotCompute(); 8754 } 8755 8756 std::pair<BasicBlock *, BasicBlock *> 8757 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8758 // If the block has a unique predecessor, then there is no path from the 8759 // predecessor to the block that does not go through the direct edge 8760 // from the predecessor to the block. 8761 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8762 return {Pred, BB}; 8763 8764 // A loop's header is defined to be a block that dominates the loop. 8765 // If the header has a unique predecessor outside the loop, it must be 8766 // a block that has exactly one successor that can reach the loop. 8767 if (Loop *L = LI.getLoopFor(BB)) 8768 return {L->getLoopPredecessor(), L->getHeader()}; 8769 8770 return {nullptr, nullptr}; 8771 } 8772 8773 /// SCEV structural equivalence is usually sufficient for testing whether two 8774 /// expressions are equal, however for the purposes of looking for a condition 8775 /// guarding a loop, it can be useful to be a little more general, since a 8776 /// front-end may have replicated the controlling expression. 8777 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8778 // Quick check to see if they are the same SCEV. 8779 if (A == B) return true; 8780 8781 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8782 // Not all instructions that are "identical" compute the same value. For 8783 // instance, two distinct alloca instructions allocating the same type are 8784 // identical and do not read memory; but compute distinct values. 8785 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8786 }; 8787 8788 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8789 // two different instructions with the same value. Check for this case. 8790 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8791 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8792 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8793 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8794 if (ComputesEqualValues(AI, BI)) 8795 return true; 8796 8797 // Otherwise assume they may have a different value. 8798 return false; 8799 } 8800 8801 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8802 const SCEV *&LHS, const SCEV *&RHS, 8803 unsigned Depth) { 8804 bool Changed = false; 8805 8806 // If we hit the max recursion limit bail out. 8807 if (Depth >= 3) 8808 return false; 8809 8810 // Canonicalize a constant to the right side. 8811 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8812 // Check for both operands constant. 8813 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8814 if (ConstantExpr::getICmp(Pred, 8815 LHSC->getValue(), 8816 RHSC->getValue())->isNullValue()) 8817 goto trivially_false; 8818 else 8819 goto trivially_true; 8820 } 8821 // Otherwise swap the operands to put the constant on the right. 8822 std::swap(LHS, RHS); 8823 Pred = ICmpInst::getSwappedPredicate(Pred); 8824 Changed = true; 8825 } 8826 8827 // If we're comparing an addrec with a value which is loop-invariant in the 8828 // addrec's loop, put the addrec on the left. Also make a dominance check, 8829 // as both operands could be addrecs loop-invariant in each other's loop. 8830 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8831 const Loop *L = AR->getLoop(); 8832 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8833 std::swap(LHS, RHS); 8834 Pred = ICmpInst::getSwappedPredicate(Pred); 8835 Changed = true; 8836 } 8837 } 8838 8839 // If there's a constant operand, canonicalize comparisons with boundary 8840 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8841 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8842 const APInt &RA = RC->getAPInt(); 8843 8844 bool SimplifiedByConstantRange = false; 8845 8846 if (!ICmpInst::isEquality(Pred)) { 8847 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8848 if (ExactCR.isFullSet()) 8849 goto trivially_true; 8850 else if (ExactCR.isEmptySet()) 8851 goto trivially_false; 8852 8853 APInt NewRHS; 8854 CmpInst::Predicate NewPred; 8855 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8856 ICmpInst::isEquality(NewPred)) { 8857 // We were able to convert an inequality to an equality. 8858 Pred = NewPred; 8859 RHS = getConstant(NewRHS); 8860 Changed = SimplifiedByConstantRange = true; 8861 } 8862 } 8863 8864 if (!SimplifiedByConstantRange) { 8865 switch (Pred) { 8866 default: 8867 break; 8868 case ICmpInst::ICMP_EQ: 8869 case ICmpInst::ICMP_NE: 8870 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8871 if (!RA) 8872 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8873 if (const SCEVMulExpr *ME = 8874 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8875 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8876 ME->getOperand(0)->isAllOnesValue()) { 8877 RHS = AE->getOperand(1); 8878 LHS = ME->getOperand(1); 8879 Changed = true; 8880 } 8881 break; 8882 8883 8884 // The "Should have been caught earlier!" messages refer to the fact 8885 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8886 // should have fired on the corresponding cases, and canonicalized the 8887 // check to trivially_true or trivially_false. 8888 8889 case ICmpInst::ICMP_UGE: 8890 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8891 Pred = ICmpInst::ICMP_UGT; 8892 RHS = getConstant(RA - 1); 8893 Changed = true; 8894 break; 8895 case ICmpInst::ICMP_ULE: 8896 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8897 Pred = ICmpInst::ICMP_ULT; 8898 RHS = getConstant(RA + 1); 8899 Changed = true; 8900 break; 8901 case ICmpInst::ICMP_SGE: 8902 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8903 Pred = ICmpInst::ICMP_SGT; 8904 RHS = getConstant(RA - 1); 8905 Changed = true; 8906 break; 8907 case ICmpInst::ICMP_SLE: 8908 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8909 Pred = ICmpInst::ICMP_SLT; 8910 RHS = getConstant(RA + 1); 8911 Changed = true; 8912 break; 8913 } 8914 } 8915 } 8916 8917 // Check for obvious equality. 8918 if (HasSameValue(LHS, RHS)) { 8919 if (ICmpInst::isTrueWhenEqual(Pred)) 8920 goto trivially_true; 8921 if (ICmpInst::isFalseWhenEqual(Pred)) 8922 goto trivially_false; 8923 } 8924 8925 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8926 // adding or subtracting 1 from one of the operands. 8927 switch (Pred) { 8928 case ICmpInst::ICMP_SLE: 8929 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8930 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8931 SCEV::FlagNSW); 8932 Pred = ICmpInst::ICMP_SLT; 8933 Changed = true; 8934 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8935 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8936 SCEV::FlagNSW); 8937 Pred = ICmpInst::ICMP_SLT; 8938 Changed = true; 8939 } 8940 break; 8941 case ICmpInst::ICMP_SGE: 8942 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8943 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8944 SCEV::FlagNSW); 8945 Pred = ICmpInst::ICMP_SGT; 8946 Changed = true; 8947 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8948 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8949 SCEV::FlagNSW); 8950 Pred = ICmpInst::ICMP_SGT; 8951 Changed = true; 8952 } 8953 break; 8954 case ICmpInst::ICMP_ULE: 8955 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8956 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8957 SCEV::FlagNUW); 8958 Pred = ICmpInst::ICMP_ULT; 8959 Changed = true; 8960 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8961 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8962 Pred = ICmpInst::ICMP_ULT; 8963 Changed = true; 8964 } 8965 break; 8966 case ICmpInst::ICMP_UGE: 8967 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8968 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8969 Pred = ICmpInst::ICMP_UGT; 8970 Changed = true; 8971 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8972 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8973 SCEV::FlagNUW); 8974 Pred = ICmpInst::ICMP_UGT; 8975 Changed = true; 8976 } 8977 break; 8978 default: 8979 break; 8980 } 8981 8982 // TODO: More simplifications are possible here. 8983 8984 // Recursively simplify until we either hit a recursion limit or nothing 8985 // changes. 8986 if (Changed) 8987 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8988 8989 return Changed; 8990 8991 trivially_true: 8992 // Return 0 == 0. 8993 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8994 Pred = ICmpInst::ICMP_EQ; 8995 return true; 8996 8997 trivially_false: 8998 // Return 0 != 0. 8999 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9000 Pred = ICmpInst::ICMP_NE; 9001 return true; 9002 } 9003 9004 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9005 return getSignedRangeMax(S).isNegative(); 9006 } 9007 9008 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9009 return getSignedRangeMin(S).isStrictlyPositive(); 9010 } 9011 9012 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9013 return !getSignedRangeMin(S).isNegative(); 9014 } 9015 9016 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9017 return !getSignedRangeMax(S).isStrictlyPositive(); 9018 } 9019 9020 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9021 return isKnownNegative(S) || isKnownPositive(S); 9022 } 9023 9024 std::pair<const SCEV *, const SCEV *> 9025 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9026 // Compute SCEV on entry of loop L. 9027 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9028 if (Start == getCouldNotCompute()) 9029 return { Start, Start }; 9030 // Compute post increment SCEV for loop L. 9031 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9032 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9033 return { Start, PostInc }; 9034 } 9035 9036 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9037 const SCEV *LHS, const SCEV *RHS) { 9038 // First collect all loops. 9039 SmallPtrSet<const Loop *, 8> LoopsUsed; 9040 getUsedLoops(LHS, LoopsUsed); 9041 getUsedLoops(RHS, LoopsUsed); 9042 9043 if (LoopsUsed.empty()) 9044 return false; 9045 9046 // Domination relationship must be a linear order on collected loops. 9047 #ifndef NDEBUG 9048 for (auto *L1 : LoopsUsed) 9049 for (auto *L2 : LoopsUsed) 9050 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9051 DT.dominates(L2->getHeader(), L1->getHeader())) && 9052 "Domination relationship is not a linear order"); 9053 #endif 9054 9055 const Loop *MDL = 9056 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9057 [&](const Loop *L1, const Loop *L2) { 9058 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9059 }); 9060 9061 // Get init and post increment value for LHS. 9062 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9063 // if LHS contains unknown non-invariant SCEV then bail out. 9064 if (SplitLHS.first == getCouldNotCompute()) 9065 return false; 9066 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9067 // Get init and post increment value for RHS. 9068 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9069 // if RHS contains unknown non-invariant SCEV then bail out. 9070 if (SplitRHS.first == getCouldNotCompute()) 9071 return false; 9072 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9073 // It is possible that init SCEV contains an invariant load but it does 9074 // not dominate MDL and is not available at MDL loop entry, so we should 9075 // check it here. 9076 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9077 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9078 return false; 9079 9080 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9081 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9082 SplitRHS.second); 9083 } 9084 9085 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9086 const SCEV *LHS, const SCEV *RHS) { 9087 // Canonicalize the inputs first. 9088 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9089 9090 if (isKnownViaInduction(Pred, LHS, RHS)) 9091 return true; 9092 9093 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9094 return true; 9095 9096 // Otherwise see what can be done with some simple reasoning. 9097 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9098 } 9099 9100 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9101 const SCEVAddRecExpr *LHS, 9102 const SCEV *RHS) { 9103 const Loop *L = LHS->getLoop(); 9104 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9105 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9106 } 9107 9108 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9109 ICmpInst::Predicate Pred, 9110 bool &Increasing) { 9111 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9112 9113 #ifndef NDEBUG 9114 // Verify an invariant: inverting the predicate should turn a monotonically 9115 // increasing change to a monotonically decreasing one, and vice versa. 9116 bool IncreasingSwapped; 9117 bool ResultSwapped = isMonotonicPredicateImpl( 9118 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9119 9120 assert(Result == ResultSwapped && "should be able to analyze both!"); 9121 if (ResultSwapped) 9122 assert(Increasing == !IncreasingSwapped && 9123 "monotonicity should flip as we flip the predicate"); 9124 #endif 9125 9126 return Result; 9127 } 9128 9129 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9130 ICmpInst::Predicate Pred, 9131 bool &Increasing) { 9132 9133 // A zero step value for LHS means the induction variable is essentially a 9134 // loop invariant value. We don't really depend on the predicate actually 9135 // flipping from false to true (for increasing predicates, and the other way 9136 // around for decreasing predicates), all we care about is that *if* the 9137 // predicate changes then it only changes from false to true. 9138 // 9139 // A zero step value in itself is not very useful, but there may be places 9140 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9141 // as general as possible. 9142 9143 switch (Pred) { 9144 default: 9145 return false; // Conservative answer 9146 9147 case ICmpInst::ICMP_UGT: 9148 case ICmpInst::ICMP_UGE: 9149 case ICmpInst::ICMP_ULT: 9150 case ICmpInst::ICMP_ULE: 9151 if (!LHS->hasNoUnsignedWrap()) 9152 return false; 9153 9154 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9155 return true; 9156 9157 case ICmpInst::ICMP_SGT: 9158 case ICmpInst::ICMP_SGE: 9159 case ICmpInst::ICMP_SLT: 9160 case ICmpInst::ICMP_SLE: { 9161 if (!LHS->hasNoSignedWrap()) 9162 return false; 9163 9164 const SCEV *Step = LHS->getStepRecurrence(*this); 9165 9166 if (isKnownNonNegative(Step)) { 9167 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9168 return true; 9169 } 9170 9171 if (isKnownNonPositive(Step)) { 9172 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9173 return true; 9174 } 9175 9176 return false; 9177 } 9178 9179 } 9180 9181 llvm_unreachable("switch has default clause!"); 9182 } 9183 9184 bool ScalarEvolution::isLoopInvariantPredicate( 9185 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9186 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9187 const SCEV *&InvariantRHS) { 9188 9189 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9190 if (!isLoopInvariant(RHS, L)) { 9191 if (!isLoopInvariant(LHS, L)) 9192 return false; 9193 9194 std::swap(LHS, RHS); 9195 Pred = ICmpInst::getSwappedPredicate(Pred); 9196 } 9197 9198 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9199 if (!ArLHS || ArLHS->getLoop() != L) 9200 return false; 9201 9202 bool Increasing; 9203 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9204 return false; 9205 9206 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9207 // true as the loop iterates, and the backedge is control dependent on 9208 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9209 // 9210 // * if the predicate was false in the first iteration then the predicate 9211 // is never evaluated again, since the loop exits without taking the 9212 // backedge. 9213 // * if the predicate was true in the first iteration then it will 9214 // continue to be true for all future iterations since it is 9215 // monotonically increasing. 9216 // 9217 // For both the above possibilities, we can replace the loop varying 9218 // predicate with its value on the first iteration of the loop (which is 9219 // loop invariant). 9220 // 9221 // A similar reasoning applies for a monotonically decreasing predicate, by 9222 // replacing true with false and false with true in the above two bullets. 9223 9224 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9225 9226 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9227 return false; 9228 9229 InvariantPred = Pred; 9230 InvariantLHS = ArLHS->getStart(); 9231 InvariantRHS = RHS; 9232 return true; 9233 } 9234 9235 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9236 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9237 if (HasSameValue(LHS, RHS)) 9238 return ICmpInst::isTrueWhenEqual(Pred); 9239 9240 // This code is split out from isKnownPredicate because it is called from 9241 // within isLoopEntryGuardedByCond. 9242 9243 auto CheckRanges = 9244 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9245 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9246 .contains(RangeLHS); 9247 }; 9248 9249 // The check at the top of the function catches the case where the values are 9250 // known to be equal. 9251 if (Pred == CmpInst::ICMP_EQ) 9252 return false; 9253 9254 if (Pred == CmpInst::ICMP_NE) 9255 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9256 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9257 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9258 9259 if (CmpInst::isSigned(Pred)) 9260 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9261 9262 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9263 } 9264 9265 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9266 const SCEV *LHS, 9267 const SCEV *RHS) { 9268 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9269 // Return Y via OutY. 9270 auto MatchBinaryAddToConst = 9271 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9272 SCEV::NoWrapFlags ExpectedFlags) { 9273 const SCEV *NonConstOp, *ConstOp; 9274 SCEV::NoWrapFlags FlagsPresent; 9275 9276 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9277 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9278 return false; 9279 9280 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9281 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9282 }; 9283 9284 APInt C; 9285 9286 switch (Pred) { 9287 default: 9288 break; 9289 9290 case ICmpInst::ICMP_SGE: 9291 std::swap(LHS, RHS); 9292 LLVM_FALLTHROUGH; 9293 case ICmpInst::ICMP_SLE: 9294 // X s<= (X + C)<nsw> if C >= 0 9295 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9296 return true; 9297 9298 // (X + C)<nsw> s<= X if C <= 0 9299 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9300 !C.isStrictlyPositive()) 9301 return true; 9302 break; 9303 9304 case ICmpInst::ICMP_SGT: 9305 std::swap(LHS, RHS); 9306 LLVM_FALLTHROUGH; 9307 case ICmpInst::ICMP_SLT: 9308 // X s< (X + C)<nsw> if C > 0 9309 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9310 C.isStrictlyPositive()) 9311 return true; 9312 9313 // (X + C)<nsw> s< X if C < 0 9314 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9315 return true; 9316 break; 9317 } 9318 9319 return false; 9320 } 9321 9322 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9323 const SCEV *LHS, 9324 const SCEV *RHS) { 9325 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9326 return false; 9327 9328 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9329 // the stack can result in exponential time complexity. 9330 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9331 9332 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9333 // 9334 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9335 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9336 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9337 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9338 // use isKnownPredicate later if needed. 9339 return isKnownNonNegative(RHS) && 9340 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9341 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9342 } 9343 9344 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9345 ICmpInst::Predicate Pred, 9346 const SCEV *LHS, const SCEV *RHS) { 9347 // No need to even try if we know the module has no guards. 9348 if (!HasGuards) 9349 return false; 9350 9351 return any_of(*BB, [&](Instruction &I) { 9352 using namespace llvm::PatternMatch; 9353 9354 Value *Condition; 9355 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9356 m_Value(Condition))) && 9357 isImpliedCond(Pred, LHS, RHS, Condition, false); 9358 }); 9359 } 9360 9361 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9362 /// protected by a conditional between LHS and RHS. This is used to 9363 /// to eliminate casts. 9364 bool 9365 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9366 ICmpInst::Predicate Pred, 9367 const SCEV *LHS, const SCEV *RHS) { 9368 // Interpret a null as meaning no loop, where there is obviously no guard 9369 // (interprocedural conditions notwithstanding). 9370 if (!L) return true; 9371 9372 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9373 return true; 9374 9375 BasicBlock *Latch = L->getLoopLatch(); 9376 if (!Latch) 9377 return false; 9378 9379 BranchInst *LoopContinuePredicate = 9380 dyn_cast<BranchInst>(Latch->getTerminator()); 9381 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9382 isImpliedCond(Pred, LHS, RHS, 9383 LoopContinuePredicate->getCondition(), 9384 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9385 return true; 9386 9387 // We don't want more than one activation of the following loops on the stack 9388 // -- that can lead to O(n!) time complexity. 9389 if (WalkingBEDominatingConds) 9390 return false; 9391 9392 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9393 9394 // See if we can exploit a trip count to prove the predicate. 9395 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9396 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9397 if (LatchBECount != getCouldNotCompute()) { 9398 // We know that Latch branches back to the loop header exactly 9399 // LatchBECount times. This means the backdege condition at Latch is 9400 // equivalent to "{0,+,1} u< LatchBECount". 9401 Type *Ty = LatchBECount->getType(); 9402 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9403 const SCEV *LoopCounter = 9404 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9405 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9406 LatchBECount)) 9407 return true; 9408 } 9409 9410 // Check conditions due to any @llvm.assume intrinsics. 9411 for (auto &AssumeVH : AC.assumptions()) { 9412 if (!AssumeVH) 9413 continue; 9414 auto *CI = cast<CallInst>(AssumeVH); 9415 if (!DT.dominates(CI, Latch->getTerminator())) 9416 continue; 9417 9418 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9419 return true; 9420 } 9421 9422 // If the loop is not reachable from the entry block, we risk running into an 9423 // infinite loop as we walk up into the dom tree. These loops do not matter 9424 // anyway, so we just return a conservative answer when we see them. 9425 if (!DT.isReachableFromEntry(L->getHeader())) 9426 return false; 9427 9428 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9429 return true; 9430 9431 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9432 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9433 assert(DTN && "should reach the loop header before reaching the root!"); 9434 9435 BasicBlock *BB = DTN->getBlock(); 9436 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9437 return true; 9438 9439 BasicBlock *PBB = BB->getSinglePredecessor(); 9440 if (!PBB) 9441 continue; 9442 9443 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9444 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9445 continue; 9446 9447 Value *Condition = ContinuePredicate->getCondition(); 9448 9449 // If we have an edge `E` within the loop body that dominates the only 9450 // latch, the condition guarding `E` also guards the backedge. This 9451 // reasoning works only for loops with a single latch. 9452 9453 BasicBlockEdge DominatingEdge(PBB, BB); 9454 if (DominatingEdge.isSingleEdge()) { 9455 // We're constructively (and conservatively) enumerating edges within the 9456 // loop body that dominate the latch. The dominator tree better agree 9457 // with us on this: 9458 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9459 9460 if (isImpliedCond(Pred, LHS, RHS, Condition, 9461 BB != ContinuePredicate->getSuccessor(0))) 9462 return true; 9463 } 9464 } 9465 9466 return false; 9467 } 9468 9469 bool 9470 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9471 ICmpInst::Predicate Pred, 9472 const SCEV *LHS, const SCEV *RHS) { 9473 // Interpret a null as meaning no loop, where there is obviously no guard 9474 // (interprocedural conditions notwithstanding). 9475 if (!L) return false; 9476 9477 // Both LHS and RHS must be available at loop entry. 9478 assert(isAvailableAtLoopEntry(LHS, L) && 9479 "LHS is not available at Loop Entry"); 9480 assert(isAvailableAtLoopEntry(RHS, L) && 9481 "RHS is not available at Loop Entry"); 9482 9483 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9484 return true; 9485 9486 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9487 // the facts (a >= b && a != b) separately. A typical situation is when the 9488 // non-strict comparison is known from ranges and non-equality is known from 9489 // dominating predicates. If we are proving strict comparison, we always try 9490 // to prove non-equality and non-strict comparison separately. 9491 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9492 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9493 bool ProvedNonStrictComparison = false; 9494 bool ProvedNonEquality = false; 9495 9496 if (ProvingStrictComparison) { 9497 ProvedNonStrictComparison = 9498 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9499 ProvedNonEquality = 9500 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9501 if (ProvedNonStrictComparison && ProvedNonEquality) 9502 return true; 9503 } 9504 9505 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9506 auto ProveViaGuard = [&](BasicBlock *Block) { 9507 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9508 return true; 9509 if (ProvingStrictComparison) { 9510 if (!ProvedNonStrictComparison) 9511 ProvedNonStrictComparison = 9512 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9513 if (!ProvedNonEquality) 9514 ProvedNonEquality = 9515 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9516 if (ProvedNonStrictComparison && ProvedNonEquality) 9517 return true; 9518 } 9519 return false; 9520 }; 9521 9522 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9523 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9524 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9525 return true; 9526 if (ProvingStrictComparison) { 9527 if (!ProvedNonStrictComparison) 9528 ProvedNonStrictComparison = 9529 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9530 if (!ProvedNonEquality) 9531 ProvedNonEquality = 9532 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9533 if (ProvedNonStrictComparison && ProvedNonEquality) 9534 return true; 9535 } 9536 return false; 9537 }; 9538 9539 // Starting at the loop predecessor, climb up the predecessor chain, as long 9540 // as there are predecessors that can be found that have unique successors 9541 // leading to the original header. 9542 for (std::pair<BasicBlock *, BasicBlock *> 9543 Pair(L->getLoopPredecessor(), L->getHeader()); 9544 Pair.first; 9545 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9546 9547 if (ProveViaGuard(Pair.first)) 9548 return true; 9549 9550 BranchInst *LoopEntryPredicate = 9551 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9552 if (!LoopEntryPredicate || 9553 LoopEntryPredicate->isUnconditional()) 9554 continue; 9555 9556 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9557 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9558 return true; 9559 } 9560 9561 // Check conditions due to any @llvm.assume intrinsics. 9562 for (auto &AssumeVH : AC.assumptions()) { 9563 if (!AssumeVH) 9564 continue; 9565 auto *CI = cast<CallInst>(AssumeVH); 9566 if (!DT.dominates(CI, L->getHeader())) 9567 continue; 9568 9569 if (ProveViaCond(CI->getArgOperand(0), false)) 9570 return true; 9571 } 9572 9573 return false; 9574 } 9575 9576 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9577 const SCEV *LHS, const SCEV *RHS, 9578 Value *FoundCondValue, 9579 bool Inverse) { 9580 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9581 return false; 9582 9583 auto ClearOnExit = 9584 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9585 9586 // Recursively handle And and Or conditions. 9587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9588 if (BO->getOpcode() == Instruction::And) { 9589 if (!Inverse) 9590 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9591 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9592 } else if (BO->getOpcode() == Instruction::Or) { 9593 if (Inverse) 9594 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9595 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9596 } 9597 } 9598 9599 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9600 if (!ICI) return false; 9601 9602 // Now that we found a conditional branch that dominates the loop or controls 9603 // the loop latch. Check to see if it is the comparison we are looking for. 9604 ICmpInst::Predicate FoundPred; 9605 if (Inverse) 9606 FoundPred = ICI->getInversePredicate(); 9607 else 9608 FoundPred = ICI->getPredicate(); 9609 9610 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9611 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9612 9613 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9614 } 9615 9616 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9617 const SCEV *RHS, 9618 ICmpInst::Predicate FoundPred, 9619 const SCEV *FoundLHS, 9620 const SCEV *FoundRHS) { 9621 // Balance the types. 9622 if (getTypeSizeInBits(LHS->getType()) < 9623 getTypeSizeInBits(FoundLHS->getType())) { 9624 if (CmpInst::isSigned(Pred)) { 9625 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9626 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9627 } else { 9628 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9629 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9630 } 9631 } else if (getTypeSizeInBits(LHS->getType()) > 9632 getTypeSizeInBits(FoundLHS->getType())) { 9633 if (CmpInst::isSigned(FoundPred)) { 9634 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9635 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9636 } else { 9637 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9638 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9639 } 9640 } 9641 9642 // Canonicalize the query to match the way instcombine will have 9643 // canonicalized the comparison. 9644 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9645 if (LHS == RHS) 9646 return CmpInst::isTrueWhenEqual(Pred); 9647 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9648 if (FoundLHS == FoundRHS) 9649 return CmpInst::isFalseWhenEqual(FoundPred); 9650 9651 // Check to see if we can make the LHS or RHS match. 9652 if (LHS == FoundRHS || RHS == FoundLHS) { 9653 if (isa<SCEVConstant>(RHS)) { 9654 std::swap(FoundLHS, FoundRHS); 9655 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9656 } else { 9657 std::swap(LHS, RHS); 9658 Pred = ICmpInst::getSwappedPredicate(Pred); 9659 } 9660 } 9661 9662 // Check whether the found predicate is the same as the desired predicate. 9663 if (FoundPred == Pred) 9664 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9665 9666 // Check whether swapping the found predicate makes it the same as the 9667 // desired predicate. 9668 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9669 if (isa<SCEVConstant>(RHS)) 9670 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9671 else 9672 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9673 RHS, LHS, FoundLHS, FoundRHS); 9674 } 9675 9676 // Unsigned comparison is the same as signed comparison when both the operands 9677 // are non-negative. 9678 if (CmpInst::isUnsigned(FoundPred) && 9679 CmpInst::getSignedPredicate(FoundPred) == Pred && 9680 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9681 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9682 9683 // Check if we can make progress by sharpening ranges. 9684 if (FoundPred == ICmpInst::ICMP_NE && 9685 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9686 9687 const SCEVConstant *C = nullptr; 9688 const SCEV *V = nullptr; 9689 9690 if (isa<SCEVConstant>(FoundLHS)) { 9691 C = cast<SCEVConstant>(FoundLHS); 9692 V = FoundRHS; 9693 } else { 9694 C = cast<SCEVConstant>(FoundRHS); 9695 V = FoundLHS; 9696 } 9697 9698 // The guarding predicate tells us that C != V. If the known range 9699 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9700 // range we consider has to correspond to same signedness as the 9701 // predicate we're interested in folding. 9702 9703 APInt Min = ICmpInst::isSigned(Pred) ? 9704 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9705 9706 if (Min == C->getAPInt()) { 9707 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9708 // This is true even if (Min + 1) wraps around -- in case of 9709 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9710 9711 APInt SharperMin = Min + 1; 9712 9713 switch (Pred) { 9714 case ICmpInst::ICMP_SGE: 9715 case ICmpInst::ICMP_UGE: 9716 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9717 // RHS, we're done. 9718 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9719 getConstant(SharperMin))) 9720 return true; 9721 LLVM_FALLTHROUGH; 9722 9723 case ICmpInst::ICMP_SGT: 9724 case ICmpInst::ICMP_UGT: 9725 // We know from the range information that (V `Pred` Min || 9726 // V == Min). We know from the guarding condition that !(V 9727 // == Min). This gives us 9728 // 9729 // V `Pred` Min || V == Min && !(V == Min) 9730 // => V `Pred` Min 9731 // 9732 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9733 9734 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9735 return true; 9736 LLVM_FALLTHROUGH; 9737 9738 default: 9739 // No change 9740 break; 9741 } 9742 } 9743 } 9744 9745 // Check whether the actual condition is beyond sufficient. 9746 if (FoundPred == ICmpInst::ICMP_EQ) 9747 if (ICmpInst::isTrueWhenEqual(Pred)) 9748 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9749 return true; 9750 if (Pred == ICmpInst::ICMP_NE) 9751 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9752 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9753 return true; 9754 9755 // Otherwise assume the worst. 9756 return false; 9757 } 9758 9759 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9760 const SCEV *&L, const SCEV *&R, 9761 SCEV::NoWrapFlags &Flags) { 9762 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9763 if (!AE || AE->getNumOperands() != 2) 9764 return false; 9765 9766 L = AE->getOperand(0); 9767 R = AE->getOperand(1); 9768 Flags = AE->getNoWrapFlags(); 9769 return true; 9770 } 9771 9772 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9773 const SCEV *Less) { 9774 // We avoid subtracting expressions here because this function is usually 9775 // fairly deep in the call stack (i.e. is called many times). 9776 9777 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9778 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9779 const auto *MAR = cast<SCEVAddRecExpr>(More); 9780 9781 if (LAR->getLoop() != MAR->getLoop()) 9782 return None; 9783 9784 // We look at affine expressions only; not for correctness but to keep 9785 // getStepRecurrence cheap. 9786 if (!LAR->isAffine() || !MAR->isAffine()) 9787 return None; 9788 9789 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9790 return None; 9791 9792 Less = LAR->getStart(); 9793 More = MAR->getStart(); 9794 9795 // fall through 9796 } 9797 9798 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9799 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9800 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9801 return M - L; 9802 } 9803 9804 SCEV::NoWrapFlags Flags; 9805 const SCEV *LLess = nullptr, *RLess = nullptr; 9806 const SCEV *LMore = nullptr, *RMore = nullptr; 9807 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9808 // Compare (X + C1) vs X. 9809 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9810 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9811 if (RLess == More) 9812 return -(C1->getAPInt()); 9813 9814 // Compare X vs (X + C2). 9815 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9816 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9817 if (RMore == Less) 9818 return C2->getAPInt(); 9819 9820 // Compare (X + C1) vs (X + C2). 9821 if (C1 && C2 && RLess == RMore) 9822 return C2->getAPInt() - C1->getAPInt(); 9823 9824 return None; 9825 } 9826 9827 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9828 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9829 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9830 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9831 return false; 9832 9833 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9834 if (!AddRecLHS) 9835 return false; 9836 9837 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9838 if (!AddRecFoundLHS) 9839 return false; 9840 9841 // We'd like to let SCEV reason about control dependencies, so we constrain 9842 // both the inequalities to be about add recurrences on the same loop. This 9843 // way we can use isLoopEntryGuardedByCond later. 9844 9845 const Loop *L = AddRecFoundLHS->getLoop(); 9846 if (L != AddRecLHS->getLoop()) 9847 return false; 9848 9849 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9850 // 9851 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9852 // ... (2) 9853 // 9854 // Informal proof for (2), assuming (1) [*]: 9855 // 9856 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9857 // 9858 // Then 9859 // 9860 // FoundLHS s< FoundRHS s< INT_MIN - C 9861 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9862 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9863 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9864 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9865 // <=> FoundLHS + C s< FoundRHS + C 9866 // 9867 // [*]: (1) can be proved by ruling out overflow. 9868 // 9869 // [**]: This can be proved by analyzing all the four possibilities: 9870 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9871 // (A s>= 0, B s>= 0). 9872 // 9873 // Note: 9874 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9875 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9876 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9877 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9878 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9879 // C)". 9880 9881 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9882 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9883 if (!LDiff || !RDiff || *LDiff != *RDiff) 9884 return false; 9885 9886 if (LDiff->isMinValue()) 9887 return true; 9888 9889 APInt FoundRHSLimit; 9890 9891 if (Pred == CmpInst::ICMP_ULT) { 9892 FoundRHSLimit = -(*RDiff); 9893 } else { 9894 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9895 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9896 } 9897 9898 // Try to prove (1) or (2), as needed. 9899 return isAvailableAtLoopEntry(FoundRHS, L) && 9900 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9901 getConstant(FoundRHSLimit)); 9902 } 9903 9904 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9905 const SCEV *LHS, const SCEV *RHS, 9906 const SCEV *FoundLHS, 9907 const SCEV *FoundRHS, unsigned Depth) { 9908 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9909 9910 auto ClearOnExit = make_scope_exit([&]() { 9911 if (LPhi) { 9912 bool Erased = PendingMerges.erase(LPhi); 9913 assert(Erased && "Failed to erase LPhi!"); 9914 (void)Erased; 9915 } 9916 if (RPhi) { 9917 bool Erased = PendingMerges.erase(RPhi); 9918 assert(Erased && "Failed to erase RPhi!"); 9919 (void)Erased; 9920 } 9921 }); 9922 9923 // Find respective Phis and check that they are not being pending. 9924 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9925 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9926 if (!PendingMerges.insert(Phi).second) 9927 return false; 9928 LPhi = Phi; 9929 } 9930 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9931 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9932 // If we detect a loop of Phi nodes being processed by this method, for 9933 // example: 9934 // 9935 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9936 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9937 // 9938 // we don't want to deal with a case that complex, so return conservative 9939 // answer false. 9940 if (!PendingMerges.insert(Phi).second) 9941 return false; 9942 RPhi = Phi; 9943 } 9944 9945 // If none of LHS, RHS is a Phi, nothing to do here. 9946 if (!LPhi && !RPhi) 9947 return false; 9948 9949 // If there is a SCEVUnknown Phi we are interested in, make it left. 9950 if (!LPhi) { 9951 std::swap(LHS, RHS); 9952 std::swap(FoundLHS, FoundRHS); 9953 std::swap(LPhi, RPhi); 9954 Pred = ICmpInst::getSwappedPredicate(Pred); 9955 } 9956 9957 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9958 const BasicBlock *LBB = LPhi->getParent(); 9959 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9960 9961 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9962 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9963 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9964 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9965 }; 9966 9967 if (RPhi && RPhi->getParent() == LBB) { 9968 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9969 // If we compare two Phis from the same block, and for each entry block 9970 // the predicate is true for incoming values from this block, then the 9971 // predicate is also true for the Phis. 9972 for (const BasicBlock *IncBB : predecessors(LBB)) { 9973 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9974 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9975 if (!ProvedEasily(L, R)) 9976 return false; 9977 } 9978 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9979 // Case two: RHS is also a Phi from the same basic block, and it is an 9980 // AddRec. It means that there is a loop which has both AddRec and Unknown 9981 // PHIs, for it we can compare incoming values of AddRec from above the loop 9982 // and latch with their respective incoming values of LPhi. 9983 // TODO: Generalize to handle loops with many inputs in a header. 9984 if (LPhi->getNumIncomingValues() != 2) return false; 9985 9986 auto *RLoop = RAR->getLoop(); 9987 auto *Predecessor = RLoop->getLoopPredecessor(); 9988 assert(Predecessor && "Loop with AddRec with no predecessor?"); 9989 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 9990 if (!ProvedEasily(L1, RAR->getStart())) 9991 return false; 9992 auto *Latch = RLoop->getLoopLatch(); 9993 assert(Latch && "Loop with AddRec with no latch?"); 9994 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 9995 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 9996 return false; 9997 } else { 9998 // In all other cases go over inputs of LHS and compare each of them to RHS, 9999 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10000 // At this point RHS is either a non-Phi, or it is a Phi from some block 10001 // different from LBB. 10002 for (const BasicBlock *IncBB : predecessors(LBB)) { 10003 // Check that RHS is available in this block. 10004 if (!dominates(RHS, IncBB)) 10005 return false; 10006 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10007 if (!ProvedEasily(L, RHS)) 10008 return false; 10009 } 10010 } 10011 return true; 10012 } 10013 10014 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10015 const SCEV *LHS, const SCEV *RHS, 10016 const SCEV *FoundLHS, 10017 const SCEV *FoundRHS) { 10018 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10019 return true; 10020 10021 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10022 return true; 10023 10024 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10025 FoundLHS, FoundRHS) || 10026 // ~x < ~y --> x > y 10027 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10028 getNotSCEV(FoundRHS), 10029 getNotSCEV(FoundLHS)); 10030 } 10031 10032 /// If Expr computes ~A, return A else return nullptr 10033 static const SCEV *MatchNotExpr(const SCEV *Expr) { 10034 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 10035 if (!Add || Add->getNumOperands() != 2 || 10036 !Add->getOperand(0)->isAllOnesValue()) 10037 return nullptr; 10038 10039 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 10040 if (!AddRHS || AddRHS->getNumOperands() != 2 || 10041 !AddRHS->getOperand(0)->isAllOnesValue()) 10042 return nullptr; 10043 10044 return AddRHS->getOperand(1); 10045 } 10046 10047 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 10048 template<typename MaxExprType> 10049 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 10050 const SCEV *Candidate) { 10051 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 10052 if (!MaxExpr) return false; 10053 10054 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 10055 } 10056 10057 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 10058 template<typename MaxExprType> 10059 static bool IsMinConsistingOf(ScalarEvolution &SE, 10060 const SCEV *MaybeMinExpr, 10061 const SCEV *Candidate) { 10062 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 10063 if (!MaybeMaxExpr) 10064 return false; 10065 10066 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 10067 } 10068 10069 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10070 ICmpInst::Predicate Pred, 10071 const SCEV *LHS, const SCEV *RHS) { 10072 // If both sides are affine addrecs for the same loop, with equal 10073 // steps, and we know the recurrences don't wrap, then we only 10074 // need to check the predicate on the starting values. 10075 10076 if (!ICmpInst::isRelational(Pred)) 10077 return false; 10078 10079 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10080 if (!LAR) 10081 return false; 10082 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10083 if (!RAR) 10084 return false; 10085 if (LAR->getLoop() != RAR->getLoop()) 10086 return false; 10087 if (!LAR->isAffine() || !RAR->isAffine()) 10088 return false; 10089 10090 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10091 return false; 10092 10093 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10094 SCEV::FlagNSW : SCEV::FlagNUW; 10095 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10096 return false; 10097 10098 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10099 } 10100 10101 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10102 /// expression? 10103 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10104 ICmpInst::Predicate Pred, 10105 const SCEV *LHS, const SCEV *RHS) { 10106 switch (Pred) { 10107 default: 10108 return false; 10109 10110 case ICmpInst::ICMP_SGE: 10111 std::swap(LHS, RHS); 10112 LLVM_FALLTHROUGH; 10113 case ICmpInst::ICMP_SLE: 10114 return 10115 // min(A, ...) <= A 10116 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 10117 // A <= max(A, ...) 10118 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10119 10120 case ICmpInst::ICMP_UGE: 10121 std::swap(LHS, RHS); 10122 LLVM_FALLTHROUGH; 10123 case ICmpInst::ICMP_ULE: 10124 return 10125 // min(A, ...) <= A 10126 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 10127 // A <= max(A, ...) 10128 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10129 } 10130 10131 llvm_unreachable("covered switch fell through?!"); 10132 } 10133 10134 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10135 const SCEV *LHS, const SCEV *RHS, 10136 const SCEV *FoundLHS, 10137 const SCEV *FoundRHS, 10138 unsigned Depth) { 10139 assert(getTypeSizeInBits(LHS->getType()) == 10140 getTypeSizeInBits(RHS->getType()) && 10141 "LHS and RHS have different sizes?"); 10142 assert(getTypeSizeInBits(FoundLHS->getType()) == 10143 getTypeSizeInBits(FoundRHS->getType()) && 10144 "FoundLHS and FoundRHS have different sizes?"); 10145 // We want to avoid hurting the compile time with analysis of too big trees. 10146 if (Depth > MaxSCEVOperationsImplicationDepth) 10147 return false; 10148 // We only want to work with ICMP_SGT comparison so far. 10149 // TODO: Extend to ICMP_UGT? 10150 if (Pred == ICmpInst::ICMP_SLT) { 10151 Pred = ICmpInst::ICMP_SGT; 10152 std::swap(LHS, RHS); 10153 std::swap(FoundLHS, FoundRHS); 10154 } 10155 if (Pred != ICmpInst::ICMP_SGT) 10156 return false; 10157 10158 auto GetOpFromSExt = [&](const SCEV *S) { 10159 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10160 return Ext->getOperand(); 10161 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10162 // the constant in some cases. 10163 return S; 10164 }; 10165 10166 // Acquire values from extensions. 10167 auto *OrigLHS = LHS; 10168 auto *OrigFoundLHS = FoundLHS; 10169 LHS = GetOpFromSExt(LHS); 10170 FoundLHS = GetOpFromSExt(FoundLHS); 10171 10172 // Is the SGT predicate can be proved trivially or using the found context. 10173 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10174 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10175 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10176 FoundRHS, Depth + 1); 10177 }; 10178 10179 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10180 // We want to avoid creation of any new non-constant SCEV. Since we are 10181 // going to compare the operands to RHS, we should be certain that we don't 10182 // need any size extensions for this. So let's decline all cases when the 10183 // sizes of types of LHS and RHS do not match. 10184 // TODO: Maybe try to get RHS from sext to catch more cases? 10185 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10186 return false; 10187 10188 // Should not overflow. 10189 if (!LHSAddExpr->hasNoSignedWrap()) 10190 return false; 10191 10192 auto *LL = LHSAddExpr->getOperand(0); 10193 auto *LR = LHSAddExpr->getOperand(1); 10194 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10195 10196 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10197 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10198 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10199 }; 10200 // Try to prove the following rule: 10201 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10202 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10203 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10204 return true; 10205 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10206 Value *LL, *LR; 10207 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10208 10209 using namespace llvm::PatternMatch; 10210 10211 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10212 // Rules for division. 10213 // We are going to perform some comparisons with Denominator and its 10214 // derivative expressions. In general case, creating a SCEV for it may 10215 // lead to a complex analysis of the entire graph, and in particular it 10216 // can request trip count recalculation for the same loop. This would 10217 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10218 // this, we only want to create SCEVs that are constants in this section. 10219 // So we bail if Denominator is not a constant. 10220 if (!isa<ConstantInt>(LR)) 10221 return false; 10222 10223 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10224 10225 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10226 // then a SCEV for the numerator already exists and matches with FoundLHS. 10227 auto *Numerator = getExistingSCEV(LL); 10228 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10229 return false; 10230 10231 // Make sure that the numerator matches with FoundLHS and the denominator 10232 // is positive. 10233 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10234 return false; 10235 10236 auto *DTy = Denominator->getType(); 10237 auto *FRHSTy = FoundRHS->getType(); 10238 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10239 // One of types is a pointer and another one is not. We cannot extend 10240 // them properly to a wider type, so let us just reject this case. 10241 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10242 // to avoid this check. 10243 return false; 10244 10245 // Given that: 10246 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10247 auto *WTy = getWiderType(DTy, FRHSTy); 10248 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10249 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10250 10251 // Try to prove the following rule: 10252 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10253 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10254 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10255 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10256 if (isKnownNonPositive(RHS) && 10257 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10258 return true; 10259 10260 // Try to prove the following rule: 10261 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10262 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10263 // If we divide it by Denominator > 2, then: 10264 // 1. If FoundLHS is negative, then the result is 0. 10265 // 2. If FoundLHS is non-negative, then the result is non-negative. 10266 // Anyways, the result is non-negative. 10267 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10268 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10269 if (isKnownNegative(RHS) && 10270 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10271 return true; 10272 } 10273 } 10274 10275 // If our expression contained SCEVUnknown Phis, and we split it down and now 10276 // need to prove something for them, try to prove the predicate for every 10277 // possible incoming values of those Phis. 10278 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10279 return true; 10280 10281 return false; 10282 } 10283 10284 bool 10285 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10286 const SCEV *LHS, const SCEV *RHS) { 10287 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10288 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10289 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10290 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10291 } 10292 10293 bool 10294 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10295 const SCEV *LHS, const SCEV *RHS, 10296 const SCEV *FoundLHS, 10297 const SCEV *FoundRHS) { 10298 switch (Pred) { 10299 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10300 case ICmpInst::ICMP_EQ: 10301 case ICmpInst::ICMP_NE: 10302 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10303 return true; 10304 break; 10305 case ICmpInst::ICMP_SLT: 10306 case ICmpInst::ICMP_SLE: 10307 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10308 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10309 return true; 10310 break; 10311 case ICmpInst::ICMP_SGT: 10312 case ICmpInst::ICMP_SGE: 10313 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10314 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10315 return true; 10316 break; 10317 case ICmpInst::ICMP_ULT: 10318 case ICmpInst::ICMP_ULE: 10319 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10320 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10321 return true; 10322 break; 10323 case ICmpInst::ICMP_UGT: 10324 case ICmpInst::ICMP_UGE: 10325 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10326 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10327 return true; 10328 break; 10329 } 10330 10331 // Maybe it can be proved via operations? 10332 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10333 return true; 10334 10335 return false; 10336 } 10337 10338 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10339 const SCEV *LHS, 10340 const SCEV *RHS, 10341 const SCEV *FoundLHS, 10342 const SCEV *FoundRHS) { 10343 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10344 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10345 // reduce the compile time impact of this optimization. 10346 return false; 10347 10348 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10349 if (!Addend) 10350 return false; 10351 10352 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10353 10354 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10355 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10356 ConstantRange FoundLHSRange = 10357 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10358 10359 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10360 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10361 10362 // We can also compute the range of values for `LHS` that satisfy the 10363 // consequent, "`LHS` `Pred` `RHS`": 10364 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10365 ConstantRange SatisfyingLHSRange = 10366 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10367 10368 // The antecedent implies the consequent if every value of `LHS` that 10369 // satisfies the antecedent also satisfies the consequent. 10370 return SatisfyingLHSRange.contains(LHSRange); 10371 } 10372 10373 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10374 bool IsSigned, bool NoWrap) { 10375 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10376 10377 if (NoWrap) return false; 10378 10379 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10380 const SCEV *One = getOne(Stride->getType()); 10381 10382 if (IsSigned) { 10383 APInt MaxRHS = getSignedRangeMax(RHS); 10384 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10385 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10386 10387 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10388 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10389 } 10390 10391 APInt MaxRHS = getUnsignedRangeMax(RHS); 10392 APInt MaxValue = APInt::getMaxValue(BitWidth); 10393 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10394 10395 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10396 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10397 } 10398 10399 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10400 bool IsSigned, bool NoWrap) { 10401 if (NoWrap) return false; 10402 10403 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10404 const SCEV *One = getOne(Stride->getType()); 10405 10406 if (IsSigned) { 10407 APInt MinRHS = getSignedRangeMin(RHS); 10408 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10409 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10410 10411 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10412 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10413 } 10414 10415 APInt MinRHS = getUnsignedRangeMin(RHS); 10416 APInt MinValue = APInt::getMinValue(BitWidth); 10417 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10418 10419 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10420 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10421 } 10422 10423 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10424 bool Equality) { 10425 const SCEV *One = getOne(Step->getType()); 10426 Delta = Equality ? getAddExpr(Delta, Step) 10427 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10428 return getUDivExpr(Delta, Step); 10429 } 10430 10431 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10432 const SCEV *Stride, 10433 const SCEV *End, 10434 unsigned BitWidth, 10435 bool IsSigned) { 10436 10437 assert(!isKnownNonPositive(Stride) && 10438 "Stride is expected strictly positive!"); 10439 // Calculate the maximum backedge count based on the range of values 10440 // permitted by Start, End, and Stride. 10441 const SCEV *MaxBECount; 10442 APInt MinStart = 10443 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10444 10445 APInt StrideForMaxBECount = 10446 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10447 10448 // We already know that the stride is positive, so we paper over conservatism 10449 // in our range computation by forcing StrideForMaxBECount to be at least one. 10450 // In theory this is unnecessary, but we expect MaxBECount to be a 10451 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10452 // is nothing to constant fold it to). 10453 APInt One(BitWidth, 1, IsSigned); 10454 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10455 10456 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10457 : APInt::getMaxValue(BitWidth); 10458 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10459 10460 // Although End can be a MAX expression we estimate MaxEnd considering only 10461 // the case End = RHS of the loop termination condition. This is safe because 10462 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10463 // taken count. 10464 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10465 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10466 10467 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10468 getConstant(StrideForMaxBECount) /* Step */, 10469 false /* Equality */); 10470 10471 return MaxBECount; 10472 } 10473 10474 ScalarEvolution::ExitLimit 10475 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10476 const Loop *L, bool IsSigned, 10477 bool ControlsExit, bool AllowPredicates) { 10478 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10479 10480 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10481 bool PredicatedIV = false; 10482 10483 if (!IV && AllowPredicates) { 10484 // Try to make this an AddRec using runtime tests, in the first X 10485 // iterations of this loop, where X is the SCEV expression found by the 10486 // algorithm below. 10487 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10488 PredicatedIV = true; 10489 } 10490 10491 // Avoid weird loops 10492 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10493 return getCouldNotCompute(); 10494 10495 bool NoWrap = ControlsExit && 10496 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10497 10498 const SCEV *Stride = IV->getStepRecurrence(*this); 10499 10500 bool PositiveStride = isKnownPositive(Stride); 10501 10502 // Avoid negative or zero stride values. 10503 if (!PositiveStride) { 10504 // We can compute the correct backedge taken count for loops with unknown 10505 // strides if we can prove that the loop is not an infinite loop with side 10506 // effects. Here's the loop structure we are trying to handle - 10507 // 10508 // i = start 10509 // do { 10510 // A[i] = i; 10511 // i += s; 10512 // } while (i < end); 10513 // 10514 // The backedge taken count for such loops is evaluated as - 10515 // (max(end, start + stride) - start - 1) /u stride 10516 // 10517 // The additional preconditions that we need to check to prove correctness 10518 // of the above formula is as follows - 10519 // 10520 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10521 // NoWrap flag). 10522 // b) loop is single exit with no side effects. 10523 // 10524 // 10525 // Precondition a) implies that if the stride is negative, this is a single 10526 // trip loop. The backedge taken count formula reduces to zero in this case. 10527 // 10528 // Precondition b) implies that the unknown stride cannot be zero otherwise 10529 // we have UB. 10530 // 10531 // The positive stride case is the same as isKnownPositive(Stride) returning 10532 // true (original behavior of the function). 10533 // 10534 // We want to make sure that the stride is truly unknown as there are edge 10535 // cases where ScalarEvolution propagates no wrap flags to the 10536 // post-increment/decrement IV even though the increment/decrement operation 10537 // itself is wrapping. The computed backedge taken count may be wrong in 10538 // such cases. This is prevented by checking that the stride is not known to 10539 // be either positive or non-positive. For example, no wrap flags are 10540 // propagated to the post-increment IV of this loop with a trip count of 2 - 10541 // 10542 // unsigned char i; 10543 // for(i=127; i<128; i+=129) 10544 // A[i] = i; 10545 // 10546 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10547 !loopHasNoSideEffects(L)) 10548 return getCouldNotCompute(); 10549 } else if (!Stride->isOne() && 10550 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10551 // Avoid proven overflow cases: this will ensure that the backedge taken 10552 // count will not generate any unsigned overflow. Relaxed no-overflow 10553 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10554 // undefined behaviors like the case of C language. 10555 return getCouldNotCompute(); 10556 10557 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10558 : ICmpInst::ICMP_ULT; 10559 const SCEV *Start = IV->getStart(); 10560 const SCEV *End = RHS; 10561 // When the RHS is not invariant, we do not know the end bound of the loop and 10562 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10563 // calculate the MaxBECount, given the start, stride and max value for the end 10564 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10565 // checked above). 10566 if (!isLoopInvariant(RHS, L)) { 10567 const SCEV *MaxBECount = computeMaxBECountForLT( 10568 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10569 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10570 false /*MaxOrZero*/, Predicates); 10571 } 10572 // If the backedge is taken at least once, then it will be taken 10573 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10574 // is the LHS value of the less-than comparison the first time it is evaluated 10575 // and End is the RHS. 10576 const SCEV *BECountIfBackedgeTaken = 10577 computeBECount(getMinusSCEV(End, Start), Stride, false); 10578 // If the loop entry is guarded by the result of the backedge test of the 10579 // first loop iteration, then we know the backedge will be taken at least 10580 // once and so the backedge taken count is as above. If not then we use the 10581 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10582 // as if the backedge is taken at least once max(End,Start) is End and so the 10583 // result is as above, and if not max(End,Start) is Start so we get a backedge 10584 // count of zero. 10585 const SCEV *BECount; 10586 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10587 BECount = BECountIfBackedgeTaken; 10588 else { 10589 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10590 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10591 } 10592 10593 const SCEV *MaxBECount; 10594 bool MaxOrZero = false; 10595 if (isa<SCEVConstant>(BECount)) 10596 MaxBECount = BECount; 10597 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10598 // If we know exactly how many times the backedge will be taken if it's 10599 // taken at least once, then the backedge count will either be that or 10600 // zero. 10601 MaxBECount = BECountIfBackedgeTaken; 10602 MaxOrZero = true; 10603 } else { 10604 MaxBECount = computeMaxBECountForLT( 10605 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10606 } 10607 10608 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10609 !isa<SCEVCouldNotCompute>(BECount)) 10610 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10611 10612 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10613 } 10614 10615 ScalarEvolution::ExitLimit 10616 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10617 const Loop *L, bool IsSigned, 10618 bool ControlsExit, bool AllowPredicates) { 10619 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10620 // We handle only IV > Invariant 10621 if (!isLoopInvariant(RHS, L)) 10622 return getCouldNotCompute(); 10623 10624 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10625 if (!IV && AllowPredicates) 10626 // Try to make this an AddRec using runtime tests, in the first X 10627 // iterations of this loop, where X is the SCEV expression found by the 10628 // algorithm below. 10629 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10630 10631 // Avoid weird loops 10632 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10633 return getCouldNotCompute(); 10634 10635 bool NoWrap = ControlsExit && 10636 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10637 10638 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10639 10640 // Avoid negative or zero stride values 10641 if (!isKnownPositive(Stride)) 10642 return getCouldNotCompute(); 10643 10644 // Avoid proven overflow cases: this will ensure that the backedge taken count 10645 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10646 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10647 // behaviors like the case of C language. 10648 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10649 return getCouldNotCompute(); 10650 10651 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10652 : ICmpInst::ICMP_UGT; 10653 10654 const SCEV *Start = IV->getStart(); 10655 const SCEV *End = RHS; 10656 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10657 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10658 10659 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10660 10661 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10662 : getUnsignedRangeMax(Start); 10663 10664 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10665 : getUnsignedRangeMin(Stride); 10666 10667 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10668 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10669 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10670 10671 // Although End can be a MIN expression we estimate MinEnd considering only 10672 // the case End = RHS. This is safe because in the other case (Start - End) 10673 // is zero, leading to a zero maximum backedge taken count. 10674 APInt MinEnd = 10675 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10676 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10677 10678 10679 const SCEV *MaxBECount = getCouldNotCompute(); 10680 if (isa<SCEVConstant>(BECount)) 10681 MaxBECount = BECount; 10682 else 10683 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10684 getConstant(MinStride), false); 10685 10686 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10687 MaxBECount = BECount; 10688 10689 return ExitLimit(BECount, MaxBECount, false, Predicates); 10690 } 10691 10692 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10693 ScalarEvolution &SE) const { 10694 if (Range.isFullSet()) // Infinite loop. 10695 return SE.getCouldNotCompute(); 10696 10697 // If the start is a non-zero constant, shift the range to simplify things. 10698 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10699 if (!SC->getValue()->isZero()) { 10700 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10701 Operands[0] = SE.getZero(SC->getType()); 10702 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10703 getNoWrapFlags(FlagNW)); 10704 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10705 return ShiftedAddRec->getNumIterationsInRange( 10706 Range.subtract(SC->getAPInt()), SE); 10707 // This is strange and shouldn't happen. 10708 return SE.getCouldNotCompute(); 10709 } 10710 10711 // The only time we can solve this is when we have all constant indices. 10712 // Otherwise, we cannot determine the overflow conditions. 10713 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10714 return SE.getCouldNotCompute(); 10715 10716 // Okay at this point we know that all elements of the chrec are constants and 10717 // that the start element is zero. 10718 10719 // First check to see if the range contains zero. If not, the first 10720 // iteration exits. 10721 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10722 if (!Range.contains(APInt(BitWidth, 0))) 10723 return SE.getZero(getType()); 10724 10725 if (isAffine()) { 10726 // If this is an affine expression then we have this situation: 10727 // Solve {0,+,A} in Range === Ax in Range 10728 10729 // We know that zero is in the range. If A is positive then we know that 10730 // the upper value of the range must be the first possible exit value. 10731 // If A is negative then the lower of the range is the last possible loop 10732 // value. Also note that we already checked for a full range. 10733 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10734 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10735 10736 // The exit value should be (End+A)/A. 10737 APInt ExitVal = (End + A).udiv(A); 10738 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10739 10740 // Evaluate at the exit value. If we really did fall out of the valid 10741 // range, then we computed our trip count, otherwise wrap around or other 10742 // things must have happened. 10743 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10744 if (Range.contains(Val->getValue())) 10745 return SE.getCouldNotCompute(); // Something strange happened 10746 10747 // Ensure that the previous value is in the range. This is a sanity check. 10748 assert(Range.contains( 10749 EvaluateConstantChrecAtConstant(this, 10750 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10751 "Linear scev computation is off in a bad way!"); 10752 return SE.getConstant(ExitValue); 10753 } 10754 10755 if (isQuadratic()) { 10756 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10757 return SE.getConstant(S.getValue()); 10758 } 10759 10760 return SE.getCouldNotCompute(); 10761 } 10762 10763 const SCEVAddRecExpr * 10764 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10765 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10766 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10767 // but in this case we cannot guarantee that the value returned will be an 10768 // AddRec because SCEV does not have a fixed point where it stops 10769 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10770 // may happen if we reach arithmetic depth limit while simplifying. So we 10771 // construct the returned value explicitly. 10772 SmallVector<const SCEV *, 3> Ops; 10773 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10774 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10775 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10776 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10777 // We know that the last operand is not a constant zero (otherwise it would 10778 // have been popped out earlier). This guarantees us that if the result has 10779 // the same last operand, then it will also not be popped out, meaning that 10780 // the returned value will be an AddRec. 10781 const SCEV *Last = getOperand(getNumOperands() - 1); 10782 assert(!Last->isZero() && "Recurrency with zero step?"); 10783 Ops.push_back(Last); 10784 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10785 SCEV::FlagAnyWrap)); 10786 } 10787 10788 // Return true when S contains at least an undef value. 10789 static inline bool containsUndefs(const SCEV *S) { 10790 return SCEVExprContains(S, [](const SCEV *S) { 10791 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10792 return isa<UndefValue>(SU->getValue()); 10793 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10794 return isa<UndefValue>(SC->getValue()); 10795 return false; 10796 }); 10797 } 10798 10799 namespace { 10800 10801 // Collect all steps of SCEV expressions. 10802 struct SCEVCollectStrides { 10803 ScalarEvolution &SE; 10804 SmallVectorImpl<const SCEV *> &Strides; 10805 10806 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10807 : SE(SE), Strides(S) {} 10808 10809 bool follow(const SCEV *S) { 10810 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10811 Strides.push_back(AR->getStepRecurrence(SE)); 10812 return true; 10813 } 10814 10815 bool isDone() const { return false; } 10816 }; 10817 10818 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10819 struct SCEVCollectTerms { 10820 SmallVectorImpl<const SCEV *> &Terms; 10821 10822 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10823 10824 bool follow(const SCEV *S) { 10825 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10826 isa<SCEVSignExtendExpr>(S)) { 10827 if (!containsUndefs(S)) 10828 Terms.push_back(S); 10829 10830 // Stop recursion: once we collected a term, do not walk its operands. 10831 return false; 10832 } 10833 10834 // Keep looking. 10835 return true; 10836 } 10837 10838 bool isDone() const { return false; } 10839 }; 10840 10841 // Check if a SCEV contains an AddRecExpr. 10842 struct SCEVHasAddRec { 10843 bool &ContainsAddRec; 10844 10845 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10846 ContainsAddRec = false; 10847 } 10848 10849 bool follow(const SCEV *S) { 10850 if (isa<SCEVAddRecExpr>(S)) { 10851 ContainsAddRec = true; 10852 10853 // Stop recursion: once we collected a term, do not walk its operands. 10854 return false; 10855 } 10856 10857 // Keep looking. 10858 return true; 10859 } 10860 10861 bool isDone() const { return false; } 10862 }; 10863 10864 // Find factors that are multiplied with an expression that (possibly as a 10865 // subexpression) contains an AddRecExpr. In the expression: 10866 // 10867 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10868 // 10869 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10870 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10871 // parameters as they form a product with an induction variable. 10872 // 10873 // This collector expects all array size parameters to be in the same MulExpr. 10874 // It might be necessary to later add support for collecting parameters that are 10875 // spread over different nested MulExpr. 10876 struct SCEVCollectAddRecMultiplies { 10877 SmallVectorImpl<const SCEV *> &Terms; 10878 ScalarEvolution &SE; 10879 10880 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10881 : Terms(T), SE(SE) {} 10882 10883 bool follow(const SCEV *S) { 10884 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10885 bool HasAddRec = false; 10886 SmallVector<const SCEV *, 0> Operands; 10887 for (auto Op : Mul->operands()) { 10888 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10889 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10890 Operands.push_back(Op); 10891 } else if (Unknown) { 10892 HasAddRec = true; 10893 } else { 10894 bool ContainsAddRec; 10895 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10896 visitAll(Op, ContiansAddRec); 10897 HasAddRec |= ContainsAddRec; 10898 } 10899 } 10900 if (Operands.size() == 0) 10901 return true; 10902 10903 if (!HasAddRec) 10904 return false; 10905 10906 Terms.push_back(SE.getMulExpr(Operands)); 10907 // Stop recursion: once we collected a term, do not walk its operands. 10908 return false; 10909 } 10910 10911 // Keep looking. 10912 return true; 10913 } 10914 10915 bool isDone() const { return false; } 10916 }; 10917 10918 } // end anonymous namespace 10919 10920 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10921 /// two places: 10922 /// 1) The strides of AddRec expressions. 10923 /// 2) Unknowns that are multiplied with AddRec expressions. 10924 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10925 SmallVectorImpl<const SCEV *> &Terms) { 10926 SmallVector<const SCEV *, 4> Strides; 10927 SCEVCollectStrides StrideCollector(*this, Strides); 10928 visitAll(Expr, StrideCollector); 10929 10930 LLVM_DEBUG({ 10931 dbgs() << "Strides:\n"; 10932 for (const SCEV *S : Strides) 10933 dbgs() << *S << "\n"; 10934 }); 10935 10936 for (const SCEV *S : Strides) { 10937 SCEVCollectTerms TermCollector(Terms); 10938 visitAll(S, TermCollector); 10939 } 10940 10941 LLVM_DEBUG({ 10942 dbgs() << "Terms:\n"; 10943 for (const SCEV *T : Terms) 10944 dbgs() << *T << "\n"; 10945 }); 10946 10947 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10948 visitAll(Expr, MulCollector); 10949 } 10950 10951 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10952 SmallVectorImpl<const SCEV *> &Terms, 10953 SmallVectorImpl<const SCEV *> &Sizes) { 10954 int Last = Terms.size() - 1; 10955 const SCEV *Step = Terms[Last]; 10956 10957 // End of recursion. 10958 if (Last == 0) { 10959 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10960 SmallVector<const SCEV *, 2> Qs; 10961 for (const SCEV *Op : M->operands()) 10962 if (!isa<SCEVConstant>(Op)) 10963 Qs.push_back(Op); 10964 10965 Step = SE.getMulExpr(Qs); 10966 } 10967 10968 Sizes.push_back(Step); 10969 return true; 10970 } 10971 10972 for (const SCEV *&Term : Terms) { 10973 // Normalize the terms before the next call to findArrayDimensionsRec. 10974 const SCEV *Q, *R; 10975 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10976 10977 // Bail out when GCD does not evenly divide one of the terms. 10978 if (!R->isZero()) 10979 return false; 10980 10981 Term = Q; 10982 } 10983 10984 // Remove all SCEVConstants. 10985 Terms.erase( 10986 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10987 Terms.end()); 10988 10989 if (Terms.size() > 0) 10990 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10991 return false; 10992 10993 Sizes.push_back(Step); 10994 return true; 10995 } 10996 10997 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10998 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10999 for (const SCEV *T : Terms) 11000 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11001 return true; 11002 return false; 11003 } 11004 11005 // Return the number of product terms in S. 11006 static inline int numberOfTerms(const SCEV *S) { 11007 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11008 return Expr->getNumOperands(); 11009 return 1; 11010 } 11011 11012 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11013 if (isa<SCEVConstant>(T)) 11014 return nullptr; 11015 11016 if (isa<SCEVUnknown>(T)) 11017 return T; 11018 11019 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11020 SmallVector<const SCEV *, 2> Factors; 11021 for (const SCEV *Op : M->operands()) 11022 if (!isa<SCEVConstant>(Op)) 11023 Factors.push_back(Op); 11024 11025 return SE.getMulExpr(Factors); 11026 } 11027 11028 return T; 11029 } 11030 11031 /// Return the size of an element read or written by Inst. 11032 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11033 Type *Ty; 11034 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11035 Ty = Store->getValueOperand()->getType(); 11036 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11037 Ty = Load->getType(); 11038 else 11039 return nullptr; 11040 11041 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11042 return getSizeOfExpr(ETy, Ty); 11043 } 11044 11045 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11046 SmallVectorImpl<const SCEV *> &Sizes, 11047 const SCEV *ElementSize) { 11048 if (Terms.size() < 1 || !ElementSize) 11049 return; 11050 11051 // Early return when Terms do not contain parameters: we do not delinearize 11052 // non parametric SCEVs. 11053 if (!containsParameters(Terms)) 11054 return; 11055 11056 LLVM_DEBUG({ 11057 dbgs() << "Terms:\n"; 11058 for (const SCEV *T : Terms) 11059 dbgs() << *T << "\n"; 11060 }); 11061 11062 // Remove duplicates. 11063 array_pod_sort(Terms.begin(), Terms.end()); 11064 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11065 11066 // Put larger terms first. 11067 llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 11068 return numberOfTerms(LHS) > numberOfTerms(RHS); 11069 }); 11070 11071 // Try to divide all terms by the element size. If term is not divisible by 11072 // element size, proceed with the original term. 11073 for (const SCEV *&Term : Terms) { 11074 const SCEV *Q, *R; 11075 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11076 if (!Q->isZero()) 11077 Term = Q; 11078 } 11079 11080 SmallVector<const SCEV *, 4> NewTerms; 11081 11082 // Remove constant factors. 11083 for (const SCEV *T : Terms) 11084 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11085 NewTerms.push_back(NewT); 11086 11087 LLVM_DEBUG({ 11088 dbgs() << "Terms after sorting:\n"; 11089 for (const SCEV *T : NewTerms) 11090 dbgs() << *T << "\n"; 11091 }); 11092 11093 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11094 Sizes.clear(); 11095 return; 11096 } 11097 11098 // The last element to be pushed into Sizes is the size of an element. 11099 Sizes.push_back(ElementSize); 11100 11101 LLVM_DEBUG({ 11102 dbgs() << "Sizes:\n"; 11103 for (const SCEV *S : Sizes) 11104 dbgs() << *S << "\n"; 11105 }); 11106 } 11107 11108 void ScalarEvolution::computeAccessFunctions( 11109 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11110 SmallVectorImpl<const SCEV *> &Sizes) { 11111 // Early exit in case this SCEV is not an affine multivariate function. 11112 if (Sizes.empty()) 11113 return; 11114 11115 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11116 if (!AR->isAffine()) 11117 return; 11118 11119 const SCEV *Res = Expr; 11120 int Last = Sizes.size() - 1; 11121 for (int i = Last; i >= 0; i--) { 11122 const SCEV *Q, *R; 11123 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11124 11125 LLVM_DEBUG({ 11126 dbgs() << "Res: " << *Res << "\n"; 11127 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11128 dbgs() << "Res divided by Sizes[i]:\n"; 11129 dbgs() << "Quotient: " << *Q << "\n"; 11130 dbgs() << "Remainder: " << *R << "\n"; 11131 }); 11132 11133 Res = Q; 11134 11135 // Do not record the last subscript corresponding to the size of elements in 11136 // the array. 11137 if (i == Last) { 11138 11139 // Bail out if the remainder is too complex. 11140 if (isa<SCEVAddRecExpr>(R)) { 11141 Subscripts.clear(); 11142 Sizes.clear(); 11143 return; 11144 } 11145 11146 continue; 11147 } 11148 11149 // Record the access function for the current subscript. 11150 Subscripts.push_back(R); 11151 } 11152 11153 // Also push in last position the remainder of the last division: it will be 11154 // the access function of the innermost dimension. 11155 Subscripts.push_back(Res); 11156 11157 std::reverse(Subscripts.begin(), Subscripts.end()); 11158 11159 LLVM_DEBUG({ 11160 dbgs() << "Subscripts:\n"; 11161 for (const SCEV *S : Subscripts) 11162 dbgs() << *S << "\n"; 11163 }); 11164 } 11165 11166 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11167 /// sizes of an array access. Returns the remainder of the delinearization that 11168 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11169 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11170 /// expressions in the stride and base of a SCEV corresponding to the 11171 /// computation of a GCD (greatest common divisor) of base and stride. When 11172 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11173 /// 11174 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11175 /// 11176 /// void foo(long n, long m, long o, double A[n][m][o]) { 11177 /// 11178 /// for (long i = 0; i < n; i++) 11179 /// for (long j = 0; j < m; j++) 11180 /// for (long k = 0; k < o; k++) 11181 /// A[i][j][k] = 1.0; 11182 /// } 11183 /// 11184 /// the delinearization input is the following AddRec SCEV: 11185 /// 11186 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11187 /// 11188 /// From this SCEV, we are able to say that the base offset of the access is %A 11189 /// because it appears as an offset that does not divide any of the strides in 11190 /// the loops: 11191 /// 11192 /// CHECK: Base offset: %A 11193 /// 11194 /// and then SCEV->delinearize determines the size of some of the dimensions of 11195 /// the array as these are the multiples by which the strides are happening: 11196 /// 11197 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11198 /// 11199 /// Note that the outermost dimension remains of UnknownSize because there are 11200 /// no strides that would help identifying the size of the last dimension: when 11201 /// the array has been statically allocated, one could compute the size of that 11202 /// dimension by dividing the overall size of the array by the size of the known 11203 /// dimensions: %m * %o * 8. 11204 /// 11205 /// Finally delinearize provides the access functions for the array reference 11206 /// that does correspond to A[i][j][k] of the above C testcase: 11207 /// 11208 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11209 /// 11210 /// The testcases are checking the output of a function pass: 11211 /// DelinearizationPass that walks through all loads and stores of a function 11212 /// asking for the SCEV of the memory access with respect to all enclosing 11213 /// loops, calling SCEV->delinearize on that and printing the results. 11214 void ScalarEvolution::delinearize(const SCEV *Expr, 11215 SmallVectorImpl<const SCEV *> &Subscripts, 11216 SmallVectorImpl<const SCEV *> &Sizes, 11217 const SCEV *ElementSize) { 11218 // First step: collect parametric terms. 11219 SmallVector<const SCEV *, 4> Terms; 11220 collectParametricTerms(Expr, Terms); 11221 11222 if (Terms.empty()) 11223 return; 11224 11225 // Second step: find subscript sizes. 11226 findArrayDimensions(Terms, Sizes, ElementSize); 11227 11228 if (Sizes.empty()) 11229 return; 11230 11231 // Third step: compute the access functions for each subscript. 11232 computeAccessFunctions(Expr, Subscripts, Sizes); 11233 11234 if (Subscripts.empty()) 11235 return; 11236 11237 LLVM_DEBUG({ 11238 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11239 dbgs() << "ArrayDecl[UnknownSize]"; 11240 for (const SCEV *S : Sizes) 11241 dbgs() << "[" << *S << "]"; 11242 11243 dbgs() << "\nArrayRef"; 11244 for (const SCEV *S : Subscripts) 11245 dbgs() << "[" << *S << "]"; 11246 dbgs() << "\n"; 11247 }); 11248 } 11249 11250 //===----------------------------------------------------------------------===// 11251 // SCEVCallbackVH Class Implementation 11252 //===----------------------------------------------------------------------===// 11253 11254 void ScalarEvolution::SCEVCallbackVH::deleted() { 11255 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11256 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11257 SE->ConstantEvolutionLoopExitValue.erase(PN); 11258 SE->eraseValueFromMap(getValPtr()); 11259 // this now dangles! 11260 } 11261 11262 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11263 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11264 11265 // Forget all the expressions associated with users of the old value, 11266 // so that future queries will recompute the expressions using the new 11267 // value. 11268 Value *Old = getValPtr(); 11269 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11270 SmallPtrSet<User *, 8> Visited; 11271 while (!Worklist.empty()) { 11272 User *U = Worklist.pop_back_val(); 11273 // Deleting the Old value will cause this to dangle. Postpone 11274 // that until everything else is done. 11275 if (U == Old) 11276 continue; 11277 if (!Visited.insert(U).second) 11278 continue; 11279 if (PHINode *PN = dyn_cast<PHINode>(U)) 11280 SE->ConstantEvolutionLoopExitValue.erase(PN); 11281 SE->eraseValueFromMap(U); 11282 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11283 } 11284 // Delete the Old value. 11285 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11286 SE->ConstantEvolutionLoopExitValue.erase(PN); 11287 SE->eraseValueFromMap(Old); 11288 // this now dangles! 11289 } 11290 11291 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11292 : CallbackVH(V), SE(se) {} 11293 11294 //===----------------------------------------------------------------------===// 11295 // ScalarEvolution Class Implementation 11296 //===----------------------------------------------------------------------===// 11297 11298 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11299 AssumptionCache &AC, DominatorTree &DT, 11300 LoopInfo &LI) 11301 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11302 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11303 LoopDispositions(64), BlockDispositions(64) { 11304 // To use guards for proving predicates, we need to scan every instruction in 11305 // relevant basic blocks, and not just terminators. Doing this is a waste of 11306 // time if the IR does not actually contain any calls to 11307 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11308 // 11309 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11310 // to _add_ guards to the module when there weren't any before, and wants 11311 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11312 // efficient in lieu of being smart in that rather obscure case. 11313 11314 auto *GuardDecl = F.getParent()->getFunction( 11315 Intrinsic::getName(Intrinsic::experimental_guard)); 11316 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11317 } 11318 11319 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11320 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11321 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11322 ValueExprMap(std::move(Arg.ValueExprMap)), 11323 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11324 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11325 PendingMerges(std::move(Arg.PendingMerges)), 11326 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11327 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11328 PredicatedBackedgeTakenCounts( 11329 std::move(Arg.PredicatedBackedgeTakenCounts)), 11330 ConstantEvolutionLoopExitValue( 11331 std::move(Arg.ConstantEvolutionLoopExitValue)), 11332 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11333 LoopDispositions(std::move(Arg.LoopDispositions)), 11334 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11335 BlockDispositions(std::move(Arg.BlockDispositions)), 11336 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11337 SignedRanges(std::move(Arg.SignedRanges)), 11338 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11339 UniquePreds(std::move(Arg.UniquePreds)), 11340 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11341 LoopUsers(std::move(Arg.LoopUsers)), 11342 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11343 FirstUnknown(Arg.FirstUnknown) { 11344 Arg.FirstUnknown = nullptr; 11345 } 11346 11347 ScalarEvolution::~ScalarEvolution() { 11348 // Iterate through all the SCEVUnknown instances and call their 11349 // destructors, so that they release their references to their values. 11350 for (SCEVUnknown *U = FirstUnknown; U;) { 11351 SCEVUnknown *Tmp = U; 11352 U = U->Next; 11353 Tmp->~SCEVUnknown(); 11354 } 11355 FirstUnknown = nullptr; 11356 11357 ExprValueMap.clear(); 11358 ValueExprMap.clear(); 11359 HasRecMap.clear(); 11360 11361 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11362 // that a loop had multiple computable exits. 11363 for (auto &BTCI : BackedgeTakenCounts) 11364 BTCI.second.clear(); 11365 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11366 BTCI.second.clear(); 11367 11368 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11369 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11370 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11371 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11372 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11373 } 11374 11375 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11376 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11377 } 11378 11379 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11380 const Loop *L) { 11381 // Print all inner loops first 11382 for (Loop *I : *L) 11383 PrintLoopInfo(OS, SE, I); 11384 11385 OS << "Loop "; 11386 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11387 OS << ": "; 11388 11389 SmallVector<BasicBlock *, 8> ExitBlocks; 11390 L->getExitBlocks(ExitBlocks); 11391 if (ExitBlocks.size() != 1) 11392 OS << "<multiple exits> "; 11393 11394 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11395 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 11396 } else { 11397 OS << "Unpredictable backedge-taken count. "; 11398 } 11399 11400 OS << "\n" 11401 "Loop "; 11402 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11403 OS << ": "; 11404 11405 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 11406 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 11407 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11408 OS << ", actual taken count either this or zero."; 11409 } else { 11410 OS << "Unpredictable max backedge-taken count. "; 11411 } 11412 11413 OS << "\n" 11414 "Loop "; 11415 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11416 OS << ": "; 11417 11418 SCEVUnionPredicate Pred; 11419 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11420 if (!isa<SCEVCouldNotCompute>(PBT)) { 11421 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11422 OS << " Predicates:\n"; 11423 Pred.print(OS, 4); 11424 } else { 11425 OS << "Unpredictable predicated backedge-taken count. "; 11426 } 11427 OS << "\n"; 11428 11429 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11430 OS << "Loop "; 11431 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11432 OS << ": "; 11433 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11434 } 11435 } 11436 11437 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11438 switch (LD) { 11439 case ScalarEvolution::LoopVariant: 11440 return "Variant"; 11441 case ScalarEvolution::LoopInvariant: 11442 return "Invariant"; 11443 case ScalarEvolution::LoopComputable: 11444 return "Computable"; 11445 } 11446 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11447 } 11448 11449 void ScalarEvolution::print(raw_ostream &OS) const { 11450 // ScalarEvolution's implementation of the print method is to print 11451 // out SCEV values of all instructions that are interesting. Doing 11452 // this potentially causes it to create new SCEV objects though, 11453 // which technically conflicts with the const qualifier. This isn't 11454 // observable from outside the class though, so casting away the 11455 // const isn't dangerous. 11456 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11457 11458 OS << "Classifying expressions for: "; 11459 F.printAsOperand(OS, /*PrintType=*/false); 11460 OS << "\n"; 11461 for (Instruction &I : instructions(F)) 11462 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11463 OS << I << '\n'; 11464 OS << " --> "; 11465 const SCEV *SV = SE.getSCEV(&I); 11466 SV->print(OS); 11467 if (!isa<SCEVCouldNotCompute>(SV)) { 11468 OS << " U: "; 11469 SE.getUnsignedRange(SV).print(OS); 11470 OS << " S: "; 11471 SE.getSignedRange(SV).print(OS); 11472 } 11473 11474 const Loop *L = LI.getLoopFor(I.getParent()); 11475 11476 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11477 if (AtUse != SV) { 11478 OS << " --> "; 11479 AtUse->print(OS); 11480 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11481 OS << " U: "; 11482 SE.getUnsignedRange(AtUse).print(OS); 11483 OS << " S: "; 11484 SE.getSignedRange(AtUse).print(OS); 11485 } 11486 } 11487 11488 if (L) { 11489 OS << "\t\t" "Exits: "; 11490 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11491 if (!SE.isLoopInvariant(ExitValue, L)) { 11492 OS << "<<Unknown>>"; 11493 } else { 11494 OS << *ExitValue; 11495 } 11496 11497 bool First = true; 11498 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11499 if (First) { 11500 OS << "\t\t" "LoopDispositions: { "; 11501 First = false; 11502 } else { 11503 OS << ", "; 11504 } 11505 11506 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11507 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11508 } 11509 11510 for (auto *InnerL : depth_first(L)) { 11511 if (InnerL == L) 11512 continue; 11513 if (First) { 11514 OS << "\t\t" "LoopDispositions: { "; 11515 First = false; 11516 } else { 11517 OS << ", "; 11518 } 11519 11520 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11521 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11522 } 11523 11524 OS << " }"; 11525 } 11526 11527 OS << "\n"; 11528 } 11529 11530 OS << "Determining loop execution counts for: "; 11531 F.printAsOperand(OS, /*PrintType=*/false); 11532 OS << "\n"; 11533 for (Loop *I : LI) 11534 PrintLoopInfo(OS, &SE, I); 11535 } 11536 11537 ScalarEvolution::LoopDisposition 11538 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11539 auto &Values = LoopDispositions[S]; 11540 for (auto &V : Values) { 11541 if (V.getPointer() == L) 11542 return V.getInt(); 11543 } 11544 Values.emplace_back(L, LoopVariant); 11545 LoopDisposition D = computeLoopDisposition(S, L); 11546 auto &Values2 = LoopDispositions[S]; 11547 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11548 if (V.getPointer() == L) { 11549 V.setInt(D); 11550 break; 11551 } 11552 } 11553 return D; 11554 } 11555 11556 ScalarEvolution::LoopDisposition 11557 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11558 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11559 case scConstant: 11560 return LoopInvariant; 11561 case scTruncate: 11562 case scZeroExtend: 11563 case scSignExtend: 11564 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11565 case scAddRecExpr: { 11566 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11567 11568 // If L is the addrec's loop, it's computable. 11569 if (AR->getLoop() == L) 11570 return LoopComputable; 11571 11572 // Add recurrences are never invariant in the function-body (null loop). 11573 if (!L) 11574 return LoopVariant; 11575 11576 // Everything that is not defined at loop entry is variant. 11577 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11578 return LoopVariant; 11579 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11580 " dominate the contained loop's header?"); 11581 11582 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11583 if (AR->getLoop()->contains(L)) 11584 return LoopInvariant; 11585 11586 // This recurrence is variant w.r.t. L if any of its operands 11587 // are variant. 11588 for (auto *Op : AR->operands()) 11589 if (!isLoopInvariant(Op, L)) 11590 return LoopVariant; 11591 11592 // Otherwise it's loop-invariant. 11593 return LoopInvariant; 11594 } 11595 case scAddExpr: 11596 case scMulExpr: 11597 case scUMaxExpr: 11598 case scSMaxExpr: { 11599 bool HasVarying = false; 11600 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11601 LoopDisposition D = getLoopDisposition(Op, L); 11602 if (D == LoopVariant) 11603 return LoopVariant; 11604 if (D == LoopComputable) 11605 HasVarying = true; 11606 } 11607 return HasVarying ? LoopComputable : LoopInvariant; 11608 } 11609 case scUDivExpr: { 11610 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11611 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11612 if (LD == LoopVariant) 11613 return LoopVariant; 11614 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11615 if (RD == LoopVariant) 11616 return LoopVariant; 11617 return (LD == LoopInvariant && RD == LoopInvariant) ? 11618 LoopInvariant : LoopComputable; 11619 } 11620 case scUnknown: 11621 // All non-instruction values are loop invariant. All instructions are loop 11622 // invariant if they are not contained in the specified loop. 11623 // Instructions are never considered invariant in the function body 11624 // (null loop) because they are defined within the "loop". 11625 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11626 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11627 return LoopInvariant; 11628 case scCouldNotCompute: 11629 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11630 } 11631 llvm_unreachable("Unknown SCEV kind!"); 11632 } 11633 11634 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11635 return getLoopDisposition(S, L) == LoopInvariant; 11636 } 11637 11638 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11639 return getLoopDisposition(S, L) == LoopComputable; 11640 } 11641 11642 ScalarEvolution::BlockDisposition 11643 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11644 auto &Values = BlockDispositions[S]; 11645 for (auto &V : Values) { 11646 if (V.getPointer() == BB) 11647 return V.getInt(); 11648 } 11649 Values.emplace_back(BB, DoesNotDominateBlock); 11650 BlockDisposition D = computeBlockDisposition(S, BB); 11651 auto &Values2 = BlockDispositions[S]; 11652 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11653 if (V.getPointer() == BB) { 11654 V.setInt(D); 11655 break; 11656 } 11657 } 11658 return D; 11659 } 11660 11661 ScalarEvolution::BlockDisposition 11662 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11663 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11664 case scConstant: 11665 return ProperlyDominatesBlock; 11666 case scTruncate: 11667 case scZeroExtend: 11668 case scSignExtend: 11669 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11670 case scAddRecExpr: { 11671 // This uses a "dominates" query instead of "properly dominates" query 11672 // to test for proper dominance too, because the instruction which 11673 // produces the addrec's value is a PHI, and a PHI effectively properly 11674 // dominates its entire containing block. 11675 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11676 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11677 return DoesNotDominateBlock; 11678 11679 // Fall through into SCEVNAryExpr handling. 11680 LLVM_FALLTHROUGH; 11681 } 11682 case scAddExpr: 11683 case scMulExpr: 11684 case scUMaxExpr: 11685 case scSMaxExpr: { 11686 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11687 bool Proper = true; 11688 for (const SCEV *NAryOp : NAry->operands()) { 11689 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11690 if (D == DoesNotDominateBlock) 11691 return DoesNotDominateBlock; 11692 if (D == DominatesBlock) 11693 Proper = false; 11694 } 11695 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11696 } 11697 case scUDivExpr: { 11698 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11699 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11700 BlockDisposition LD = getBlockDisposition(LHS, BB); 11701 if (LD == DoesNotDominateBlock) 11702 return DoesNotDominateBlock; 11703 BlockDisposition RD = getBlockDisposition(RHS, BB); 11704 if (RD == DoesNotDominateBlock) 11705 return DoesNotDominateBlock; 11706 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11707 ProperlyDominatesBlock : DominatesBlock; 11708 } 11709 case scUnknown: 11710 if (Instruction *I = 11711 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11712 if (I->getParent() == BB) 11713 return DominatesBlock; 11714 if (DT.properlyDominates(I->getParent(), BB)) 11715 return ProperlyDominatesBlock; 11716 return DoesNotDominateBlock; 11717 } 11718 return ProperlyDominatesBlock; 11719 case scCouldNotCompute: 11720 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11721 } 11722 llvm_unreachable("Unknown SCEV kind!"); 11723 } 11724 11725 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11726 return getBlockDisposition(S, BB) >= DominatesBlock; 11727 } 11728 11729 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11730 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11731 } 11732 11733 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11734 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11735 } 11736 11737 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11738 auto IsS = [&](const SCEV *X) { return S == X; }; 11739 auto ContainsS = [&](const SCEV *X) { 11740 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11741 }; 11742 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11743 } 11744 11745 void 11746 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11747 ValuesAtScopes.erase(S); 11748 LoopDispositions.erase(S); 11749 BlockDispositions.erase(S); 11750 UnsignedRanges.erase(S); 11751 SignedRanges.erase(S); 11752 ExprValueMap.erase(S); 11753 HasRecMap.erase(S); 11754 MinTrailingZerosCache.erase(S); 11755 11756 for (auto I = PredicatedSCEVRewrites.begin(); 11757 I != PredicatedSCEVRewrites.end();) { 11758 std::pair<const SCEV *, const Loop *> Entry = I->first; 11759 if (Entry.first == S) 11760 PredicatedSCEVRewrites.erase(I++); 11761 else 11762 ++I; 11763 } 11764 11765 auto RemoveSCEVFromBackedgeMap = 11766 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11767 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11768 BackedgeTakenInfo &BEInfo = I->second; 11769 if (BEInfo.hasOperand(S, this)) { 11770 BEInfo.clear(); 11771 Map.erase(I++); 11772 } else 11773 ++I; 11774 } 11775 }; 11776 11777 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11778 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11779 } 11780 11781 void 11782 ScalarEvolution::getUsedLoops(const SCEV *S, 11783 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11784 struct FindUsedLoops { 11785 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11786 : LoopsUsed(LoopsUsed) {} 11787 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11788 bool follow(const SCEV *S) { 11789 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11790 LoopsUsed.insert(AR->getLoop()); 11791 return true; 11792 } 11793 11794 bool isDone() const { return false; } 11795 }; 11796 11797 FindUsedLoops F(LoopsUsed); 11798 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11799 } 11800 11801 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11802 SmallPtrSet<const Loop *, 8> LoopsUsed; 11803 getUsedLoops(S, LoopsUsed); 11804 for (auto *L : LoopsUsed) 11805 LoopUsers[L].push_back(S); 11806 } 11807 11808 void ScalarEvolution::verify() const { 11809 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11810 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11811 11812 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11813 11814 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11815 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11816 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11817 11818 const SCEV *visitConstant(const SCEVConstant *Constant) { 11819 return SE.getConstant(Constant->getAPInt()); 11820 } 11821 11822 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11823 return SE.getUnknown(Expr->getValue()); 11824 } 11825 11826 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11827 return SE.getCouldNotCompute(); 11828 } 11829 }; 11830 11831 SCEVMapper SCM(SE2); 11832 11833 while (!LoopStack.empty()) { 11834 auto *L = LoopStack.pop_back_val(); 11835 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11836 11837 auto *CurBECount = SCM.visit( 11838 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11839 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11840 11841 if (CurBECount == SE2.getCouldNotCompute() || 11842 NewBECount == SE2.getCouldNotCompute()) { 11843 // NB! This situation is legal, but is very suspicious -- whatever pass 11844 // change the loop to make a trip count go from could not compute to 11845 // computable or vice-versa *should have* invalidated SCEV. However, we 11846 // choose not to assert here (for now) since we don't want false 11847 // positives. 11848 continue; 11849 } 11850 11851 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11852 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11853 // not propagate undef aggressively). This means we can (and do) fail 11854 // verification in cases where a transform makes the trip count of a loop 11855 // go from "undef" to "undef+1" (say). The transform is fine, since in 11856 // both cases the loop iterates "undef" times, but SCEV thinks we 11857 // increased the trip count of the loop by 1 incorrectly. 11858 continue; 11859 } 11860 11861 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11862 SE.getTypeSizeInBits(NewBECount->getType())) 11863 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11864 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11865 SE.getTypeSizeInBits(NewBECount->getType())) 11866 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11867 11868 auto *ConstantDelta = 11869 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11870 11871 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11872 dbgs() << "Trip Count Changed!\n"; 11873 dbgs() << "Old: " << *CurBECount << "\n"; 11874 dbgs() << "New: " << *NewBECount << "\n"; 11875 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11876 std::abort(); 11877 } 11878 } 11879 } 11880 11881 bool ScalarEvolution::invalidate( 11882 Function &F, const PreservedAnalyses &PA, 11883 FunctionAnalysisManager::Invalidator &Inv) { 11884 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11885 // of its dependencies is invalidated. 11886 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11887 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11888 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11889 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11890 Inv.invalidate<LoopAnalysis>(F, PA); 11891 } 11892 11893 AnalysisKey ScalarEvolutionAnalysis::Key; 11894 11895 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11896 FunctionAnalysisManager &AM) { 11897 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11898 AM.getResult<AssumptionAnalysis>(F), 11899 AM.getResult<DominatorTreeAnalysis>(F), 11900 AM.getResult<LoopAnalysis>(F)); 11901 } 11902 11903 PreservedAnalyses 11904 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11905 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11906 return PreservedAnalyses::all(); 11907 } 11908 11909 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11910 "Scalar Evolution Analysis", false, true) 11911 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11912 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11913 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11914 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11915 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11916 "Scalar Evolution Analysis", false, true) 11917 11918 char ScalarEvolutionWrapperPass::ID = 0; 11919 11920 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11921 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11922 } 11923 11924 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11925 SE.reset(new ScalarEvolution( 11926 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11927 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11928 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11929 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11930 return false; 11931 } 11932 11933 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11934 11935 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11936 SE->print(OS); 11937 } 11938 11939 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11940 if (!VerifySCEV) 11941 return; 11942 11943 SE->verify(); 11944 } 11945 11946 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11947 AU.setPreservesAll(); 11948 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11949 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11950 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11951 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11952 } 11953 11954 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11955 const SCEV *RHS) { 11956 FoldingSetNodeID ID; 11957 assert(LHS->getType() == RHS->getType() && 11958 "Type mismatch between LHS and RHS"); 11959 // Unique this node based on the arguments 11960 ID.AddInteger(SCEVPredicate::P_Equal); 11961 ID.AddPointer(LHS); 11962 ID.AddPointer(RHS); 11963 void *IP = nullptr; 11964 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11965 return S; 11966 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11967 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11968 UniquePreds.InsertNode(Eq, IP); 11969 return Eq; 11970 } 11971 11972 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11973 const SCEVAddRecExpr *AR, 11974 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11975 FoldingSetNodeID ID; 11976 // Unique this node based on the arguments 11977 ID.AddInteger(SCEVPredicate::P_Wrap); 11978 ID.AddPointer(AR); 11979 ID.AddInteger(AddedFlags); 11980 void *IP = nullptr; 11981 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11982 return S; 11983 auto *OF = new (SCEVAllocator) 11984 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11985 UniquePreds.InsertNode(OF, IP); 11986 return OF; 11987 } 11988 11989 namespace { 11990 11991 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11992 public: 11993 11994 /// Rewrites \p S in the context of a loop L and the SCEV predication 11995 /// infrastructure. 11996 /// 11997 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11998 /// equivalences present in \p Pred. 11999 /// 12000 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12001 /// \p NewPreds such that the result will be an AddRecExpr. 12002 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12003 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12004 SCEVUnionPredicate *Pred) { 12005 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12006 return Rewriter.visit(S); 12007 } 12008 12009 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12010 if (Pred) { 12011 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12012 for (auto *Pred : ExprPreds) 12013 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12014 if (IPred->getLHS() == Expr) 12015 return IPred->getRHS(); 12016 } 12017 return convertToAddRecWithPreds(Expr); 12018 } 12019 12020 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12021 const SCEV *Operand = visit(Expr->getOperand()); 12022 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12023 if (AR && AR->getLoop() == L && AR->isAffine()) { 12024 // This couldn't be folded because the operand didn't have the nuw 12025 // flag. Add the nusw flag as an assumption that we could make. 12026 const SCEV *Step = AR->getStepRecurrence(SE); 12027 Type *Ty = Expr->getType(); 12028 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12029 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12030 SE.getSignExtendExpr(Step, Ty), L, 12031 AR->getNoWrapFlags()); 12032 } 12033 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12034 } 12035 12036 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12037 const SCEV *Operand = visit(Expr->getOperand()); 12038 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12039 if (AR && AR->getLoop() == L && AR->isAffine()) { 12040 // This couldn't be folded because the operand didn't have the nsw 12041 // flag. Add the nssw flag as an assumption that we could make. 12042 const SCEV *Step = AR->getStepRecurrence(SE); 12043 Type *Ty = Expr->getType(); 12044 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12045 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12046 SE.getSignExtendExpr(Step, Ty), L, 12047 AR->getNoWrapFlags()); 12048 } 12049 return SE.getSignExtendExpr(Operand, Expr->getType()); 12050 } 12051 12052 private: 12053 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12054 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12055 SCEVUnionPredicate *Pred) 12056 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12057 12058 bool addOverflowAssumption(const SCEVPredicate *P) { 12059 if (!NewPreds) { 12060 // Check if we've already made this assumption. 12061 return Pred && Pred->implies(P); 12062 } 12063 NewPreds->insert(P); 12064 return true; 12065 } 12066 12067 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12068 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12069 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12070 return addOverflowAssumption(A); 12071 } 12072 12073 // If \p Expr represents a PHINode, we try to see if it can be represented 12074 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12075 // to add this predicate as a runtime overflow check, we return the AddRec. 12076 // If \p Expr does not meet these conditions (is not a PHI node, or we 12077 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12078 // return \p Expr. 12079 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12080 if (!isa<PHINode>(Expr->getValue())) 12081 return Expr; 12082 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12083 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12084 if (!PredicatedRewrite) 12085 return Expr; 12086 for (auto *P : PredicatedRewrite->second){ 12087 // Wrap predicates from outer loops are not supported. 12088 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12089 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12090 if (L != AR->getLoop()) 12091 return Expr; 12092 } 12093 if (!addOverflowAssumption(P)) 12094 return Expr; 12095 } 12096 return PredicatedRewrite->first; 12097 } 12098 12099 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12100 SCEVUnionPredicate *Pred; 12101 const Loop *L; 12102 }; 12103 12104 } // end anonymous namespace 12105 12106 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12107 SCEVUnionPredicate &Preds) { 12108 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12109 } 12110 12111 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12112 const SCEV *S, const Loop *L, 12113 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12114 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12115 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12116 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12117 12118 if (!AddRec) 12119 return nullptr; 12120 12121 // Since the transformation was successful, we can now transfer the SCEV 12122 // predicates. 12123 for (auto *P : TransformPreds) 12124 Preds.insert(P); 12125 12126 return AddRec; 12127 } 12128 12129 /// SCEV predicates 12130 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12131 SCEVPredicateKind Kind) 12132 : FastID(ID), Kind(Kind) {} 12133 12134 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12135 const SCEV *LHS, const SCEV *RHS) 12136 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12137 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12138 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12139 } 12140 12141 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12142 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12143 12144 if (!Op) 12145 return false; 12146 12147 return Op->LHS == LHS && Op->RHS == RHS; 12148 } 12149 12150 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12151 12152 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12153 12154 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12155 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12156 } 12157 12158 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12159 const SCEVAddRecExpr *AR, 12160 IncrementWrapFlags Flags) 12161 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12162 12163 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12164 12165 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12166 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12167 12168 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12169 } 12170 12171 bool SCEVWrapPredicate::isAlwaysTrue() const { 12172 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12173 IncrementWrapFlags IFlags = Flags; 12174 12175 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12176 IFlags = clearFlags(IFlags, IncrementNSSW); 12177 12178 return IFlags == IncrementAnyWrap; 12179 } 12180 12181 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12182 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12183 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12184 OS << "<nusw>"; 12185 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12186 OS << "<nssw>"; 12187 OS << "\n"; 12188 } 12189 12190 SCEVWrapPredicate::IncrementWrapFlags 12191 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12192 ScalarEvolution &SE) { 12193 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12194 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12195 12196 // We can safely transfer the NSW flag as NSSW. 12197 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12198 ImpliedFlags = IncrementNSSW; 12199 12200 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12201 // If the increment is positive, the SCEV NUW flag will also imply the 12202 // WrapPredicate NUSW flag. 12203 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12204 if (Step->getValue()->getValue().isNonNegative()) 12205 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12206 } 12207 12208 return ImpliedFlags; 12209 } 12210 12211 /// Union predicates don't get cached so create a dummy set ID for it. 12212 SCEVUnionPredicate::SCEVUnionPredicate() 12213 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12214 12215 bool SCEVUnionPredicate::isAlwaysTrue() const { 12216 return all_of(Preds, 12217 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12218 } 12219 12220 ArrayRef<const SCEVPredicate *> 12221 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12222 auto I = SCEVToPreds.find(Expr); 12223 if (I == SCEVToPreds.end()) 12224 return ArrayRef<const SCEVPredicate *>(); 12225 return I->second; 12226 } 12227 12228 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12229 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12230 return all_of(Set->Preds, 12231 [this](const SCEVPredicate *I) { return this->implies(I); }); 12232 12233 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12234 if (ScevPredsIt == SCEVToPreds.end()) 12235 return false; 12236 auto &SCEVPreds = ScevPredsIt->second; 12237 12238 return any_of(SCEVPreds, 12239 [N](const SCEVPredicate *I) { return I->implies(N); }); 12240 } 12241 12242 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12243 12244 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12245 for (auto Pred : Preds) 12246 Pred->print(OS, Depth); 12247 } 12248 12249 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12250 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12251 for (auto Pred : Set->Preds) 12252 add(Pred); 12253 return; 12254 } 12255 12256 if (implies(N)) 12257 return; 12258 12259 const SCEV *Key = N->getExpr(); 12260 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12261 " associated expression!"); 12262 12263 SCEVToPreds[Key].push_back(N); 12264 Preds.push_back(N); 12265 } 12266 12267 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12268 Loop &L) 12269 : SE(SE), L(L) {} 12270 12271 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12272 const SCEV *Expr = SE.getSCEV(V); 12273 RewriteEntry &Entry = RewriteMap[Expr]; 12274 12275 // If we already have an entry and the version matches, return it. 12276 if (Entry.second && Generation == Entry.first) 12277 return Entry.second; 12278 12279 // We found an entry but it's stale. Rewrite the stale entry 12280 // according to the current predicate. 12281 if (Entry.second) 12282 Expr = Entry.second; 12283 12284 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12285 Entry = {Generation, NewSCEV}; 12286 12287 return NewSCEV; 12288 } 12289 12290 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12291 if (!BackedgeCount) { 12292 SCEVUnionPredicate BackedgePred; 12293 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12294 addPredicate(BackedgePred); 12295 } 12296 return BackedgeCount; 12297 } 12298 12299 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12300 if (Preds.implies(&Pred)) 12301 return; 12302 Preds.add(&Pred); 12303 updateGeneration(); 12304 } 12305 12306 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12307 return Preds; 12308 } 12309 12310 void PredicatedScalarEvolution::updateGeneration() { 12311 // If the generation number wrapped recompute everything. 12312 if (++Generation == 0) { 12313 for (auto &II : RewriteMap) { 12314 const SCEV *Rewritten = II.second.second; 12315 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12316 } 12317 } 12318 } 12319 12320 void PredicatedScalarEvolution::setNoOverflow( 12321 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12322 const SCEV *Expr = getSCEV(V); 12323 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12324 12325 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12326 12327 // Clear the statically implied flags. 12328 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12329 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12330 12331 auto II = FlagsMap.insert({V, Flags}); 12332 if (!II.second) 12333 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12334 } 12335 12336 bool PredicatedScalarEvolution::hasNoOverflow( 12337 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12338 const SCEV *Expr = getSCEV(V); 12339 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12340 12341 Flags = SCEVWrapPredicate::clearFlags( 12342 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12343 12344 auto II = FlagsMap.find(V); 12345 12346 if (II != FlagsMap.end()) 12347 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12348 12349 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12350 } 12351 12352 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12353 const SCEV *Expr = this->getSCEV(V); 12354 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12355 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12356 12357 if (!New) 12358 return nullptr; 12359 12360 for (auto *P : NewPreds) 12361 Preds.add(P); 12362 12363 updateGeneration(); 12364 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12365 return New; 12366 } 12367 12368 PredicatedScalarEvolution::PredicatedScalarEvolution( 12369 const PredicatedScalarEvolution &Init) 12370 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12371 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12372 for (const auto &I : Init.FlagsMap) 12373 FlagsMap.insert(I); 12374 } 12375 12376 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12377 // For each block. 12378 for (auto *BB : L.getBlocks()) 12379 for (auto &I : *BB) { 12380 if (!SE.isSCEVable(I.getType())) 12381 continue; 12382 12383 auto *Expr = SE.getSCEV(&I); 12384 auto II = RewriteMap.find(Expr); 12385 12386 if (II == RewriteMap.end()) 12387 continue; 12388 12389 // Don't print things that are not interesting. 12390 if (II->second.second == Expr) 12391 continue; 12392 12393 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12394 OS.indent(Depth + 2) << *Expr << "\n"; 12395 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12396 } 12397 } 12398 12399 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12400 // arbitrary expressions. 12401 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12402 // 4, A / B becomes X / 8). 12403 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12404 const SCEV *&RHS) { 12405 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12406 if (Add == nullptr || Add->getNumOperands() != 2) 12407 return false; 12408 12409 const SCEV *A = Add->getOperand(1); 12410 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12411 12412 if (Mul == nullptr) 12413 return false; 12414 12415 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12416 // (SomeExpr + (-(SomeExpr / B) * B)). 12417 if (Expr == getURemExpr(A, B)) { 12418 LHS = A; 12419 RHS = B; 12420 return true; 12421 } 12422 return false; 12423 }; 12424 12425 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12426 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12427 return MatchURemWithDivisor(Mul->getOperand(1)) || 12428 MatchURemWithDivisor(Mul->getOperand(2)); 12429 12430 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12431 if (Mul->getNumOperands() == 2) 12432 return MatchURemWithDivisor(Mul->getOperand(1)) || 12433 MatchURemWithDivisor(Mul->getOperand(0)) || 12434 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12435 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12436 return false; 12437 } 12438