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/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/Pass.h" 115 #include "llvm/Support/Casting.h" 116 #include "llvm/Support/CommandLine.h" 117 #include "llvm/Support/Compiler.h" 118 #include "llvm/Support/Debug.h" 119 #include "llvm/Support/ErrorHandling.h" 120 #include "llvm/Support/KnownBits.h" 121 #include "llvm/Support/SaveAndRestore.h" 122 #include "llvm/Support/raw_ostream.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <climits> 126 #include <cstddef> 127 #include <cstdint> 128 #include <cstdlib> 129 #include <map> 130 #include <memory> 131 #include <tuple> 132 #include <utility> 133 #include <vector> 134 135 using namespace llvm; 136 137 #define DEBUG_TYPE "scalar-evolution" 138 139 STATISTIC(NumArrayLenItCounts, 140 "Number of trip counts computed with array length"); 141 STATISTIC(NumTripCountsComputed, 142 "Number of loops with predictable loop counts"); 143 STATISTIC(NumTripCountsNotComputed, 144 "Number of loops without predictable loop counts"); 145 STATISTIC(NumBruteForceTripCountsComputed, 146 "Number of loops with trip counts computed by force"); 147 148 static cl::opt<unsigned> 149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 150 cl::desc("Maximum number of iterations SCEV will " 151 "symbolically execute a constant " 152 "derived loop"), 153 cl::init(100)); 154 155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 156 static cl::opt<bool> VerifySCEV( 157 "verify-scev", cl::Hidden, 158 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 159 static cl::opt<bool> 160 VerifySCEVMap("verify-scev-maps", cl::Hidden, 161 cl::desc("Verify no dangling value in ScalarEvolution's " 162 "ExprValueMap (slow)")); 163 164 static cl::opt<unsigned> MulOpsInlineThreshold( 165 "scev-mulops-inline-threshold", cl::Hidden, 166 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 167 cl::init(32)); 168 169 static cl::opt<unsigned> AddOpsInlineThreshold( 170 "scev-addops-inline-threshold", cl::Hidden, 171 cl::desc("Threshold for inlining addition operands into a SCEV"), 172 cl::init(500)); 173 174 static cl::opt<unsigned> MaxSCEVCompareDepth( 175 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 176 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 180 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 181 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 182 cl::init(2)); 183 184 static cl::opt<unsigned> MaxValueCompareDepth( 185 "scalar-evolution-max-value-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive value complexity comparisons"), 187 cl::init(2)); 188 189 static cl::opt<unsigned> 190 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive arithmetics"), 192 cl::init(32)); 193 194 static cl::opt<unsigned> MaxConstantEvolvingDepth( 195 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 197 198 static cl::opt<unsigned> 199 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 200 cl::desc("Maximum depth of recursive SExt/ZExt"), 201 cl::init(8)); 202 203 static cl::opt<unsigned> 204 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 205 cl::desc("Max coefficients in AddRec during evolving"), 206 cl::init(16)); 207 208 //===----------------------------------------------------------------------===// 209 // SCEV class definitions 210 //===----------------------------------------------------------------------===// 211 212 //===----------------------------------------------------------------------===// 213 // Implementation of the SCEV class. 214 // 215 216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 217 LLVM_DUMP_METHOD void SCEV::dump() const { 218 print(dbgs()); 219 dbgs() << '\n'; 220 } 221 #endif 222 223 void SCEV::print(raw_ostream &OS) const { 224 switch (static_cast<SCEVTypes>(getSCEVType())) { 225 case scConstant: 226 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 227 return; 228 case scTruncate: { 229 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 230 const SCEV *Op = Trunc->getOperand(); 231 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 232 << *Trunc->getType() << ")"; 233 return; 234 } 235 case scZeroExtend: { 236 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 237 const SCEV *Op = ZExt->getOperand(); 238 OS << "(zext " << *Op->getType() << " " << *Op << " to " 239 << *ZExt->getType() << ")"; 240 return; 241 } 242 case scSignExtend: { 243 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 244 const SCEV *Op = SExt->getOperand(); 245 OS << "(sext " << *Op->getType() << " " << *Op << " to " 246 << *SExt->getType() << ")"; 247 return; 248 } 249 case scAddRecExpr: { 250 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 251 OS << "{" << *AR->getOperand(0); 252 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 253 OS << ",+," << *AR->getOperand(i); 254 OS << "}<"; 255 if (AR->hasNoUnsignedWrap()) 256 OS << "nuw><"; 257 if (AR->hasNoSignedWrap()) 258 OS << "nsw><"; 259 if (AR->hasNoSelfWrap() && 260 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 261 OS << "nw><"; 262 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 263 OS << ">"; 264 return; 265 } 266 case scAddExpr: 267 case scMulExpr: 268 case scUMaxExpr: 269 case scSMaxExpr: { 270 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 271 const char *OpStr = nullptr; 272 switch (NAry->getSCEVType()) { 273 case scAddExpr: OpStr = " + "; break; 274 case scMulExpr: OpStr = " * "; break; 275 case scUMaxExpr: OpStr = " umax "; break; 276 case scSMaxExpr: OpStr = " smax "; break; 277 } 278 OS << "("; 279 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 280 I != E; ++I) { 281 OS << **I; 282 if (std::next(I) != E) 283 OS << OpStr; 284 } 285 OS << ")"; 286 switch (NAry->getSCEVType()) { 287 case scAddExpr: 288 case scMulExpr: 289 if (NAry->hasNoUnsignedWrap()) 290 OS << "<nuw>"; 291 if (NAry->hasNoSignedWrap()) 292 OS << "<nsw>"; 293 } 294 return; 295 } 296 case scUDivExpr: { 297 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 298 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 299 return; 300 } 301 case scUnknown: { 302 const SCEVUnknown *U = cast<SCEVUnknown>(this); 303 Type *AllocTy; 304 if (U->isSizeOf(AllocTy)) { 305 OS << "sizeof(" << *AllocTy << ")"; 306 return; 307 } 308 if (U->isAlignOf(AllocTy)) { 309 OS << "alignof(" << *AllocTy << ")"; 310 return; 311 } 312 313 Type *CTy; 314 Constant *FieldNo; 315 if (U->isOffsetOf(CTy, FieldNo)) { 316 OS << "offsetof(" << *CTy << ", "; 317 FieldNo->printAsOperand(OS, false); 318 OS << ")"; 319 return; 320 } 321 322 // Otherwise just print it normally. 323 U->getValue()->printAsOperand(OS, false); 324 return; 325 } 326 case scCouldNotCompute: 327 OS << "***COULDNOTCOMPUTE***"; 328 return; 329 } 330 llvm_unreachable("Unknown SCEV kind!"); 331 } 332 333 Type *SCEV::getType() const { 334 switch (static_cast<SCEVTypes>(getSCEVType())) { 335 case scConstant: 336 return cast<SCEVConstant>(this)->getType(); 337 case scTruncate: 338 case scZeroExtend: 339 case scSignExtend: 340 return cast<SCEVCastExpr>(this)->getType(); 341 case scAddRecExpr: 342 case scMulExpr: 343 case scUMaxExpr: 344 case scSMaxExpr: 345 return cast<SCEVNAryExpr>(this)->getType(); 346 case scAddExpr: 347 return cast<SCEVAddExpr>(this)->getType(); 348 case scUDivExpr: 349 return cast<SCEVUDivExpr>(this)->getType(); 350 case scUnknown: 351 return cast<SCEVUnknown>(this)->getType(); 352 case scCouldNotCompute: 353 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 354 } 355 llvm_unreachable("Unknown SCEV kind!"); 356 } 357 358 bool SCEV::isZero() const { 359 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 360 return SC->getValue()->isZero(); 361 return false; 362 } 363 364 bool SCEV::isOne() const { 365 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 366 return SC->getValue()->isOne(); 367 return false; 368 } 369 370 bool SCEV::isAllOnesValue() const { 371 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 372 return SC->getValue()->isMinusOne(); 373 return false; 374 } 375 376 bool SCEV::isNonConstantNegative() const { 377 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 378 if (!Mul) return false; 379 380 // If there is a constant factor, it will be first. 381 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 382 if (!SC) return false; 383 384 // Return true if the value is negative, this matches things like (-42 * V). 385 return SC->getAPInt().isNegative(); 386 } 387 388 SCEVCouldNotCompute::SCEVCouldNotCompute() : 389 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 390 391 bool SCEVCouldNotCompute::classof(const SCEV *S) { 392 return S->getSCEVType() == scCouldNotCompute; 393 } 394 395 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 396 FoldingSetNodeID ID; 397 ID.AddInteger(scConstant); 398 ID.AddPointer(V); 399 void *IP = nullptr; 400 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 401 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 402 UniqueSCEVs.InsertNode(S, IP); 403 return S; 404 } 405 406 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 407 return getConstant(ConstantInt::get(getContext(), Val)); 408 } 409 410 const SCEV * 411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 412 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 413 return getConstant(ConstantInt::get(ITy, V, isSigned)); 414 } 415 416 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 417 unsigned SCEVTy, const SCEV *op, Type *ty) 418 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 419 420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 421 const SCEV *op, Type *ty) 422 : SCEVCastExpr(ID, scTruncate, op, ty) { 423 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 424 (Ty->isIntegerTy() || Ty->isPointerTy()) && 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()->isIntegerTy() || Op->getType()->isPointerTy()) && 432 (Ty->isIntegerTy() || Ty->isPointerTy()) && 433 "Cannot zero extend non-integer value!"); 434 } 435 436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 437 const SCEV *op, Type *ty) 438 : SCEVCastExpr(ID, scSignExtend, op, ty) { 439 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 440 (Ty->isIntegerTy() || Ty->isPointerTy()) && 441 "Cannot sign extend non-integer value!"); 442 } 443 444 void SCEVUnknown::deleted() { 445 // Clear this SCEVUnknown from various maps. 446 SE->forgetMemoizedResults(this); 447 448 // Remove this SCEVUnknown from the uniquing map. 449 SE->UniqueSCEVs.RemoveNode(this); 450 451 // Release the value. 452 setValPtr(nullptr); 453 } 454 455 void SCEVUnknown::allUsesReplacedWith(Value *New) { 456 // Remove this SCEVUnknown from the uniquing map. 457 SE->UniqueSCEVs.RemoveNode(this); 458 459 // Update this SCEVUnknown to point to the new value. This is needed 460 // because there may still be outstanding SCEVs which still point to 461 // this SCEVUnknown. 462 setValPtr(New); 463 } 464 465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 466 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 467 if (VCE->getOpcode() == Instruction::PtrToInt) 468 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 469 if (CE->getOpcode() == Instruction::GetElementPtr && 470 CE->getOperand(0)->isNullValue() && 471 CE->getNumOperands() == 2) 472 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 473 if (CI->isOne()) { 474 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 475 ->getElementType(); 476 return true; 477 } 478 479 return false; 480 } 481 482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 483 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 484 if (VCE->getOpcode() == Instruction::PtrToInt) 485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 486 if (CE->getOpcode() == Instruction::GetElementPtr && 487 CE->getOperand(0)->isNullValue()) { 488 Type *Ty = 489 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 490 if (StructType *STy = dyn_cast<StructType>(Ty)) 491 if (!STy->isPacked() && 492 CE->getNumOperands() == 3 && 493 CE->getOperand(1)->isNullValue()) { 494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 495 if (CI->isOne() && 496 STy->getNumElements() == 2 && 497 STy->getElementType(0)->isIntegerTy(1)) { 498 AllocTy = STy->getElementType(1); 499 return true; 500 } 501 } 502 } 503 504 return false; 505 } 506 507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 508 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 509 if (VCE->getOpcode() == Instruction::PtrToInt) 510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 511 if (CE->getOpcode() == Instruction::GetElementPtr && 512 CE->getNumOperands() == 3 && 513 CE->getOperand(0)->isNullValue() && 514 CE->getOperand(1)->isNullValue()) { 515 Type *Ty = 516 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 517 // Ignore vector types here so that ScalarEvolutionExpander doesn't 518 // emit getelementptrs that index into vectors. 519 if (Ty->isStructTy() || Ty->isArrayTy()) { 520 CTy = Ty; 521 FieldNo = CE->getOperand(2); 522 return true; 523 } 524 } 525 526 return false; 527 } 528 529 //===----------------------------------------------------------------------===// 530 // SCEV Utilities 531 //===----------------------------------------------------------------------===// 532 533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 535 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 536 /// have been previously deemed to be "equally complex" by this routine. It is 537 /// intended to avoid exponential time complexity in cases like: 538 /// 539 /// %a = f(%x, %y) 540 /// %b = f(%a, %a) 541 /// %c = f(%b, %b) 542 /// 543 /// %d = f(%x, %y) 544 /// %e = f(%d, %d) 545 /// %f = f(%e, %e) 546 /// 547 /// CompareValueComplexity(%f, %c) 548 /// 549 /// Since we do not continue running this routine on expression trees once we 550 /// have seen unequal values, there is no need to track them in the cache. 551 static int 552 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 553 const LoopInfo *const LI, Value *LV, Value *RV, 554 unsigned Depth) { 555 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 556 return 0; 557 558 // Order pointer values after integer values. This helps SCEVExpander form 559 // GEPs. 560 bool LIsPointer = LV->getType()->isPointerTy(), 561 RIsPointer = RV->getType()->isPointerTy(); 562 if (LIsPointer != RIsPointer) 563 return (int)LIsPointer - (int)RIsPointer; 564 565 // Compare getValueID values. 566 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 567 if (LID != RID) 568 return (int)LID - (int)RID; 569 570 // Sort arguments by their position. 571 if (const auto *LA = dyn_cast<Argument>(LV)) { 572 const auto *RA = cast<Argument>(RV); 573 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 574 return (int)LArgNo - (int)RArgNo; 575 } 576 577 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 578 const auto *RGV = cast<GlobalValue>(RV); 579 580 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 581 auto LT = GV->getLinkage(); 582 return !(GlobalValue::isPrivateLinkage(LT) || 583 GlobalValue::isInternalLinkage(LT)); 584 }; 585 586 // Use the names to distinguish the two values, but only if the 587 // names are semantically important. 588 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 589 return LGV->getName().compare(RGV->getName()); 590 } 591 592 // For instructions, compare their loop depth, and their operand count. This 593 // is pretty loose. 594 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 595 const auto *RInst = cast<Instruction>(RV); 596 597 // Compare loop depths. 598 const BasicBlock *LParent = LInst->getParent(), 599 *RParent = RInst->getParent(); 600 if (LParent != RParent) { 601 unsigned LDepth = LI->getLoopDepth(LParent), 602 RDepth = LI->getLoopDepth(RParent); 603 if (LDepth != RDepth) 604 return (int)LDepth - (int)RDepth; 605 } 606 607 // Compare the number of operands. 608 unsigned LNumOps = LInst->getNumOperands(), 609 RNumOps = RInst->getNumOperands(); 610 if (LNumOps != RNumOps) 611 return (int)LNumOps - (int)RNumOps; 612 613 for (unsigned Idx : seq(0u, LNumOps)) { 614 int Result = 615 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 616 RInst->getOperand(Idx), Depth + 1); 617 if (Result != 0) 618 return Result; 619 } 620 } 621 622 EqCacheValue.unionSets(LV, RV); 623 return 0; 624 } 625 626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 627 // than RHS, respectively. A three-way result allows recursive comparisons to be 628 // more efficient. 629 static int CompareSCEVComplexity( 630 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 631 EquivalenceClasses<const Value *> &EqCacheValue, 632 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 633 DominatorTree &DT, unsigned Depth = 0) { 634 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 635 if (LHS == RHS) 636 return 0; 637 638 // Primarily, sort the SCEVs by their getSCEVType(). 639 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 640 if (LType != RType) 641 return (int)LType - (int)RType; 642 643 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 644 return 0; 645 // Aside from the getSCEVType() ordering, the particular ordering 646 // isn't very important except that it's beneficial to be consistent, 647 // so that (a + b) and (b + a) don't end up as different expressions. 648 switch (static_cast<SCEVTypes>(LType)) { 649 case scUnknown: { 650 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 651 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 652 653 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 654 RU->getValue(), Depth + 1); 655 if (X == 0) 656 EqCacheSCEV.unionSets(LHS, RHS); 657 return X; 658 } 659 660 case scConstant: { 661 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 662 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 663 664 // Compare constant values. 665 const APInt &LA = LC->getAPInt(); 666 const APInt &RA = RC->getAPInt(); 667 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 668 if (LBitWidth != RBitWidth) 669 return (int)LBitWidth - (int)RBitWidth; 670 return LA.ult(RA) ? -1 : 1; 671 } 672 673 case scAddRecExpr: { 674 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 675 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 676 677 // There is always a dominance between two recs that are used by one SCEV, 678 // so we can safely sort recs by loop header dominance. We require such 679 // order in getAddExpr. 680 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 681 if (LLoop != RLoop) { 682 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 683 assert(LHead != RHead && "Two loops share the same header?"); 684 if (DT.dominates(LHead, RHead)) 685 return 1; 686 else 687 assert(DT.dominates(RHead, LHead) && 688 "No dominance between recurrences used by one SCEV?"); 689 return -1; 690 } 691 692 // Addrec complexity grows with operand count. 693 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 694 if (LNumOps != RNumOps) 695 return (int)LNumOps - (int)RNumOps; 696 697 // Compare NoWrap flags. 698 if (LA->getNoWrapFlags() != RA->getNoWrapFlags()) 699 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags(); 700 701 // Lexicographically compare. 702 for (unsigned i = 0; i != LNumOps; ++i) { 703 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 704 LA->getOperand(i), RA->getOperand(i), DT, 705 Depth + 1); 706 if (X != 0) 707 return X; 708 } 709 EqCacheSCEV.unionSets(LHS, RHS); 710 return 0; 711 } 712 713 case scAddExpr: 714 case scMulExpr: 715 case scSMaxExpr: 716 case scUMaxExpr: { 717 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 718 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 719 720 // Lexicographically compare n-ary expressions. 721 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 722 if (LNumOps != RNumOps) 723 return (int)LNumOps - (int)RNumOps; 724 725 // Compare NoWrap flags. 726 if (LC->getNoWrapFlags() != RC->getNoWrapFlags()) 727 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags(); 728 729 for (unsigned i = 0; i != LNumOps; ++i) { 730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 731 LC->getOperand(i), RC->getOperand(i), DT, 732 Depth + 1); 733 if (X != 0) 734 return X; 735 } 736 EqCacheSCEV.unionSets(LHS, RHS); 737 return 0; 738 } 739 740 case scUDivExpr: { 741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 743 744 // Lexicographically compare udiv expressions. 745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 746 RC->getLHS(), DT, Depth + 1); 747 if (X != 0) 748 return X; 749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 750 RC->getRHS(), DT, Depth + 1); 751 if (X == 0) 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return X; 754 } 755 756 case scTruncate: 757 case scZeroExtend: 758 case scSignExtend: { 759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 761 762 // Compare cast expressions by operand. 763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 764 LC->getOperand(), RC->getOperand(), DT, 765 Depth + 1); 766 if (X == 0) 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return X; 769 } 770 771 case scCouldNotCompute: 772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 773 } 774 llvm_unreachable("Unknown SCEV kind!"); 775 } 776 777 /// Given a list of SCEV objects, order them by their complexity, and group 778 /// objects of the same complexity together by value. When this routine is 779 /// finished, we know that any duplicates in the vector are consecutive and that 780 /// complexity is monotonically increasing. 781 /// 782 /// Note that we go take special precautions to ensure that we get deterministic 783 /// results from this routine. In other words, we don't want the results of 784 /// this to depend on where the addresses of various SCEV objects happened to 785 /// land in memory. 786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 787 LoopInfo *LI, DominatorTree &DT) { 788 if (Ops.size() < 2) return; // Noop 789 790 EquivalenceClasses<const SCEV *> EqCacheSCEV; 791 EquivalenceClasses<const Value *> EqCacheValue; 792 if (Ops.size() == 2) { 793 // This is the common case, which also happens to be trivially simple. 794 // Special case it. 795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 797 std::swap(LHS, RHS); 798 return; 799 } 800 801 // Do the rough sort by complexity. 802 std::stable_sort(Ops.begin(), Ops.end(), 803 [&](const SCEV *LHS, const SCEV *RHS) { 804 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 805 LHS, RHS, DT) < 0; 806 }); 807 808 // Now that we are sorted by complexity, group elements of the same 809 // complexity. Note that this is, at worst, N^2, but the vector is likely to 810 // be extremely short in practice. Note that we take this approach because we 811 // do not want to depend on the addresses of the objects we are grouping. 812 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 813 const SCEV *S = Ops[i]; 814 unsigned Complexity = S->getSCEVType(); 815 816 // If there are any objects of the same complexity and same value as this 817 // one, group them. 818 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 819 if (Ops[j] == S) { // Found a duplicate. 820 // Move it to immediately after i'th element. 821 std::swap(Ops[i+1], Ops[j]); 822 ++i; // no need to rescan it. 823 if (i == e-2) return; // Done! 824 } 825 } 826 } 827 } 828 829 // Returns the size of the SCEV S. 830 static inline int sizeOfSCEV(const SCEV *S) { 831 struct FindSCEVSize { 832 int Size = 0; 833 834 FindSCEVSize() = default; 835 836 bool follow(const SCEV *S) { 837 ++Size; 838 // Keep looking at all operands of S. 839 return true; 840 } 841 842 bool isDone() const { 843 return false; 844 } 845 }; 846 847 FindSCEVSize F; 848 SCEVTraversal<FindSCEVSize> ST(F); 849 ST.visitAll(S); 850 return F.Size; 851 } 852 853 namespace { 854 855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 856 public: 857 // Computes the Quotient and Remainder of the division of Numerator by 858 // Denominator. 859 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 860 const SCEV *Denominator, const SCEV **Quotient, 861 const SCEV **Remainder) { 862 assert(Numerator && Denominator && "Uninitialized SCEV"); 863 864 SCEVDivision D(SE, Numerator, Denominator); 865 866 // Check for the trivial case here to avoid having to check for it in the 867 // rest of the code. 868 if (Numerator == Denominator) { 869 *Quotient = D.One; 870 *Remainder = D.Zero; 871 return; 872 } 873 874 if (Numerator->isZero()) { 875 *Quotient = D.Zero; 876 *Remainder = D.Zero; 877 return; 878 } 879 880 // A simple case when N/1. The quotient is N. 881 if (Denominator->isOne()) { 882 *Quotient = Numerator; 883 *Remainder = D.Zero; 884 return; 885 } 886 887 // Split the Denominator when it is a product. 888 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 889 const SCEV *Q, *R; 890 *Quotient = Numerator; 891 for (const SCEV *Op : T->operands()) { 892 divide(SE, *Quotient, Op, &Q, &R); 893 *Quotient = Q; 894 895 // Bail out when the Numerator is not divisible by one of the terms of 896 // the Denominator. 897 if (!R->isZero()) { 898 *Quotient = D.Zero; 899 *Remainder = Numerator; 900 return; 901 } 902 } 903 *Remainder = D.Zero; 904 return; 905 } 906 907 D.visit(Numerator); 908 *Quotient = D.Quotient; 909 *Remainder = D.Remainder; 910 } 911 912 // Except in the trivial case described above, we do not know how to divide 913 // Expr by Denominator for the following functions with empty implementation. 914 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 915 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 916 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 917 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 918 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 919 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 920 void visitUnknown(const SCEVUnknown *Numerator) {} 921 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 922 923 void visitConstant(const SCEVConstant *Numerator) { 924 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 925 APInt NumeratorVal = Numerator->getAPInt(); 926 APInt DenominatorVal = D->getAPInt(); 927 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 928 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 929 930 if (NumeratorBW > DenominatorBW) 931 DenominatorVal = DenominatorVal.sext(NumeratorBW); 932 else if (NumeratorBW < DenominatorBW) 933 NumeratorVal = NumeratorVal.sext(DenominatorBW); 934 935 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 936 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 937 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 938 Quotient = SE.getConstant(QuotientVal); 939 Remainder = SE.getConstant(RemainderVal); 940 return; 941 } 942 } 943 944 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 945 const SCEV *StartQ, *StartR, *StepQ, *StepR; 946 if (!Numerator->isAffine()) 947 return cannotDivide(Numerator); 948 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 949 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 950 // Bail out if the types do not match. 951 Type *Ty = Denominator->getType(); 952 if (Ty != StartQ->getType() || Ty != StartR->getType() || 953 Ty != StepQ->getType() || Ty != StepR->getType()) 954 return cannotDivide(Numerator); 955 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 956 Numerator->getNoWrapFlags()); 957 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 958 Numerator->getNoWrapFlags()); 959 } 960 961 void visitAddExpr(const SCEVAddExpr *Numerator) { 962 SmallVector<const SCEV *, 2> Qs, Rs; 963 Type *Ty = Denominator->getType(); 964 965 for (const SCEV *Op : Numerator->operands()) { 966 const SCEV *Q, *R; 967 divide(SE, Op, Denominator, &Q, &R); 968 969 // Bail out if types do not match. 970 if (Ty != Q->getType() || Ty != R->getType()) 971 return cannotDivide(Numerator); 972 973 Qs.push_back(Q); 974 Rs.push_back(R); 975 } 976 977 if (Qs.size() == 1) { 978 Quotient = Qs[0]; 979 Remainder = Rs[0]; 980 return; 981 } 982 983 Quotient = SE.getAddExpr(Qs); 984 Remainder = SE.getAddExpr(Rs); 985 } 986 987 void visitMulExpr(const SCEVMulExpr *Numerator) { 988 SmallVector<const SCEV *, 2> Qs; 989 Type *Ty = Denominator->getType(); 990 991 bool FoundDenominatorTerm = false; 992 for (const SCEV *Op : Numerator->operands()) { 993 // Bail out if types do not match. 994 if (Ty != Op->getType()) 995 return cannotDivide(Numerator); 996 997 if (FoundDenominatorTerm) { 998 Qs.push_back(Op); 999 continue; 1000 } 1001 1002 // Check whether Denominator divides one of the product operands. 1003 const SCEV *Q, *R; 1004 divide(SE, Op, Denominator, &Q, &R); 1005 if (!R->isZero()) { 1006 Qs.push_back(Op); 1007 continue; 1008 } 1009 1010 // Bail out if types do not match. 1011 if (Ty != Q->getType()) 1012 return cannotDivide(Numerator); 1013 1014 FoundDenominatorTerm = true; 1015 Qs.push_back(Q); 1016 } 1017 1018 if (FoundDenominatorTerm) { 1019 Remainder = Zero; 1020 if (Qs.size() == 1) 1021 Quotient = Qs[0]; 1022 else 1023 Quotient = SE.getMulExpr(Qs); 1024 return; 1025 } 1026 1027 if (!isa<SCEVUnknown>(Denominator)) 1028 return cannotDivide(Numerator); 1029 1030 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1031 ValueToValueMap RewriteMap; 1032 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1033 cast<SCEVConstant>(Zero)->getValue(); 1034 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1035 1036 if (Remainder->isZero()) { 1037 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1038 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1039 cast<SCEVConstant>(One)->getValue(); 1040 Quotient = 1041 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1042 return; 1043 } 1044 1045 // Quotient is (Numerator - Remainder) divided by Denominator. 1046 const SCEV *Q, *R; 1047 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1048 // This SCEV does not seem to simplify: fail the division here. 1049 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1050 return cannotDivide(Numerator); 1051 divide(SE, Diff, Denominator, &Q, &R); 1052 if (R != Zero) 1053 return cannotDivide(Numerator); 1054 Quotient = Q; 1055 } 1056 1057 private: 1058 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1059 const SCEV *Denominator) 1060 : SE(S), Denominator(Denominator) { 1061 Zero = SE.getZero(Denominator->getType()); 1062 One = SE.getOne(Denominator->getType()); 1063 1064 // We generally do not know how to divide Expr by Denominator. We 1065 // initialize the division to a "cannot divide" state to simplify the rest 1066 // of the code. 1067 cannotDivide(Numerator); 1068 } 1069 1070 // Convenience function for giving up on the division. We set the quotient to 1071 // be equal to zero and the remainder to be equal to the numerator. 1072 void cannotDivide(const SCEV *Numerator) { 1073 Quotient = Zero; 1074 Remainder = Numerator; 1075 } 1076 1077 ScalarEvolution &SE; 1078 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1079 }; 1080 1081 } // end anonymous namespace 1082 1083 //===----------------------------------------------------------------------===// 1084 // Simple SCEV method implementations 1085 //===----------------------------------------------------------------------===// 1086 1087 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1089 ScalarEvolution &SE, 1090 Type *ResultTy) { 1091 // Handle the simplest case efficiently. 1092 if (K == 1) 1093 return SE.getTruncateOrZeroExtend(It, ResultTy); 1094 1095 // We are using the following formula for BC(It, K): 1096 // 1097 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1098 // 1099 // Suppose, W is the bitwidth of the return value. We must be prepared for 1100 // overflow. Hence, we must assure that the result of our computation is 1101 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1102 // safe in modular arithmetic. 1103 // 1104 // However, this code doesn't use exactly that formula; the formula it uses 1105 // is something like the following, where T is the number of factors of 2 in 1106 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1107 // exponentiation: 1108 // 1109 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1110 // 1111 // This formula is trivially equivalent to the previous formula. However, 1112 // this formula can be implemented much more efficiently. The trick is that 1113 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1114 // arithmetic. To do exact division in modular arithmetic, all we have 1115 // to do is multiply by the inverse. Therefore, this step can be done at 1116 // width W. 1117 // 1118 // The next issue is how to safely do the division by 2^T. The way this 1119 // is done is by doing the multiplication step at a width of at least W + T 1120 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1121 // when we perform the division by 2^T (which is equivalent to a right shift 1122 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1123 // truncated out after the division by 2^T. 1124 // 1125 // In comparison to just directly using the first formula, this technique 1126 // is much more efficient; using the first formula requires W * K bits, 1127 // but this formula less than W + K bits. Also, the first formula requires 1128 // a division step, whereas this formula only requires multiplies and shifts. 1129 // 1130 // It doesn't matter whether the subtraction step is done in the calculation 1131 // width or the input iteration count's width; if the subtraction overflows, 1132 // the result must be zero anyway. We prefer here to do it in the width of 1133 // the induction variable because it helps a lot for certain cases; CodeGen 1134 // isn't smart enough to ignore the overflow, which leads to much less 1135 // efficient code if the width of the subtraction is wider than the native 1136 // register width. 1137 // 1138 // (It's possible to not widen at all by pulling out factors of 2 before 1139 // the multiplication; for example, K=2 can be calculated as 1140 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1141 // extra arithmetic, so it's not an obvious win, and it gets 1142 // much more complicated for K > 3.) 1143 1144 // Protection from insane SCEVs; this bound is conservative, 1145 // but it probably doesn't matter. 1146 if (K > 1000) 1147 return SE.getCouldNotCompute(); 1148 1149 unsigned W = SE.getTypeSizeInBits(ResultTy); 1150 1151 // Calculate K! / 2^T and T; we divide out the factors of two before 1152 // multiplying for calculating K! / 2^T to avoid overflow. 1153 // Other overflow doesn't matter because we only care about the bottom 1154 // W bits of the result. 1155 APInt OddFactorial(W, 1); 1156 unsigned T = 1; 1157 for (unsigned i = 3; i <= K; ++i) { 1158 APInt Mult(W, i); 1159 unsigned TwoFactors = Mult.countTrailingZeros(); 1160 T += TwoFactors; 1161 Mult.lshrInPlace(TwoFactors); 1162 OddFactorial *= Mult; 1163 } 1164 1165 // We need at least W + T bits for the multiplication step 1166 unsigned CalculationBits = W + T; 1167 1168 // Calculate 2^T, at width T+W. 1169 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1170 1171 // Calculate the multiplicative inverse of K! / 2^T; 1172 // this multiplication factor will perform the exact division by 1173 // K! / 2^T. 1174 APInt Mod = APInt::getSignedMinValue(W+1); 1175 APInt MultiplyFactor = OddFactorial.zext(W+1); 1176 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1177 MultiplyFactor = MultiplyFactor.trunc(W); 1178 1179 // Calculate the product, at width T+W 1180 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1181 CalculationBits); 1182 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1183 for (unsigned i = 1; i != K; ++i) { 1184 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1185 Dividend = SE.getMulExpr(Dividend, 1186 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1187 } 1188 1189 // Divide by 2^T 1190 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1191 1192 // Truncate the result, and divide by K! / 2^T. 1193 1194 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1195 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1196 } 1197 1198 /// Return the value of this chain of recurrences at the specified iteration 1199 /// number. We can evaluate this recurrence by multiplying each element in the 1200 /// chain by the binomial coefficient corresponding to it. In other words, we 1201 /// can evaluate {A,+,B,+,C,+,D} as: 1202 /// 1203 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1204 /// 1205 /// where BC(It, k) stands for binomial coefficient. 1206 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1207 ScalarEvolution &SE) const { 1208 const SCEV *Result = getStart(); 1209 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1210 // The computation is correct in the face of overflow provided that the 1211 // multiplication is performed _after_ the evaluation of the binomial 1212 // coefficient. 1213 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1214 if (isa<SCEVCouldNotCompute>(Coeff)) 1215 return Coeff; 1216 1217 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1218 } 1219 return Result; 1220 } 1221 1222 //===----------------------------------------------------------------------===// 1223 // SCEV Expression folder implementations 1224 //===----------------------------------------------------------------------===// 1225 1226 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1227 Type *Ty) { 1228 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1229 "This is not a truncating conversion!"); 1230 assert(isSCEVable(Ty) && 1231 "This is not a conversion to a SCEVable type!"); 1232 Ty = getEffectiveSCEVType(Ty); 1233 1234 FoldingSetNodeID ID; 1235 ID.AddInteger(scTruncate); 1236 ID.AddPointer(Op); 1237 ID.AddPointer(Ty); 1238 void *IP = nullptr; 1239 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1240 1241 // Fold if the operand is constant. 1242 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1243 return getConstant( 1244 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1245 1246 // trunc(trunc(x)) --> trunc(x) 1247 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1248 return getTruncateExpr(ST->getOperand(), Ty); 1249 1250 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1251 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1252 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1253 1254 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1255 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1256 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1257 1258 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1259 // eliminate all the truncates, or we replace other casts with truncates. 1260 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1261 SmallVector<const SCEV *, 4> Operands; 1262 bool hasTrunc = false; 1263 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1264 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1265 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1266 hasTrunc = isa<SCEVTruncateExpr>(S); 1267 Operands.push_back(S); 1268 } 1269 if (!hasTrunc) 1270 return getAddExpr(Operands); 1271 // In spite we checked in the beginning that ID is not in the cache, 1272 // it is possible that during recursion and different modification 1273 // ID came to cache, so if we found it, just return it. 1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1275 return S; 1276 } 1277 1278 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1279 // eliminate all the truncates, or we replace other casts with truncates. 1280 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1281 SmallVector<const SCEV *, 4> Operands; 1282 bool hasTrunc = false; 1283 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1284 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1285 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1286 hasTrunc = isa<SCEVTruncateExpr>(S); 1287 Operands.push_back(S); 1288 } 1289 if (!hasTrunc) 1290 return getMulExpr(Operands); 1291 // In spite we checked in the beginning that ID is not in the cache, 1292 // it is possible that during recursion and different modification 1293 // ID came to cache, so if we found it, just return it. 1294 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1295 return S; 1296 } 1297 1298 // If the input value is a chrec scev, truncate the chrec's operands. 1299 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1300 SmallVector<const SCEV *, 4> Operands; 1301 for (const SCEV *Op : AddRec->operands()) 1302 Operands.push_back(getTruncateExpr(Op, Ty)); 1303 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1304 } 1305 1306 // The cast wasn't folded; create an explicit cast node. We can reuse 1307 // the existing insert position since if we get here, we won't have 1308 // made any changes which would invalidate it. 1309 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1310 Op, Ty); 1311 UniqueSCEVs.InsertNode(S, IP); 1312 addToLoopUseLists(S); 1313 return S; 1314 } 1315 1316 // Get the limit of a recurrence such that incrementing by Step cannot cause 1317 // signed overflow as long as the value of the recurrence within the 1318 // loop does not exceed this limit before incrementing. 1319 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1320 ICmpInst::Predicate *Pred, 1321 ScalarEvolution *SE) { 1322 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1323 if (SE->isKnownPositive(Step)) { 1324 *Pred = ICmpInst::ICMP_SLT; 1325 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1326 SE->getSignedRangeMax(Step)); 1327 } 1328 if (SE->isKnownNegative(Step)) { 1329 *Pred = ICmpInst::ICMP_SGT; 1330 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1331 SE->getSignedRangeMin(Step)); 1332 } 1333 return nullptr; 1334 } 1335 1336 // Get the limit of a recurrence such that incrementing by Step cannot cause 1337 // unsigned overflow as long as the value of the recurrence within the loop does 1338 // not exceed this limit before incrementing. 1339 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1340 ICmpInst::Predicate *Pred, 1341 ScalarEvolution *SE) { 1342 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1343 *Pred = ICmpInst::ICMP_ULT; 1344 1345 return SE->getConstant(APInt::getMinValue(BitWidth) - 1346 SE->getUnsignedRangeMax(Step)); 1347 } 1348 1349 namespace { 1350 1351 struct ExtendOpTraitsBase { 1352 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1353 unsigned); 1354 }; 1355 1356 // Used to make code generic over signed and unsigned overflow. 1357 template <typename ExtendOp> struct ExtendOpTraits { 1358 // Members present: 1359 // 1360 // static const SCEV::NoWrapFlags WrapType; 1361 // 1362 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1363 // 1364 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1365 // ICmpInst::Predicate *Pred, 1366 // ScalarEvolution *SE); 1367 }; 1368 1369 template <> 1370 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1371 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1372 1373 static const GetExtendExprTy GetExtendExpr; 1374 1375 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1376 ICmpInst::Predicate *Pred, 1377 ScalarEvolution *SE) { 1378 return getSignedOverflowLimitForStep(Step, Pred, SE); 1379 } 1380 }; 1381 1382 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1383 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1384 1385 template <> 1386 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1387 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1388 1389 static const GetExtendExprTy GetExtendExpr; 1390 1391 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1392 ICmpInst::Predicate *Pred, 1393 ScalarEvolution *SE) { 1394 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1395 } 1396 }; 1397 1398 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1399 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1400 1401 } // end anonymous namespace 1402 1403 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1404 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1405 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1406 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1407 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1408 // expression "Step + sext/zext(PreIncAR)" is congruent with 1409 // "sext/zext(PostIncAR)" 1410 template <typename ExtendOpTy> 1411 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1412 ScalarEvolution *SE, unsigned Depth) { 1413 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1414 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1415 1416 const Loop *L = AR->getLoop(); 1417 const SCEV *Start = AR->getStart(); 1418 const SCEV *Step = AR->getStepRecurrence(*SE); 1419 1420 // Check for a simple looking step prior to loop entry. 1421 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1422 if (!SA) 1423 return nullptr; 1424 1425 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1426 // subtraction is expensive. For this purpose, perform a quick and dirty 1427 // difference, by checking for Step in the operand list. 1428 SmallVector<const SCEV *, 4> DiffOps; 1429 for (const SCEV *Op : SA->operands()) 1430 if (Op != Step) 1431 DiffOps.push_back(Op); 1432 1433 if (DiffOps.size() == SA->getNumOperands()) 1434 return nullptr; 1435 1436 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1437 // `Step`: 1438 1439 // 1. NSW/NUW flags on the step increment. 1440 auto PreStartFlags = 1441 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1442 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1443 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1444 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1445 1446 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1447 // "S+X does not sign/unsign-overflow". 1448 // 1449 1450 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1451 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1452 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1453 return PreStart; 1454 1455 // 2. Direct overflow check on the step operation's expression. 1456 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1457 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1458 const SCEV *OperandExtendedStart = 1459 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1460 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1461 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1462 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1463 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1464 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1465 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1466 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1467 } 1468 return PreStart; 1469 } 1470 1471 // 3. Loop precondition. 1472 ICmpInst::Predicate Pred; 1473 const SCEV *OverflowLimit = 1474 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1475 1476 if (OverflowLimit && 1477 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1478 return PreStart; 1479 1480 return nullptr; 1481 } 1482 1483 // Get the normalized zero or sign extended expression for this AddRec's Start. 1484 template <typename ExtendOpTy> 1485 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1486 ScalarEvolution *SE, 1487 unsigned Depth) { 1488 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1489 1490 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1491 if (!PreStart) 1492 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1493 1494 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1495 Depth), 1496 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1497 } 1498 1499 // Try to prove away overflow by looking at "nearby" add recurrences. A 1500 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1501 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1502 // 1503 // Formally: 1504 // 1505 // {S,+,X} == {S-T,+,X} + T 1506 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1507 // 1508 // If ({S-T,+,X} + T) does not overflow ... (1) 1509 // 1510 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1511 // 1512 // If {S-T,+,X} does not overflow ... (2) 1513 // 1514 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1515 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1516 // 1517 // If (S-T)+T does not overflow ... (3) 1518 // 1519 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1520 // == {Ext(S),+,Ext(X)} == LHS 1521 // 1522 // Thus, if (1), (2) and (3) are true for some T, then 1523 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1524 // 1525 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1526 // does not overflow" restricted to the 0th iteration. Therefore we only need 1527 // to check for (1) and (2). 1528 // 1529 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1530 // is `Delta` (defined below). 1531 template <typename ExtendOpTy> 1532 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1533 const SCEV *Step, 1534 const Loop *L) { 1535 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1536 1537 // We restrict `Start` to a constant to prevent SCEV from spending too much 1538 // time here. It is correct (but more expensive) to continue with a 1539 // non-constant `Start` and do a general SCEV subtraction to compute 1540 // `PreStart` below. 1541 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1542 if (!StartC) 1543 return false; 1544 1545 APInt StartAI = StartC->getAPInt(); 1546 1547 for (unsigned Delta : {-2, -1, 1, 2}) { 1548 const SCEV *PreStart = getConstant(StartAI - Delta); 1549 1550 FoldingSetNodeID ID; 1551 ID.AddInteger(scAddRecExpr); 1552 ID.AddPointer(PreStart); 1553 ID.AddPointer(Step); 1554 ID.AddPointer(L); 1555 void *IP = nullptr; 1556 const auto *PreAR = 1557 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1558 1559 // Give up if we don't already have the add recurrence we need because 1560 // actually constructing an add recurrence is relatively expensive. 1561 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1562 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1563 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1564 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1565 DeltaS, &Pred, this); 1566 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1567 return true; 1568 } 1569 } 1570 1571 return false; 1572 } 1573 1574 const SCEV * 1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1576 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1577 "This is not an extending conversion!"); 1578 assert(isSCEVable(Ty) && 1579 "This is not a conversion to a SCEVable type!"); 1580 Ty = getEffectiveSCEVType(Ty); 1581 1582 // Fold if the operand is constant. 1583 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1584 return getConstant( 1585 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1586 1587 // zext(zext(x)) --> zext(x) 1588 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1589 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1590 1591 // Before doing any expensive analysis, check to see if we've already 1592 // computed a SCEV for this Op and Ty. 1593 FoldingSetNodeID ID; 1594 ID.AddInteger(scZeroExtend); 1595 ID.AddPointer(Op); 1596 ID.AddPointer(Ty); 1597 void *IP = nullptr; 1598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1599 if (Depth > MaxExtDepth) { 1600 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1601 Op, Ty); 1602 UniqueSCEVs.InsertNode(S, IP); 1603 addToLoopUseLists(S); 1604 return S; 1605 } 1606 1607 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1608 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1609 // It's possible the bits taken off by the truncate were all zero bits. If 1610 // so, we should be able to simplify this further. 1611 const SCEV *X = ST->getOperand(); 1612 ConstantRange CR = getUnsignedRange(X); 1613 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1614 unsigned NewBits = getTypeSizeInBits(Ty); 1615 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1616 CR.zextOrTrunc(NewBits))) 1617 return getTruncateOrZeroExtend(X, Ty); 1618 } 1619 1620 // If the input value is a chrec scev, and we can prove that the value 1621 // did not overflow the old, smaller, value, we can zero extend all of the 1622 // operands (often constants). This allows analysis of something like 1623 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1624 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1625 if (AR->isAffine()) { 1626 const SCEV *Start = AR->getStart(); 1627 const SCEV *Step = AR->getStepRecurrence(*this); 1628 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1629 const Loop *L = AR->getLoop(); 1630 1631 if (!AR->hasNoUnsignedWrap()) { 1632 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1633 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1634 } 1635 1636 // If we have special knowledge that this addrec won't overflow, 1637 // we don't need to do any further analysis. 1638 if (AR->hasNoUnsignedWrap()) 1639 return getAddRecExpr( 1640 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1641 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1642 1643 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1644 // Note that this serves two purposes: It filters out loops that are 1645 // simply not analyzable, and it covers the case where this code is 1646 // being called from within backedge-taken count analysis, such that 1647 // attempting to ask for the backedge-taken count would likely result 1648 // in infinite recursion. In the later case, the analysis code will 1649 // cope with a conservative value, and it will take care to purge 1650 // that value once it has finished. 1651 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1652 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1653 // Manually compute the final value for AR, checking for 1654 // overflow. 1655 1656 // Check whether the backedge-taken count can be losslessly casted to 1657 // the addrec's type. The count is always unsigned. 1658 const SCEV *CastedMaxBECount = 1659 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1660 const SCEV *RecastedMaxBECount = 1661 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1662 if (MaxBECount == RecastedMaxBECount) { 1663 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1664 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1665 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1666 SCEV::FlagAnyWrap, Depth + 1); 1667 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1668 SCEV::FlagAnyWrap, 1669 Depth + 1), 1670 WideTy, Depth + 1); 1671 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1672 const SCEV *WideMaxBECount = 1673 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1674 const SCEV *OperandExtendedAdd = 1675 getAddExpr(WideStart, 1676 getMulExpr(WideMaxBECount, 1677 getZeroExtendExpr(Step, WideTy, Depth + 1), 1678 SCEV::FlagAnyWrap, Depth + 1), 1679 SCEV::FlagAnyWrap, Depth + 1); 1680 if (ZAdd == OperandExtendedAdd) { 1681 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1682 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1683 // Return the expression with the addrec on the outside. 1684 return getAddRecExpr( 1685 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1686 Depth + 1), 1687 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1688 AR->getNoWrapFlags()); 1689 } 1690 // Similar to above, only this time treat the step value as signed. 1691 // This covers loops that count down. 1692 OperandExtendedAdd = 1693 getAddExpr(WideStart, 1694 getMulExpr(WideMaxBECount, 1695 getSignExtendExpr(Step, WideTy, Depth + 1), 1696 SCEV::FlagAnyWrap, Depth + 1), 1697 SCEV::FlagAnyWrap, Depth + 1); 1698 if (ZAdd == OperandExtendedAdd) { 1699 // Cache knowledge of AR NW, which is propagated to this AddRec. 1700 // Negative step causes unsigned wrap, but it still can't self-wrap. 1701 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1702 // Return the expression with the addrec on the outside. 1703 return getAddRecExpr( 1704 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1705 Depth + 1), 1706 getSignExtendExpr(Step, Ty, Depth + 1), L, 1707 AR->getNoWrapFlags()); 1708 } 1709 } 1710 } 1711 1712 // Normally, in the cases we can prove no-overflow via a 1713 // backedge guarding condition, we can also compute a backedge 1714 // taken count for the loop. The exceptions are assumptions and 1715 // guards present in the loop -- SCEV is not great at exploiting 1716 // these to compute max backedge taken counts, but can still use 1717 // these to prove lack of overflow. Use this fact to avoid 1718 // doing extra work that may not pay off. 1719 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1720 !AC.assumptions().empty()) { 1721 // If the backedge is guarded by a comparison with the pre-inc 1722 // value the addrec is safe. Also, if the entry is guarded by 1723 // a comparison with the start value and the backedge is 1724 // guarded by a comparison with the post-inc value, the addrec 1725 // is safe. 1726 if (isKnownPositive(Step)) { 1727 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1728 getUnsignedRangeMax(Step)); 1729 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1730 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1731 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1732 AR->getPostIncExpr(*this), N))) { 1733 // Cache knowledge of AR NUW, which is propagated to this 1734 // AddRec. 1735 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1736 // Return the expression with the addrec on the outside. 1737 return getAddRecExpr( 1738 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1739 Depth + 1), 1740 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1741 AR->getNoWrapFlags()); 1742 } 1743 } else if (isKnownNegative(Step)) { 1744 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1745 getSignedRangeMin(Step)); 1746 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1747 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1748 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1749 AR->getPostIncExpr(*this), N))) { 1750 // Cache knowledge of AR NW, which is propagated to this 1751 // AddRec. Negative step causes unsigned wrap, but it 1752 // still can't self-wrap. 1753 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1754 // Return the expression with the addrec on the outside. 1755 return getAddRecExpr( 1756 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1757 Depth + 1), 1758 getSignExtendExpr(Step, Ty, Depth + 1), L, 1759 AR->getNoWrapFlags()); 1760 } 1761 } 1762 } 1763 1764 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1765 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1766 return getAddRecExpr( 1767 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1768 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1769 } 1770 } 1771 1772 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1773 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1774 if (SA->hasNoUnsignedWrap()) { 1775 // If the addition does not unsign overflow then we can, by definition, 1776 // commute the zero extension with the addition operation. 1777 SmallVector<const SCEV *, 4> Ops; 1778 for (const auto *Op : SA->operands()) 1779 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1780 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1781 } 1782 } 1783 1784 // The cast wasn't folded; create an explicit cast node. 1785 // Recompute the insert position, as it may have been invalidated. 1786 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1787 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1788 Op, Ty); 1789 UniqueSCEVs.InsertNode(S, IP); 1790 addToLoopUseLists(S); 1791 return S; 1792 } 1793 1794 const SCEV * 1795 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1796 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1797 "This is not an extending conversion!"); 1798 assert(isSCEVable(Ty) && 1799 "This is not a conversion to a SCEVable type!"); 1800 Ty = getEffectiveSCEVType(Ty); 1801 1802 // Fold if the operand is constant. 1803 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1804 return getConstant( 1805 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1806 1807 // sext(sext(x)) --> sext(x) 1808 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1809 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1810 1811 // sext(zext(x)) --> zext(x) 1812 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1813 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1814 1815 // Before doing any expensive analysis, check to see if we've already 1816 // computed a SCEV for this Op and Ty. 1817 FoldingSetNodeID ID; 1818 ID.AddInteger(scSignExtend); 1819 ID.AddPointer(Op); 1820 ID.AddPointer(Ty); 1821 void *IP = nullptr; 1822 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1823 // Limit recursion depth. 1824 if (Depth > MaxExtDepth) { 1825 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1826 Op, Ty); 1827 UniqueSCEVs.InsertNode(S, IP); 1828 addToLoopUseLists(S); 1829 return S; 1830 } 1831 1832 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1833 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1834 // It's possible the bits taken off by the truncate were all sign bits. If 1835 // so, we should be able to simplify this further. 1836 const SCEV *X = ST->getOperand(); 1837 ConstantRange CR = getSignedRange(X); 1838 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1839 unsigned NewBits = getTypeSizeInBits(Ty); 1840 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1841 CR.sextOrTrunc(NewBits))) 1842 return getTruncateOrSignExtend(X, Ty); 1843 } 1844 1845 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1846 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1847 if (SA->getNumOperands() == 2) { 1848 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1849 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1850 if (SMul && SC1) { 1851 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1852 const APInt &C1 = SC1->getAPInt(); 1853 const APInt &C2 = SC2->getAPInt(); 1854 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1855 C2.ugt(C1) && C2.isPowerOf2()) 1856 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1857 getSignExtendExpr(SMul, Ty, Depth + 1), 1858 SCEV::FlagAnyWrap, Depth + 1); 1859 } 1860 } 1861 } 1862 1863 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1864 if (SA->hasNoSignedWrap()) { 1865 // If the addition does not sign overflow then we can, by definition, 1866 // commute the sign extension with the addition operation. 1867 SmallVector<const SCEV *, 4> Ops; 1868 for (const auto *Op : SA->operands()) 1869 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1870 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1871 } 1872 } 1873 // If the input value is a chrec scev, and we can prove that the value 1874 // did not overflow the old, smaller, value, we can sign extend all of the 1875 // operands (often constants). This allows analysis of something like 1876 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1877 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1878 if (AR->isAffine()) { 1879 const SCEV *Start = AR->getStart(); 1880 const SCEV *Step = AR->getStepRecurrence(*this); 1881 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1882 const Loop *L = AR->getLoop(); 1883 1884 if (!AR->hasNoSignedWrap()) { 1885 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1886 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1887 } 1888 1889 // If we have special knowledge that this addrec won't overflow, 1890 // we don't need to do any further analysis. 1891 if (AR->hasNoSignedWrap()) 1892 return getAddRecExpr( 1893 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1894 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1895 1896 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1897 // Note that this serves two purposes: It filters out loops that are 1898 // simply not analyzable, and it covers the case where this code is 1899 // being called from within backedge-taken count analysis, such that 1900 // attempting to ask for the backedge-taken count would likely result 1901 // in infinite recursion. In the later case, the analysis code will 1902 // cope with a conservative value, and it will take care to purge 1903 // that value once it has finished. 1904 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1905 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1906 // Manually compute the final value for AR, checking for 1907 // overflow. 1908 1909 // Check whether the backedge-taken count can be losslessly casted to 1910 // the addrec's type. The count is always unsigned. 1911 const SCEV *CastedMaxBECount = 1912 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1913 const SCEV *RecastedMaxBECount = 1914 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1915 if (MaxBECount == RecastedMaxBECount) { 1916 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1917 // Check whether Start+Step*MaxBECount has no signed overflow. 1918 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1919 SCEV::FlagAnyWrap, Depth + 1); 1920 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1921 SCEV::FlagAnyWrap, 1922 Depth + 1), 1923 WideTy, Depth + 1); 1924 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1925 const SCEV *WideMaxBECount = 1926 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1927 const SCEV *OperandExtendedAdd = 1928 getAddExpr(WideStart, 1929 getMulExpr(WideMaxBECount, 1930 getSignExtendExpr(Step, WideTy, Depth + 1), 1931 SCEV::FlagAnyWrap, Depth + 1), 1932 SCEV::FlagAnyWrap, Depth + 1); 1933 if (SAdd == OperandExtendedAdd) { 1934 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1935 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1936 // Return the expression with the addrec on the outside. 1937 return getAddRecExpr( 1938 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1939 Depth + 1), 1940 getSignExtendExpr(Step, Ty, Depth + 1), L, 1941 AR->getNoWrapFlags()); 1942 } 1943 // Similar to above, only this time treat the step value as unsigned. 1944 // This covers loops that count up with an unsigned step. 1945 OperandExtendedAdd = 1946 getAddExpr(WideStart, 1947 getMulExpr(WideMaxBECount, 1948 getZeroExtendExpr(Step, WideTy, Depth + 1), 1949 SCEV::FlagAnyWrap, Depth + 1), 1950 SCEV::FlagAnyWrap, Depth + 1); 1951 if (SAdd == OperandExtendedAdd) { 1952 // If AR wraps around then 1953 // 1954 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1955 // => SAdd != OperandExtendedAdd 1956 // 1957 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1958 // (SAdd == OperandExtendedAdd => AR is NW) 1959 1960 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1961 1962 // Return the expression with the addrec on the outside. 1963 return getAddRecExpr( 1964 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1965 Depth + 1), 1966 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1967 AR->getNoWrapFlags()); 1968 } 1969 } 1970 } 1971 1972 // Normally, in the cases we can prove no-overflow via a 1973 // backedge guarding condition, we can also compute a backedge 1974 // taken count for the loop. The exceptions are assumptions and 1975 // guards present in the loop -- SCEV is not great at exploiting 1976 // these to compute max backedge taken counts, but can still use 1977 // these to prove lack of overflow. Use this fact to avoid 1978 // doing extra work that may not pay off. 1979 1980 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1981 !AC.assumptions().empty()) { 1982 // If the backedge is guarded by a comparison with the pre-inc 1983 // value the addrec is safe. Also, if the entry is guarded by 1984 // a comparison with the start value and the backedge is 1985 // guarded by a comparison with the post-inc value, the addrec 1986 // is safe. 1987 ICmpInst::Predicate Pred; 1988 const SCEV *OverflowLimit = 1989 getSignedOverflowLimitForStep(Step, &Pred, this); 1990 if (OverflowLimit && 1991 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1992 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1993 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1994 OverflowLimit)))) { 1995 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1996 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1997 return getAddRecExpr( 1998 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1999 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2000 } 2001 } 2002 2003 // If Start and Step are constants, check if we can apply this 2004 // transformation: 2005 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2006 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2007 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2008 if (SC1 && SC2) { 2009 const APInt &C1 = SC1->getAPInt(); 2010 const APInt &C2 = SC2->getAPInt(); 2011 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2012 C2.isPowerOf2()) { 2013 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2014 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2015 AR->getNoWrapFlags()); 2016 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2017 SCEV::FlagAnyWrap, Depth + 1); 2018 } 2019 } 2020 2021 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2022 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2023 return getAddRecExpr( 2024 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2025 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2026 } 2027 } 2028 2029 // If the input value is provably positive and we could not simplify 2030 // away the sext build a zext instead. 2031 if (isKnownNonNegative(Op)) 2032 return getZeroExtendExpr(Op, Ty, Depth + 1); 2033 2034 // The cast wasn't folded; create an explicit cast node. 2035 // Recompute the insert position, as it may have been invalidated. 2036 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2037 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2038 Op, Ty); 2039 UniqueSCEVs.InsertNode(S, IP); 2040 addToLoopUseLists(S); 2041 return S; 2042 } 2043 2044 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2045 /// unspecified bits out to the given type. 2046 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2047 Type *Ty) { 2048 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2049 "This is not an extending conversion!"); 2050 assert(isSCEVable(Ty) && 2051 "This is not a conversion to a SCEVable type!"); 2052 Ty = getEffectiveSCEVType(Ty); 2053 2054 // Sign-extend negative constants. 2055 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2056 if (SC->getAPInt().isNegative()) 2057 return getSignExtendExpr(Op, Ty); 2058 2059 // Peel off a truncate cast. 2060 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2061 const SCEV *NewOp = T->getOperand(); 2062 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2063 return getAnyExtendExpr(NewOp, Ty); 2064 return getTruncateOrNoop(NewOp, Ty); 2065 } 2066 2067 // Next try a zext cast. If the cast is folded, use it. 2068 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2069 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2070 return ZExt; 2071 2072 // Next try a sext cast. If the cast is folded, use it. 2073 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2074 if (!isa<SCEVSignExtendExpr>(SExt)) 2075 return SExt; 2076 2077 // Force the cast to be folded into the operands of an addrec. 2078 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2079 SmallVector<const SCEV *, 4> Ops; 2080 for (const SCEV *Op : AR->operands()) 2081 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2082 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2083 } 2084 2085 // If the expression is obviously signed, use the sext cast value. 2086 if (isa<SCEVSMaxExpr>(Op)) 2087 return SExt; 2088 2089 // Absent any other information, use the zext cast value. 2090 return ZExt; 2091 } 2092 2093 /// Process the given Ops list, which is a list of operands to be added under 2094 /// the given scale, update the given map. This is a helper function for 2095 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2096 /// that would form an add expression like this: 2097 /// 2098 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2099 /// 2100 /// where A and B are constants, update the map with these values: 2101 /// 2102 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2103 /// 2104 /// and add 13 + A*B*29 to AccumulatedConstant. 2105 /// This will allow getAddRecExpr to produce this: 2106 /// 2107 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2108 /// 2109 /// This form often exposes folding opportunities that are hidden in 2110 /// the original operand list. 2111 /// 2112 /// Return true iff it appears that any interesting folding opportunities 2113 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2114 /// the common case where no interesting opportunities are present, and 2115 /// is also used as a check to avoid infinite recursion. 2116 static bool 2117 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2118 SmallVectorImpl<const SCEV *> &NewOps, 2119 APInt &AccumulatedConstant, 2120 const SCEV *const *Ops, size_t NumOperands, 2121 const APInt &Scale, 2122 ScalarEvolution &SE) { 2123 bool Interesting = false; 2124 2125 // Iterate over the add operands. They are sorted, with constants first. 2126 unsigned i = 0; 2127 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2128 ++i; 2129 // Pull a buried constant out to the outside. 2130 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2131 Interesting = true; 2132 AccumulatedConstant += Scale * C->getAPInt(); 2133 } 2134 2135 // Next comes everything else. We're especially interested in multiplies 2136 // here, but they're in the middle, so just visit the rest with one loop. 2137 for (; i != NumOperands; ++i) { 2138 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2139 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2140 APInt NewScale = 2141 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2142 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2143 // A multiplication of a constant with another add; recurse. 2144 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2145 Interesting |= 2146 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2147 Add->op_begin(), Add->getNumOperands(), 2148 NewScale, SE); 2149 } else { 2150 // A multiplication of a constant with some other value. Update 2151 // the map. 2152 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2153 const SCEV *Key = SE.getMulExpr(MulOps); 2154 auto Pair = M.insert({Key, NewScale}); 2155 if (Pair.second) { 2156 NewOps.push_back(Pair.first->first); 2157 } else { 2158 Pair.first->second += NewScale; 2159 // The map already had an entry for this value, which may indicate 2160 // a folding opportunity. 2161 Interesting = true; 2162 } 2163 } 2164 } else { 2165 // An ordinary operand. Update the map. 2166 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2167 M.insert({Ops[i], Scale}); 2168 if (Pair.second) { 2169 NewOps.push_back(Pair.first->first); 2170 } else { 2171 Pair.first->second += Scale; 2172 // The map already had an entry for this value, which may indicate 2173 // a folding opportunity. 2174 Interesting = true; 2175 } 2176 } 2177 } 2178 2179 return Interesting; 2180 } 2181 2182 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2183 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2184 // can't-overflow flags for the operation if possible. 2185 static SCEV::NoWrapFlags 2186 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2187 const SmallVectorImpl<const SCEV *> &Ops, 2188 SCEV::NoWrapFlags Flags) { 2189 using namespace std::placeholders; 2190 2191 using OBO = OverflowingBinaryOperator; 2192 2193 bool CanAnalyze = 2194 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2195 (void)CanAnalyze; 2196 assert(CanAnalyze && "don't call from other places!"); 2197 2198 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2199 SCEV::NoWrapFlags SignOrUnsignWrap = 2200 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2201 2202 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2203 auto IsKnownNonNegative = [&](const SCEV *S) { 2204 return SE->isKnownNonNegative(S); 2205 }; 2206 2207 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2208 Flags = 2209 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2210 2211 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2212 2213 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2214 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2215 2216 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2217 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2218 2219 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2220 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2221 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2222 Instruction::Add, C, OBO::NoSignedWrap); 2223 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2224 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2225 } 2226 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2227 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2228 Instruction::Add, C, OBO::NoUnsignedWrap); 2229 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2230 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2231 } 2232 } 2233 2234 return Flags; 2235 } 2236 2237 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2238 if (!isLoopInvariant(S, L)) 2239 return false; 2240 // If a value depends on a SCEVUnknown which is defined after the loop, we 2241 // conservatively assume that we cannot calculate it at the loop's entry. 2242 struct FindDominatedSCEVUnknown { 2243 bool Found = false; 2244 const Loop *L; 2245 DominatorTree &DT; 2246 LoopInfo &LI; 2247 2248 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI) 2249 : L(L), DT(DT), LI(LI) {} 2250 2251 bool checkSCEVUnknown(const SCEVUnknown *SU) { 2252 if (auto *I = dyn_cast<Instruction>(SU->getValue())) { 2253 if (DT.dominates(L->getHeader(), I->getParent())) 2254 Found = true; 2255 else 2256 assert(DT.dominates(I->getParent(), L->getHeader()) && 2257 "No dominance relationship between SCEV and loop?"); 2258 } 2259 return false; 2260 } 2261 2262 bool follow(const SCEV *S) { 2263 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 2264 case scConstant: 2265 return false; 2266 case scAddRecExpr: 2267 case scTruncate: 2268 case scZeroExtend: 2269 case scSignExtend: 2270 case scAddExpr: 2271 case scMulExpr: 2272 case scUMaxExpr: 2273 case scSMaxExpr: 2274 case scUDivExpr: 2275 return true; 2276 case scUnknown: 2277 return checkSCEVUnknown(cast<SCEVUnknown>(S)); 2278 case scCouldNotCompute: 2279 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 2280 } 2281 return false; 2282 } 2283 2284 bool isDone() { return Found; } 2285 }; 2286 2287 FindDominatedSCEVUnknown FSU(L, DT, LI); 2288 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU); 2289 ST.visitAll(S); 2290 return !FSU.Found; 2291 } 2292 2293 /// Get a canonical add expression, or something simpler if possible. 2294 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2295 SCEV::NoWrapFlags Flags, 2296 unsigned Depth) { 2297 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2298 "only nuw or nsw allowed"); 2299 assert(!Ops.empty() && "Cannot get empty add!"); 2300 if (Ops.size() == 1) return Ops[0]; 2301 #ifndef NDEBUG 2302 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2303 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2304 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2305 "SCEVAddExpr operand types don't match!"); 2306 #endif 2307 2308 // Sort by complexity, this groups all similar expression types together. 2309 GroupByComplexity(Ops, &LI, DT); 2310 2311 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2312 2313 // If there are any constants, fold them together. 2314 unsigned Idx = 0; 2315 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2316 ++Idx; 2317 assert(Idx < Ops.size()); 2318 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2319 // We found two constants, fold them together! 2320 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2321 if (Ops.size() == 2) return Ops[0]; 2322 Ops.erase(Ops.begin()+1); // Erase the folded element 2323 LHSC = cast<SCEVConstant>(Ops[0]); 2324 } 2325 2326 // If we are left with a constant zero being added, strip it off. 2327 if (LHSC->getValue()->isZero()) { 2328 Ops.erase(Ops.begin()); 2329 --Idx; 2330 } 2331 2332 if (Ops.size() == 1) return Ops[0]; 2333 } 2334 2335 // Limit recursion calls depth. 2336 if (Depth > MaxArithDepth) 2337 return getOrCreateAddExpr(Ops, Flags); 2338 2339 // Okay, check to see if the same value occurs in the operand list more than 2340 // once. If so, merge them together into an multiply expression. Since we 2341 // sorted the list, these values are required to be adjacent. 2342 Type *Ty = Ops[0]->getType(); 2343 bool FoundMatch = false; 2344 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2345 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2346 // Scan ahead to count how many equal operands there are. 2347 unsigned Count = 2; 2348 while (i+Count != e && Ops[i+Count] == Ops[i]) 2349 ++Count; 2350 // Merge the values into a multiply. 2351 const SCEV *Scale = getConstant(Ty, Count); 2352 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2353 if (Ops.size() == Count) 2354 return Mul; 2355 Ops[i] = Mul; 2356 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2357 --i; e -= Count - 1; 2358 FoundMatch = true; 2359 } 2360 if (FoundMatch) 2361 return getAddExpr(Ops, Flags, Depth + 1); 2362 2363 // Check for truncates. If all the operands are truncated from the same 2364 // type, see if factoring out the truncate would permit the result to be 2365 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2366 // if the contents of the resulting outer trunc fold to something simple. 2367 auto FindTruncSrcType = [&]() -> Type * { 2368 // We're ultimately looking to fold an addrec of truncs and muls of only 2369 // constants and truncs, so if we find any other types of SCEV 2370 // as operands of the addrec then we bail and return nullptr here. 2371 // Otherwise, we return the type of the operand of a trunc that we find. 2372 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2373 return T->getOperand()->getType(); 2374 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2375 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2376 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2377 return T->getOperand()->getType(); 2378 } 2379 return nullptr; 2380 }; 2381 if (auto *SrcType = FindTruncSrcType()) { 2382 SmallVector<const SCEV *, 8> LargeOps; 2383 bool Ok = true; 2384 // Check all the operands to see if they can be represented in the 2385 // source type of the truncate. 2386 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2387 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2388 if (T->getOperand()->getType() != SrcType) { 2389 Ok = false; 2390 break; 2391 } 2392 LargeOps.push_back(T->getOperand()); 2393 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2394 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2395 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2396 SmallVector<const SCEV *, 8> LargeMulOps; 2397 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2398 if (const SCEVTruncateExpr *T = 2399 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2400 if (T->getOperand()->getType() != SrcType) { 2401 Ok = false; 2402 break; 2403 } 2404 LargeMulOps.push_back(T->getOperand()); 2405 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2406 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2407 } else { 2408 Ok = false; 2409 break; 2410 } 2411 } 2412 if (Ok) 2413 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2414 } else { 2415 Ok = false; 2416 break; 2417 } 2418 } 2419 if (Ok) { 2420 // Evaluate the expression in the larger type. 2421 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2422 // If it folds to something simple, use it. Otherwise, don't. 2423 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2424 return getTruncateExpr(Fold, Ty); 2425 } 2426 } 2427 2428 // Skip past any other cast SCEVs. 2429 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2430 ++Idx; 2431 2432 // If there are add operands they would be next. 2433 if (Idx < Ops.size()) { 2434 bool DeletedAdd = false; 2435 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2436 if (Ops.size() > AddOpsInlineThreshold || 2437 Add->getNumOperands() > AddOpsInlineThreshold) 2438 break; 2439 // If we have an add, expand the add operands onto the end of the operands 2440 // list. 2441 Ops.erase(Ops.begin()+Idx); 2442 Ops.append(Add->op_begin(), Add->op_end()); 2443 DeletedAdd = true; 2444 } 2445 2446 // If we deleted at least one add, we added operands to the end of the list, 2447 // and they are not necessarily sorted. Recurse to resort and resimplify 2448 // any operands we just acquired. 2449 if (DeletedAdd) 2450 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2451 } 2452 2453 // Skip over the add expression until we get to a multiply. 2454 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2455 ++Idx; 2456 2457 // Check to see if there are any folding opportunities present with 2458 // operands multiplied by constant values. 2459 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2460 uint64_t BitWidth = getTypeSizeInBits(Ty); 2461 DenseMap<const SCEV *, APInt> M; 2462 SmallVector<const SCEV *, 8> NewOps; 2463 APInt AccumulatedConstant(BitWidth, 0); 2464 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2465 Ops.data(), Ops.size(), 2466 APInt(BitWidth, 1), *this)) { 2467 struct APIntCompare { 2468 bool operator()(const APInt &LHS, const APInt &RHS) const { 2469 return LHS.ult(RHS); 2470 } 2471 }; 2472 2473 // Some interesting folding opportunity is present, so its worthwhile to 2474 // re-generate the operands list. Group the operands by constant scale, 2475 // to avoid multiplying by the same constant scale multiple times. 2476 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2477 for (const SCEV *NewOp : NewOps) 2478 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2479 // Re-generate the operands list. 2480 Ops.clear(); 2481 if (AccumulatedConstant != 0) 2482 Ops.push_back(getConstant(AccumulatedConstant)); 2483 for (auto &MulOp : MulOpLists) 2484 if (MulOp.first != 0) 2485 Ops.push_back(getMulExpr( 2486 getConstant(MulOp.first), 2487 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2488 SCEV::FlagAnyWrap, Depth + 1)); 2489 if (Ops.empty()) 2490 return getZero(Ty); 2491 if (Ops.size() == 1) 2492 return Ops[0]; 2493 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2494 } 2495 } 2496 2497 // If we are adding something to a multiply expression, make sure the 2498 // something is not already an operand of the multiply. If so, merge it into 2499 // the multiply. 2500 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2501 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2502 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2503 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2504 if (isa<SCEVConstant>(MulOpSCEV)) 2505 continue; 2506 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2507 if (MulOpSCEV == Ops[AddOp]) { 2508 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2509 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2510 if (Mul->getNumOperands() != 2) { 2511 // If the multiply has more than two operands, we must get the 2512 // Y*Z term. 2513 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2514 Mul->op_begin()+MulOp); 2515 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2516 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2517 } 2518 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2519 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2520 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2521 SCEV::FlagAnyWrap, Depth + 1); 2522 if (Ops.size() == 2) return OuterMul; 2523 if (AddOp < Idx) { 2524 Ops.erase(Ops.begin()+AddOp); 2525 Ops.erase(Ops.begin()+Idx-1); 2526 } else { 2527 Ops.erase(Ops.begin()+Idx); 2528 Ops.erase(Ops.begin()+AddOp-1); 2529 } 2530 Ops.push_back(OuterMul); 2531 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2532 } 2533 2534 // Check this multiply against other multiplies being added together. 2535 for (unsigned OtherMulIdx = Idx+1; 2536 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2537 ++OtherMulIdx) { 2538 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2539 // If MulOp occurs in OtherMul, we can fold the two multiplies 2540 // together. 2541 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2542 OMulOp != e; ++OMulOp) 2543 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2544 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2545 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2546 if (Mul->getNumOperands() != 2) { 2547 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2548 Mul->op_begin()+MulOp); 2549 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2550 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2551 } 2552 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2553 if (OtherMul->getNumOperands() != 2) { 2554 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2555 OtherMul->op_begin()+OMulOp); 2556 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2557 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2558 } 2559 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2560 const SCEV *InnerMulSum = 2561 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2562 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2563 SCEV::FlagAnyWrap, Depth + 1); 2564 if (Ops.size() == 2) return OuterMul; 2565 Ops.erase(Ops.begin()+Idx); 2566 Ops.erase(Ops.begin()+OtherMulIdx-1); 2567 Ops.push_back(OuterMul); 2568 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2569 } 2570 } 2571 } 2572 } 2573 2574 // If there are any add recurrences in the operands list, see if any other 2575 // added values are loop invariant. If so, we can fold them into the 2576 // recurrence. 2577 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2578 ++Idx; 2579 2580 // Scan over all recurrences, trying to fold loop invariants into them. 2581 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2582 // Scan all of the other operands to this add and add them to the vector if 2583 // they are loop invariant w.r.t. the recurrence. 2584 SmallVector<const SCEV *, 8> LIOps; 2585 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2586 const Loop *AddRecLoop = AddRec->getLoop(); 2587 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2588 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2589 LIOps.push_back(Ops[i]); 2590 Ops.erase(Ops.begin()+i); 2591 --i; --e; 2592 } 2593 2594 // If we found some loop invariants, fold them into the recurrence. 2595 if (!LIOps.empty()) { 2596 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2597 LIOps.push_back(AddRec->getStart()); 2598 2599 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2600 AddRec->op_end()); 2601 // This follows from the fact that the no-wrap flags on the outer add 2602 // expression are applicable on the 0th iteration, when the add recurrence 2603 // will be equal to its start value. 2604 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2605 2606 // Build the new addrec. Propagate the NUW and NSW flags if both the 2607 // outer add and the inner addrec are guaranteed to have no overflow. 2608 // Always propagate NW. 2609 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2610 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2611 2612 // If all of the other operands were loop invariant, we are done. 2613 if (Ops.size() == 1) return NewRec; 2614 2615 // Otherwise, add the folded AddRec by the non-invariant parts. 2616 for (unsigned i = 0;; ++i) 2617 if (Ops[i] == AddRec) { 2618 Ops[i] = NewRec; 2619 break; 2620 } 2621 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2622 } 2623 2624 // Okay, if there weren't any loop invariants to be folded, check to see if 2625 // there are multiple AddRec's with the same loop induction variable being 2626 // added together. If so, we can fold them. 2627 for (unsigned OtherIdx = Idx+1; 2628 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2629 ++OtherIdx) { 2630 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2631 // so that the 1st found AddRecExpr is dominated by all others. 2632 assert(DT.dominates( 2633 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2634 AddRec->getLoop()->getHeader()) && 2635 "AddRecExprs are not sorted in reverse dominance order?"); 2636 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2637 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2638 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2639 AddRec->op_end()); 2640 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2641 ++OtherIdx) { 2642 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2643 if (OtherAddRec->getLoop() == AddRecLoop) { 2644 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2645 i != e; ++i) { 2646 if (i >= AddRecOps.size()) { 2647 AddRecOps.append(OtherAddRec->op_begin()+i, 2648 OtherAddRec->op_end()); 2649 break; 2650 } 2651 SmallVector<const SCEV *, 2> TwoOps = { 2652 AddRecOps[i], OtherAddRec->getOperand(i)}; 2653 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2654 } 2655 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2656 } 2657 } 2658 // Step size has changed, so we cannot guarantee no self-wraparound. 2659 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2660 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2661 } 2662 } 2663 2664 // Otherwise couldn't fold anything into this recurrence. Move onto the 2665 // next one. 2666 } 2667 2668 // Okay, it looks like we really DO need an add expr. Check to see if we 2669 // already have one, otherwise create a new one. 2670 return getOrCreateAddExpr(Ops, Flags); 2671 } 2672 2673 const SCEV * 2674 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2675 SCEV::NoWrapFlags Flags) { 2676 FoldingSetNodeID ID; 2677 ID.AddInteger(scAddExpr); 2678 for (const SCEV *Op : Ops) 2679 ID.AddPointer(Op); 2680 void *IP = nullptr; 2681 SCEVAddExpr *S = 2682 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2683 if (!S) { 2684 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2685 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2686 S = new (SCEVAllocator) 2687 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2688 UniqueSCEVs.InsertNode(S, IP); 2689 addToLoopUseLists(S); 2690 } 2691 S->setNoWrapFlags(Flags); 2692 return S; 2693 } 2694 2695 const SCEV * 2696 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2697 SCEV::NoWrapFlags Flags) { 2698 FoldingSetNodeID ID; 2699 ID.AddInteger(scMulExpr); 2700 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2701 ID.AddPointer(Ops[i]); 2702 void *IP = nullptr; 2703 SCEVMulExpr *S = 2704 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2705 if (!S) { 2706 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2707 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2708 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2709 O, Ops.size()); 2710 UniqueSCEVs.InsertNode(S, IP); 2711 addToLoopUseLists(S); 2712 } 2713 S->setNoWrapFlags(Flags); 2714 return S; 2715 } 2716 2717 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2718 uint64_t k = i*j; 2719 if (j > 1 && k / j != i) Overflow = true; 2720 return k; 2721 } 2722 2723 /// Compute the result of "n choose k", the binomial coefficient. If an 2724 /// intermediate computation overflows, Overflow will be set and the return will 2725 /// be garbage. Overflow is not cleared on absence of overflow. 2726 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2727 // We use the multiplicative formula: 2728 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2729 // At each iteration, we take the n-th term of the numeral and divide by the 2730 // (k-n)th term of the denominator. This division will always produce an 2731 // integral result, and helps reduce the chance of overflow in the 2732 // intermediate computations. However, we can still overflow even when the 2733 // final result would fit. 2734 2735 if (n == 0 || n == k) return 1; 2736 if (k > n) return 0; 2737 2738 if (k > n/2) 2739 k = n-k; 2740 2741 uint64_t r = 1; 2742 for (uint64_t i = 1; i <= k; ++i) { 2743 r = umul_ov(r, n-(i-1), Overflow); 2744 r /= i; 2745 } 2746 return r; 2747 } 2748 2749 /// Determine if any of the operands in this SCEV are a constant or if 2750 /// any of the add or multiply expressions in this SCEV contain a constant. 2751 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2752 struct FindConstantInAddMulChain { 2753 bool FoundConstant = false; 2754 2755 bool follow(const SCEV *S) { 2756 FoundConstant |= isa<SCEVConstant>(S); 2757 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2758 } 2759 2760 bool isDone() const { 2761 return FoundConstant; 2762 } 2763 }; 2764 2765 FindConstantInAddMulChain F; 2766 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2767 ST.visitAll(StartExpr); 2768 return F.FoundConstant; 2769 } 2770 2771 /// Get a canonical multiply expression, or something simpler if possible. 2772 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2773 SCEV::NoWrapFlags Flags, 2774 unsigned Depth) { 2775 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2776 "only nuw or nsw allowed"); 2777 assert(!Ops.empty() && "Cannot get empty mul!"); 2778 if (Ops.size() == 1) return Ops[0]; 2779 #ifndef NDEBUG 2780 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2781 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2782 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2783 "SCEVMulExpr operand types don't match!"); 2784 #endif 2785 2786 // Sort by complexity, this groups all similar expression types together. 2787 GroupByComplexity(Ops, &LI, DT); 2788 2789 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2790 2791 // Limit recursion calls depth. 2792 if (Depth > MaxArithDepth) 2793 return getOrCreateMulExpr(Ops, Flags); 2794 2795 // If there are any constants, fold them together. 2796 unsigned Idx = 0; 2797 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2798 2799 // C1*(C2+V) -> C1*C2 + C1*V 2800 if (Ops.size() == 2) 2801 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2802 // If any of Add's ops are Adds or Muls with a constant, 2803 // apply this transformation as well. 2804 if (Add->getNumOperands() == 2) 2805 // TODO: There are some cases where this transformation is not 2806 // profitable, for example: 2807 // Add = (C0 + X) * Y + Z. 2808 // Maybe the scope of this transformation should be narrowed down. 2809 if (containsConstantInAddMulChain(Add)) 2810 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2811 SCEV::FlagAnyWrap, Depth + 1), 2812 getMulExpr(LHSC, Add->getOperand(1), 2813 SCEV::FlagAnyWrap, Depth + 1), 2814 SCEV::FlagAnyWrap, Depth + 1); 2815 2816 ++Idx; 2817 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2818 // We found two constants, fold them together! 2819 ConstantInt *Fold = 2820 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2821 Ops[0] = getConstant(Fold); 2822 Ops.erase(Ops.begin()+1); // Erase the folded element 2823 if (Ops.size() == 1) return Ops[0]; 2824 LHSC = cast<SCEVConstant>(Ops[0]); 2825 } 2826 2827 // If we are left with a constant one being multiplied, strip it off. 2828 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2829 Ops.erase(Ops.begin()); 2830 --Idx; 2831 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2832 // If we have a multiply of zero, it will always be zero. 2833 return Ops[0]; 2834 } else if (Ops[0]->isAllOnesValue()) { 2835 // If we have a mul by -1 of an add, try distributing the -1 among the 2836 // add operands. 2837 if (Ops.size() == 2) { 2838 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2839 SmallVector<const SCEV *, 4> NewOps; 2840 bool AnyFolded = false; 2841 for (const SCEV *AddOp : Add->operands()) { 2842 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2843 Depth + 1); 2844 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2845 NewOps.push_back(Mul); 2846 } 2847 if (AnyFolded) 2848 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2849 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2850 // Negation preserves a recurrence's no self-wrap property. 2851 SmallVector<const SCEV *, 4> Operands; 2852 for (const SCEV *AddRecOp : AddRec->operands()) 2853 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2854 Depth + 1)); 2855 2856 return getAddRecExpr(Operands, AddRec->getLoop(), 2857 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2858 } 2859 } 2860 } 2861 2862 if (Ops.size() == 1) 2863 return Ops[0]; 2864 } 2865 2866 // Skip over the add expression until we get to a multiply. 2867 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2868 ++Idx; 2869 2870 // If there are mul operands inline them all into this expression. 2871 if (Idx < Ops.size()) { 2872 bool DeletedMul = false; 2873 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2874 if (Ops.size() > MulOpsInlineThreshold) 2875 break; 2876 // If we have an mul, expand the mul operands onto the end of the 2877 // operands list. 2878 Ops.erase(Ops.begin()+Idx); 2879 Ops.append(Mul->op_begin(), Mul->op_end()); 2880 DeletedMul = true; 2881 } 2882 2883 // If we deleted at least one mul, we added operands to the end of the 2884 // list, and they are not necessarily sorted. Recurse to resort and 2885 // resimplify any operands we just acquired. 2886 if (DeletedMul) 2887 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2888 } 2889 2890 // If there are any add recurrences in the operands list, see if any other 2891 // added values are loop invariant. If so, we can fold them into the 2892 // recurrence. 2893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2894 ++Idx; 2895 2896 // Scan over all recurrences, trying to fold loop invariants into them. 2897 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2898 // Scan all of the other operands to this mul and add them to the vector 2899 // if they are loop invariant w.r.t. the recurrence. 2900 SmallVector<const SCEV *, 8> LIOps; 2901 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2902 const Loop *AddRecLoop = AddRec->getLoop(); 2903 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2904 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2905 LIOps.push_back(Ops[i]); 2906 Ops.erase(Ops.begin()+i); 2907 --i; --e; 2908 } 2909 2910 // If we found some loop invariants, fold them into the recurrence. 2911 if (!LIOps.empty()) { 2912 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2913 SmallVector<const SCEV *, 4> NewOps; 2914 NewOps.reserve(AddRec->getNumOperands()); 2915 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2916 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2917 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2918 SCEV::FlagAnyWrap, Depth + 1)); 2919 2920 // Build the new addrec. Propagate the NUW and NSW flags if both the 2921 // outer mul and the inner addrec are guaranteed to have no overflow. 2922 // 2923 // No self-wrap cannot be guaranteed after changing the step size, but 2924 // will be inferred if either NUW or NSW is true. 2925 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2926 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2927 2928 // If all of the other operands were loop invariant, we are done. 2929 if (Ops.size() == 1) return NewRec; 2930 2931 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2932 for (unsigned i = 0;; ++i) 2933 if (Ops[i] == AddRec) { 2934 Ops[i] = NewRec; 2935 break; 2936 } 2937 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2938 } 2939 2940 // Okay, if there weren't any loop invariants to be folded, check to see 2941 // if there are multiple AddRec's with the same loop induction variable 2942 // being multiplied together. If so, we can fold them. 2943 2944 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2945 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2946 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2947 // ]]],+,...up to x=2n}. 2948 // Note that the arguments to choose() are always integers with values 2949 // known at compile time, never SCEV objects. 2950 // 2951 // The implementation avoids pointless extra computations when the two 2952 // addrec's are of different length (mathematically, it's equivalent to 2953 // an infinite stream of zeros on the right). 2954 bool OpsModified = false; 2955 for (unsigned OtherIdx = Idx+1; 2956 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2957 ++OtherIdx) { 2958 const SCEVAddRecExpr *OtherAddRec = 2959 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2960 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2961 continue; 2962 2963 // Limit max number of arguments to avoid creation of unreasonably big 2964 // SCEVAddRecs with very complex operands. 2965 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2966 MaxAddRecSize) 2967 continue; 2968 2969 bool Overflow = false; 2970 Type *Ty = AddRec->getType(); 2971 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2972 SmallVector<const SCEV*, 7> AddRecOps; 2973 for (int x = 0, xe = AddRec->getNumOperands() + 2974 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2975 const SCEV *Term = getZero(Ty); 2976 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2977 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2978 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2979 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2980 z < ze && !Overflow; ++z) { 2981 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2982 uint64_t Coeff; 2983 if (LargerThan64Bits) 2984 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2985 else 2986 Coeff = Coeff1*Coeff2; 2987 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2988 const SCEV *Term1 = AddRec->getOperand(y-z); 2989 const SCEV *Term2 = OtherAddRec->getOperand(z); 2990 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2991 SCEV::FlagAnyWrap, Depth + 1), 2992 SCEV::FlagAnyWrap, Depth + 1); 2993 } 2994 } 2995 AddRecOps.push_back(Term); 2996 } 2997 if (!Overflow) { 2998 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2999 SCEV::FlagAnyWrap); 3000 if (Ops.size() == 2) return NewAddRec; 3001 Ops[Idx] = NewAddRec; 3002 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3003 OpsModified = true; 3004 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3005 if (!AddRec) 3006 break; 3007 } 3008 } 3009 if (OpsModified) 3010 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3011 3012 // Otherwise couldn't fold anything into this recurrence. Move onto the 3013 // next one. 3014 } 3015 3016 // Okay, it looks like we really DO need an mul expr. Check to see if we 3017 // already have one, otherwise create a new one. 3018 return getOrCreateMulExpr(Ops, Flags); 3019 } 3020 3021 /// Represents an unsigned remainder expression based on unsigned division. 3022 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3023 const SCEV *RHS) { 3024 assert(getEffectiveSCEVType(LHS->getType()) == 3025 getEffectiveSCEVType(RHS->getType()) && 3026 "SCEVURemExpr operand types don't match!"); 3027 3028 // Short-circuit easy cases 3029 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3030 // If constant is one, the result is trivial 3031 if (RHSC->getValue()->isOne()) 3032 return getZero(LHS->getType()); // X urem 1 --> 0 3033 3034 // If constant is a power of two, fold into a zext(trunc(LHS)). 3035 if (RHSC->getAPInt().isPowerOf2()) { 3036 Type *FullTy = LHS->getType(); 3037 Type *TruncTy = 3038 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3039 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3040 } 3041 } 3042 3043 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3044 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3045 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3046 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3047 } 3048 3049 /// Get a canonical unsigned division expression, or something simpler if 3050 /// possible. 3051 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3052 const SCEV *RHS) { 3053 assert(getEffectiveSCEVType(LHS->getType()) == 3054 getEffectiveSCEVType(RHS->getType()) && 3055 "SCEVUDivExpr operand types don't match!"); 3056 3057 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3058 if (RHSC->getValue()->isOne()) 3059 return LHS; // X udiv 1 --> x 3060 // If the denominator is zero, the result of the udiv is undefined. Don't 3061 // try to analyze it, because the resolution chosen here may differ from 3062 // the resolution chosen in other parts of the compiler. 3063 if (!RHSC->getValue()->isZero()) { 3064 // Determine if the division can be folded into the operands of 3065 // its operands. 3066 // TODO: Generalize this to non-constants by using known-bits information. 3067 Type *Ty = LHS->getType(); 3068 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3069 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3070 // For non-power-of-two values, effectively round the value up to the 3071 // nearest power of two. 3072 if (!RHSC->getAPInt().isPowerOf2()) 3073 ++MaxShiftAmt; 3074 IntegerType *ExtTy = 3075 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3076 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3077 if (const SCEVConstant *Step = 3078 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3079 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3080 const APInt &StepInt = Step->getAPInt(); 3081 const APInt &DivInt = RHSC->getAPInt(); 3082 if (!StepInt.urem(DivInt) && 3083 getZeroExtendExpr(AR, ExtTy) == 3084 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3085 getZeroExtendExpr(Step, ExtTy), 3086 AR->getLoop(), SCEV::FlagAnyWrap)) { 3087 SmallVector<const SCEV *, 4> Operands; 3088 for (const SCEV *Op : AR->operands()) 3089 Operands.push_back(getUDivExpr(Op, RHS)); 3090 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3091 } 3092 /// Get a canonical UDivExpr for a recurrence. 3093 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3094 // We can currently only fold X%N if X is constant. 3095 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3096 if (StartC && !DivInt.urem(StepInt) && 3097 getZeroExtendExpr(AR, ExtTy) == 3098 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3099 getZeroExtendExpr(Step, ExtTy), 3100 AR->getLoop(), SCEV::FlagAnyWrap)) { 3101 const APInt &StartInt = StartC->getAPInt(); 3102 const APInt &StartRem = StartInt.urem(StepInt); 3103 if (StartRem != 0) 3104 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3105 AR->getLoop(), SCEV::FlagNW); 3106 } 3107 } 3108 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3109 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3110 SmallVector<const SCEV *, 4> Operands; 3111 for (const SCEV *Op : M->operands()) 3112 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3113 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3114 // Find an operand that's safely divisible. 3115 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3116 const SCEV *Op = M->getOperand(i); 3117 const SCEV *Div = getUDivExpr(Op, RHSC); 3118 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3119 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3120 M->op_end()); 3121 Operands[i] = Div; 3122 return getMulExpr(Operands); 3123 } 3124 } 3125 } 3126 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3127 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3128 SmallVector<const SCEV *, 4> Operands; 3129 for (const SCEV *Op : A->operands()) 3130 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3131 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3132 Operands.clear(); 3133 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3134 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3135 if (isa<SCEVUDivExpr>(Op) || 3136 getMulExpr(Op, RHS) != A->getOperand(i)) 3137 break; 3138 Operands.push_back(Op); 3139 } 3140 if (Operands.size() == A->getNumOperands()) 3141 return getAddExpr(Operands); 3142 } 3143 } 3144 3145 // Fold if both operands are constant. 3146 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3147 Constant *LHSCV = LHSC->getValue(); 3148 Constant *RHSCV = RHSC->getValue(); 3149 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3150 RHSCV))); 3151 } 3152 } 3153 } 3154 3155 FoldingSetNodeID ID; 3156 ID.AddInteger(scUDivExpr); 3157 ID.AddPointer(LHS); 3158 ID.AddPointer(RHS); 3159 void *IP = nullptr; 3160 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3161 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3162 LHS, RHS); 3163 UniqueSCEVs.InsertNode(S, IP); 3164 addToLoopUseLists(S); 3165 return S; 3166 } 3167 3168 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3169 APInt A = C1->getAPInt().abs(); 3170 APInt B = C2->getAPInt().abs(); 3171 uint32_t ABW = A.getBitWidth(); 3172 uint32_t BBW = B.getBitWidth(); 3173 3174 if (ABW > BBW) 3175 B = B.zext(ABW); 3176 else if (ABW < BBW) 3177 A = A.zext(BBW); 3178 3179 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3180 } 3181 3182 /// Get a canonical unsigned division expression, or something simpler if 3183 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3184 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3185 /// it's not exact because the udiv may be clearing bits. 3186 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3187 const SCEV *RHS) { 3188 // TODO: we could try to find factors in all sorts of things, but for now we 3189 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3190 // end of this file for inspiration. 3191 3192 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3193 if (!Mul || !Mul->hasNoUnsignedWrap()) 3194 return getUDivExpr(LHS, RHS); 3195 3196 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3197 // If the mulexpr multiplies by a constant, then that constant must be the 3198 // first element of the mulexpr. 3199 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3200 if (LHSCst == RHSCst) { 3201 SmallVector<const SCEV *, 2> Operands; 3202 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3203 return getMulExpr(Operands); 3204 } 3205 3206 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3207 // that there's a factor provided by one of the other terms. We need to 3208 // check. 3209 APInt Factor = gcd(LHSCst, RHSCst); 3210 if (!Factor.isIntN(1)) { 3211 LHSCst = 3212 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3213 RHSCst = 3214 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3215 SmallVector<const SCEV *, 2> Operands; 3216 Operands.push_back(LHSCst); 3217 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3218 LHS = getMulExpr(Operands); 3219 RHS = RHSCst; 3220 Mul = dyn_cast<SCEVMulExpr>(LHS); 3221 if (!Mul) 3222 return getUDivExactExpr(LHS, RHS); 3223 } 3224 } 3225 } 3226 3227 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3228 if (Mul->getOperand(i) == RHS) { 3229 SmallVector<const SCEV *, 2> Operands; 3230 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3231 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3232 return getMulExpr(Operands); 3233 } 3234 } 3235 3236 return getUDivExpr(LHS, RHS); 3237 } 3238 3239 /// Get an add recurrence expression for the specified loop. Simplify the 3240 /// expression as much as possible. 3241 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3242 const Loop *L, 3243 SCEV::NoWrapFlags Flags) { 3244 SmallVector<const SCEV *, 4> Operands; 3245 Operands.push_back(Start); 3246 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3247 if (StepChrec->getLoop() == L) { 3248 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3249 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3250 } 3251 3252 Operands.push_back(Step); 3253 return getAddRecExpr(Operands, L, Flags); 3254 } 3255 3256 /// Get an add recurrence expression for the specified loop. Simplify the 3257 /// expression as much as possible. 3258 const SCEV * 3259 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3260 const Loop *L, SCEV::NoWrapFlags Flags) { 3261 if (Operands.size() == 1) return Operands[0]; 3262 #ifndef NDEBUG 3263 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3264 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3265 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3266 "SCEVAddRecExpr operand types don't match!"); 3267 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3268 assert(isLoopInvariant(Operands[i], L) && 3269 "SCEVAddRecExpr operand is not loop-invariant!"); 3270 #endif 3271 3272 if (Operands.back()->isZero()) { 3273 Operands.pop_back(); 3274 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3275 } 3276 3277 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3278 // use that information to infer NUW and NSW flags. However, computing a 3279 // BE count requires calling getAddRecExpr, so we may not yet have a 3280 // meaningful BE count at this point (and if we don't, we'd be stuck 3281 // with a SCEVCouldNotCompute as the cached BE count). 3282 3283 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3284 3285 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3286 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3287 const Loop *NestedLoop = NestedAR->getLoop(); 3288 if (L->contains(NestedLoop) 3289 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3290 : (!NestedLoop->contains(L) && 3291 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3292 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3293 NestedAR->op_end()); 3294 Operands[0] = NestedAR->getStart(); 3295 // AddRecs require their operands be loop-invariant with respect to their 3296 // loops. Don't perform this transformation if it would break this 3297 // requirement. 3298 bool AllInvariant = all_of( 3299 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3300 3301 if (AllInvariant) { 3302 // Create a recurrence for the outer loop with the same step size. 3303 // 3304 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3305 // inner recurrence has the same property. 3306 SCEV::NoWrapFlags OuterFlags = 3307 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3308 3309 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3310 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3311 return isLoopInvariant(Op, NestedLoop); 3312 }); 3313 3314 if (AllInvariant) { 3315 // Ok, both add recurrences are valid after the transformation. 3316 // 3317 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3318 // the outer recurrence has the same property. 3319 SCEV::NoWrapFlags InnerFlags = 3320 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3321 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3322 } 3323 } 3324 // Reset Operands to its original state. 3325 Operands[0] = NestedAR; 3326 } 3327 } 3328 3329 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3330 // already have one, otherwise create a new one. 3331 FoldingSetNodeID ID; 3332 ID.AddInteger(scAddRecExpr); 3333 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3334 ID.AddPointer(Operands[i]); 3335 ID.AddPointer(L); 3336 void *IP = nullptr; 3337 SCEVAddRecExpr *S = 3338 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3339 if (!S) { 3340 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3341 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3342 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3343 O, Operands.size(), L); 3344 UniqueSCEVs.InsertNode(S, IP); 3345 addToLoopUseLists(S); 3346 } 3347 S->setNoWrapFlags(Flags); 3348 return S; 3349 } 3350 3351 const SCEV * 3352 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3353 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3354 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3355 // getSCEV(Base)->getType() has the same address space as Base->getType() 3356 // because SCEV::getType() preserves the address space. 3357 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3358 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3359 // instruction to its SCEV, because the Instruction may be guarded by control 3360 // flow and the no-overflow bits may not be valid for the expression in any 3361 // context. This can be fixed similarly to how these flags are handled for 3362 // adds. 3363 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3364 : SCEV::FlagAnyWrap; 3365 3366 const SCEV *TotalOffset = getZero(IntPtrTy); 3367 // The array size is unimportant. The first thing we do on CurTy is getting 3368 // its element type. 3369 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3370 for (const SCEV *IndexExpr : IndexExprs) { 3371 // Compute the (potentially symbolic) offset in bytes for this index. 3372 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3373 // For a struct, add the member offset. 3374 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3375 unsigned FieldNo = Index->getZExtValue(); 3376 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3377 3378 // Add the field offset to the running total offset. 3379 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3380 3381 // Update CurTy to the type of the field at Index. 3382 CurTy = STy->getTypeAtIndex(Index); 3383 } else { 3384 // Update CurTy to its element type. 3385 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3386 // For an array, add the element offset, explicitly scaled. 3387 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3388 // Getelementptr indices are signed. 3389 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3390 3391 // Multiply the index by the element size to compute the element offset. 3392 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3393 3394 // Add the element offset to the running total offset. 3395 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3396 } 3397 } 3398 3399 // Add the total offset from all the GEP indices to the base. 3400 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3401 } 3402 3403 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3404 const SCEV *RHS) { 3405 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3406 return getSMaxExpr(Ops); 3407 } 3408 3409 const SCEV * 3410 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3411 assert(!Ops.empty() && "Cannot get empty smax!"); 3412 if (Ops.size() == 1) return Ops[0]; 3413 #ifndef NDEBUG 3414 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3415 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3416 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3417 "SCEVSMaxExpr operand types don't match!"); 3418 #endif 3419 3420 // Sort by complexity, this groups all similar expression types together. 3421 GroupByComplexity(Ops, &LI, DT); 3422 3423 // If there are any constants, fold them together. 3424 unsigned Idx = 0; 3425 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3426 ++Idx; 3427 assert(Idx < Ops.size()); 3428 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3429 // We found two constants, fold them together! 3430 ConstantInt *Fold = ConstantInt::get( 3431 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3432 Ops[0] = getConstant(Fold); 3433 Ops.erase(Ops.begin()+1); // Erase the folded element 3434 if (Ops.size() == 1) return Ops[0]; 3435 LHSC = cast<SCEVConstant>(Ops[0]); 3436 } 3437 3438 // If we are left with a constant minimum-int, strip it off. 3439 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3440 Ops.erase(Ops.begin()); 3441 --Idx; 3442 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3443 // If we have an smax with a constant maximum-int, it will always be 3444 // maximum-int. 3445 return Ops[0]; 3446 } 3447 3448 if (Ops.size() == 1) return Ops[0]; 3449 } 3450 3451 // Find the first SMax 3452 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3453 ++Idx; 3454 3455 // Check to see if one of the operands is an SMax. If so, expand its operands 3456 // onto our operand list, and recurse to simplify. 3457 if (Idx < Ops.size()) { 3458 bool DeletedSMax = false; 3459 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3460 Ops.erase(Ops.begin()+Idx); 3461 Ops.append(SMax->op_begin(), SMax->op_end()); 3462 DeletedSMax = true; 3463 } 3464 3465 if (DeletedSMax) 3466 return getSMaxExpr(Ops); 3467 } 3468 3469 // Okay, check to see if the same value occurs in the operand list twice. If 3470 // so, delete one. Since we sorted the list, these values are required to 3471 // be adjacent. 3472 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3473 // X smax Y smax Y --> X smax Y 3474 // X smax Y --> X, if X is always greater than Y 3475 if (Ops[i] == Ops[i+1] || 3476 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3477 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3478 --i; --e; 3479 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3480 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3481 --i; --e; 3482 } 3483 3484 if (Ops.size() == 1) return Ops[0]; 3485 3486 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3487 3488 // Okay, it looks like we really DO need an smax expr. Check to see if we 3489 // already have one, otherwise create a new one. 3490 FoldingSetNodeID ID; 3491 ID.AddInteger(scSMaxExpr); 3492 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3493 ID.AddPointer(Ops[i]); 3494 void *IP = nullptr; 3495 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3496 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3497 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3498 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3499 O, Ops.size()); 3500 UniqueSCEVs.InsertNode(S, IP); 3501 addToLoopUseLists(S); 3502 return S; 3503 } 3504 3505 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3506 const SCEV *RHS) { 3507 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3508 return getUMaxExpr(Ops); 3509 } 3510 3511 const SCEV * 3512 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3513 assert(!Ops.empty() && "Cannot get empty umax!"); 3514 if (Ops.size() == 1) return Ops[0]; 3515 #ifndef NDEBUG 3516 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3517 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3518 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3519 "SCEVUMaxExpr operand types don't match!"); 3520 #endif 3521 3522 // Sort by complexity, this groups all similar expression types together. 3523 GroupByComplexity(Ops, &LI, DT); 3524 3525 // If there are any constants, fold them together. 3526 unsigned Idx = 0; 3527 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3528 ++Idx; 3529 assert(Idx < Ops.size()); 3530 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3531 // We found two constants, fold them together! 3532 ConstantInt *Fold = ConstantInt::get( 3533 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3534 Ops[0] = getConstant(Fold); 3535 Ops.erase(Ops.begin()+1); // Erase the folded element 3536 if (Ops.size() == 1) return Ops[0]; 3537 LHSC = cast<SCEVConstant>(Ops[0]); 3538 } 3539 3540 // If we are left with a constant minimum-int, strip it off. 3541 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3542 Ops.erase(Ops.begin()); 3543 --Idx; 3544 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3545 // If we have an umax with a constant maximum-int, it will always be 3546 // maximum-int. 3547 return Ops[0]; 3548 } 3549 3550 if (Ops.size() == 1) return Ops[0]; 3551 } 3552 3553 // Find the first UMax 3554 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3555 ++Idx; 3556 3557 // Check to see if one of the operands is a UMax. If so, expand its operands 3558 // onto our operand list, and recurse to simplify. 3559 if (Idx < Ops.size()) { 3560 bool DeletedUMax = false; 3561 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3562 Ops.erase(Ops.begin()+Idx); 3563 Ops.append(UMax->op_begin(), UMax->op_end()); 3564 DeletedUMax = true; 3565 } 3566 3567 if (DeletedUMax) 3568 return getUMaxExpr(Ops); 3569 } 3570 3571 // Okay, check to see if the same value occurs in the operand list twice. If 3572 // so, delete one. Since we sorted the list, these values are required to 3573 // be adjacent. 3574 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3575 // X umax Y umax Y --> X umax Y 3576 // X umax Y --> X, if X is always greater than Y 3577 if (Ops[i] == Ops[i+1] || 3578 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3579 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3580 --i; --e; 3581 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3582 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3583 --i; --e; 3584 } 3585 3586 if (Ops.size() == 1) return Ops[0]; 3587 3588 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3589 3590 // Okay, it looks like we really DO need a umax expr. Check to see if we 3591 // already have one, otherwise create a new one. 3592 FoldingSetNodeID ID; 3593 ID.AddInteger(scUMaxExpr); 3594 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3595 ID.AddPointer(Ops[i]); 3596 void *IP = nullptr; 3597 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3598 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3599 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3600 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3601 O, Ops.size()); 3602 UniqueSCEVs.InsertNode(S, IP); 3603 addToLoopUseLists(S); 3604 return S; 3605 } 3606 3607 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3608 const SCEV *RHS) { 3609 // ~smax(~x, ~y) == smin(x, y). 3610 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3611 } 3612 3613 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3614 const SCEV *RHS) { 3615 // ~umax(~x, ~y) == umin(x, y) 3616 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3617 } 3618 3619 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3620 // We can bypass creating a target-independent 3621 // constant expression and then folding it back into a ConstantInt. 3622 // This is just a compile-time optimization. 3623 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3624 } 3625 3626 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3627 StructType *STy, 3628 unsigned FieldNo) { 3629 // We can bypass creating a target-independent 3630 // constant expression and then folding it back into a ConstantInt. 3631 // This is just a compile-time optimization. 3632 return getConstant( 3633 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3634 } 3635 3636 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3637 // Don't attempt to do anything other than create a SCEVUnknown object 3638 // here. createSCEV only calls getUnknown after checking for all other 3639 // interesting possibilities, and any other code that calls getUnknown 3640 // is doing so in order to hide a value from SCEV canonicalization. 3641 3642 FoldingSetNodeID ID; 3643 ID.AddInteger(scUnknown); 3644 ID.AddPointer(V); 3645 void *IP = nullptr; 3646 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3647 assert(cast<SCEVUnknown>(S)->getValue() == V && 3648 "Stale SCEVUnknown in uniquing map!"); 3649 return S; 3650 } 3651 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3652 FirstUnknown); 3653 FirstUnknown = cast<SCEVUnknown>(S); 3654 UniqueSCEVs.InsertNode(S, IP); 3655 return S; 3656 } 3657 3658 //===----------------------------------------------------------------------===// 3659 // Basic SCEV Analysis and PHI Idiom Recognition Code 3660 // 3661 3662 /// Test if values of the given type are analyzable within the SCEV 3663 /// framework. This primarily includes integer types, and it can optionally 3664 /// include pointer types if the ScalarEvolution class has access to 3665 /// target-specific information. 3666 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3667 // Integers and pointers are always SCEVable. 3668 return Ty->isIntegerTy() || Ty->isPointerTy(); 3669 } 3670 3671 /// Return the size in bits of the specified type, for which isSCEVable must 3672 /// return true. 3673 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3674 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3675 return getDataLayout().getTypeSizeInBits(Ty); 3676 } 3677 3678 /// Return a type with the same bitwidth as the given type and which represents 3679 /// how SCEV will treat the given type, for which isSCEVable must return 3680 /// true. For pointer types, this is the pointer-sized integer type. 3681 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3682 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3683 3684 if (Ty->isIntegerTy()) 3685 return Ty; 3686 3687 // The only other support type is pointer. 3688 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3689 return getDataLayout().getIntPtrType(Ty); 3690 } 3691 3692 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3693 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3694 } 3695 3696 const SCEV *ScalarEvolution::getCouldNotCompute() { 3697 return CouldNotCompute.get(); 3698 } 3699 3700 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3701 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3702 auto *SU = dyn_cast<SCEVUnknown>(S); 3703 return SU && SU->getValue() == nullptr; 3704 }); 3705 3706 return !ContainsNulls; 3707 } 3708 3709 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3710 HasRecMapType::iterator I = HasRecMap.find(S); 3711 if (I != HasRecMap.end()) 3712 return I->second; 3713 3714 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3715 HasRecMap.insert({S, FoundAddRec}); 3716 return FoundAddRec; 3717 } 3718 3719 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3720 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3721 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3722 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3723 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3724 if (!Add) 3725 return {S, nullptr}; 3726 3727 if (Add->getNumOperands() != 2) 3728 return {S, nullptr}; 3729 3730 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3731 if (!ConstOp) 3732 return {S, nullptr}; 3733 3734 return {Add->getOperand(1), ConstOp->getValue()}; 3735 } 3736 3737 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3738 /// by the value and offset from any ValueOffsetPair in the set. 3739 SetVector<ScalarEvolution::ValueOffsetPair> * 3740 ScalarEvolution::getSCEVValues(const SCEV *S) { 3741 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3742 if (SI == ExprValueMap.end()) 3743 return nullptr; 3744 #ifndef NDEBUG 3745 if (VerifySCEVMap) { 3746 // Check there is no dangling Value in the set returned. 3747 for (const auto &VE : SI->second) 3748 assert(ValueExprMap.count(VE.first)); 3749 } 3750 #endif 3751 return &SI->second; 3752 } 3753 3754 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3755 /// cannot be used separately. eraseValueFromMap should be used to remove 3756 /// V from ValueExprMap and ExprValueMap at the same time. 3757 void ScalarEvolution::eraseValueFromMap(Value *V) { 3758 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3759 if (I != ValueExprMap.end()) { 3760 const SCEV *S = I->second; 3761 // Remove {V, 0} from the set of ExprValueMap[S] 3762 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3763 SV->remove({V, nullptr}); 3764 3765 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3766 const SCEV *Stripped; 3767 ConstantInt *Offset; 3768 std::tie(Stripped, Offset) = splitAddExpr(S); 3769 if (Offset != nullptr) { 3770 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3771 SV->remove({V, Offset}); 3772 } 3773 ValueExprMap.erase(V); 3774 } 3775 } 3776 3777 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3778 /// TODO: In reality it is better to check the poison recursevely 3779 /// but this is better than nothing. 3780 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3781 if (auto *I = dyn_cast<Instruction>(V)) { 3782 if (isa<OverflowingBinaryOperator>(I)) { 3783 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3784 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3785 return true; 3786 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3787 return true; 3788 } 3789 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3790 return true; 3791 } 3792 return false; 3793 } 3794 3795 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3796 /// create a new one. 3797 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3798 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3799 3800 const SCEV *S = getExistingSCEV(V); 3801 if (S == nullptr) { 3802 S = createSCEV(V); 3803 // During PHI resolution, it is possible to create two SCEVs for the same 3804 // V, so it is needed to double check whether V->S is inserted into 3805 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3806 std::pair<ValueExprMapType::iterator, bool> Pair = 3807 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3808 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3809 ExprValueMap[S].insert({V, nullptr}); 3810 3811 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3812 // ExprValueMap. 3813 const SCEV *Stripped = S; 3814 ConstantInt *Offset = nullptr; 3815 std::tie(Stripped, Offset) = splitAddExpr(S); 3816 // If stripped is SCEVUnknown, don't bother to save 3817 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3818 // increase the complexity of the expansion code. 3819 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3820 // because it may generate add/sub instead of GEP in SCEV expansion. 3821 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3822 !isa<GetElementPtrInst>(V)) 3823 ExprValueMap[Stripped].insert({V, Offset}); 3824 } 3825 } 3826 return S; 3827 } 3828 3829 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3830 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3831 3832 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3833 if (I != ValueExprMap.end()) { 3834 const SCEV *S = I->second; 3835 if (checkValidity(S)) 3836 return S; 3837 eraseValueFromMap(V); 3838 forgetMemoizedResults(S); 3839 } 3840 return nullptr; 3841 } 3842 3843 /// Return a SCEV corresponding to -V = -1*V 3844 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3845 SCEV::NoWrapFlags Flags) { 3846 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3847 return getConstant( 3848 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3849 3850 Type *Ty = V->getType(); 3851 Ty = getEffectiveSCEVType(Ty); 3852 return getMulExpr( 3853 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3854 } 3855 3856 /// Return a SCEV corresponding to ~V = -1-V 3857 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3858 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3859 return getConstant( 3860 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3861 3862 Type *Ty = V->getType(); 3863 Ty = getEffectiveSCEVType(Ty); 3864 const SCEV *AllOnes = 3865 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3866 return getMinusSCEV(AllOnes, V); 3867 } 3868 3869 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3870 SCEV::NoWrapFlags Flags, 3871 unsigned Depth) { 3872 // Fast path: X - X --> 0. 3873 if (LHS == RHS) 3874 return getZero(LHS->getType()); 3875 3876 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3877 // makes it so that we cannot make much use of NUW. 3878 auto AddFlags = SCEV::FlagAnyWrap; 3879 const bool RHSIsNotMinSigned = 3880 !getSignedRangeMin(RHS).isMinSignedValue(); 3881 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3882 // Let M be the minimum representable signed value. Then (-1)*RHS 3883 // signed-wraps if and only if RHS is M. That can happen even for 3884 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3885 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3886 // (-1)*RHS, we need to prove that RHS != M. 3887 // 3888 // If LHS is non-negative and we know that LHS - RHS does not 3889 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3890 // either by proving that RHS > M or that LHS >= 0. 3891 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3892 AddFlags = SCEV::FlagNSW; 3893 } 3894 } 3895 3896 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3897 // RHS is NSW and LHS >= 0. 3898 // 3899 // The difficulty here is that the NSW flag may have been proven 3900 // relative to a loop that is to be found in a recurrence in LHS and 3901 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3902 // larger scope than intended. 3903 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3904 3905 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3906 } 3907 3908 const SCEV * 3909 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3910 Type *SrcTy = V->getType(); 3911 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3912 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3913 "Cannot truncate or zero extend with non-integer arguments!"); 3914 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3915 return V; // No conversion 3916 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3917 return getTruncateExpr(V, Ty); 3918 return getZeroExtendExpr(V, Ty); 3919 } 3920 3921 const SCEV * 3922 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3923 Type *Ty) { 3924 Type *SrcTy = V->getType(); 3925 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3926 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3927 "Cannot truncate or zero extend with non-integer arguments!"); 3928 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3929 return V; // No conversion 3930 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3931 return getTruncateExpr(V, Ty); 3932 return getSignExtendExpr(V, Ty); 3933 } 3934 3935 const SCEV * 3936 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3937 Type *SrcTy = V->getType(); 3938 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3939 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3940 "Cannot noop or zero extend with non-integer arguments!"); 3941 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3942 "getNoopOrZeroExtend cannot truncate!"); 3943 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3944 return V; // No conversion 3945 return getZeroExtendExpr(V, Ty); 3946 } 3947 3948 const SCEV * 3949 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3950 Type *SrcTy = V->getType(); 3951 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3952 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3953 "Cannot noop or sign extend with non-integer arguments!"); 3954 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3955 "getNoopOrSignExtend cannot truncate!"); 3956 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3957 return V; // No conversion 3958 return getSignExtendExpr(V, Ty); 3959 } 3960 3961 const SCEV * 3962 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3963 Type *SrcTy = V->getType(); 3964 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3965 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3966 "Cannot noop or any extend with non-integer arguments!"); 3967 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3968 "getNoopOrAnyExtend cannot truncate!"); 3969 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3970 return V; // No conversion 3971 return getAnyExtendExpr(V, Ty); 3972 } 3973 3974 const SCEV * 3975 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3976 Type *SrcTy = V->getType(); 3977 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3978 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3979 "Cannot truncate or noop with non-integer arguments!"); 3980 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3981 "getTruncateOrNoop cannot extend!"); 3982 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3983 return V; // No conversion 3984 return getTruncateExpr(V, Ty); 3985 } 3986 3987 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3988 const SCEV *RHS) { 3989 const SCEV *PromotedLHS = LHS; 3990 const SCEV *PromotedRHS = RHS; 3991 3992 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3993 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3994 else 3995 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3996 3997 return getUMaxExpr(PromotedLHS, PromotedRHS); 3998 } 3999 4000 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4001 const SCEV *RHS) { 4002 const SCEV *PromotedLHS = LHS; 4003 const SCEV *PromotedRHS = RHS; 4004 4005 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4006 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4007 else 4008 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4009 4010 return getUMinExpr(PromotedLHS, PromotedRHS); 4011 } 4012 4013 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4014 // A pointer operand may evaluate to a nonpointer expression, such as null. 4015 if (!V->getType()->isPointerTy()) 4016 return V; 4017 4018 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4019 return getPointerBase(Cast->getOperand()); 4020 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4021 const SCEV *PtrOp = nullptr; 4022 for (const SCEV *NAryOp : NAry->operands()) { 4023 if (NAryOp->getType()->isPointerTy()) { 4024 // Cannot find the base of an expression with multiple pointer operands. 4025 if (PtrOp) 4026 return V; 4027 PtrOp = NAryOp; 4028 } 4029 } 4030 if (!PtrOp) 4031 return V; 4032 return getPointerBase(PtrOp); 4033 } 4034 return V; 4035 } 4036 4037 /// Push users of the given Instruction onto the given Worklist. 4038 static void 4039 PushDefUseChildren(Instruction *I, 4040 SmallVectorImpl<Instruction *> &Worklist) { 4041 // Push the def-use children onto the Worklist stack. 4042 for (User *U : I->users()) 4043 Worklist.push_back(cast<Instruction>(U)); 4044 } 4045 4046 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4047 SmallVector<Instruction *, 16> Worklist; 4048 PushDefUseChildren(PN, Worklist); 4049 4050 SmallPtrSet<Instruction *, 8> Visited; 4051 Visited.insert(PN); 4052 while (!Worklist.empty()) { 4053 Instruction *I = Worklist.pop_back_val(); 4054 if (!Visited.insert(I).second) 4055 continue; 4056 4057 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4058 if (It != ValueExprMap.end()) { 4059 const SCEV *Old = It->second; 4060 4061 // Short-circuit the def-use traversal if the symbolic name 4062 // ceases to appear in expressions. 4063 if (Old != SymName && !hasOperand(Old, SymName)) 4064 continue; 4065 4066 // SCEVUnknown for a PHI either means that it has an unrecognized 4067 // structure, it's a PHI that's in the progress of being computed 4068 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4069 // additional loop trip count information isn't going to change anything. 4070 // In the second case, createNodeForPHI will perform the necessary 4071 // updates on its own when it gets to that point. In the third, we do 4072 // want to forget the SCEVUnknown. 4073 if (!isa<PHINode>(I) || 4074 !isa<SCEVUnknown>(Old) || 4075 (I != PN && Old == SymName)) { 4076 eraseValueFromMap(It->first); 4077 forgetMemoizedResults(Old); 4078 } 4079 } 4080 4081 PushDefUseChildren(I, Worklist); 4082 } 4083 } 4084 4085 namespace { 4086 4087 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4088 public: 4089 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4090 ScalarEvolution &SE) { 4091 SCEVInitRewriter Rewriter(L, SE); 4092 const SCEV *Result = Rewriter.visit(S); 4093 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4094 } 4095 4096 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4097 if (!SE.isLoopInvariant(Expr, L)) 4098 Valid = false; 4099 return Expr; 4100 } 4101 4102 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4103 // Only allow AddRecExprs for this loop. 4104 if (Expr->getLoop() == L) 4105 return Expr->getStart(); 4106 Valid = false; 4107 return Expr; 4108 } 4109 4110 bool isValid() { return Valid; } 4111 4112 private: 4113 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4114 : SCEVRewriteVisitor(SE), L(L) {} 4115 4116 const Loop *L; 4117 bool Valid = true; 4118 }; 4119 4120 /// This class evaluates the compare condition by matching it against the 4121 /// condition of loop latch. If there is a match we assume a true value 4122 /// for the condition while building SCEV nodes. 4123 class SCEVBackedgeConditionFolder 4124 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4125 public: 4126 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4127 ScalarEvolution &SE) { 4128 bool IsPosBECond = false; 4129 Value *BECond = nullptr; 4130 if (BasicBlock *Latch = L->getLoopLatch()) { 4131 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4132 if (BI && BI->isConditional()) { 4133 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4134 "Both outgoing branches should not target same header!"); 4135 BECond = BI->getCondition(); 4136 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4137 } else { 4138 return S; 4139 } 4140 } 4141 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4142 return Rewriter.visit(S); 4143 } 4144 4145 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4146 const SCEV *Result = Expr; 4147 bool InvariantF = SE.isLoopInvariant(Expr, L); 4148 4149 if (!InvariantF) { 4150 Instruction *I = cast<Instruction>(Expr->getValue()); 4151 switch (I->getOpcode()) { 4152 case Instruction::Select: { 4153 SelectInst *SI = cast<SelectInst>(I); 4154 Optional<const SCEV *> Res = 4155 compareWithBackedgeCondition(SI->getCondition()); 4156 if (Res.hasValue()) { 4157 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4158 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4159 } 4160 break; 4161 } 4162 default: { 4163 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4164 if (Res.hasValue()) 4165 Result = Res.getValue(); 4166 break; 4167 } 4168 } 4169 } 4170 return Result; 4171 } 4172 4173 private: 4174 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4175 bool IsPosBECond, ScalarEvolution &SE) 4176 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4177 IsPositiveBECond(IsPosBECond) {} 4178 4179 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4180 4181 const Loop *L; 4182 /// Loop back condition. 4183 Value *BackedgeCond = nullptr; 4184 /// Set to true if loop back is on positive branch condition. 4185 bool IsPositiveBECond; 4186 }; 4187 4188 Optional<const SCEV *> 4189 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4190 4191 // If value matches the backedge condition for loop latch, 4192 // then return a constant evolution node based on loopback 4193 // branch taken. 4194 if (BackedgeCond == IC) 4195 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4196 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4197 return None; 4198 } 4199 4200 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4201 public: 4202 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4203 ScalarEvolution &SE) { 4204 SCEVShiftRewriter Rewriter(L, SE); 4205 const SCEV *Result = Rewriter.visit(S); 4206 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4207 } 4208 4209 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4210 // Only allow AddRecExprs for this loop. 4211 if (!SE.isLoopInvariant(Expr, L)) 4212 Valid = false; 4213 return Expr; 4214 } 4215 4216 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4217 if (Expr->getLoop() == L && Expr->isAffine()) 4218 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4219 Valid = false; 4220 return Expr; 4221 } 4222 4223 bool isValid() { return Valid; } 4224 4225 private: 4226 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4227 : SCEVRewriteVisitor(SE), L(L) {} 4228 4229 const Loop *L; 4230 bool Valid = true; 4231 }; 4232 4233 } // end anonymous namespace 4234 4235 SCEV::NoWrapFlags 4236 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4237 if (!AR->isAffine()) 4238 return SCEV::FlagAnyWrap; 4239 4240 using OBO = OverflowingBinaryOperator; 4241 4242 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4243 4244 if (!AR->hasNoSignedWrap()) { 4245 ConstantRange AddRecRange = getSignedRange(AR); 4246 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4247 4248 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4249 Instruction::Add, IncRange, OBO::NoSignedWrap); 4250 if (NSWRegion.contains(AddRecRange)) 4251 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4252 } 4253 4254 if (!AR->hasNoUnsignedWrap()) { 4255 ConstantRange AddRecRange = getUnsignedRange(AR); 4256 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4257 4258 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4259 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4260 if (NUWRegion.contains(AddRecRange)) 4261 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4262 } 4263 4264 return Result; 4265 } 4266 4267 namespace { 4268 4269 /// Represents an abstract binary operation. This may exist as a 4270 /// normal instruction or constant expression, or may have been 4271 /// derived from an expression tree. 4272 struct BinaryOp { 4273 unsigned Opcode; 4274 Value *LHS; 4275 Value *RHS; 4276 bool IsNSW = false; 4277 bool IsNUW = false; 4278 4279 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4280 /// constant expression. 4281 Operator *Op = nullptr; 4282 4283 explicit BinaryOp(Operator *Op) 4284 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4285 Op(Op) { 4286 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4287 IsNSW = OBO->hasNoSignedWrap(); 4288 IsNUW = OBO->hasNoUnsignedWrap(); 4289 } 4290 } 4291 4292 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4293 bool IsNUW = false) 4294 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4295 }; 4296 4297 } // end anonymous namespace 4298 4299 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4300 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4301 auto *Op = dyn_cast<Operator>(V); 4302 if (!Op) 4303 return None; 4304 4305 // Implementation detail: all the cleverness here should happen without 4306 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4307 // SCEV expressions when possible, and we should not break that. 4308 4309 switch (Op->getOpcode()) { 4310 case Instruction::Add: 4311 case Instruction::Sub: 4312 case Instruction::Mul: 4313 case Instruction::UDiv: 4314 case Instruction::URem: 4315 case Instruction::And: 4316 case Instruction::Or: 4317 case Instruction::AShr: 4318 case Instruction::Shl: 4319 return BinaryOp(Op); 4320 4321 case Instruction::Xor: 4322 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4323 // If the RHS of the xor is a signmask, then this is just an add. 4324 // Instcombine turns add of signmask into xor as a strength reduction step. 4325 if (RHSC->getValue().isSignMask()) 4326 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4327 return BinaryOp(Op); 4328 4329 case Instruction::LShr: 4330 // Turn logical shift right of a constant into a unsigned divide. 4331 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4332 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4333 4334 // If the shift count is not less than the bitwidth, the result of 4335 // the shift is undefined. Don't try to analyze it, because the 4336 // resolution chosen here may differ from the resolution chosen in 4337 // other parts of the compiler. 4338 if (SA->getValue().ult(BitWidth)) { 4339 Constant *X = 4340 ConstantInt::get(SA->getContext(), 4341 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4342 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4343 } 4344 } 4345 return BinaryOp(Op); 4346 4347 case Instruction::ExtractValue: { 4348 auto *EVI = cast<ExtractValueInst>(Op); 4349 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4350 break; 4351 4352 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4353 if (!CI) 4354 break; 4355 4356 if (auto *F = CI->getCalledFunction()) 4357 switch (F->getIntrinsicID()) { 4358 case Intrinsic::sadd_with_overflow: 4359 case Intrinsic::uadd_with_overflow: 4360 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4361 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4362 CI->getArgOperand(1)); 4363 4364 // Now that we know that all uses of the arithmetic-result component of 4365 // CI are guarded by the overflow check, we can go ahead and pretend 4366 // that the arithmetic is non-overflowing. 4367 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4368 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4369 CI->getArgOperand(1), /* IsNSW = */ true, 4370 /* IsNUW = */ false); 4371 else 4372 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4373 CI->getArgOperand(1), /* IsNSW = */ false, 4374 /* IsNUW*/ true); 4375 case Intrinsic::ssub_with_overflow: 4376 case Intrinsic::usub_with_overflow: 4377 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4378 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4379 CI->getArgOperand(1)); 4380 4381 // The same reasoning as sadd/uadd above. 4382 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4383 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4384 CI->getArgOperand(1), /* IsNSW = */ true, 4385 /* IsNUW = */ false); 4386 else 4387 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4388 CI->getArgOperand(1), /* IsNSW = */ false, 4389 /* IsNUW = */ true); 4390 case Intrinsic::smul_with_overflow: 4391 case Intrinsic::umul_with_overflow: 4392 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4393 CI->getArgOperand(1)); 4394 default: 4395 break; 4396 } 4397 break; 4398 } 4399 4400 default: 4401 break; 4402 } 4403 4404 return None; 4405 } 4406 4407 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4408 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4409 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4410 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4411 /// follows one of the following patterns: 4412 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4413 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4414 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4415 /// we return the type of the truncation operation, and indicate whether the 4416 /// truncated type should be treated as signed/unsigned by setting 4417 /// \p Signed to true/false, respectively. 4418 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4419 bool &Signed, ScalarEvolution &SE) { 4420 // The case where Op == SymbolicPHI (that is, with no type conversions on 4421 // the way) is handled by the regular add recurrence creating logic and 4422 // would have already been triggered in createAddRecForPHI. Reaching it here 4423 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4424 // because one of the other operands of the SCEVAddExpr updating this PHI is 4425 // not invariant). 4426 // 4427 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4428 // this case predicates that allow us to prove that Op == SymbolicPHI will 4429 // be added. 4430 if (Op == SymbolicPHI) 4431 return nullptr; 4432 4433 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4434 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4435 if (SourceBits != NewBits) 4436 return nullptr; 4437 4438 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4439 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4440 if (!SExt && !ZExt) 4441 return nullptr; 4442 const SCEVTruncateExpr *Trunc = 4443 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4444 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4445 if (!Trunc) 4446 return nullptr; 4447 const SCEV *X = Trunc->getOperand(); 4448 if (X != SymbolicPHI) 4449 return nullptr; 4450 Signed = SExt != nullptr; 4451 return Trunc->getType(); 4452 } 4453 4454 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4455 if (!PN->getType()->isIntegerTy()) 4456 return nullptr; 4457 const Loop *L = LI.getLoopFor(PN->getParent()); 4458 if (!L || L->getHeader() != PN->getParent()) 4459 return nullptr; 4460 return L; 4461 } 4462 4463 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4464 // computation that updates the phi follows the following pattern: 4465 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4466 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4467 // If so, try to see if it can be rewritten as an AddRecExpr under some 4468 // Predicates. If successful, return them as a pair. Also cache the results 4469 // of the analysis. 4470 // 4471 // Example usage scenario: 4472 // Say the Rewriter is called for the following SCEV: 4473 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4474 // where: 4475 // %X = phi i64 (%Start, %BEValue) 4476 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4477 // and call this function with %SymbolicPHI = %X. 4478 // 4479 // The analysis will find that the value coming around the backedge has 4480 // the following SCEV: 4481 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4482 // Upon concluding that this matches the desired pattern, the function 4483 // will return the pair {NewAddRec, SmallPredsVec} where: 4484 // NewAddRec = {%Start,+,%Step} 4485 // SmallPredsVec = {P1, P2, P3} as follows: 4486 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4487 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4488 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4489 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4490 // under the predicates {P1,P2,P3}. 4491 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4492 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4493 // 4494 // TODO's: 4495 // 4496 // 1) Extend the Induction descriptor to also support inductions that involve 4497 // casts: When needed (namely, when we are called in the context of the 4498 // vectorizer induction analysis), a Set of cast instructions will be 4499 // populated by this method, and provided back to isInductionPHI. This is 4500 // needed to allow the vectorizer to properly record them to be ignored by 4501 // the cost model and to avoid vectorizing them (otherwise these casts, 4502 // which are redundant under the runtime overflow checks, will be 4503 // vectorized, which can be costly). 4504 // 4505 // 2) Support additional induction/PHISCEV patterns: We also want to support 4506 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4507 // after the induction update operation (the induction increment): 4508 // 4509 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4510 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4511 // 4512 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4513 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4514 // 4515 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4516 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4517 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4518 SmallVector<const SCEVPredicate *, 3> Predicates; 4519 4520 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4521 // return an AddRec expression under some predicate. 4522 4523 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4524 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4525 assert(L && "Expecting an integer loop header phi"); 4526 4527 // The loop may have multiple entrances or multiple exits; we can analyze 4528 // this phi as an addrec if it has a unique entry value and a unique 4529 // backedge value. 4530 Value *BEValueV = nullptr, *StartValueV = nullptr; 4531 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4532 Value *V = PN->getIncomingValue(i); 4533 if (L->contains(PN->getIncomingBlock(i))) { 4534 if (!BEValueV) { 4535 BEValueV = V; 4536 } else if (BEValueV != V) { 4537 BEValueV = nullptr; 4538 break; 4539 } 4540 } else if (!StartValueV) { 4541 StartValueV = V; 4542 } else if (StartValueV != V) { 4543 StartValueV = nullptr; 4544 break; 4545 } 4546 } 4547 if (!BEValueV || !StartValueV) 4548 return None; 4549 4550 const SCEV *BEValue = getSCEV(BEValueV); 4551 4552 // If the value coming around the backedge is an add with the symbolic 4553 // value we just inserted, possibly with casts that we can ignore under 4554 // an appropriate runtime guard, then we found a simple induction variable! 4555 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4556 if (!Add) 4557 return None; 4558 4559 // If there is a single occurrence of the symbolic value, possibly 4560 // casted, replace it with a recurrence. 4561 unsigned FoundIndex = Add->getNumOperands(); 4562 Type *TruncTy = nullptr; 4563 bool Signed; 4564 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4565 if ((TruncTy = 4566 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4567 if (FoundIndex == e) { 4568 FoundIndex = i; 4569 break; 4570 } 4571 4572 if (FoundIndex == Add->getNumOperands()) 4573 return None; 4574 4575 // Create an add with everything but the specified operand. 4576 SmallVector<const SCEV *, 8> Ops; 4577 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4578 if (i != FoundIndex) 4579 Ops.push_back(Add->getOperand(i)); 4580 const SCEV *Accum = getAddExpr(Ops); 4581 4582 // The runtime checks will not be valid if the step amount is 4583 // varying inside the loop. 4584 if (!isLoopInvariant(Accum, L)) 4585 return None; 4586 4587 // *** Part2: Create the predicates 4588 4589 // Analysis was successful: we have a phi-with-cast pattern for which we 4590 // can return an AddRec expression under the following predicates: 4591 // 4592 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4593 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4594 // P2: An Equal predicate that guarantees that 4595 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4596 // P3: An Equal predicate that guarantees that 4597 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4598 // 4599 // As we next prove, the above predicates guarantee that: 4600 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4601 // 4602 // 4603 // More formally, we want to prove that: 4604 // Expr(i+1) = Start + (i+1) * Accum 4605 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4606 // 4607 // Given that: 4608 // 1) Expr(0) = Start 4609 // 2) Expr(1) = Start + Accum 4610 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4611 // 3) Induction hypothesis (step i): 4612 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4613 // 4614 // Proof: 4615 // Expr(i+1) = 4616 // = Start + (i+1)*Accum 4617 // = (Start + i*Accum) + Accum 4618 // = Expr(i) + Accum 4619 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4620 // :: from step i 4621 // 4622 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4623 // 4624 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4625 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4626 // + Accum :: from P3 4627 // 4628 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4629 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4630 // 4631 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4632 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4633 // 4634 // By induction, the same applies to all iterations 1<=i<n: 4635 // 4636 4637 // Create a truncated addrec for which we will add a no overflow check (P1). 4638 const SCEV *StartVal = getSCEV(StartValueV); 4639 const SCEV *PHISCEV = 4640 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4641 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4642 4643 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4644 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4645 // will be constant. 4646 // 4647 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4648 // add P1. 4649 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4650 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4651 Signed ? SCEVWrapPredicate::IncrementNSSW 4652 : SCEVWrapPredicate::IncrementNUSW; 4653 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4654 Predicates.push_back(AddRecPred); 4655 } 4656 4657 // Create the Equal Predicates P2,P3: 4658 4659 // It is possible that the predicates P2 and/or P3 are computable at 4660 // compile time due to StartVal and/or Accum being constants. 4661 // If either one is, then we can check that now and escape if either P2 4662 // or P3 is false. 4663 4664 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4665 // for each of StartVal and Accum 4666 auto getExtendedExpr = [&](const SCEV *Expr, 4667 bool CreateSignExtend) -> const SCEV * { 4668 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4669 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4670 const SCEV *ExtendedExpr = 4671 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4672 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4673 return ExtendedExpr; 4674 }; 4675 4676 // Given: 4677 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4678 // = getExtendedExpr(Expr) 4679 // Determine whether the predicate P: Expr == ExtendedExpr 4680 // is known to be false at compile time 4681 auto PredIsKnownFalse = [&](const SCEV *Expr, 4682 const SCEV *ExtendedExpr) -> bool { 4683 return Expr != ExtendedExpr && 4684 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4685 }; 4686 4687 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4688 if (PredIsKnownFalse(StartVal, StartExtended)) { 4689 DEBUG(dbgs() << "P2 is compile-time false\n";); 4690 return None; 4691 } 4692 4693 // The Step is always Signed (because the overflow checks are either 4694 // NSSW or NUSW) 4695 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4696 if (PredIsKnownFalse(Accum, AccumExtended)) { 4697 DEBUG(dbgs() << "P3 is compile-time false\n";); 4698 return None; 4699 } 4700 4701 auto AppendPredicate = [&](const SCEV *Expr, 4702 const SCEV *ExtendedExpr) -> void { 4703 if (Expr != ExtendedExpr && 4704 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4705 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4706 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4707 Predicates.push_back(Pred); 4708 } 4709 }; 4710 4711 AppendPredicate(StartVal, StartExtended); 4712 AppendPredicate(Accum, AccumExtended); 4713 4714 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4715 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4716 // into NewAR if it will also add the runtime overflow checks specified in 4717 // Predicates. 4718 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4719 4720 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4721 std::make_pair(NewAR, Predicates); 4722 // Remember the result of the analysis for this SCEV at this locayyytion. 4723 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4724 return PredRewrite; 4725 } 4726 4727 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4728 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4729 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4730 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4731 if (!L) 4732 return None; 4733 4734 // Check to see if we already analyzed this PHI. 4735 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4736 if (I != PredicatedSCEVRewrites.end()) { 4737 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4738 I->second; 4739 // Analysis was done before and failed to create an AddRec: 4740 if (Rewrite.first == SymbolicPHI) 4741 return None; 4742 // Analysis was done before and succeeded to create an AddRec under 4743 // a predicate: 4744 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4745 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4746 return Rewrite; 4747 } 4748 4749 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4750 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4751 4752 // Record in the cache that the analysis failed 4753 if (!Rewrite) { 4754 SmallVector<const SCEVPredicate *, 3> Predicates; 4755 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4756 return None; 4757 } 4758 4759 return Rewrite; 4760 } 4761 4762 // FIXME: This utility is currently required because the Rewriter currently 4763 // does not rewrite this expression: 4764 // {0, +, (sext ix (trunc iy to ix) to iy)} 4765 // into {0, +, %step}, 4766 // even when the following Equal predicate exists: 4767 // "%step == (sext ix (trunc iy to ix) to iy)". 4768 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4769 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4770 if (AR1 == AR2) 4771 return true; 4772 4773 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4774 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4775 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4776 return false; 4777 return true; 4778 }; 4779 4780 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4781 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4782 return false; 4783 return true; 4784 } 4785 4786 /// A helper function for createAddRecFromPHI to handle simple cases. 4787 /// 4788 /// This function tries to find an AddRec expression for the simplest (yet most 4789 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4790 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4791 /// technique for finding the AddRec expression. 4792 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4793 Value *BEValueV, 4794 Value *StartValueV) { 4795 const Loop *L = LI.getLoopFor(PN->getParent()); 4796 assert(L && L->getHeader() == PN->getParent()); 4797 assert(BEValueV && StartValueV); 4798 4799 auto BO = MatchBinaryOp(BEValueV, DT); 4800 if (!BO) 4801 return nullptr; 4802 4803 if (BO->Opcode != Instruction::Add) 4804 return nullptr; 4805 4806 const SCEV *Accum = nullptr; 4807 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4808 Accum = getSCEV(BO->RHS); 4809 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4810 Accum = getSCEV(BO->LHS); 4811 4812 if (!Accum) 4813 return nullptr; 4814 4815 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4816 if (BO->IsNUW) 4817 Flags = setFlags(Flags, SCEV::FlagNUW); 4818 if (BO->IsNSW) 4819 Flags = setFlags(Flags, SCEV::FlagNSW); 4820 4821 const SCEV *StartVal = getSCEV(StartValueV); 4822 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4823 4824 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4825 4826 // We can add Flags to the post-inc expression only if we 4827 // know that it is *undefined behavior* for BEValueV to 4828 // overflow. 4829 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4830 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4831 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4832 4833 return PHISCEV; 4834 } 4835 4836 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4837 const Loop *L = LI.getLoopFor(PN->getParent()); 4838 if (!L || L->getHeader() != PN->getParent()) 4839 return nullptr; 4840 4841 // The loop may have multiple entrances or multiple exits; we can analyze 4842 // this phi as an addrec if it has a unique entry value and a unique 4843 // backedge value. 4844 Value *BEValueV = nullptr, *StartValueV = nullptr; 4845 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4846 Value *V = PN->getIncomingValue(i); 4847 if (L->contains(PN->getIncomingBlock(i))) { 4848 if (!BEValueV) { 4849 BEValueV = V; 4850 } else if (BEValueV != V) { 4851 BEValueV = nullptr; 4852 break; 4853 } 4854 } else if (!StartValueV) { 4855 StartValueV = V; 4856 } else if (StartValueV != V) { 4857 StartValueV = nullptr; 4858 break; 4859 } 4860 } 4861 if (!BEValueV || !StartValueV) 4862 return nullptr; 4863 4864 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4865 "PHI node already processed?"); 4866 4867 // First, try to find AddRec expression without creating a fictituos symbolic 4868 // value for PN. 4869 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4870 return S; 4871 4872 // Handle PHI node value symbolically. 4873 const SCEV *SymbolicName = getUnknown(PN); 4874 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4875 4876 // Using this symbolic name for the PHI, analyze the value coming around 4877 // the back-edge. 4878 const SCEV *BEValue = getSCEV(BEValueV); 4879 4880 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4881 // has a special value for the first iteration of the loop. 4882 4883 // If the value coming around the backedge is an add with the symbolic 4884 // value we just inserted, then we found a simple induction variable! 4885 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4886 // If there is a single occurrence of the symbolic value, replace it 4887 // with a recurrence. 4888 unsigned FoundIndex = Add->getNumOperands(); 4889 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4890 if (Add->getOperand(i) == SymbolicName) 4891 if (FoundIndex == e) { 4892 FoundIndex = i; 4893 break; 4894 } 4895 4896 if (FoundIndex != Add->getNumOperands()) { 4897 // Create an add with everything but the specified operand. 4898 SmallVector<const SCEV *, 8> Ops; 4899 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4900 if (i != FoundIndex) 4901 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4902 L, *this)); 4903 const SCEV *Accum = getAddExpr(Ops); 4904 4905 // This is not a valid addrec if the step amount is varying each 4906 // loop iteration, but is not itself an addrec in this loop. 4907 if (isLoopInvariant(Accum, L) || 4908 (isa<SCEVAddRecExpr>(Accum) && 4909 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4910 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4911 4912 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4913 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4914 if (BO->IsNUW) 4915 Flags = setFlags(Flags, SCEV::FlagNUW); 4916 if (BO->IsNSW) 4917 Flags = setFlags(Flags, SCEV::FlagNSW); 4918 } 4919 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4920 // If the increment is an inbounds GEP, then we know the address 4921 // space cannot be wrapped around. We cannot make any guarantee 4922 // about signed or unsigned overflow because pointers are 4923 // unsigned but we may have a negative index from the base 4924 // pointer. We can guarantee that no unsigned wrap occurs if the 4925 // indices form a positive value. 4926 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4927 Flags = setFlags(Flags, SCEV::FlagNW); 4928 4929 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4930 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4931 Flags = setFlags(Flags, SCEV::FlagNUW); 4932 } 4933 4934 // We cannot transfer nuw and nsw flags from subtraction 4935 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4936 // for instance. 4937 } 4938 4939 const SCEV *StartVal = getSCEV(StartValueV); 4940 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4941 4942 // Okay, for the entire analysis of this edge we assumed the PHI 4943 // to be symbolic. We now need to go back and purge all of the 4944 // entries for the scalars that use the symbolic expression. 4945 forgetSymbolicName(PN, SymbolicName); 4946 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4947 4948 // We can add Flags to the post-inc expression only if we 4949 // know that it is *undefined behavior* for BEValueV to 4950 // overflow. 4951 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4952 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4953 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4954 4955 return PHISCEV; 4956 } 4957 } 4958 } else { 4959 // Otherwise, this could be a loop like this: 4960 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4961 // In this case, j = {1,+,1} and BEValue is j. 4962 // Because the other in-value of i (0) fits the evolution of BEValue 4963 // i really is an addrec evolution. 4964 // 4965 // We can generalize this saying that i is the shifted value of BEValue 4966 // by one iteration: 4967 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4968 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4969 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4970 if (Shifted != getCouldNotCompute() && 4971 Start != getCouldNotCompute()) { 4972 const SCEV *StartVal = getSCEV(StartValueV); 4973 if (Start == StartVal) { 4974 // Okay, for the entire analysis of this edge we assumed the PHI 4975 // to be symbolic. We now need to go back and purge all of the 4976 // entries for the scalars that use the symbolic expression. 4977 forgetSymbolicName(PN, SymbolicName); 4978 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4979 return Shifted; 4980 } 4981 } 4982 } 4983 4984 // Remove the temporary PHI node SCEV that has been inserted while intending 4985 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4986 // as it will prevent later (possibly simpler) SCEV expressions to be added 4987 // to the ValueExprMap. 4988 eraseValueFromMap(PN); 4989 4990 return nullptr; 4991 } 4992 4993 // Checks if the SCEV S is available at BB. S is considered available at BB 4994 // if S can be materialized at BB without introducing a fault. 4995 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4996 BasicBlock *BB) { 4997 struct CheckAvailable { 4998 bool TraversalDone = false; 4999 bool Available = true; 5000 5001 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5002 BasicBlock *BB = nullptr; 5003 DominatorTree &DT; 5004 5005 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5006 : L(L), BB(BB), DT(DT) {} 5007 5008 bool setUnavailable() { 5009 TraversalDone = true; 5010 Available = false; 5011 return false; 5012 } 5013 5014 bool follow(const SCEV *S) { 5015 switch (S->getSCEVType()) { 5016 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5017 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5018 // These expressions are available if their operand(s) is/are. 5019 return true; 5020 5021 case scAddRecExpr: { 5022 // We allow add recurrences that are on the loop BB is in, or some 5023 // outer loop. This guarantees availability because the value of the 5024 // add recurrence at BB is simply the "current" value of the induction 5025 // variable. We can relax this in the future; for instance an add 5026 // recurrence on a sibling dominating loop is also available at BB. 5027 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5028 if (L && (ARLoop == L || ARLoop->contains(L))) 5029 return true; 5030 5031 return setUnavailable(); 5032 } 5033 5034 case scUnknown: { 5035 // For SCEVUnknown, we check for simple dominance. 5036 const auto *SU = cast<SCEVUnknown>(S); 5037 Value *V = SU->getValue(); 5038 5039 if (isa<Argument>(V)) 5040 return false; 5041 5042 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5043 return false; 5044 5045 return setUnavailable(); 5046 } 5047 5048 case scUDivExpr: 5049 case scCouldNotCompute: 5050 // We do not try to smart about these at all. 5051 return setUnavailable(); 5052 } 5053 llvm_unreachable("switch should be fully covered!"); 5054 } 5055 5056 bool isDone() { return TraversalDone; } 5057 }; 5058 5059 CheckAvailable CA(L, BB, DT); 5060 SCEVTraversal<CheckAvailable> ST(CA); 5061 5062 ST.visitAll(S); 5063 return CA.Available; 5064 } 5065 5066 // Try to match a control flow sequence that branches out at BI and merges back 5067 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5068 // match. 5069 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5070 Value *&C, Value *&LHS, Value *&RHS) { 5071 C = BI->getCondition(); 5072 5073 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5074 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5075 5076 if (!LeftEdge.isSingleEdge()) 5077 return false; 5078 5079 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5080 5081 Use &LeftUse = Merge->getOperandUse(0); 5082 Use &RightUse = Merge->getOperandUse(1); 5083 5084 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5085 LHS = LeftUse; 5086 RHS = RightUse; 5087 return true; 5088 } 5089 5090 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5091 LHS = RightUse; 5092 RHS = LeftUse; 5093 return true; 5094 } 5095 5096 return false; 5097 } 5098 5099 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5100 auto IsReachable = 5101 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5102 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5103 const Loop *L = LI.getLoopFor(PN->getParent()); 5104 5105 // We don't want to break LCSSA, even in a SCEV expression tree. 5106 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5107 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5108 return nullptr; 5109 5110 // Try to match 5111 // 5112 // br %cond, label %left, label %right 5113 // left: 5114 // br label %merge 5115 // right: 5116 // br label %merge 5117 // merge: 5118 // V = phi [ %x, %left ], [ %y, %right ] 5119 // 5120 // as "select %cond, %x, %y" 5121 5122 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5123 assert(IDom && "At least the entry block should dominate PN"); 5124 5125 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5126 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5127 5128 if (BI && BI->isConditional() && 5129 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5130 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5131 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5132 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5133 } 5134 5135 return nullptr; 5136 } 5137 5138 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5139 if (const SCEV *S = createAddRecFromPHI(PN)) 5140 return S; 5141 5142 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5143 return S; 5144 5145 // If the PHI has a single incoming value, follow that value, unless the 5146 // PHI's incoming blocks are in a different loop, in which case doing so 5147 // risks breaking LCSSA form. Instcombine would normally zap these, but 5148 // it doesn't have DominatorTree information, so it may miss cases. 5149 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5150 if (LI.replacementPreservesLCSSAForm(PN, V)) 5151 return getSCEV(V); 5152 5153 // If it's not a loop phi, we can't handle it yet. 5154 return getUnknown(PN); 5155 } 5156 5157 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5158 Value *Cond, 5159 Value *TrueVal, 5160 Value *FalseVal) { 5161 // Handle "constant" branch or select. This can occur for instance when a 5162 // loop pass transforms an inner loop and moves on to process the outer loop. 5163 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5164 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5165 5166 // Try to match some simple smax or umax patterns. 5167 auto *ICI = dyn_cast<ICmpInst>(Cond); 5168 if (!ICI) 5169 return getUnknown(I); 5170 5171 Value *LHS = ICI->getOperand(0); 5172 Value *RHS = ICI->getOperand(1); 5173 5174 switch (ICI->getPredicate()) { 5175 case ICmpInst::ICMP_SLT: 5176 case ICmpInst::ICMP_SLE: 5177 std::swap(LHS, RHS); 5178 LLVM_FALLTHROUGH; 5179 case ICmpInst::ICMP_SGT: 5180 case ICmpInst::ICMP_SGE: 5181 // a >s b ? a+x : b+x -> smax(a, b)+x 5182 // a >s b ? b+x : a+x -> smin(a, b)+x 5183 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5184 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5185 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5186 const SCEV *LA = getSCEV(TrueVal); 5187 const SCEV *RA = getSCEV(FalseVal); 5188 const SCEV *LDiff = getMinusSCEV(LA, LS); 5189 const SCEV *RDiff = getMinusSCEV(RA, RS); 5190 if (LDiff == RDiff) 5191 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5192 LDiff = getMinusSCEV(LA, RS); 5193 RDiff = getMinusSCEV(RA, LS); 5194 if (LDiff == RDiff) 5195 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5196 } 5197 break; 5198 case ICmpInst::ICMP_ULT: 5199 case ICmpInst::ICMP_ULE: 5200 std::swap(LHS, RHS); 5201 LLVM_FALLTHROUGH; 5202 case ICmpInst::ICMP_UGT: 5203 case ICmpInst::ICMP_UGE: 5204 // a >u b ? a+x : b+x -> umax(a, b)+x 5205 // a >u b ? b+x : a+x -> umin(a, b)+x 5206 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5207 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5208 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5209 const SCEV *LA = getSCEV(TrueVal); 5210 const SCEV *RA = getSCEV(FalseVal); 5211 const SCEV *LDiff = getMinusSCEV(LA, LS); 5212 const SCEV *RDiff = getMinusSCEV(RA, RS); 5213 if (LDiff == RDiff) 5214 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5215 LDiff = getMinusSCEV(LA, RS); 5216 RDiff = getMinusSCEV(RA, LS); 5217 if (LDiff == RDiff) 5218 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5219 } 5220 break; 5221 case ICmpInst::ICMP_NE: 5222 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5223 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5224 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5225 const SCEV *One = getOne(I->getType()); 5226 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5227 const SCEV *LA = getSCEV(TrueVal); 5228 const SCEV *RA = getSCEV(FalseVal); 5229 const SCEV *LDiff = getMinusSCEV(LA, LS); 5230 const SCEV *RDiff = getMinusSCEV(RA, One); 5231 if (LDiff == RDiff) 5232 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5233 } 5234 break; 5235 case ICmpInst::ICMP_EQ: 5236 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5237 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5238 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5239 const SCEV *One = getOne(I->getType()); 5240 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5241 const SCEV *LA = getSCEV(TrueVal); 5242 const SCEV *RA = getSCEV(FalseVal); 5243 const SCEV *LDiff = getMinusSCEV(LA, One); 5244 const SCEV *RDiff = getMinusSCEV(RA, LS); 5245 if (LDiff == RDiff) 5246 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5247 } 5248 break; 5249 default: 5250 break; 5251 } 5252 5253 return getUnknown(I); 5254 } 5255 5256 /// Expand GEP instructions into add and multiply operations. This allows them 5257 /// to be analyzed by regular SCEV code. 5258 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5259 // Don't attempt to analyze GEPs over unsized objects. 5260 if (!GEP->getSourceElementType()->isSized()) 5261 return getUnknown(GEP); 5262 5263 SmallVector<const SCEV *, 4> IndexExprs; 5264 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5265 IndexExprs.push_back(getSCEV(*Index)); 5266 return getGEPExpr(GEP, IndexExprs); 5267 } 5268 5269 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5270 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5271 return C->getAPInt().countTrailingZeros(); 5272 5273 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5274 return std::min(GetMinTrailingZeros(T->getOperand()), 5275 (uint32_t)getTypeSizeInBits(T->getType())); 5276 5277 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5278 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5279 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5280 ? getTypeSizeInBits(E->getType()) 5281 : OpRes; 5282 } 5283 5284 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5285 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5286 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5287 ? getTypeSizeInBits(E->getType()) 5288 : OpRes; 5289 } 5290 5291 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5292 // The result is the min of all operands results. 5293 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5294 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5295 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5296 return MinOpRes; 5297 } 5298 5299 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5300 // The result is the sum of all operands results. 5301 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5302 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5303 for (unsigned i = 1, e = M->getNumOperands(); 5304 SumOpRes != BitWidth && i != e; ++i) 5305 SumOpRes = 5306 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5307 return SumOpRes; 5308 } 5309 5310 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5311 // The result is the min of all operands results. 5312 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5313 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5314 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5315 return MinOpRes; 5316 } 5317 5318 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5319 // The result is the min of all operands results. 5320 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5321 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5322 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5323 return MinOpRes; 5324 } 5325 5326 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5327 // The result is the min of all operands results. 5328 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5329 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5330 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5331 return MinOpRes; 5332 } 5333 5334 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5335 // For a SCEVUnknown, ask ValueTracking. 5336 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5337 return Known.countMinTrailingZeros(); 5338 } 5339 5340 // SCEVUDivExpr 5341 return 0; 5342 } 5343 5344 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5345 auto I = MinTrailingZerosCache.find(S); 5346 if (I != MinTrailingZerosCache.end()) 5347 return I->second; 5348 5349 uint32_t Result = GetMinTrailingZerosImpl(S); 5350 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5351 assert(InsertPair.second && "Should insert a new key"); 5352 return InsertPair.first->second; 5353 } 5354 5355 /// Helper method to assign a range to V from metadata present in the IR. 5356 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5357 if (Instruction *I = dyn_cast<Instruction>(V)) 5358 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5359 return getConstantRangeFromMetadata(*MD); 5360 5361 return None; 5362 } 5363 5364 /// Determine the range for a particular SCEV. If SignHint is 5365 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5366 /// with a "cleaner" unsigned (resp. signed) representation. 5367 const ConstantRange & 5368 ScalarEvolution::getRangeRef(const SCEV *S, 5369 ScalarEvolution::RangeSignHint SignHint) { 5370 DenseMap<const SCEV *, ConstantRange> &Cache = 5371 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5372 : SignedRanges; 5373 5374 // See if we've computed this range already. 5375 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5376 if (I != Cache.end()) 5377 return I->second; 5378 5379 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5380 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5381 5382 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5383 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5384 5385 // If the value has known zeros, the maximum value will have those known zeros 5386 // as well. 5387 uint32_t TZ = GetMinTrailingZeros(S); 5388 if (TZ != 0) { 5389 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5390 ConservativeResult = 5391 ConstantRange(APInt::getMinValue(BitWidth), 5392 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5393 else 5394 ConservativeResult = ConstantRange( 5395 APInt::getSignedMinValue(BitWidth), 5396 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5397 } 5398 5399 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5400 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5401 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5402 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5403 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5404 } 5405 5406 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5407 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5408 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5409 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5410 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5411 } 5412 5413 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5414 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5415 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5416 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5417 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5418 } 5419 5420 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5421 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5422 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5423 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5424 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5425 } 5426 5427 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5428 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5429 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5430 return setRange(UDiv, SignHint, 5431 ConservativeResult.intersectWith(X.udiv(Y))); 5432 } 5433 5434 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5435 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5436 return setRange(ZExt, SignHint, 5437 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5438 } 5439 5440 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5441 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5442 return setRange(SExt, SignHint, 5443 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5444 } 5445 5446 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5447 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5448 return setRange(Trunc, SignHint, 5449 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5450 } 5451 5452 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5453 // If there's no unsigned wrap, the value will never be less than its 5454 // initial value. 5455 if (AddRec->hasNoUnsignedWrap()) 5456 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5457 if (!C->getValue()->isZero()) 5458 ConservativeResult = ConservativeResult.intersectWith( 5459 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5460 5461 // If there's no signed wrap, and all the operands have the same sign or 5462 // zero, the value won't ever change sign. 5463 if (AddRec->hasNoSignedWrap()) { 5464 bool AllNonNeg = true; 5465 bool AllNonPos = true; 5466 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5467 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5468 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5469 } 5470 if (AllNonNeg) 5471 ConservativeResult = ConservativeResult.intersectWith( 5472 ConstantRange(APInt(BitWidth, 0), 5473 APInt::getSignedMinValue(BitWidth))); 5474 else if (AllNonPos) 5475 ConservativeResult = ConservativeResult.intersectWith( 5476 ConstantRange(APInt::getSignedMinValue(BitWidth), 5477 APInt(BitWidth, 1))); 5478 } 5479 5480 // TODO: non-affine addrec 5481 if (AddRec->isAffine()) { 5482 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5483 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5484 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5485 auto RangeFromAffine = getRangeForAffineAR( 5486 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5487 BitWidth); 5488 if (!RangeFromAffine.isFullSet()) 5489 ConservativeResult = 5490 ConservativeResult.intersectWith(RangeFromAffine); 5491 5492 auto RangeFromFactoring = getRangeViaFactoring( 5493 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5494 BitWidth); 5495 if (!RangeFromFactoring.isFullSet()) 5496 ConservativeResult = 5497 ConservativeResult.intersectWith(RangeFromFactoring); 5498 } 5499 } 5500 5501 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5502 } 5503 5504 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5505 // Check if the IR explicitly contains !range metadata. 5506 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5507 if (MDRange.hasValue()) 5508 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5509 5510 // Split here to avoid paying the compile-time cost of calling both 5511 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5512 // if needed. 5513 const DataLayout &DL = getDataLayout(); 5514 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5515 // For a SCEVUnknown, ask ValueTracking. 5516 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5517 if (Known.One != ~Known.Zero + 1) 5518 ConservativeResult = 5519 ConservativeResult.intersectWith(ConstantRange(Known.One, 5520 ~Known.Zero + 1)); 5521 } else { 5522 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5523 "generalize as needed!"); 5524 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5525 if (NS > 1) 5526 ConservativeResult = ConservativeResult.intersectWith( 5527 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5528 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5529 } 5530 5531 return setRange(U, SignHint, std::move(ConservativeResult)); 5532 } 5533 5534 return setRange(S, SignHint, std::move(ConservativeResult)); 5535 } 5536 5537 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5538 // values that the expression can take. Initially, the expression has a value 5539 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5540 // argument defines if we treat Step as signed or unsigned. 5541 static ConstantRange getRangeForAffineARHelper(APInt Step, 5542 const ConstantRange &StartRange, 5543 const APInt &MaxBECount, 5544 unsigned BitWidth, bool Signed) { 5545 // If either Step or MaxBECount is 0, then the expression won't change, and we 5546 // just need to return the initial range. 5547 if (Step == 0 || MaxBECount == 0) 5548 return StartRange; 5549 5550 // If we don't know anything about the initial value (i.e. StartRange is 5551 // FullRange), then we don't know anything about the final range either. 5552 // Return FullRange. 5553 if (StartRange.isFullSet()) 5554 return ConstantRange(BitWidth, /* isFullSet = */ true); 5555 5556 // If Step is signed and negative, then we use its absolute value, but we also 5557 // note that we're moving in the opposite direction. 5558 bool Descending = Signed && Step.isNegative(); 5559 5560 if (Signed) 5561 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5562 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5563 // This equations hold true due to the well-defined wrap-around behavior of 5564 // APInt. 5565 Step = Step.abs(); 5566 5567 // Check if Offset is more than full span of BitWidth. If it is, the 5568 // expression is guaranteed to overflow. 5569 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5570 return ConstantRange(BitWidth, /* isFullSet = */ true); 5571 5572 // Offset is by how much the expression can change. Checks above guarantee no 5573 // overflow here. 5574 APInt Offset = Step * MaxBECount; 5575 5576 // Minimum value of the final range will match the minimal value of StartRange 5577 // if the expression is increasing and will be decreased by Offset otherwise. 5578 // Maximum value of the final range will match the maximal value of StartRange 5579 // if the expression is decreasing and will be increased by Offset otherwise. 5580 APInt StartLower = StartRange.getLower(); 5581 APInt StartUpper = StartRange.getUpper() - 1; 5582 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5583 : (StartUpper + std::move(Offset)); 5584 5585 // It's possible that the new minimum/maximum value will fall into the initial 5586 // range (due to wrap around). This means that the expression can take any 5587 // value in this bitwidth, and we have to return full range. 5588 if (StartRange.contains(MovedBoundary)) 5589 return ConstantRange(BitWidth, /* isFullSet = */ true); 5590 5591 APInt NewLower = 5592 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5593 APInt NewUpper = 5594 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5595 NewUpper += 1; 5596 5597 // If we end up with full range, return a proper full range. 5598 if (NewLower == NewUpper) 5599 return ConstantRange(BitWidth, /* isFullSet = */ true); 5600 5601 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5602 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5603 } 5604 5605 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5606 const SCEV *Step, 5607 const SCEV *MaxBECount, 5608 unsigned BitWidth) { 5609 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5610 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5611 "Precondition!"); 5612 5613 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5614 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5615 5616 // First, consider step signed. 5617 ConstantRange StartSRange = getSignedRange(Start); 5618 ConstantRange StepSRange = getSignedRange(Step); 5619 5620 // If Step can be both positive and negative, we need to find ranges for the 5621 // maximum absolute step values in both directions and union them. 5622 ConstantRange SR = 5623 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5624 MaxBECountValue, BitWidth, /* Signed = */ true); 5625 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5626 StartSRange, MaxBECountValue, 5627 BitWidth, /* Signed = */ true)); 5628 5629 // Next, consider step unsigned. 5630 ConstantRange UR = getRangeForAffineARHelper( 5631 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5632 MaxBECountValue, BitWidth, /* Signed = */ false); 5633 5634 // Finally, intersect signed and unsigned ranges. 5635 return SR.intersectWith(UR); 5636 } 5637 5638 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5639 const SCEV *Step, 5640 const SCEV *MaxBECount, 5641 unsigned BitWidth) { 5642 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5643 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5644 5645 struct SelectPattern { 5646 Value *Condition = nullptr; 5647 APInt TrueValue; 5648 APInt FalseValue; 5649 5650 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5651 const SCEV *S) { 5652 Optional<unsigned> CastOp; 5653 APInt Offset(BitWidth, 0); 5654 5655 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5656 "Should be!"); 5657 5658 // Peel off a constant offset: 5659 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5660 // In the future we could consider being smarter here and handle 5661 // {Start+Step,+,Step} too. 5662 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5663 return; 5664 5665 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5666 S = SA->getOperand(1); 5667 } 5668 5669 // Peel off a cast operation 5670 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5671 CastOp = SCast->getSCEVType(); 5672 S = SCast->getOperand(); 5673 } 5674 5675 using namespace llvm::PatternMatch; 5676 5677 auto *SU = dyn_cast<SCEVUnknown>(S); 5678 const APInt *TrueVal, *FalseVal; 5679 if (!SU || 5680 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5681 m_APInt(FalseVal)))) { 5682 Condition = nullptr; 5683 return; 5684 } 5685 5686 TrueValue = *TrueVal; 5687 FalseValue = *FalseVal; 5688 5689 // Re-apply the cast we peeled off earlier 5690 if (CastOp.hasValue()) 5691 switch (*CastOp) { 5692 default: 5693 llvm_unreachable("Unknown SCEV cast type!"); 5694 5695 case scTruncate: 5696 TrueValue = TrueValue.trunc(BitWidth); 5697 FalseValue = FalseValue.trunc(BitWidth); 5698 break; 5699 case scZeroExtend: 5700 TrueValue = TrueValue.zext(BitWidth); 5701 FalseValue = FalseValue.zext(BitWidth); 5702 break; 5703 case scSignExtend: 5704 TrueValue = TrueValue.sext(BitWidth); 5705 FalseValue = FalseValue.sext(BitWidth); 5706 break; 5707 } 5708 5709 // Re-apply the constant offset we peeled off earlier 5710 TrueValue += Offset; 5711 FalseValue += Offset; 5712 } 5713 5714 bool isRecognized() { return Condition != nullptr; } 5715 }; 5716 5717 SelectPattern StartPattern(*this, BitWidth, Start); 5718 if (!StartPattern.isRecognized()) 5719 return ConstantRange(BitWidth, /* isFullSet = */ true); 5720 5721 SelectPattern StepPattern(*this, BitWidth, Step); 5722 if (!StepPattern.isRecognized()) 5723 return ConstantRange(BitWidth, /* isFullSet = */ true); 5724 5725 if (StartPattern.Condition != StepPattern.Condition) { 5726 // We don't handle this case today; but we could, by considering four 5727 // possibilities below instead of two. I'm not sure if there are cases where 5728 // that will help over what getRange already does, though. 5729 return ConstantRange(BitWidth, /* isFullSet = */ true); 5730 } 5731 5732 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5733 // construct arbitrary general SCEV expressions here. This function is called 5734 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5735 // say) can end up caching a suboptimal value. 5736 5737 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5738 // C2352 and C2512 (otherwise it isn't needed). 5739 5740 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5741 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5742 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5743 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5744 5745 ConstantRange TrueRange = 5746 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5747 ConstantRange FalseRange = 5748 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5749 5750 return TrueRange.unionWith(FalseRange); 5751 } 5752 5753 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5754 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5755 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5756 5757 // Return early if there are no flags to propagate to the SCEV. 5758 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5759 if (BinOp->hasNoUnsignedWrap()) 5760 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5761 if (BinOp->hasNoSignedWrap()) 5762 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5763 if (Flags == SCEV::FlagAnyWrap) 5764 return SCEV::FlagAnyWrap; 5765 5766 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5767 } 5768 5769 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5770 // Here we check that I is in the header of the innermost loop containing I, 5771 // since we only deal with instructions in the loop header. The actual loop we 5772 // need to check later will come from an add recurrence, but getting that 5773 // requires computing the SCEV of the operands, which can be expensive. This 5774 // check we can do cheaply to rule out some cases early. 5775 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5776 if (InnermostContainingLoop == nullptr || 5777 InnermostContainingLoop->getHeader() != I->getParent()) 5778 return false; 5779 5780 // Only proceed if we can prove that I does not yield poison. 5781 if (!programUndefinedIfFullPoison(I)) 5782 return false; 5783 5784 // At this point we know that if I is executed, then it does not wrap 5785 // according to at least one of NSW or NUW. If I is not executed, then we do 5786 // not know if the calculation that I represents would wrap. Multiple 5787 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5788 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5789 // derived from other instructions that map to the same SCEV. We cannot make 5790 // that guarantee for cases where I is not executed. So we need to find the 5791 // loop that I is considered in relation to and prove that I is executed for 5792 // every iteration of that loop. That implies that the value that I 5793 // calculates does not wrap anywhere in the loop, so then we can apply the 5794 // flags to the SCEV. 5795 // 5796 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5797 // from different loops, so that we know which loop to prove that I is 5798 // executed in. 5799 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5800 // I could be an extractvalue from a call to an overflow intrinsic. 5801 // TODO: We can do better here in some cases. 5802 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5803 return false; 5804 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5805 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5806 bool AllOtherOpsLoopInvariant = true; 5807 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5808 ++OtherOpIndex) { 5809 if (OtherOpIndex != OpIndex) { 5810 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5811 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5812 AllOtherOpsLoopInvariant = false; 5813 break; 5814 } 5815 } 5816 } 5817 if (AllOtherOpsLoopInvariant && 5818 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5819 return true; 5820 } 5821 } 5822 return false; 5823 } 5824 5825 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5826 // If we know that \c I can never be poison period, then that's enough. 5827 if (isSCEVExprNeverPoison(I)) 5828 return true; 5829 5830 // For an add recurrence specifically, we assume that infinite loops without 5831 // side effects are undefined behavior, and then reason as follows: 5832 // 5833 // If the add recurrence is poison in any iteration, it is poison on all 5834 // future iterations (since incrementing poison yields poison). If the result 5835 // of the add recurrence is fed into the loop latch condition and the loop 5836 // does not contain any throws or exiting blocks other than the latch, we now 5837 // have the ability to "choose" whether the backedge is taken or not (by 5838 // choosing a sufficiently evil value for the poison feeding into the branch) 5839 // for every iteration including and after the one in which \p I first became 5840 // poison. There are two possibilities (let's call the iteration in which \p 5841 // I first became poison as K): 5842 // 5843 // 1. In the set of iterations including and after K, the loop body executes 5844 // no side effects. In this case executing the backege an infinte number 5845 // of times will yield undefined behavior. 5846 // 5847 // 2. In the set of iterations including and after K, the loop body executes 5848 // at least one side effect. In this case, that specific instance of side 5849 // effect is control dependent on poison, which also yields undefined 5850 // behavior. 5851 5852 auto *ExitingBB = L->getExitingBlock(); 5853 auto *LatchBB = L->getLoopLatch(); 5854 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5855 return false; 5856 5857 SmallPtrSet<const Instruction *, 16> Pushed; 5858 SmallVector<const Instruction *, 8> PoisonStack; 5859 5860 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5861 // things that are known to be fully poison under that assumption go on the 5862 // PoisonStack. 5863 Pushed.insert(I); 5864 PoisonStack.push_back(I); 5865 5866 bool LatchControlDependentOnPoison = false; 5867 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5868 const Instruction *Poison = PoisonStack.pop_back_val(); 5869 5870 for (auto *PoisonUser : Poison->users()) { 5871 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5872 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5873 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5874 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5875 assert(BI->isConditional() && "Only possibility!"); 5876 if (BI->getParent() == LatchBB) { 5877 LatchControlDependentOnPoison = true; 5878 break; 5879 } 5880 } 5881 } 5882 } 5883 5884 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5885 } 5886 5887 ScalarEvolution::LoopProperties 5888 ScalarEvolution::getLoopProperties(const Loop *L) { 5889 using LoopProperties = ScalarEvolution::LoopProperties; 5890 5891 auto Itr = LoopPropertiesCache.find(L); 5892 if (Itr == LoopPropertiesCache.end()) { 5893 auto HasSideEffects = [](Instruction *I) { 5894 if (auto *SI = dyn_cast<StoreInst>(I)) 5895 return !SI->isSimple(); 5896 5897 return I->mayHaveSideEffects(); 5898 }; 5899 5900 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5901 /*HasNoSideEffects*/ true}; 5902 5903 for (auto *BB : L->getBlocks()) 5904 for (auto &I : *BB) { 5905 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5906 LP.HasNoAbnormalExits = false; 5907 if (HasSideEffects(&I)) 5908 LP.HasNoSideEffects = false; 5909 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5910 break; // We're already as pessimistic as we can get. 5911 } 5912 5913 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5914 assert(InsertPair.second && "We just checked!"); 5915 Itr = InsertPair.first; 5916 } 5917 5918 return Itr->second; 5919 } 5920 5921 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5922 if (!isSCEVable(V->getType())) 5923 return getUnknown(V); 5924 5925 if (Instruction *I = dyn_cast<Instruction>(V)) { 5926 // Don't attempt to analyze instructions in blocks that aren't 5927 // reachable. Such instructions don't matter, and they aren't required 5928 // to obey basic rules for definitions dominating uses which this 5929 // analysis depends on. 5930 if (!DT.isReachableFromEntry(I->getParent())) 5931 return getUnknown(V); 5932 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5933 return getConstant(CI); 5934 else if (isa<ConstantPointerNull>(V)) 5935 return getZero(V->getType()); 5936 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5937 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5938 else if (!isa<ConstantExpr>(V)) 5939 return getUnknown(V); 5940 5941 Operator *U = cast<Operator>(V); 5942 if (auto BO = MatchBinaryOp(U, DT)) { 5943 switch (BO->Opcode) { 5944 case Instruction::Add: { 5945 // The simple thing to do would be to just call getSCEV on both operands 5946 // and call getAddExpr with the result. However if we're looking at a 5947 // bunch of things all added together, this can be quite inefficient, 5948 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5949 // Instead, gather up all the operands and make a single getAddExpr call. 5950 // LLVM IR canonical form means we need only traverse the left operands. 5951 SmallVector<const SCEV *, 4> AddOps; 5952 do { 5953 if (BO->Op) { 5954 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5955 AddOps.push_back(OpSCEV); 5956 break; 5957 } 5958 5959 // If a NUW or NSW flag can be applied to the SCEV for this 5960 // addition, then compute the SCEV for this addition by itself 5961 // with a separate call to getAddExpr. We need to do that 5962 // instead of pushing the operands of the addition onto AddOps, 5963 // since the flags are only known to apply to this particular 5964 // addition - they may not apply to other additions that can be 5965 // formed with operands from AddOps. 5966 const SCEV *RHS = getSCEV(BO->RHS); 5967 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5968 if (Flags != SCEV::FlagAnyWrap) { 5969 const SCEV *LHS = getSCEV(BO->LHS); 5970 if (BO->Opcode == Instruction::Sub) 5971 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5972 else 5973 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5974 break; 5975 } 5976 } 5977 5978 if (BO->Opcode == Instruction::Sub) 5979 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5980 else 5981 AddOps.push_back(getSCEV(BO->RHS)); 5982 5983 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5984 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5985 NewBO->Opcode != Instruction::Sub)) { 5986 AddOps.push_back(getSCEV(BO->LHS)); 5987 break; 5988 } 5989 BO = NewBO; 5990 } while (true); 5991 5992 return getAddExpr(AddOps); 5993 } 5994 5995 case Instruction::Mul: { 5996 SmallVector<const SCEV *, 4> MulOps; 5997 do { 5998 if (BO->Op) { 5999 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6000 MulOps.push_back(OpSCEV); 6001 break; 6002 } 6003 6004 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6005 if (Flags != SCEV::FlagAnyWrap) { 6006 MulOps.push_back( 6007 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6008 break; 6009 } 6010 } 6011 6012 MulOps.push_back(getSCEV(BO->RHS)); 6013 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6014 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6015 MulOps.push_back(getSCEV(BO->LHS)); 6016 break; 6017 } 6018 BO = NewBO; 6019 } while (true); 6020 6021 return getMulExpr(MulOps); 6022 } 6023 case Instruction::UDiv: 6024 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6025 case Instruction::URem: 6026 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6027 case Instruction::Sub: { 6028 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6029 if (BO->Op) 6030 Flags = getNoWrapFlagsFromUB(BO->Op); 6031 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6032 } 6033 case Instruction::And: 6034 // For an expression like x&255 that merely masks off the high bits, 6035 // use zext(trunc(x)) as the SCEV expression. 6036 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6037 if (CI->isZero()) 6038 return getSCEV(BO->RHS); 6039 if (CI->isMinusOne()) 6040 return getSCEV(BO->LHS); 6041 const APInt &A = CI->getValue(); 6042 6043 // Instcombine's ShrinkDemandedConstant may strip bits out of 6044 // constants, obscuring what would otherwise be a low-bits mask. 6045 // Use computeKnownBits to compute what ShrinkDemandedConstant 6046 // knew about to reconstruct a low-bits mask value. 6047 unsigned LZ = A.countLeadingZeros(); 6048 unsigned TZ = A.countTrailingZeros(); 6049 unsigned BitWidth = A.getBitWidth(); 6050 KnownBits Known(BitWidth); 6051 computeKnownBits(BO->LHS, Known, getDataLayout(), 6052 0, &AC, nullptr, &DT); 6053 6054 APInt EffectiveMask = 6055 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6056 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6057 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6058 const SCEV *LHS = getSCEV(BO->LHS); 6059 const SCEV *ShiftedLHS = nullptr; 6060 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6061 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6062 // For an expression like (x * 8) & 8, simplify the multiply. 6063 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6064 unsigned GCD = std::min(MulZeros, TZ); 6065 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6066 SmallVector<const SCEV*, 4> MulOps; 6067 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6068 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6069 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6070 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6071 } 6072 } 6073 if (!ShiftedLHS) 6074 ShiftedLHS = getUDivExpr(LHS, MulCount); 6075 return getMulExpr( 6076 getZeroExtendExpr( 6077 getTruncateExpr(ShiftedLHS, 6078 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6079 BO->LHS->getType()), 6080 MulCount); 6081 } 6082 } 6083 break; 6084 6085 case Instruction::Or: 6086 // If the RHS of the Or is a constant, we may have something like: 6087 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6088 // optimizations will transparently handle this case. 6089 // 6090 // In order for this transformation to be safe, the LHS must be of the 6091 // form X*(2^n) and the Or constant must be less than 2^n. 6092 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6093 const SCEV *LHS = getSCEV(BO->LHS); 6094 const APInt &CIVal = CI->getValue(); 6095 if (GetMinTrailingZeros(LHS) >= 6096 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6097 // Build a plain add SCEV. 6098 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6099 // If the LHS of the add was an addrec and it has no-wrap flags, 6100 // transfer the no-wrap flags, since an or won't introduce a wrap. 6101 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6102 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6103 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6104 OldAR->getNoWrapFlags()); 6105 } 6106 return S; 6107 } 6108 } 6109 break; 6110 6111 case Instruction::Xor: 6112 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6113 // If the RHS of xor is -1, then this is a not operation. 6114 if (CI->isMinusOne()) 6115 return getNotSCEV(getSCEV(BO->LHS)); 6116 6117 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6118 // This is a variant of the check for xor with -1, and it handles 6119 // the case where instcombine has trimmed non-demanded bits out 6120 // of an xor with -1. 6121 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6122 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6123 if (LBO->getOpcode() == Instruction::And && 6124 LCI->getValue() == CI->getValue()) 6125 if (const SCEVZeroExtendExpr *Z = 6126 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6127 Type *UTy = BO->LHS->getType(); 6128 const SCEV *Z0 = Z->getOperand(); 6129 Type *Z0Ty = Z0->getType(); 6130 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6131 6132 // If C is a low-bits mask, the zero extend is serving to 6133 // mask off the high bits. Complement the operand and 6134 // re-apply the zext. 6135 if (CI->getValue().isMask(Z0TySize)) 6136 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6137 6138 // If C is a single bit, it may be in the sign-bit position 6139 // before the zero-extend. In this case, represent the xor 6140 // using an add, which is equivalent, and re-apply the zext. 6141 APInt Trunc = CI->getValue().trunc(Z0TySize); 6142 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6143 Trunc.isSignMask()) 6144 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6145 UTy); 6146 } 6147 } 6148 break; 6149 6150 case Instruction::Shl: 6151 // Turn shift left of a constant amount into a multiply. 6152 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6153 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6154 6155 // If the shift count is not less than the bitwidth, the result of 6156 // the shift is undefined. Don't try to analyze it, because the 6157 // resolution chosen here may differ from the resolution chosen in 6158 // other parts of the compiler. 6159 if (SA->getValue().uge(BitWidth)) 6160 break; 6161 6162 // It is currently not resolved how to interpret NSW for left 6163 // shift by BitWidth - 1, so we avoid applying flags in that 6164 // case. Remove this check (or this comment) once the situation 6165 // is resolved. See 6166 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6167 // and http://reviews.llvm.org/D8890 . 6168 auto Flags = SCEV::FlagAnyWrap; 6169 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6170 Flags = getNoWrapFlagsFromUB(BO->Op); 6171 6172 Constant *X = ConstantInt::get(getContext(), 6173 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6174 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6175 } 6176 break; 6177 6178 case Instruction::AShr: { 6179 // AShr X, C, where C is a constant. 6180 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6181 if (!CI) 6182 break; 6183 6184 Type *OuterTy = BO->LHS->getType(); 6185 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6186 // If the shift count is not less than the bitwidth, the result of 6187 // the shift is undefined. Don't try to analyze it, because the 6188 // resolution chosen here may differ from the resolution chosen in 6189 // other parts of the compiler. 6190 if (CI->getValue().uge(BitWidth)) 6191 break; 6192 6193 if (CI->isZero()) 6194 return getSCEV(BO->LHS); // shift by zero --> noop 6195 6196 uint64_t AShrAmt = CI->getZExtValue(); 6197 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6198 6199 Operator *L = dyn_cast<Operator>(BO->LHS); 6200 if (L && L->getOpcode() == Instruction::Shl) { 6201 // X = Shl A, n 6202 // Y = AShr X, m 6203 // Both n and m are constant. 6204 6205 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6206 if (L->getOperand(1) == BO->RHS) 6207 // For a two-shift sext-inreg, i.e. n = m, 6208 // use sext(trunc(x)) as the SCEV expression. 6209 return getSignExtendExpr( 6210 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6211 6212 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6213 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6214 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6215 if (ShlAmt > AShrAmt) { 6216 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6217 // expression. We already checked that ShlAmt < BitWidth, so 6218 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6219 // ShlAmt - AShrAmt < Amt. 6220 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6221 ShlAmt - AShrAmt); 6222 return getSignExtendExpr( 6223 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6224 getConstant(Mul)), OuterTy); 6225 } 6226 } 6227 } 6228 break; 6229 } 6230 } 6231 } 6232 6233 switch (U->getOpcode()) { 6234 case Instruction::Trunc: 6235 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6236 6237 case Instruction::ZExt: 6238 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6239 6240 case Instruction::SExt: 6241 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6242 // The NSW flag of a subtract does not always survive the conversion to 6243 // A + (-1)*B. By pushing sign extension onto its operands we are much 6244 // more likely to preserve NSW and allow later AddRec optimisations. 6245 // 6246 // NOTE: This is effectively duplicating this logic from getSignExtend: 6247 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6248 // but by that point the NSW information has potentially been lost. 6249 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6250 Type *Ty = U->getType(); 6251 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6252 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6253 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6254 } 6255 } 6256 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6257 6258 case Instruction::BitCast: 6259 // BitCasts are no-op casts so we just eliminate the cast. 6260 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6261 return getSCEV(U->getOperand(0)); 6262 break; 6263 6264 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6265 // lead to pointer expressions which cannot safely be expanded to GEPs, 6266 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6267 // simplifying integer expressions. 6268 6269 case Instruction::GetElementPtr: 6270 return createNodeForGEP(cast<GEPOperator>(U)); 6271 6272 case Instruction::PHI: 6273 return createNodeForPHI(cast<PHINode>(U)); 6274 6275 case Instruction::Select: 6276 // U can also be a select constant expr, which let fall through. Since 6277 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6278 // constant expressions cannot have instructions as operands, we'd have 6279 // returned getUnknown for a select constant expressions anyway. 6280 if (isa<Instruction>(U)) 6281 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6282 U->getOperand(1), U->getOperand(2)); 6283 break; 6284 6285 case Instruction::Call: 6286 case Instruction::Invoke: 6287 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6288 return getSCEV(RV); 6289 break; 6290 } 6291 6292 return getUnknown(V); 6293 } 6294 6295 //===----------------------------------------------------------------------===// 6296 // Iteration Count Computation Code 6297 // 6298 6299 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6300 if (!ExitCount) 6301 return 0; 6302 6303 ConstantInt *ExitConst = ExitCount->getValue(); 6304 6305 // Guard against huge trip counts. 6306 if (ExitConst->getValue().getActiveBits() > 32) 6307 return 0; 6308 6309 // In case of integer overflow, this returns 0, which is correct. 6310 return ((unsigned)ExitConst->getZExtValue()) + 1; 6311 } 6312 6313 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6314 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6315 return getSmallConstantTripCount(L, ExitingBB); 6316 6317 // No trip count information for multiple exits. 6318 return 0; 6319 } 6320 6321 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6322 BasicBlock *ExitingBlock) { 6323 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6324 assert(L->isLoopExiting(ExitingBlock) && 6325 "Exiting block must actually branch out of the loop!"); 6326 const SCEVConstant *ExitCount = 6327 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6328 return getConstantTripCount(ExitCount); 6329 } 6330 6331 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6332 const auto *MaxExitCount = 6333 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6334 return getConstantTripCount(MaxExitCount); 6335 } 6336 6337 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6338 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6339 return getSmallConstantTripMultiple(L, ExitingBB); 6340 6341 // No trip multiple information for multiple exits. 6342 return 0; 6343 } 6344 6345 /// Returns the largest constant divisor of the trip count of this loop as a 6346 /// normal unsigned value, if possible. This means that the actual trip count is 6347 /// always a multiple of the returned value (don't forget the trip count could 6348 /// very well be zero as well!). 6349 /// 6350 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6351 /// multiple of a constant (which is also the case if the trip count is simply 6352 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6353 /// if the trip count is very large (>= 2^32). 6354 /// 6355 /// As explained in the comments for getSmallConstantTripCount, this assumes 6356 /// that control exits the loop via ExitingBlock. 6357 unsigned 6358 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6359 BasicBlock *ExitingBlock) { 6360 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6361 assert(L->isLoopExiting(ExitingBlock) && 6362 "Exiting block must actually branch out of the loop!"); 6363 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6364 if (ExitCount == getCouldNotCompute()) 6365 return 1; 6366 6367 // Get the trip count from the BE count by adding 1. 6368 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6369 6370 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6371 if (!TC) 6372 // Attempt to factor more general cases. Returns the greatest power of 6373 // two divisor. If overflow happens, the trip count expression is still 6374 // divisible by the greatest power of 2 divisor returned. 6375 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6376 6377 ConstantInt *Result = TC->getValue(); 6378 6379 // Guard against huge trip counts (this requires checking 6380 // for zero to handle the case where the trip count == -1 and the 6381 // addition wraps). 6382 if (!Result || Result->getValue().getActiveBits() > 32 || 6383 Result->getValue().getActiveBits() == 0) 6384 return 1; 6385 6386 return (unsigned)Result->getZExtValue(); 6387 } 6388 6389 /// Get the expression for the number of loop iterations for which this loop is 6390 /// guaranteed not to exit via ExitingBlock. Otherwise return 6391 /// SCEVCouldNotCompute. 6392 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6393 BasicBlock *ExitingBlock) { 6394 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6395 } 6396 6397 const SCEV * 6398 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6399 SCEVUnionPredicate &Preds) { 6400 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6401 } 6402 6403 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6404 return getBackedgeTakenInfo(L).getExact(this); 6405 } 6406 6407 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6408 /// known never to be less than the actual backedge taken count. 6409 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6410 return getBackedgeTakenInfo(L).getMax(this); 6411 } 6412 6413 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6414 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6415 } 6416 6417 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6418 static void 6419 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6420 BasicBlock *Header = L->getHeader(); 6421 6422 // Push all Loop-header PHIs onto the Worklist stack. 6423 for (PHINode &PN : Header->phis()) 6424 Worklist.push_back(&PN); 6425 } 6426 6427 const ScalarEvolution::BackedgeTakenInfo & 6428 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6429 auto &BTI = getBackedgeTakenInfo(L); 6430 if (BTI.hasFullInfo()) 6431 return BTI; 6432 6433 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6434 6435 if (!Pair.second) 6436 return Pair.first->second; 6437 6438 BackedgeTakenInfo Result = 6439 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6440 6441 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6442 } 6443 6444 const ScalarEvolution::BackedgeTakenInfo & 6445 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6446 // Initially insert an invalid entry for this loop. If the insertion 6447 // succeeds, proceed to actually compute a backedge-taken count and 6448 // update the value. The temporary CouldNotCompute value tells SCEV 6449 // code elsewhere that it shouldn't attempt to request a new 6450 // backedge-taken count, which could result in infinite recursion. 6451 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6452 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6453 if (!Pair.second) 6454 return Pair.first->second; 6455 6456 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6457 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6458 // must be cleared in this scope. 6459 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6460 6461 if (Result.getExact(this) != getCouldNotCompute()) { 6462 assert(isLoopInvariant(Result.getExact(this), L) && 6463 isLoopInvariant(Result.getMax(this), L) && 6464 "Computed backedge-taken count isn't loop invariant for loop!"); 6465 ++NumTripCountsComputed; 6466 } 6467 else if (Result.getMax(this) == getCouldNotCompute() && 6468 isa<PHINode>(L->getHeader()->begin())) { 6469 // Only count loops that have phi nodes as not being computable. 6470 ++NumTripCountsNotComputed; 6471 } 6472 6473 // Now that we know more about the trip count for this loop, forget any 6474 // existing SCEV values for PHI nodes in this loop since they are only 6475 // conservative estimates made without the benefit of trip count 6476 // information. This is similar to the code in forgetLoop, except that 6477 // it handles SCEVUnknown PHI nodes specially. 6478 if (Result.hasAnyInfo()) { 6479 SmallVector<Instruction *, 16> Worklist; 6480 PushLoopPHIs(L, Worklist); 6481 6482 SmallPtrSet<Instruction *, 8> Discovered; 6483 while (!Worklist.empty()) { 6484 Instruction *I = Worklist.pop_back_val(); 6485 6486 ValueExprMapType::iterator It = 6487 ValueExprMap.find_as(static_cast<Value *>(I)); 6488 if (It != ValueExprMap.end()) { 6489 const SCEV *Old = It->second; 6490 6491 // SCEVUnknown for a PHI either means that it has an unrecognized 6492 // structure, or it's a PHI that's in the progress of being computed 6493 // by createNodeForPHI. In the former case, additional loop trip 6494 // count information isn't going to change anything. In the later 6495 // case, createNodeForPHI will perform the necessary updates on its 6496 // own when it gets to that point. 6497 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6498 eraseValueFromMap(It->first); 6499 forgetMemoizedResults(Old); 6500 } 6501 if (PHINode *PN = dyn_cast<PHINode>(I)) 6502 ConstantEvolutionLoopExitValue.erase(PN); 6503 } 6504 6505 // Since we don't need to invalidate anything for correctness and we're 6506 // only invalidating to make SCEV's results more precise, we get to stop 6507 // early to avoid invalidating too much. This is especially important in 6508 // cases like: 6509 // 6510 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6511 // loop0: 6512 // %pn0 = phi 6513 // ... 6514 // loop1: 6515 // %pn1 = phi 6516 // ... 6517 // 6518 // where both loop0 and loop1's backedge taken count uses the SCEV 6519 // expression for %v. If we don't have the early stop below then in cases 6520 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6521 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6522 // count for loop1, effectively nullifying SCEV's trip count cache. 6523 for (auto *U : I->users()) 6524 if (auto *I = dyn_cast<Instruction>(U)) { 6525 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6526 if (LoopForUser && L->contains(LoopForUser) && 6527 Discovered.insert(I).second) 6528 Worklist.push_back(I); 6529 } 6530 } 6531 } 6532 6533 // Re-lookup the insert position, since the call to 6534 // computeBackedgeTakenCount above could result in a 6535 // recusive call to getBackedgeTakenInfo (on a different 6536 // loop), which would invalidate the iterator computed 6537 // earlier. 6538 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6539 } 6540 6541 void ScalarEvolution::forgetLoop(const Loop *L) { 6542 // Drop any stored trip count value. 6543 auto RemoveLoopFromBackedgeMap = 6544 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6545 auto BTCPos = Map.find(L); 6546 if (BTCPos != Map.end()) { 6547 BTCPos->second.clear(); 6548 Map.erase(BTCPos); 6549 } 6550 }; 6551 6552 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6553 SmallVector<Instruction *, 32> Worklist; 6554 SmallPtrSet<Instruction *, 16> Visited; 6555 6556 // Iterate over all the loops and sub-loops to drop SCEV information. 6557 while (!LoopWorklist.empty()) { 6558 auto *CurrL = LoopWorklist.pop_back_val(); 6559 6560 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6561 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6562 6563 // Drop information about predicated SCEV rewrites for this loop. 6564 for (auto I = PredicatedSCEVRewrites.begin(); 6565 I != PredicatedSCEVRewrites.end();) { 6566 std::pair<const SCEV *, const Loop *> Entry = I->first; 6567 if (Entry.second == CurrL) 6568 PredicatedSCEVRewrites.erase(I++); 6569 else 6570 ++I; 6571 } 6572 6573 auto LoopUsersItr = LoopUsers.find(CurrL); 6574 if (LoopUsersItr != LoopUsers.end()) { 6575 for (auto *S : LoopUsersItr->second) 6576 forgetMemoizedResults(S); 6577 LoopUsers.erase(LoopUsersItr); 6578 } 6579 6580 // Drop information about expressions based on loop-header PHIs. 6581 PushLoopPHIs(CurrL, Worklist); 6582 6583 while (!Worklist.empty()) { 6584 Instruction *I = Worklist.pop_back_val(); 6585 if (!Visited.insert(I).second) 6586 continue; 6587 6588 ValueExprMapType::iterator It = 6589 ValueExprMap.find_as(static_cast<Value *>(I)); 6590 if (It != ValueExprMap.end()) { 6591 eraseValueFromMap(It->first); 6592 forgetMemoizedResults(It->second); 6593 if (PHINode *PN = dyn_cast<PHINode>(I)) 6594 ConstantEvolutionLoopExitValue.erase(PN); 6595 } 6596 6597 PushDefUseChildren(I, Worklist); 6598 } 6599 6600 LoopPropertiesCache.erase(CurrL); 6601 // Forget all contained loops too, to avoid dangling entries in the 6602 // ValuesAtScopes map. 6603 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6604 } 6605 } 6606 6607 void ScalarEvolution::forgetValue(Value *V) { 6608 Instruction *I = dyn_cast<Instruction>(V); 6609 if (!I) return; 6610 6611 // Drop information about expressions based on loop-header PHIs. 6612 SmallVector<Instruction *, 16> Worklist; 6613 Worklist.push_back(I); 6614 6615 SmallPtrSet<Instruction *, 8> Visited; 6616 while (!Worklist.empty()) { 6617 I = Worklist.pop_back_val(); 6618 if (!Visited.insert(I).second) 6619 continue; 6620 6621 ValueExprMapType::iterator It = 6622 ValueExprMap.find_as(static_cast<Value *>(I)); 6623 if (It != ValueExprMap.end()) { 6624 eraseValueFromMap(It->first); 6625 forgetMemoizedResults(It->second); 6626 if (PHINode *PN = dyn_cast<PHINode>(I)) 6627 ConstantEvolutionLoopExitValue.erase(PN); 6628 } 6629 6630 PushDefUseChildren(I, Worklist); 6631 } 6632 } 6633 6634 /// Get the exact loop backedge taken count considering all loop exits. A 6635 /// computable result can only be returned for loops with a single exit. 6636 /// Returning the minimum taken count among all exits is incorrect because one 6637 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6638 /// the limit of each loop test is never skipped. This is a valid assumption as 6639 /// long as the loop exits via that test. For precise results, it is the 6640 /// caller's responsibility to specify the relevant loop exit using 6641 /// getExact(ExitingBlock, SE). 6642 const SCEV * 6643 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6644 SCEVUnionPredicate *Preds) const { 6645 // If any exits were not computable, the loop is not computable. 6646 if (!isComplete() || ExitNotTaken.empty()) 6647 return SE->getCouldNotCompute(); 6648 6649 const SCEV *BECount = nullptr; 6650 for (auto &ENT : ExitNotTaken) { 6651 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6652 6653 if (!BECount) 6654 BECount = ENT.ExactNotTaken; 6655 else if (BECount != ENT.ExactNotTaken) 6656 return SE->getCouldNotCompute(); 6657 if (Preds && !ENT.hasAlwaysTruePredicate()) 6658 Preds->add(ENT.Predicate.get()); 6659 6660 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6661 "Predicate should be always true!"); 6662 } 6663 6664 assert(BECount && "Invalid not taken count for loop exit"); 6665 return BECount; 6666 } 6667 6668 /// Get the exact not taken count for this loop exit. 6669 const SCEV * 6670 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6671 ScalarEvolution *SE) const { 6672 for (auto &ENT : ExitNotTaken) 6673 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6674 return ENT.ExactNotTaken; 6675 6676 return SE->getCouldNotCompute(); 6677 } 6678 6679 /// getMax - Get the max backedge taken count for the loop. 6680 const SCEV * 6681 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6682 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6683 return !ENT.hasAlwaysTruePredicate(); 6684 }; 6685 6686 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6687 return SE->getCouldNotCompute(); 6688 6689 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6690 "No point in having a non-constant max backedge taken count!"); 6691 return getMax(); 6692 } 6693 6694 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6695 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6696 return !ENT.hasAlwaysTruePredicate(); 6697 }; 6698 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6699 } 6700 6701 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6702 ScalarEvolution *SE) const { 6703 if (getMax() && getMax() != SE->getCouldNotCompute() && 6704 SE->hasOperand(getMax(), S)) 6705 return true; 6706 6707 for (auto &ENT : ExitNotTaken) 6708 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6709 SE->hasOperand(ENT.ExactNotTaken, S)) 6710 return true; 6711 6712 return false; 6713 } 6714 6715 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6716 : ExactNotTaken(E), MaxNotTaken(E) { 6717 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6718 isa<SCEVConstant>(MaxNotTaken)) && 6719 "No point in having a non-constant max backedge taken count!"); 6720 } 6721 6722 ScalarEvolution::ExitLimit::ExitLimit( 6723 const SCEV *E, const SCEV *M, bool MaxOrZero, 6724 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6725 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6726 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6727 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6728 "Exact is not allowed to be less precise than Max"); 6729 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6730 isa<SCEVConstant>(MaxNotTaken)) && 6731 "No point in having a non-constant max backedge taken count!"); 6732 for (auto *PredSet : PredSetList) 6733 for (auto *P : *PredSet) 6734 addPredicate(P); 6735 } 6736 6737 ScalarEvolution::ExitLimit::ExitLimit( 6738 const SCEV *E, const SCEV *M, bool MaxOrZero, 6739 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6740 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6741 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6742 isa<SCEVConstant>(MaxNotTaken)) && 6743 "No point in having a non-constant max backedge taken count!"); 6744 } 6745 6746 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6747 bool MaxOrZero) 6748 : ExitLimit(E, M, MaxOrZero, None) { 6749 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6750 isa<SCEVConstant>(MaxNotTaken)) && 6751 "No point in having a non-constant max backedge taken count!"); 6752 } 6753 6754 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6755 /// computable exit into a persistent ExitNotTakenInfo array. 6756 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6757 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6758 &&ExitCounts, 6759 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6760 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6761 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6762 6763 ExitNotTaken.reserve(ExitCounts.size()); 6764 std::transform( 6765 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6766 [&](const EdgeExitInfo &EEI) { 6767 BasicBlock *ExitBB = EEI.first; 6768 const ExitLimit &EL = EEI.second; 6769 if (EL.Predicates.empty()) 6770 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6771 6772 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6773 for (auto *Pred : EL.Predicates) 6774 Predicate->add(Pred); 6775 6776 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6777 }); 6778 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6779 "No point in having a non-constant max backedge taken count!"); 6780 } 6781 6782 /// Invalidate this result and free the ExitNotTakenInfo array. 6783 void ScalarEvolution::BackedgeTakenInfo::clear() { 6784 ExitNotTaken.clear(); 6785 } 6786 6787 /// Compute the number of times the backedge of the specified loop will execute. 6788 ScalarEvolution::BackedgeTakenInfo 6789 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6790 bool AllowPredicates) { 6791 SmallVector<BasicBlock *, 8> ExitingBlocks; 6792 L->getExitingBlocks(ExitingBlocks); 6793 6794 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6795 6796 SmallVector<EdgeExitInfo, 4> ExitCounts; 6797 bool CouldComputeBECount = true; 6798 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6799 const SCEV *MustExitMaxBECount = nullptr; 6800 const SCEV *MayExitMaxBECount = nullptr; 6801 bool MustExitMaxOrZero = false; 6802 6803 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6804 // and compute maxBECount. 6805 // Do a union of all the predicates here. 6806 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6807 BasicBlock *ExitBB = ExitingBlocks[i]; 6808 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6809 6810 assert((AllowPredicates || EL.Predicates.empty()) && 6811 "Predicated exit limit when predicates are not allowed!"); 6812 6813 // 1. For each exit that can be computed, add an entry to ExitCounts. 6814 // CouldComputeBECount is true only if all exits can be computed. 6815 if (EL.ExactNotTaken == getCouldNotCompute()) 6816 // We couldn't compute an exact value for this exit, so 6817 // we won't be able to compute an exact value for the loop. 6818 CouldComputeBECount = false; 6819 else 6820 ExitCounts.emplace_back(ExitBB, EL); 6821 6822 // 2. Derive the loop's MaxBECount from each exit's max number of 6823 // non-exiting iterations. Partition the loop exits into two kinds: 6824 // LoopMustExits and LoopMayExits. 6825 // 6826 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6827 // is a LoopMayExit. If any computable LoopMustExit is found, then 6828 // MaxBECount is the minimum EL.MaxNotTaken of computable 6829 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6830 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6831 // computable EL.MaxNotTaken. 6832 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6833 DT.dominates(ExitBB, Latch)) { 6834 if (!MustExitMaxBECount) { 6835 MustExitMaxBECount = EL.MaxNotTaken; 6836 MustExitMaxOrZero = EL.MaxOrZero; 6837 } else { 6838 MustExitMaxBECount = 6839 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6840 } 6841 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6842 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6843 MayExitMaxBECount = EL.MaxNotTaken; 6844 else { 6845 MayExitMaxBECount = 6846 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6847 } 6848 } 6849 } 6850 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6851 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6852 // The loop backedge will be taken the maximum or zero times if there's 6853 // a single exit that must be taken the maximum or zero times. 6854 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6855 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6856 MaxBECount, MaxOrZero); 6857 } 6858 6859 ScalarEvolution::ExitLimit 6860 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6861 bool AllowPredicates) { 6862 // Okay, we've chosen an exiting block. See what condition causes us to exit 6863 // at this block and remember the exit block and whether all other targets 6864 // lead to the loop header. 6865 bool MustExecuteLoopHeader = true; 6866 BasicBlock *Exit = nullptr; 6867 for (auto *SBB : successors(ExitingBlock)) 6868 if (!L->contains(SBB)) { 6869 if (Exit) // Multiple exit successors. 6870 return getCouldNotCompute(); 6871 Exit = SBB; 6872 } else if (SBB != L->getHeader()) { 6873 MustExecuteLoopHeader = false; 6874 } 6875 6876 // At this point, we know we have a conditional branch that determines whether 6877 // the loop is exited. However, we don't know if the branch is executed each 6878 // time through the loop. If not, then the execution count of the branch will 6879 // not be equal to the trip count of the loop. 6880 // 6881 // Currently we check for this by checking to see if the Exit branch goes to 6882 // the loop header. If so, we know it will always execute the same number of 6883 // times as the loop. We also handle the case where the exit block *is* the 6884 // loop header. This is common for un-rotated loops. 6885 // 6886 // If both of those tests fail, walk up the unique predecessor chain to the 6887 // header, stopping if there is an edge that doesn't exit the loop. If the 6888 // header is reached, the execution count of the branch will be equal to the 6889 // trip count of the loop. 6890 // 6891 // More extensive analysis could be done to handle more cases here. 6892 // 6893 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6894 // The simple checks failed, try climbing the unique predecessor chain 6895 // up to the header. 6896 bool Ok = false; 6897 for (BasicBlock *BB = ExitingBlock; BB; ) { 6898 BasicBlock *Pred = BB->getUniquePredecessor(); 6899 if (!Pred) 6900 return getCouldNotCompute(); 6901 TerminatorInst *PredTerm = Pred->getTerminator(); 6902 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6903 if (PredSucc == BB) 6904 continue; 6905 // If the predecessor has a successor that isn't BB and isn't 6906 // outside the loop, assume the worst. 6907 if (L->contains(PredSucc)) 6908 return getCouldNotCompute(); 6909 } 6910 if (Pred == L->getHeader()) { 6911 Ok = true; 6912 break; 6913 } 6914 BB = Pred; 6915 } 6916 if (!Ok) 6917 return getCouldNotCompute(); 6918 } 6919 6920 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6921 TerminatorInst *Term = ExitingBlock->getTerminator(); 6922 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6923 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6924 // Proceed to the next level to examine the exit condition expression. 6925 return computeExitLimitFromCond( 6926 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6927 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6928 } 6929 6930 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6931 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6932 /*ControlsExit=*/IsOnlyExit); 6933 6934 return getCouldNotCompute(); 6935 } 6936 6937 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6938 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6939 bool ControlsExit, bool AllowPredicates) { 6940 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6941 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6942 ControlsExit, AllowPredicates); 6943 } 6944 6945 Optional<ScalarEvolution::ExitLimit> 6946 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6947 BasicBlock *TBB, BasicBlock *FBB, 6948 bool ControlsExit, bool AllowPredicates) { 6949 (void)this->L; 6950 (void)this->TBB; 6951 (void)this->FBB; 6952 (void)this->AllowPredicates; 6953 6954 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6955 this->AllowPredicates == AllowPredicates && 6956 "Variance in assumed invariant key components!"); 6957 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6958 if (Itr == TripCountMap.end()) 6959 return None; 6960 return Itr->second; 6961 } 6962 6963 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6964 BasicBlock *TBB, BasicBlock *FBB, 6965 bool ControlsExit, 6966 bool AllowPredicates, 6967 const ExitLimit &EL) { 6968 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6969 this->AllowPredicates == AllowPredicates && 6970 "Variance in assumed invariant key components!"); 6971 6972 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6973 assert(InsertResult.second && "Expected successful insertion!"); 6974 (void)InsertResult; 6975 } 6976 6977 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6978 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6979 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6980 6981 if (auto MaybeEL = 6982 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6983 return *MaybeEL; 6984 6985 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6986 ControlsExit, AllowPredicates); 6987 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6988 return EL; 6989 } 6990 6991 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6992 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6993 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6994 // Check if the controlling expression for this loop is an And or Or. 6995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6996 if (BO->getOpcode() == Instruction::And) { 6997 // Recurse on the operands of the and. 6998 bool EitherMayExit = L->contains(TBB); 6999 ExitLimit EL0 = computeExitLimitFromCondCached( 7000 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 7001 AllowPredicates); 7002 ExitLimit EL1 = computeExitLimitFromCondCached( 7003 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 7004 AllowPredicates); 7005 const SCEV *BECount = getCouldNotCompute(); 7006 const SCEV *MaxBECount = getCouldNotCompute(); 7007 if (EitherMayExit) { 7008 // Both conditions must be true for the loop to continue executing. 7009 // Choose the less conservative count. 7010 if (EL0.ExactNotTaken == getCouldNotCompute() || 7011 EL1.ExactNotTaken == getCouldNotCompute()) 7012 BECount = getCouldNotCompute(); 7013 else 7014 BECount = 7015 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7016 if (EL0.MaxNotTaken == getCouldNotCompute()) 7017 MaxBECount = EL1.MaxNotTaken; 7018 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7019 MaxBECount = EL0.MaxNotTaken; 7020 else 7021 MaxBECount = 7022 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7023 } else { 7024 // Both conditions must be true at the same time for the loop to exit. 7025 // For now, be conservative. 7026 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 7027 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7028 MaxBECount = EL0.MaxNotTaken; 7029 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7030 BECount = EL0.ExactNotTaken; 7031 } 7032 7033 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7034 // to be more aggressive when computing BECount than when computing 7035 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7036 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7037 // to not. 7038 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7039 !isa<SCEVCouldNotCompute>(BECount)) 7040 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7041 7042 return ExitLimit(BECount, MaxBECount, false, 7043 {&EL0.Predicates, &EL1.Predicates}); 7044 } 7045 if (BO->getOpcode() == Instruction::Or) { 7046 // Recurse on the operands of the or. 7047 bool EitherMayExit = L->contains(FBB); 7048 ExitLimit EL0 = computeExitLimitFromCondCached( 7049 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 7050 AllowPredicates); 7051 ExitLimit EL1 = computeExitLimitFromCondCached( 7052 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 7053 AllowPredicates); 7054 const SCEV *BECount = getCouldNotCompute(); 7055 const SCEV *MaxBECount = getCouldNotCompute(); 7056 if (EitherMayExit) { 7057 // Both conditions must be false for the loop to continue executing. 7058 // Choose the less conservative count. 7059 if (EL0.ExactNotTaken == getCouldNotCompute() || 7060 EL1.ExactNotTaken == getCouldNotCompute()) 7061 BECount = getCouldNotCompute(); 7062 else 7063 BECount = 7064 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7065 if (EL0.MaxNotTaken == getCouldNotCompute()) 7066 MaxBECount = EL1.MaxNotTaken; 7067 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7068 MaxBECount = EL0.MaxNotTaken; 7069 else 7070 MaxBECount = 7071 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7072 } else { 7073 // Both conditions must be false at the same time for the loop to exit. 7074 // For now, be conservative. 7075 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 7076 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7077 MaxBECount = EL0.MaxNotTaken; 7078 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7079 BECount = EL0.ExactNotTaken; 7080 } 7081 7082 return ExitLimit(BECount, MaxBECount, false, 7083 {&EL0.Predicates, &EL1.Predicates}); 7084 } 7085 } 7086 7087 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7088 // Proceed to the next level to examine the icmp. 7089 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7090 ExitLimit EL = 7091 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 7092 if (EL.hasFullInfo() || !AllowPredicates) 7093 return EL; 7094 7095 // Try again, but use SCEV predicates this time. 7096 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 7097 /*AllowPredicates=*/true); 7098 } 7099 7100 // Check for a constant condition. These are normally stripped out by 7101 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7102 // preserve the CFG and is temporarily leaving constant conditions 7103 // in place. 7104 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7105 if (L->contains(FBB) == !CI->getZExtValue()) 7106 // The backedge is always taken. 7107 return getCouldNotCompute(); 7108 else 7109 // The backedge is never taken. 7110 return getZero(CI->getType()); 7111 } 7112 7113 // If it's not an integer or pointer comparison then compute it the hard way. 7114 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 7115 } 7116 7117 ScalarEvolution::ExitLimit 7118 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7119 ICmpInst *ExitCond, 7120 BasicBlock *TBB, 7121 BasicBlock *FBB, 7122 bool ControlsExit, 7123 bool AllowPredicates) { 7124 // If the condition was exit on true, convert the condition to exit on false 7125 ICmpInst::Predicate Pred; 7126 if (!L->contains(FBB)) 7127 Pred = ExitCond->getPredicate(); 7128 else 7129 Pred = ExitCond->getInversePredicate(); 7130 const ICmpInst::Predicate OriginalPred = Pred; 7131 7132 // Handle common loops like: for (X = "string"; *X; ++X) 7133 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7134 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7135 ExitLimit ItCnt = 7136 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7137 if (ItCnt.hasAnyInfo()) 7138 return ItCnt; 7139 } 7140 7141 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7142 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7143 7144 // Try to evaluate any dependencies out of the loop. 7145 LHS = getSCEVAtScope(LHS, L); 7146 RHS = getSCEVAtScope(RHS, L); 7147 7148 // At this point, we would like to compute how many iterations of the 7149 // loop the predicate will return true for these inputs. 7150 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7151 // If there is a loop-invariant, force it into the RHS. 7152 std::swap(LHS, RHS); 7153 Pred = ICmpInst::getSwappedPredicate(Pred); 7154 } 7155 7156 // Simplify the operands before analyzing them. 7157 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7158 7159 // If we have a comparison of a chrec against a constant, try to use value 7160 // ranges to answer this query. 7161 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7162 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7163 if (AddRec->getLoop() == L) { 7164 // Form the constant range. 7165 ConstantRange CompRange = 7166 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7167 7168 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7169 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7170 } 7171 7172 switch (Pred) { 7173 case ICmpInst::ICMP_NE: { // while (X != Y) 7174 // Convert to: while (X-Y != 0) 7175 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7176 AllowPredicates); 7177 if (EL.hasAnyInfo()) return EL; 7178 break; 7179 } 7180 case ICmpInst::ICMP_EQ: { // while (X == Y) 7181 // Convert to: while (X-Y == 0) 7182 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7183 if (EL.hasAnyInfo()) return EL; 7184 break; 7185 } 7186 case ICmpInst::ICMP_SLT: 7187 case ICmpInst::ICMP_ULT: { // while (X < Y) 7188 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7189 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7190 AllowPredicates); 7191 if (EL.hasAnyInfo()) return EL; 7192 break; 7193 } 7194 case ICmpInst::ICMP_SGT: 7195 case ICmpInst::ICMP_UGT: { // while (X > Y) 7196 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7197 ExitLimit EL = 7198 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7199 AllowPredicates); 7200 if (EL.hasAnyInfo()) return EL; 7201 break; 7202 } 7203 default: 7204 break; 7205 } 7206 7207 auto *ExhaustiveCount = 7208 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 7209 7210 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7211 return ExhaustiveCount; 7212 7213 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7214 ExitCond->getOperand(1), L, OriginalPred); 7215 } 7216 7217 ScalarEvolution::ExitLimit 7218 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7219 SwitchInst *Switch, 7220 BasicBlock *ExitingBlock, 7221 bool ControlsExit) { 7222 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7223 7224 // Give up if the exit is the default dest of a switch. 7225 if (Switch->getDefaultDest() == ExitingBlock) 7226 return getCouldNotCompute(); 7227 7228 assert(L->contains(Switch->getDefaultDest()) && 7229 "Default case must not exit the loop!"); 7230 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7231 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7232 7233 // while (X != Y) --> while (X-Y != 0) 7234 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7235 if (EL.hasAnyInfo()) 7236 return EL; 7237 7238 return getCouldNotCompute(); 7239 } 7240 7241 static ConstantInt * 7242 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7243 ScalarEvolution &SE) { 7244 const SCEV *InVal = SE.getConstant(C); 7245 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7246 assert(isa<SCEVConstant>(Val) && 7247 "Evaluation of SCEV at constant didn't fold correctly?"); 7248 return cast<SCEVConstant>(Val)->getValue(); 7249 } 7250 7251 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7252 /// compute the backedge execution count. 7253 ScalarEvolution::ExitLimit 7254 ScalarEvolution::computeLoadConstantCompareExitLimit( 7255 LoadInst *LI, 7256 Constant *RHS, 7257 const Loop *L, 7258 ICmpInst::Predicate predicate) { 7259 if (LI->isVolatile()) return getCouldNotCompute(); 7260 7261 // Check to see if the loaded pointer is a getelementptr of a global. 7262 // TODO: Use SCEV instead of manually grubbing with GEPs. 7263 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7264 if (!GEP) return getCouldNotCompute(); 7265 7266 // Make sure that it is really a constant global we are gepping, with an 7267 // initializer, and make sure the first IDX is really 0. 7268 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7269 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7270 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7271 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7272 return getCouldNotCompute(); 7273 7274 // Okay, we allow one non-constant index into the GEP instruction. 7275 Value *VarIdx = nullptr; 7276 std::vector<Constant*> Indexes; 7277 unsigned VarIdxNum = 0; 7278 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7279 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7280 Indexes.push_back(CI); 7281 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7282 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7283 VarIdx = GEP->getOperand(i); 7284 VarIdxNum = i-2; 7285 Indexes.push_back(nullptr); 7286 } 7287 7288 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7289 if (!VarIdx) 7290 return getCouldNotCompute(); 7291 7292 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7293 // Check to see if X is a loop variant variable value now. 7294 const SCEV *Idx = getSCEV(VarIdx); 7295 Idx = getSCEVAtScope(Idx, L); 7296 7297 // We can only recognize very limited forms of loop index expressions, in 7298 // particular, only affine AddRec's like {C1,+,C2}. 7299 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7300 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7301 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7302 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7303 return getCouldNotCompute(); 7304 7305 unsigned MaxSteps = MaxBruteForceIterations; 7306 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7307 ConstantInt *ItCst = ConstantInt::get( 7308 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7309 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7310 7311 // Form the GEP offset. 7312 Indexes[VarIdxNum] = Val; 7313 7314 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7315 Indexes); 7316 if (!Result) break; // Cannot compute! 7317 7318 // Evaluate the condition for this iteration. 7319 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7320 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7321 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7322 ++NumArrayLenItCounts; 7323 return getConstant(ItCst); // Found terminating iteration! 7324 } 7325 } 7326 return getCouldNotCompute(); 7327 } 7328 7329 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7330 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7331 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7332 if (!RHS) 7333 return getCouldNotCompute(); 7334 7335 const BasicBlock *Latch = L->getLoopLatch(); 7336 if (!Latch) 7337 return getCouldNotCompute(); 7338 7339 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7340 if (!Predecessor) 7341 return getCouldNotCompute(); 7342 7343 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7344 // Return LHS in OutLHS and shift_opt in OutOpCode. 7345 auto MatchPositiveShift = 7346 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7347 7348 using namespace PatternMatch; 7349 7350 ConstantInt *ShiftAmt; 7351 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7352 OutOpCode = Instruction::LShr; 7353 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7354 OutOpCode = Instruction::AShr; 7355 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7356 OutOpCode = Instruction::Shl; 7357 else 7358 return false; 7359 7360 return ShiftAmt->getValue().isStrictlyPositive(); 7361 }; 7362 7363 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7364 // 7365 // loop: 7366 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7367 // %iv.shifted = lshr i32 %iv, <positive constant> 7368 // 7369 // Return true on a successful match. Return the corresponding PHI node (%iv 7370 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7371 auto MatchShiftRecurrence = 7372 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7373 Optional<Instruction::BinaryOps> PostShiftOpCode; 7374 7375 { 7376 Instruction::BinaryOps OpC; 7377 Value *V; 7378 7379 // If we encounter a shift instruction, "peel off" the shift operation, 7380 // and remember that we did so. Later when we inspect %iv's backedge 7381 // value, we will make sure that the backedge value uses the same 7382 // operation. 7383 // 7384 // Note: the peeled shift operation does not have to be the same 7385 // instruction as the one feeding into the PHI's backedge value. We only 7386 // really care about it being the same *kind* of shift instruction -- 7387 // that's all that is required for our later inferences to hold. 7388 if (MatchPositiveShift(LHS, V, OpC)) { 7389 PostShiftOpCode = OpC; 7390 LHS = V; 7391 } 7392 } 7393 7394 PNOut = dyn_cast<PHINode>(LHS); 7395 if (!PNOut || PNOut->getParent() != L->getHeader()) 7396 return false; 7397 7398 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7399 Value *OpLHS; 7400 7401 return 7402 // The backedge value for the PHI node must be a shift by a positive 7403 // amount 7404 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7405 7406 // of the PHI node itself 7407 OpLHS == PNOut && 7408 7409 // and the kind of shift should be match the kind of shift we peeled 7410 // off, if any. 7411 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7412 }; 7413 7414 PHINode *PN; 7415 Instruction::BinaryOps OpCode; 7416 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7417 return getCouldNotCompute(); 7418 7419 const DataLayout &DL = getDataLayout(); 7420 7421 // The key rationale for this optimization is that for some kinds of shift 7422 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7423 // within a finite number of iterations. If the condition guarding the 7424 // backedge (in the sense that the backedge is taken if the condition is true) 7425 // is false for the value the shift recurrence stabilizes to, then we know 7426 // that the backedge is taken only a finite number of times. 7427 7428 ConstantInt *StableValue = nullptr; 7429 switch (OpCode) { 7430 default: 7431 llvm_unreachable("Impossible case!"); 7432 7433 case Instruction::AShr: { 7434 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7435 // bitwidth(K) iterations. 7436 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7437 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7438 Predecessor->getTerminator(), &DT); 7439 auto *Ty = cast<IntegerType>(RHS->getType()); 7440 if (Known.isNonNegative()) 7441 StableValue = ConstantInt::get(Ty, 0); 7442 else if (Known.isNegative()) 7443 StableValue = ConstantInt::get(Ty, -1, true); 7444 else 7445 return getCouldNotCompute(); 7446 7447 break; 7448 } 7449 case Instruction::LShr: 7450 case Instruction::Shl: 7451 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7452 // stabilize to 0 in at most bitwidth(K) iterations. 7453 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7454 break; 7455 } 7456 7457 auto *Result = 7458 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7459 assert(Result->getType()->isIntegerTy(1) && 7460 "Otherwise cannot be an operand to a branch instruction"); 7461 7462 if (Result->isZeroValue()) { 7463 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7464 const SCEV *UpperBound = 7465 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7466 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7467 } 7468 7469 return getCouldNotCompute(); 7470 } 7471 7472 /// Return true if we can constant fold an instruction of the specified type, 7473 /// assuming that all operands were constants. 7474 static bool CanConstantFold(const Instruction *I) { 7475 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7476 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7477 isa<LoadInst>(I)) 7478 return true; 7479 7480 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7481 if (const Function *F = CI->getCalledFunction()) 7482 return canConstantFoldCallTo(CI, F); 7483 return false; 7484 } 7485 7486 /// Determine whether this instruction can constant evolve within this loop 7487 /// assuming its operands can all constant evolve. 7488 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7489 // An instruction outside of the loop can't be derived from a loop PHI. 7490 if (!L->contains(I)) return false; 7491 7492 if (isa<PHINode>(I)) { 7493 // We don't currently keep track of the control flow needed to evaluate 7494 // PHIs, so we cannot handle PHIs inside of loops. 7495 return L->getHeader() == I->getParent(); 7496 } 7497 7498 // If we won't be able to constant fold this expression even if the operands 7499 // are constants, bail early. 7500 return CanConstantFold(I); 7501 } 7502 7503 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7504 /// recursing through each instruction operand until reaching a loop header phi. 7505 static PHINode * 7506 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7507 DenseMap<Instruction *, PHINode *> &PHIMap, 7508 unsigned Depth) { 7509 if (Depth > MaxConstantEvolvingDepth) 7510 return nullptr; 7511 7512 // Otherwise, we can evaluate this instruction if all of its operands are 7513 // constant or derived from a PHI node themselves. 7514 PHINode *PHI = nullptr; 7515 for (Value *Op : UseInst->operands()) { 7516 if (isa<Constant>(Op)) continue; 7517 7518 Instruction *OpInst = dyn_cast<Instruction>(Op); 7519 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7520 7521 PHINode *P = dyn_cast<PHINode>(OpInst); 7522 if (!P) 7523 // If this operand is already visited, reuse the prior result. 7524 // We may have P != PHI if this is the deepest point at which the 7525 // inconsistent paths meet. 7526 P = PHIMap.lookup(OpInst); 7527 if (!P) { 7528 // Recurse and memoize the results, whether a phi is found or not. 7529 // This recursive call invalidates pointers into PHIMap. 7530 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7531 PHIMap[OpInst] = P; 7532 } 7533 if (!P) 7534 return nullptr; // Not evolving from PHI 7535 if (PHI && PHI != P) 7536 return nullptr; // Evolving from multiple different PHIs. 7537 PHI = P; 7538 } 7539 // This is a expression evolving from a constant PHI! 7540 return PHI; 7541 } 7542 7543 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7544 /// in the loop that V is derived from. We allow arbitrary operations along the 7545 /// way, but the operands of an operation must either be constants or a value 7546 /// derived from a constant PHI. If this expression does not fit with these 7547 /// constraints, return null. 7548 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7549 Instruction *I = dyn_cast<Instruction>(V); 7550 if (!I || !canConstantEvolve(I, L)) return nullptr; 7551 7552 if (PHINode *PN = dyn_cast<PHINode>(I)) 7553 return PN; 7554 7555 // Record non-constant instructions contained by the loop. 7556 DenseMap<Instruction *, PHINode *> PHIMap; 7557 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7558 } 7559 7560 /// EvaluateExpression - Given an expression that passes the 7561 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7562 /// in the loop has the value PHIVal. If we can't fold this expression for some 7563 /// reason, return null. 7564 static Constant *EvaluateExpression(Value *V, const Loop *L, 7565 DenseMap<Instruction *, Constant *> &Vals, 7566 const DataLayout &DL, 7567 const TargetLibraryInfo *TLI) { 7568 // Convenient constant check, but redundant for recursive calls. 7569 if (Constant *C = dyn_cast<Constant>(V)) return C; 7570 Instruction *I = dyn_cast<Instruction>(V); 7571 if (!I) return nullptr; 7572 7573 if (Constant *C = Vals.lookup(I)) return C; 7574 7575 // An instruction inside the loop depends on a value outside the loop that we 7576 // weren't given a mapping for, or a value such as a call inside the loop. 7577 if (!canConstantEvolve(I, L)) return nullptr; 7578 7579 // An unmapped PHI can be due to a branch or another loop inside this loop, 7580 // or due to this not being the initial iteration through a loop where we 7581 // couldn't compute the evolution of this particular PHI last time. 7582 if (isa<PHINode>(I)) return nullptr; 7583 7584 std::vector<Constant*> Operands(I->getNumOperands()); 7585 7586 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7587 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7588 if (!Operand) { 7589 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7590 if (!Operands[i]) return nullptr; 7591 continue; 7592 } 7593 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7594 Vals[Operand] = C; 7595 if (!C) return nullptr; 7596 Operands[i] = C; 7597 } 7598 7599 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7600 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7601 Operands[1], DL, TLI); 7602 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7603 if (!LI->isVolatile()) 7604 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7605 } 7606 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7607 } 7608 7609 7610 // If every incoming value to PN except the one for BB is a specific Constant, 7611 // return that, else return nullptr. 7612 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7613 Constant *IncomingVal = nullptr; 7614 7615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7616 if (PN->getIncomingBlock(i) == BB) 7617 continue; 7618 7619 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7620 if (!CurrentVal) 7621 return nullptr; 7622 7623 if (IncomingVal != CurrentVal) { 7624 if (IncomingVal) 7625 return nullptr; 7626 IncomingVal = CurrentVal; 7627 } 7628 } 7629 7630 return IncomingVal; 7631 } 7632 7633 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7634 /// in the header of its containing loop, we know the loop executes a 7635 /// constant number of times, and the PHI node is just a recurrence 7636 /// involving constants, fold it. 7637 Constant * 7638 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7639 const APInt &BEs, 7640 const Loop *L) { 7641 auto I = ConstantEvolutionLoopExitValue.find(PN); 7642 if (I != ConstantEvolutionLoopExitValue.end()) 7643 return I->second; 7644 7645 if (BEs.ugt(MaxBruteForceIterations)) 7646 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7647 7648 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7649 7650 DenseMap<Instruction *, Constant *> CurrentIterVals; 7651 BasicBlock *Header = L->getHeader(); 7652 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7653 7654 BasicBlock *Latch = L->getLoopLatch(); 7655 if (!Latch) 7656 return nullptr; 7657 7658 for (PHINode &PHI : Header->phis()) { 7659 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7660 CurrentIterVals[&PHI] = StartCST; 7661 } 7662 if (!CurrentIterVals.count(PN)) 7663 return RetVal = nullptr; 7664 7665 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7666 7667 // Execute the loop symbolically to determine the exit value. 7668 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7669 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7670 7671 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7672 unsigned IterationNum = 0; 7673 const DataLayout &DL = getDataLayout(); 7674 for (; ; ++IterationNum) { 7675 if (IterationNum == NumIterations) 7676 return RetVal = CurrentIterVals[PN]; // Got exit value! 7677 7678 // Compute the value of the PHIs for the next iteration. 7679 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7680 DenseMap<Instruction *, Constant *> NextIterVals; 7681 Constant *NextPHI = 7682 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7683 if (!NextPHI) 7684 return nullptr; // Couldn't evaluate! 7685 NextIterVals[PN] = NextPHI; 7686 7687 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7688 7689 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7690 // cease to be able to evaluate one of them or if they stop evolving, 7691 // because that doesn't necessarily prevent us from computing PN. 7692 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7693 for (const auto &I : CurrentIterVals) { 7694 PHINode *PHI = dyn_cast<PHINode>(I.first); 7695 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7696 PHIsToCompute.emplace_back(PHI, I.second); 7697 } 7698 // We use two distinct loops because EvaluateExpression may invalidate any 7699 // iterators into CurrentIterVals. 7700 for (const auto &I : PHIsToCompute) { 7701 PHINode *PHI = I.first; 7702 Constant *&NextPHI = NextIterVals[PHI]; 7703 if (!NextPHI) { // Not already computed. 7704 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7705 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7706 } 7707 if (NextPHI != I.second) 7708 StoppedEvolving = false; 7709 } 7710 7711 // If all entries in CurrentIterVals == NextIterVals then we can stop 7712 // iterating, the loop can't continue to change. 7713 if (StoppedEvolving) 7714 return RetVal = CurrentIterVals[PN]; 7715 7716 CurrentIterVals.swap(NextIterVals); 7717 } 7718 } 7719 7720 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7721 Value *Cond, 7722 bool ExitWhen) { 7723 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7724 if (!PN) return getCouldNotCompute(); 7725 7726 // If the loop is canonicalized, the PHI will have exactly two entries. 7727 // That's the only form we support here. 7728 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7729 7730 DenseMap<Instruction *, Constant *> CurrentIterVals; 7731 BasicBlock *Header = L->getHeader(); 7732 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7733 7734 BasicBlock *Latch = L->getLoopLatch(); 7735 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7736 7737 for (PHINode &PHI : Header->phis()) { 7738 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7739 CurrentIterVals[&PHI] = StartCST; 7740 } 7741 if (!CurrentIterVals.count(PN)) 7742 return getCouldNotCompute(); 7743 7744 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7745 // the loop symbolically to determine when the condition gets a value of 7746 // "ExitWhen". 7747 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7748 const DataLayout &DL = getDataLayout(); 7749 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7750 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7751 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7752 7753 // Couldn't symbolically evaluate. 7754 if (!CondVal) return getCouldNotCompute(); 7755 7756 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7757 ++NumBruteForceTripCountsComputed; 7758 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7759 } 7760 7761 // Update all the PHI nodes for the next iteration. 7762 DenseMap<Instruction *, Constant *> NextIterVals; 7763 7764 // Create a list of which PHIs we need to compute. We want to do this before 7765 // calling EvaluateExpression on them because that may invalidate iterators 7766 // into CurrentIterVals. 7767 SmallVector<PHINode *, 8> PHIsToCompute; 7768 for (const auto &I : CurrentIterVals) { 7769 PHINode *PHI = dyn_cast<PHINode>(I.first); 7770 if (!PHI || PHI->getParent() != Header) continue; 7771 PHIsToCompute.push_back(PHI); 7772 } 7773 for (PHINode *PHI : PHIsToCompute) { 7774 Constant *&NextPHI = NextIterVals[PHI]; 7775 if (NextPHI) continue; // Already computed! 7776 7777 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7778 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7779 } 7780 CurrentIterVals.swap(NextIterVals); 7781 } 7782 7783 // Too many iterations were needed to evaluate. 7784 return getCouldNotCompute(); 7785 } 7786 7787 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7788 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7789 ValuesAtScopes[V]; 7790 // Check to see if we've folded this expression at this loop before. 7791 for (auto &LS : Values) 7792 if (LS.first == L) 7793 return LS.second ? LS.second : V; 7794 7795 Values.emplace_back(L, nullptr); 7796 7797 // Otherwise compute it. 7798 const SCEV *C = computeSCEVAtScope(V, L); 7799 for (auto &LS : reverse(ValuesAtScopes[V])) 7800 if (LS.first == L) { 7801 LS.second = C; 7802 break; 7803 } 7804 return C; 7805 } 7806 7807 /// This builds up a Constant using the ConstantExpr interface. That way, we 7808 /// will return Constants for objects which aren't represented by a 7809 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7810 /// Returns NULL if the SCEV isn't representable as a Constant. 7811 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7812 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7813 case scCouldNotCompute: 7814 case scAddRecExpr: 7815 break; 7816 case scConstant: 7817 return cast<SCEVConstant>(V)->getValue(); 7818 case scUnknown: 7819 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7820 case scSignExtend: { 7821 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7822 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7823 return ConstantExpr::getSExt(CastOp, SS->getType()); 7824 break; 7825 } 7826 case scZeroExtend: { 7827 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7828 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7829 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7830 break; 7831 } 7832 case scTruncate: { 7833 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7834 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7835 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7836 break; 7837 } 7838 case scAddExpr: { 7839 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7840 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7841 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7842 unsigned AS = PTy->getAddressSpace(); 7843 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7844 C = ConstantExpr::getBitCast(C, DestPtrTy); 7845 } 7846 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7847 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7848 if (!C2) return nullptr; 7849 7850 // First pointer! 7851 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7852 unsigned AS = C2->getType()->getPointerAddressSpace(); 7853 std::swap(C, C2); 7854 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7855 // The offsets have been converted to bytes. We can add bytes to an 7856 // i8* by GEP with the byte count in the first index. 7857 C = ConstantExpr::getBitCast(C, DestPtrTy); 7858 } 7859 7860 // Don't bother trying to sum two pointers. We probably can't 7861 // statically compute a load that results from it anyway. 7862 if (C2->getType()->isPointerTy()) 7863 return nullptr; 7864 7865 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7866 if (PTy->getElementType()->isStructTy()) 7867 C2 = ConstantExpr::getIntegerCast( 7868 C2, Type::getInt32Ty(C->getContext()), true); 7869 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7870 } else 7871 C = ConstantExpr::getAdd(C, C2); 7872 } 7873 return C; 7874 } 7875 break; 7876 } 7877 case scMulExpr: { 7878 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7879 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7880 // Don't bother with pointers at all. 7881 if (C->getType()->isPointerTy()) return nullptr; 7882 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7883 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7884 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7885 C = ConstantExpr::getMul(C, C2); 7886 } 7887 return C; 7888 } 7889 break; 7890 } 7891 case scUDivExpr: { 7892 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7893 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7894 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7895 if (LHS->getType() == RHS->getType()) 7896 return ConstantExpr::getUDiv(LHS, RHS); 7897 break; 7898 } 7899 case scSMaxExpr: 7900 case scUMaxExpr: 7901 break; // TODO: smax, umax. 7902 } 7903 return nullptr; 7904 } 7905 7906 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7907 if (isa<SCEVConstant>(V)) return V; 7908 7909 // If this instruction is evolved from a constant-evolving PHI, compute the 7910 // exit value from the loop without using SCEVs. 7911 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7912 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7913 const Loop *LI = this->LI[I->getParent()]; 7914 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7915 if (PHINode *PN = dyn_cast<PHINode>(I)) 7916 if (PN->getParent() == LI->getHeader()) { 7917 // Okay, there is no closed form solution for the PHI node. Check 7918 // to see if the loop that contains it has a known backedge-taken 7919 // count. If so, we may be able to force computation of the exit 7920 // value. 7921 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7922 if (const SCEVConstant *BTCC = 7923 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7924 7925 // This trivial case can show up in some degenerate cases where 7926 // the incoming IR has not yet been fully simplified. 7927 if (BTCC->getValue()->isZero()) { 7928 Value *InitValue = nullptr; 7929 bool MultipleInitValues = false; 7930 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 7931 if (!LI->contains(PN->getIncomingBlock(i))) { 7932 if (!InitValue) 7933 InitValue = PN->getIncomingValue(i); 7934 else if (InitValue != PN->getIncomingValue(i)) { 7935 MultipleInitValues = true; 7936 break; 7937 } 7938 } 7939 if (!MultipleInitValues && InitValue) 7940 return getSCEV(InitValue); 7941 } 7942 } 7943 // Okay, we know how many times the containing loop executes. If 7944 // this is a constant evolving PHI node, get the final value at 7945 // the specified iteration number. 7946 Constant *RV = 7947 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7948 if (RV) return getSCEV(RV); 7949 } 7950 } 7951 7952 // Okay, this is an expression that we cannot symbolically evaluate 7953 // into a SCEV. Check to see if it's possible to symbolically evaluate 7954 // the arguments into constants, and if so, try to constant propagate the 7955 // result. This is particularly useful for computing loop exit values. 7956 if (CanConstantFold(I)) { 7957 SmallVector<Constant *, 4> Operands; 7958 bool MadeImprovement = false; 7959 for (Value *Op : I->operands()) { 7960 if (Constant *C = dyn_cast<Constant>(Op)) { 7961 Operands.push_back(C); 7962 continue; 7963 } 7964 7965 // If any of the operands is non-constant and if they are 7966 // non-integer and non-pointer, don't even try to analyze them 7967 // with scev techniques. 7968 if (!isSCEVable(Op->getType())) 7969 return V; 7970 7971 const SCEV *OrigV = getSCEV(Op); 7972 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7973 MadeImprovement |= OrigV != OpV; 7974 7975 Constant *C = BuildConstantFromSCEV(OpV); 7976 if (!C) return V; 7977 if (C->getType() != Op->getType()) 7978 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7979 Op->getType(), 7980 false), 7981 C, Op->getType()); 7982 Operands.push_back(C); 7983 } 7984 7985 // Check to see if getSCEVAtScope actually made an improvement. 7986 if (MadeImprovement) { 7987 Constant *C = nullptr; 7988 const DataLayout &DL = getDataLayout(); 7989 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7990 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7991 Operands[1], DL, &TLI); 7992 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7993 if (!LI->isVolatile()) 7994 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7995 } else 7996 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7997 if (!C) return V; 7998 return getSCEV(C); 7999 } 8000 } 8001 } 8002 8003 // This is some other type of SCEVUnknown, just return it. 8004 return V; 8005 } 8006 8007 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8008 // Avoid performing the look-up in the common case where the specified 8009 // expression has no loop-variant portions. 8010 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8011 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8012 if (OpAtScope != Comm->getOperand(i)) { 8013 // Okay, at least one of these operands is loop variant but might be 8014 // foldable. Build a new instance of the folded commutative expression. 8015 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8016 Comm->op_begin()+i); 8017 NewOps.push_back(OpAtScope); 8018 8019 for (++i; i != e; ++i) { 8020 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8021 NewOps.push_back(OpAtScope); 8022 } 8023 if (isa<SCEVAddExpr>(Comm)) 8024 return getAddExpr(NewOps); 8025 if (isa<SCEVMulExpr>(Comm)) 8026 return getMulExpr(NewOps); 8027 if (isa<SCEVSMaxExpr>(Comm)) 8028 return getSMaxExpr(NewOps); 8029 if (isa<SCEVUMaxExpr>(Comm)) 8030 return getUMaxExpr(NewOps); 8031 llvm_unreachable("Unknown commutative SCEV type!"); 8032 } 8033 } 8034 // If we got here, all operands are loop invariant. 8035 return Comm; 8036 } 8037 8038 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8039 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8040 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8041 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8042 return Div; // must be loop invariant 8043 return getUDivExpr(LHS, RHS); 8044 } 8045 8046 // If this is a loop recurrence for a loop that does not contain L, then we 8047 // are dealing with the final value computed by the loop. 8048 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8049 // First, attempt to evaluate each operand. 8050 // Avoid performing the look-up in the common case where the specified 8051 // expression has no loop-variant portions. 8052 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8053 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8054 if (OpAtScope == AddRec->getOperand(i)) 8055 continue; 8056 8057 // Okay, at least one of these operands is loop variant but might be 8058 // foldable. Build a new instance of the folded commutative expression. 8059 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8060 AddRec->op_begin()+i); 8061 NewOps.push_back(OpAtScope); 8062 for (++i; i != e; ++i) 8063 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8064 8065 const SCEV *FoldedRec = 8066 getAddRecExpr(NewOps, AddRec->getLoop(), 8067 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8068 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8069 // The addrec may be folded to a nonrecurrence, for example, if the 8070 // induction variable is multiplied by zero after constant folding. Go 8071 // ahead and return the folded value. 8072 if (!AddRec) 8073 return FoldedRec; 8074 break; 8075 } 8076 8077 // If the scope is outside the addrec's loop, evaluate it by using the 8078 // loop exit value of the addrec. 8079 if (!AddRec->getLoop()->contains(L)) { 8080 // To evaluate this recurrence, we need to know how many times the AddRec 8081 // loop iterates. Compute this now. 8082 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8083 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8084 8085 // Then, evaluate the AddRec. 8086 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8087 } 8088 8089 return AddRec; 8090 } 8091 8092 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8093 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8094 if (Op == Cast->getOperand()) 8095 return Cast; // must be loop invariant 8096 return getZeroExtendExpr(Op, Cast->getType()); 8097 } 8098 8099 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8100 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8101 if (Op == Cast->getOperand()) 8102 return Cast; // must be loop invariant 8103 return getSignExtendExpr(Op, Cast->getType()); 8104 } 8105 8106 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8107 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8108 if (Op == Cast->getOperand()) 8109 return Cast; // must be loop invariant 8110 return getTruncateExpr(Op, Cast->getType()); 8111 } 8112 8113 llvm_unreachable("Unknown SCEV type!"); 8114 } 8115 8116 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8117 return getSCEVAtScope(getSCEV(V), L); 8118 } 8119 8120 /// Finds the minimum unsigned root of the following equation: 8121 /// 8122 /// A * X = B (mod N) 8123 /// 8124 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8125 /// A and B isn't important. 8126 /// 8127 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8128 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8129 ScalarEvolution &SE) { 8130 uint32_t BW = A.getBitWidth(); 8131 assert(BW == SE.getTypeSizeInBits(B->getType())); 8132 assert(A != 0 && "A must be non-zero."); 8133 8134 // 1. D = gcd(A, N) 8135 // 8136 // The gcd of A and N may have only one prime factor: 2. The number of 8137 // trailing zeros in A is its multiplicity 8138 uint32_t Mult2 = A.countTrailingZeros(); 8139 // D = 2^Mult2 8140 8141 // 2. Check if B is divisible by D. 8142 // 8143 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8144 // is not less than multiplicity of this prime factor for D. 8145 if (SE.GetMinTrailingZeros(B) < Mult2) 8146 return SE.getCouldNotCompute(); 8147 8148 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8149 // modulo (N / D). 8150 // 8151 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8152 // (N / D) in general. The inverse itself always fits into BW bits, though, 8153 // so we immediately truncate it. 8154 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8155 APInt Mod(BW + 1, 0); 8156 Mod.setBit(BW - Mult2); // Mod = N / D 8157 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8158 8159 // 4. Compute the minimum unsigned root of the equation: 8160 // I * (B / D) mod (N / D) 8161 // To simplify the computation, we factor out the divide by D: 8162 // (I * B mod N) / D 8163 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8164 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8165 } 8166 8167 /// Find the roots of the quadratic equation for the given quadratic chrec 8168 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8169 /// two SCEVCouldNotCompute objects. 8170 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8171 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8172 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8173 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8174 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8175 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8176 8177 // We currently can only solve this if the coefficients are constants. 8178 if (!LC || !MC || !NC) 8179 return None; 8180 8181 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8182 const APInt &L = LC->getAPInt(); 8183 const APInt &M = MC->getAPInt(); 8184 const APInt &N = NC->getAPInt(); 8185 APInt Two(BitWidth, 2); 8186 8187 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8188 8189 // The A coefficient is N/2 8190 APInt A = N.sdiv(Two); 8191 8192 // The B coefficient is M-N/2 8193 APInt B = M; 8194 B -= A; // A is the same as N/2. 8195 8196 // The C coefficient is L. 8197 const APInt& C = L; 8198 8199 // Compute the B^2-4ac term. 8200 APInt SqrtTerm = B; 8201 SqrtTerm *= B; 8202 SqrtTerm -= 4 * (A * C); 8203 8204 if (SqrtTerm.isNegative()) { 8205 // The loop is provably infinite. 8206 return None; 8207 } 8208 8209 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8210 // integer value or else APInt::sqrt() will assert. 8211 APInt SqrtVal = SqrtTerm.sqrt(); 8212 8213 // Compute the two solutions for the quadratic formula. 8214 // The divisions must be performed as signed divisions. 8215 APInt NegB = -std::move(B); 8216 APInt TwoA = std::move(A); 8217 TwoA <<= 1; 8218 if (TwoA.isNullValue()) 8219 return None; 8220 8221 LLVMContext &Context = SE.getContext(); 8222 8223 ConstantInt *Solution1 = 8224 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8225 ConstantInt *Solution2 = 8226 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8227 8228 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8229 cast<SCEVConstant>(SE.getConstant(Solution2))); 8230 } 8231 8232 ScalarEvolution::ExitLimit 8233 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8234 bool AllowPredicates) { 8235 8236 // This is only used for loops with a "x != y" exit test. The exit condition 8237 // is now expressed as a single expression, V = x-y. So the exit test is 8238 // effectively V != 0. We know and take advantage of the fact that this 8239 // expression only being used in a comparison by zero context. 8240 8241 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8242 // If the value is a constant 8243 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8244 // If the value is already zero, the branch will execute zero times. 8245 if (C->getValue()->isZero()) return C; 8246 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8247 } 8248 8249 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 8250 if (!AddRec && AllowPredicates) 8251 // Try to make this an AddRec using runtime tests, in the first X 8252 // iterations of this loop, where X is the SCEV expression found by the 8253 // algorithm below. 8254 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8255 8256 if (!AddRec || AddRec->getLoop() != L) 8257 return getCouldNotCompute(); 8258 8259 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8260 // the quadratic equation to solve it. 8261 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8262 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8263 const SCEVConstant *R1 = Roots->first; 8264 const SCEVConstant *R2 = Roots->second; 8265 // Pick the smallest positive root value. 8266 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8267 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8268 if (!CB->getZExtValue()) 8269 std::swap(R1, R2); // R1 is the minimum root now. 8270 8271 // We can only use this value if the chrec ends up with an exact zero 8272 // value at this index. When solving for "X*X != 5", for example, we 8273 // should not accept a root of 2. 8274 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8275 if (Val->isZero()) 8276 // We found a quadratic root! 8277 return ExitLimit(R1, R1, false, Predicates); 8278 } 8279 } 8280 return getCouldNotCompute(); 8281 } 8282 8283 // Otherwise we can only handle this if it is affine. 8284 if (!AddRec->isAffine()) 8285 return getCouldNotCompute(); 8286 8287 // If this is an affine expression, the execution count of this branch is 8288 // the minimum unsigned root of the following equation: 8289 // 8290 // Start + Step*N = 0 (mod 2^BW) 8291 // 8292 // equivalent to: 8293 // 8294 // Step*N = -Start (mod 2^BW) 8295 // 8296 // where BW is the common bit width of Start and Step. 8297 8298 // Get the initial value for the loop. 8299 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8300 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8301 8302 // For now we handle only constant steps. 8303 // 8304 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8305 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8306 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8307 // We have not yet seen any such cases. 8308 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8309 if (!StepC || StepC->getValue()->isZero()) 8310 return getCouldNotCompute(); 8311 8312 // For positive steps (counting up until unsigned overflow): 8313 // N = -Start/Step (as unsigned) 8314 // For negative steps (counting down to zero): 8315 // N = Start/-Step 8316 // First compute the unsigned distance from zero in the direction of Step. 8317 bool CountDown = StepC->getAPInt().isNegative(); 8318 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8319 8320 // Handle unitary steps, which cannot wraparound. 8321 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8322 // N = Distance (as unsigned) 8323 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8324 APInt MaxBECount = getUnsignedRangeMax(Distance); 8325 8326 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8327 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8328 // case, and see if we can improve the bound. 8329 // 8330 // Explicitly handling this here is necessary because getUnsignedRange 8331 // isn't context-sensitive; it doesn't know that we only care about the 8332 // range inside the loop. 8333 const SCEV *Zero = getZero(Distance->getType()); 8334 const SCEV *One = getOne(Distance->getType()); 8335 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8336 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8337 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8338 // as "unsigned_max(Distance + 1) - 1". 8339 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8340 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8341 } 8342 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8343 } 8344 8345 // If the condition controls loop exit (the loop exits only if the expression 8346 // is true) and the addition is no-wrap we can use unsigned divide to 8347 // compute the backedge count. In this case, the step may not divide the 8348 // distance, but we don't care because if the condition is "missed" the loop 8349 // will have undefined behavior due to wrapping. 8350 if (ControlsExit && AddRec->hasNoSelfWrap() && 8351 loopHasNoAbnormalExits(AddRec->getLoop())) { 8352 const SCEV *Exact = 8353 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8354 const SCEV *Max = 8355 Exact == getCouldNotCompute() 8356 ? Exact 8357 : getConstant(getUnsignedRangeMax(Exact)); 8358 return ExitLimit(Exact, Max, false, Predicates); 8359 } 8360 8361 // Solve the general equation. 8362 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8363 getNegativeSCEV(Start), *this); 8364 const SCEV *M = E == getCouldNotCompute() 8365 ? E 8366 : getConstant(getUnsignedRangeMax(E)); 8367 return ExitLimit(E, M, false, Predicates); 8368 } 8369 8370 ScalarEvolution::ExitLimit 8371 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8372 // Loops that look like: while (X == 0) are very strange indeed. We don't 8373 // handle them yet except for the trivial case. This could be expanded in the 8374 // future as needed. 8375 8376 // If the value is a constant, check to see if it is known to be non-zero 8377 // already. If so, the backedge will execute zero times. 8378 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8379 if (!C->getValue()->isZero()) 8380 return getZero(C->getType()); 8381 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8382 } 8383 8384 // We could implement others, but I really doubt anyone writes loops like 8385 // this, and if they did, they would already be constant folded. 8386 return getCouldNotCompute(); 8387 } 8388 8389 std::pair<BasicBlock *, BasicBlock *> 8390 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8391 // If the block has a unique predecessor, then there is no path from the 8392 // predecessor to the block that does not go through the direct edge 8393 // from the predecessor to the block. 8394 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8395 return {Pred, BB}; 8396 8397 // A loop's header is defined to be a block that dominates the loop. 8398 // If the header has a unique predecessor outside the loop, it must be 8399 // a block that has exactly one successor that can reach the loop. 8400 if (Loop *L = LI.getLoopFor(BB)) 8401 return {L->getLoopPredecessor(), L->getHeader()}; 8402 8403 return {nullptr, nullptr}; 8404 } 8405 8406 /// SCEV structural equivalence is usually sufficient for testing whether two 8407 /// expressions are equal, however for the purposes of looking for a condition 8408 /// guarding a loop, it can be useful to be a little more general, since a 8409 /// front-end may have replicated the controlling expression. 8410 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8411 // Quick check to see if they are the same SCEV. 8412 if (A == B) return true; 8413 8414 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8415 // Not all instructions that are "identical" compute the same value. For 8416 // instance, two distinct alloca instructions allocating the same type are 8417 // identical and do not read memory; but compute distinct values. 8418 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8419 }; 8420 8421 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8422 // two different instructions with the same value. Check for this case. 8423 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8424 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8425 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8426 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8427 if (ComputesEqualValues(AI, BI)) 8428 return true; 8429 8430 // Otherwise assume they may have a different value. 8431 return false; 8432 } 8433 8434 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8435 const SCEV *&LHS, const SCEV *&RHS, 8436 unsigned Depth) { 8437 bool Changed = false; 8438 8439 // If we hit the max recursion limit bail out. 8440 if (Depth >= 3) 8441 return false; 8442 8443 // Canonicalize a constant to the right side. 8444 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8445 // Check for both operands constant. 8446 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8447 if (ConstantExpr::getICmp(Pred, 8448 LHSC->getValue(), 8449 RHSC->getValue())->isNullValue()) 8450 goto trivially_false; 8451 else 8452 goto trivially_true; 8453 } 8454 // Otherwise swap the operands to put the constant on the right. 8455 std::swap(LHS, RHS); 8456 Pred = ICmpInst::getSwappedPredicate(Pred); 8457 Changed = true; 8458 } 8459 8460 // If we're comparing an addrec with a value which is loop-invariant in the 8461 // addrec's loop, put the addrec on the left. Also make a dominance check, 8462 // as both operands could be addrecs loop-invariant in each other's loop. 8463 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8464 const Loop *L = AR->getLoop(); 8465 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8466 std::swap(LHS, RHS); 8467 Pred = ICmpInst::getSwappedPredicate(Pred); 8468 Changed = true; 8469 } 8470 } 8471 8472 // If there's a constant operand, canonicalize comparisons with boundary 8473 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8474 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8475 const APInt &RA = RC->getAPInt(); 8476 8477 bool SimplifiedByConstantRange = false; 8478 8479 if (!ICmpInst::isEquality(Pred)) { 8480 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8481 if (ExactCR.isFullSet()) 8482 goto trivially_true; 8483 else if (ExactCR.isEmptySet()) 8484 goto trivially_false; 8485 8486 APInt NewRHS; 8487 CmpInst::Predicate NewPred; 8488 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8489 ICmpInst::isEquality(NewPred)) { 8490 // We were able to convert an inequality to an equality. 8491 Pred = NewPred; 8492 RHS = getConstant(NewRHS); 8493 Changed = SimplifiedByConstantRange = true; 8494 } 8495 } 8496 8497 if (!SimplifiedByConstantRange) { 8498 switch (Pred) { 8499 default: 8500 break; 8501 case ICmpInst::ICMP_EQ: 8502 case ICmpInst::ICMP_NE: 8503 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8504 if (!RA) 8505 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8506 if (const SCEVMulExpr *ME = 8507 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8508 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8509 ME->getOperand(0)->isAllOnesValue()) { 8510 RHS = AE->getOperand(1); 8511 LHS = ME->getOperand(1); 8512 Changed = true; 8513 } 8514 break; 8515 8516 8517 // The "Should have been caught earlier!" messages refer to the fact 8518 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8519 // should have fired on the corresponding cases, and canonicalized the 8520 // check to trivially_true or trivially_false. 8521 8522 case ICmpInst::ICMP_UGE: 8523 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8524 Pred = ICmpInst::ICMP_UGT; 8525 RHS = getConstant(RA - 1); 8526 Changed = true; 8527 break; 8528 case ICmpInst::ICMP_ULE: 8529 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8530 Pred = ICmpInst::ICMP_ULT; 8531 RHS = getConstant(RA + 1); 8532 Changed = true; 8533 break; 8534 case ICmpInst::ICMP_SGE: 8535 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8536 Pred = ICmpInst::ICMP_SGT; 8537 RHS = getConstant(RA - 1); 8538 Changed = true; 8539 break; 8540 case ICmpInst::ICMP_SLE: 8541 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8542 Pred = ICmpInst::ICMP_SLT; 8543 RHS = getConstant(RA + 1); 8544 Changed = true; 8545 break; 8546 } 8547 } 8548 } 8549 8550 // Check for obvious equality. 8551 if (HasSameValue(LHS, RHS)) { 8552 if (ICmpInst::isTrueWhenEqual(Pred)) 8553 goto trivially_true; 8554 if (ICmpInst::isFalseWhenEqual(Pred)) 8555 goto trivially_false; 8556 } 8557 8558 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8559 // adding or subtracting 1 from one of the operands. 8560 switch (Pred) { 8561 case ICmpInst::ICMP_SLE: 8562 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8563 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8564 SCEV::FlagNSW); 8565 Pred = ICmpInst::ICMP_SLT; 8566 Changed = true; 8567 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8568 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8569 SCEV::FlagNSW); 8570 Pred = ICmpInst::ICMP_SLT; 8571 Changed = true; 8572 } 8573 break; 8574 case ICmpInst::ICMP_SGE: 8575 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8576 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8577 SCEV::FlagNSW); 8578 Pred = ICmpInst::ICMP_SGT; 8579 Changed = true; 8580 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8581 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8582 SCEV::FlagNSW); 8583 Pred = ICmpInst::ICMP_SGT; 8584 Changed = true; 8585 } 8586 break; 8587 case ICmpInst::ICMP_ULE: 8588 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8589 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8590 SCEV::FlagNUW); 8591 Pred = ICmpInst::ICMP_ULT; 8592 Changed = true; 8593 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8594 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8595 Pred = ICmpInst::ICMP_ULT; 8596 Changed = true; 8597 } 8598 break; 8599 case ICmpInst::ICMP_UGE: 8600 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8601 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8602 Pred = ICmpInst::ICMP_UGT; 8603 Changed = true; 8604 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8605 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8606 SCEV::FlagNUW); 8607 Pred = ICmpInst::ICMP_UGT; 8608 Changed = true; 8609 } 8610 break; 8611 default: 8612 break; 8613 } 8614 8615 // TODO: More simplifications are possible here. 8616 8617 // Recursively simplify until we either hit a recursion limit or nothing 8618 // changes. 8619 if (Changed) 8620 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8621 8622 return Changed; 8623 8624 trivially_true: 8625 // Return 0 == 0. 8626 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8627 Pred = ICmpInst::ICMP_EQ; 8628 return true; 8629 8630 trivially_false: 8631 // Return 0 != 0. 8632 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8633 Pred = ICmpInst::ICMP_NE; 8634 return true; 8635 } 8636 8637 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8638 return getSignedRangeMax(S).isNegative(); 8639 } 8640 8641 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8642 return getSignedRangeMin(S).isStrictlyPositive(); 8643 } 8644 8645 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8646 return !getSignedRangeMin(S).isNegative(); 8647 } 8648 8649 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8650 return !getSignedRangeMax(S).isStrictlyPositive(); 8651 } 8652 8653 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8654 return isKnownNegative(S) || isKnownPositive(S); 8655 } 8656 8657 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8658 const SCEV *LHS, const SCEV *RHS) { 8659 // Canonicalize the inputs first. 8660 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8661 8662 // If LHS or RHS is an addrec, check to see if the condition is true in 8663 // every iteration of the loop. 8664 // If LHS and RHS are both addrec, both conditions must be true in 8665 // every iteration of the loop. 8666 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8667 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8668 bool LeftGuarded = false; 8669 bool RightGuarded = false; 8670 if (LAR) { 8671 const Loop *L = LAR->getLoop(); 8672 if (isAvailableAtLoopEntry(RHS, L) && 8673 isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 8674 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 8675 if (!RAR) return true; 8676 LeftGuarded = true; 8677 } 8678 } 8679 if (RAR) { 8680 const Loop *L = RAR->getLoop(); 8681 if (isAvailableAtLoopEntry(LHS, L) && 8682 isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 8683 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 8684 if (!LAR) return true; 8685 RightGuarded = true; 8686 } 8687 } 8688 if (LeftGuarded && RightGuarded) 8689 return true; 8690 8691 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8692 return true; 8693 8694 // Otherwise see what can be done with known constant ranges. 8695 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 8696 } 8697 8698 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8699 ICmpInst::Predicate Pred, 8700 bool &Increasing) { 8701 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8702 8703 #ifndef NDEBUG 8704 // Verify an invariant: inverting the predicate should turn a monotonically 8705 // increasing change to a monotonically decreasing one, and vice versa. 8706 bool IncreasingSwapped; 8707 bool ResultSwapped = isMonotonicPredicateImpl( 8708 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8709 8710 assert(Result == ResultSwapped && "should be able to analyze both!"); 8711 if (ResultSwapped) 8712 assert(Increasing == !IncreasingSwapped && 8713 "monotonicity should flip as we flip the predicate"); 8714 #endif 8715 8716 return Result; 8717 } 8718 8719 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8720 ICmpInst::Predicate Pred, 8721 bool &Increasing) { 8722 8723 // A zero step value for LHS means the induction variable is essentially a 8724 // loop invariant value. We don't really depend on the predicate actually 8725 // flipping from false to true (for increasing predicates, and the other way 8726 // around for decreasing predicates), all we care about is that *if* the 8727 // predicate changes then it only changes from false to true. 8728 // 8729 // A zero step value in itself is not very useful, but there may be places 8730 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8731 // as general as possible. 8732 8733 switch (Pred) { 8734 default: 8735 return false; // Conservative answer 8736 8737 case ICmpInst::ICMP_UGT: 8738 case ICmpInst::ICMP_UGE: 8739 case ICmpInst::ICMP_ULT: 8740 case ICmpInst::ICMP_ULE: 8741 if (!LHS->hasNoUnsignedWrap()) 8742 return false; 8743 8744 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8745 return true; 8746 8747 case ICmpInst::ICMP_SGT: 8748 case ICmpInst::ICMP_SGE: 8749 case ICmpInst::ICMP_SLT: 8750 case ICmpInst::ICMP_SLE: { 8751 if (!LHS->hasNoSignedWrap()) 8752 return false; 8753 8754 const SCEV *Step = LHS->getStepRecurrence(*this); 8755 8756 if (isKnownNonNegative(Step)) { 8757 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8758 return true; 8759 } 8760 8761 if (isKnownNonPositive(Step)) { 8762 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8763 return true; 8764 } 8765 8766 return false; 8767 } 8768 8769 } 8770 8771 llvm_unreachable("switch has default clause!"); 8772 } 8773 8774 bool ScalarEvolution::isLoopInvariantPredicate( 8775 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8776 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8777 const SCEV *&InvariantRHS) { 8778 8779 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8780 if (!isLoopInvariant(RHS, L)) { 8781 if (!isLoopInvariant(LHS, L)) 8782 return false; 8783 8784 std::swap(LHS, RHS); 8785 Pred = ICmpInst::getSwappedPredicate(Pred); 8786 } 8787 8788 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8789 if (!ArLHS || ArLHS->getLoop() != L) 8790 return false; 8791 8792 bool Increasing; 8793 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8794 return false; 8795 8796 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8797 // true as the loop iterates, and the backedge is control dependent on 8798 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8799 // 8800 // * if the predicate was false in the first iteration then the predicate 8801 // is never evaluated again, since the loop exits without taking the 8802 // backedge. 8803 // * if the predicate was true in the first iteration then it will 8804 // continue to be true for all future iterations since it is 8805 // monotonically increasing. 8806 // 8807 // For both the above possibilities, we can replace the loop varying 8808 // predicate with its value on the first iteration of the loop (which is 8809 // loop invariant). 8810 // 8811 // A similar reasoning applies for a monotonically decreasing predicate, by 8812 // replacing true with false and false with true in the above two bullets. 8813 8814 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8815 8816 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8817 return false; 8818 8819 InvariantPred = Pred; 8820 InvariantLHS = ArLHS->getStart(); 8821 InvariantRHS = RHS; 8822 return true; 8823 } 8824 8825 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8826 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8827 if (HasSameValue(LHS, RHS)) 8828 return ICmpInst::isTrueWhenEqual(Pred); 8829 8830 // This code is split out from isKnownPredicate because it is called from 8831 // within isLoopEntryGuardedByCond. 8832 8833 auto CheckRanges = 8834 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8835 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8836 .contains(RangeLHS); 8837 }; 8838 8839 // The check at the top of the function catches the case where the values are 8840 // known to be equal. 8841 if (Pred == CmpInst::ICMP_EQ) 8842 return false; 8843 8844 if (Pred == CmpInst::ICMP_NE) 8845 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8846 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8847 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8848 8849 if (CmpInst::isSigned(Pred)) 8850 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8851 8852 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8853 } 8854 8855 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8856 const SCEV *LHS, 8857 const SCEV *RHS) { 8858 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8859 // Return Y via OutY. 8860 auto MatchBinaryAddToConst = 8861 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8862 SCEV::NoWrapFlags ExpectedFlags) { 8863 const SCEV *NonConstOp, *ConstOp; 8864 SCEV::NoWrapFlags FlagsPresent; 8865 8866 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8867 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8868 return false; 8869 8870 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8871 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8872 }; 8873 8874 APInt C; 8875 8876 switch (Pred) { 8877 default: 8878 break; 8879 8880 case ICmpInst::ICMP_SGE: 8881 std::swap(LHS, RHS); 8882 LLVM_FALLTHROUGH; 8883 case ICmpInst::ICMP_SLE: 8884 // X s<= (X + C)<nsw> if C >= 0 8885 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8886 return true; 8887 8888 // (X + C)<nsw> s<= X if C <= 0 8889 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8890 !C.isStrictlyPositive()) 8891 return true; 8892 break; 8893 8894 case ICmpInst::ICMP_SGT: 8895 std::swap(LHS, RHS); 8896 LLVM_FALLTHROUGH; 8897 case ICmpInst::ICMP_SLT: 8898 // X s< (X + C)<nsw> if C > 0 8899 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8900 C.isStrictlyPositive()) 8901 return true; 8902 8903 // (X + C)<nsw> s< X if C < 0 8904 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8905 return true; 8906 break; 8907 } 8908 8909 return false; 8910 } 8911 8912 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8913 const SCEV *LHS, 8914 const SCEV *RHS) { 8915 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8916 return false; 8917 8918 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8919 // the stack can result in exponential time complexity. 8920 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8921 8922 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8923 // 8924 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8925 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8926 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8927 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8928 // use isKnownPredicate later if needed. 8929 return isKnownNonNegative(RHS) && 8930 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8931 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8932 } 8933 8934 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8935 ICmpInst::Predicate Pred, 8936 const SCEV *LHS, const SCEV *RHS) { 8937 // No need to even try if we know the module has no guards. 8938 if (!HasGuards) 8939 return false; 8940 8941 return any_of(*BB, [&](Instruction &I) { 8942 using namespace llvm::PatternMatch; 8943 8944 Value *Condition; 8945 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8946 m_Value(Condition))) && 8947 isImpliedCond(Pred, LHS, RHS, Condition, false); 8948 }); 8949 } 8950 8951 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8952 /// protected by a conditional between LHS and RHS. This is used to 8953 /// to eliminate casts. 8954 bool 8955 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8956 ICmpInst::Predicate Pred, 8957 const SCEV *LHS, const SCEV *RHS) { 8958 // Interpret a null as meaning no loop, where there is obviously no guard 8959 // (interprocedural conditions notwithstanding). 8960 if (!L) return true; 8961 8962 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8963 return true; 8964 8965 BasicBlock *Latch = L->getLoopLatch(); 8966 if (!Latch) 8967 return false; 8968 8969 BranchInst *LoopContinuePredicate = 8970 dyn_cast<BranchInst>(Latch->getTerminator()); 8971 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8972 isImpliedCond(Pred, LHS, RHS, 8973 LoopContinuePredicate->getCondition(), 8974 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8975 return true; 8976 8977 // We don't want more than one activation of the following loops on the stack 8978 // -- that can lead to O(n!) time complexity. 8979 if (WalkingBEDominatingConds) 8980 return false; 8981 8982 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8983 8984 // See if we can exploit a trip count to prove the predicate. 8985 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8986 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8987 if (LatchBECount != getCouldNotCompute()) { 8988 // We know that Latch branches back to the loop header exactly 8989 // LatchBECount times. This means the backdege condition at Latch is 8990 // equivalent to "{0,+,1} u< LatchBECount". 8991 Type *Ty = LatchBECount->getType(); 8992 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8993 const SCEV *LoopCounter = 8994 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8995 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8996 LatchBECount)) 8997 return true; 8998 } 8999 9000 // Check conditions due to any @llvm.assume intrinsics. 9001 for (auto &AssumeVH : AC.assumptions()) { 9002 if (!AssumeVH) 9003 continue; 9004 auto *CI = cast<CallInst>(AssumeVH); 9005 if (!DT.dominates(CI, Latch->getTerminator())) 9006 continue; 9007 9008 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9009 return true; 9010 } 9011 9012 // If the loop is not reachable from the entry block, we risk running into an 9013 // infinite loop as we walk up into the dom tree. These loops do not matter 9014 // anyway, so we just return a conservative answer when we see them. 9015 if (!DT.isReachableFromEntry(L->getHeader())) 9016 return false; 9017 9018 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9019 return true; 9020 9021 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9022 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9023 assert(DTN && "should reach the loop header before reaching the root!"); 9024 9025 BasicBlock *BB = DTN->getBlock(); 9026 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9027 return true; 9028 9029 BasicBlock *PBB = BB->getSinglePredecessor(); 9030 if (!PBB) 9031 continue; 9032 9033 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9034 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9035 continue; 9036 9037 Value *Condition = ContinuePredicate->getCondition(); 9038 9039 // If we have an edge `E` within the loop body that dominates the only 9040 // latch, the condition guarding `E` also guards the backedge. This 9041 // reasoning works only for loops with a single latch. 9042 9043 BasicBlockEdge DominatingEdge(PBB, BB); 9044 if (DominatingEdge.isSingleEdge()) { 9045 // We're constructively (and conservatively) enumerating edges within the 9046 // loop body that dominate the latch. The dominator tree better agree 9047 // with us on this: 9048 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9049 9050 if (isImpliedCond(Pred, LHS, RHS, Condition, 9051 BB != ContinuePredicate->getSuccessor(0))) 9052 return true; 9053 } 9054 } 9055 9056 return false; 9057 } 9058 9059 bool 9060 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9061 ICmpInst::Predicate Pred, 9062 const SCEV *LHS, const SCEV *RHS) { 9063 // Interpret a null as meaning no loop, where there is obviously no guard 9064 // (interprocedural conditions notwithstanding). 9065 if (!L) return false; 9066 9067 // Both LHS and RHS must be available at loop entry. 9068 assert(isAvailableAtLoopEntry(LHS, L) && 9069 "LHS is not available at Loop Entry"); 9070 assert(isAvailableAtLoopEntry(RHS, L) && 9071 "RHS is not available at Loop Entry"); 9072 9073 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 9074 return true; 9075 9076 // Starting at the loop predecessor, climb up the predecessor chain, as long 9077 // as there are predecessors that can be found that have unique successors 9078 // leading to the original header. 9079 for (std::pair<BasicBlock *, BasicBlock *> 9080 Pair(L->getLoopPredecessor(), L->getHeader()); 9081 Pair.first; 9082 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9083 9084 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 9085 return true; 9086 9087 BranchInst *LoopEntryPredicate = 9088 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9089 if (!LoopEntryPredicate || 9090 LoopEntryPredicate->isUnconditional()) 9091 continue; 9092 9093 if (isImpliedCond(Pred, LHS, RHS, 9094 LoopEntryPredicate->getCondition(), 9095 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9096 return true; 9097 } 9098 9099 // Check conditions due to any @llvm.assume intrinsics. 9100 for (auto &AssumeVH : AC.assumptions()) { 9101 if (!AssumeVH) 9102 continue; 9103 auto *CI = cast<CallInst>(AssumeVH); 9104 if (!DT.dominates(CI, L->getHeader())) 9105 continue; 9106 9107 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9108 return true; 9109 } 9110 9111 return false; 9112 } 9113 9114 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9115 const SCEV *LHS, const SCEV *RHS, 9116 Value *FoundCondValue, 9117 bool Inverse) { 9118 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9119 return false; 9120 9121 auto ClearOnExit = 9122 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9123 9124 // Recursively handle And and Or conditions. 9125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9126 if (BO->getOpcode() == Instruction::And) { 9127 if (!Inverse) 9128 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9129 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9130 } else if (BO->getOpcode() == Instruction::Or) { 9131 if (Inverse) 9132 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9133 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9134 } 9135 } 9136 9137 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9138 if (!ICI) return false; 9139 9140 // Now that we found a conditional branch that dominates the loop or controls 9141 // the loop latch. Check to see if it is the comparison we are looking for. 9142 ICmpInst::Predicate FoundPred; 9143 if (Inverse) 9144 FoundPred = ICI->getInversePredicate(); 9145 else 9146 FoundPred = ICI->getPredicate(); 9147 9148 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9149 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9150 9151 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9152 } 9153 9154 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9155 const SCEV *RHS, 9156 ICmpInst::Predicate FoundPred, 9157 const SCEV *FoundLHS, 9158 const SCEV *FoundRHS) { 9159 // Balance the types. 9160 if (getTypeSizeInBits(LHS->getType()) < 9161 getTypeSizeInBits(FoundLHS->getType())) { 9162 if (CmpInst::isSigned(Pred)) { 9163 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9164 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9165 } else { 9166 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9167 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9168 } 9169 } else if (getTypeSizeInBits(LHS->getType()) > 9170 getTypeSizeInBits(FoundLHS->getType())) { 9171 if (CmpInst::isSigned(FoundPred)) { 9172 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9173 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9174 } else { 9175 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9176 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9177 } 9178 } 9179 9180 // Canonicalize the query to match the way instcombine will have 9181 // canonicalized the comparison. 9182 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9183 if (LHS == RHS) 9184 return CmpInst::isTrueWhenEqual(Pred); 9185 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9186 if (FoundLHS == FoundRHS) 9187 return CmpInst::isFalseWhenEqual(FoundPred); 9188 9189 // Check to see if we can make the LHS or RHS match. 9190 if (LHS == FoundRHS || RHS == FoundLHS) { 9191 if (isa<SCEVConstant>(RHS)) { 9192 std::swap(FoundLHS, FoundRHS); 9193 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9194 } else { 9195 std::swap(LHS, RHS); 9196 Pred = ICmpInst::getSwappedPredicate(Pred); 9197 } 9198 } 9199 9200 // Check whether the found predicate is the same as the desired predicate. 9201 if (FoundPred == Pred) 9202 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9203 9204 // Check whether swapping the found predicate makes it the same as the 9205 // desired predicate. 9206 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9207 if (isa<SCEVConstant>(RHS)) 9208 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9209 else 9210 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9211 RHS, LHS, FoundLHS, FoundRHS); 9212 } 9213 9214 // Unsigned comparison is the same as signed comparison when both the operands 9215 // are non-negative. 9216 if (CmpInst::isUnsigned(FoundPred) && 9217 CmpInst::getSignedPredicate(FoundPred) == Pred && 9218 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9219 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9220 9221 // Check if we can make progress by sharpening ranges. 9222 if (FoundPred == ICmpInst::ICMP_NE && 9223 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9224 9225 const SCEVConstant *C = nullptr; 9226 const SCEV *V = nullptr; 9227 9228 if (isa<SCEVConstant>(FoundLHS)) { 9229 C = cast<SCEVConstant>(FoundLHS); 9230 V = FoundRHS; 9231 } else { 9232 C = cast<SCEVConstant>(FoundRHS); 9233 V = FoundLHS; 9234 } 9235 9236 // The guarding predicate tells us that C != V. If the known range 9237 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9238 // range we consider has to correspond to same signedness as the 9239 // predicate we're interested in folding. 9240 9241 APInt Min = ICmpInst::isSigned(Pred) ? 9242 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9243 9244 if (Min == C->getAPInt()) { 9245 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9246 // This is true even if (Min + 1) wraps around -- in case of 9247 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9248 9249 APInt SharperMin = Min + 1; 9250 9251 switch (Pred) { 9252 case ICmpInst::ICMP_SGE: 9253 case ICmpInst::ICMP_UGE: 9254 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9255 // RHS, we're done. 9256 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9257 getConstant(SharperMin))) 9258 return true; 9259 LLVM_FALLTHROUGH; 9260 9261 case ICmpInst::ICMP_SGT: 9262 case ICmpInst::ICMP_UGT: 9263 // We know from the range information that (V `Pred` Min || 9264 // V == Min). We know from the guarding condition that !(V 9265 // == Min). This gives us 9266 // 9267 // V `Pred` Min || V == Min && !(V == Min) 9268 // => V `Pred` Min 9269 // 9270 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9271 9272 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9273 return true; 9274 LLVM_FALLTHROUGH; 9275 9276 default: 9277 // No change 9278 break; 9279 } 9280 } 9281 } 9282 9283 // Check whether the actual condition is beyond sufficient. 9284 if (FoundPred == ICmpInst::ICMP_EQ) 9285 if (ICmpInst::isTrueWhenEqual(Pred)) 9286 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9287 return true; 9288 if (Pred == ICmpInst::ICMP_NE) 9289 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9290 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9291 return true; 9292 9293 // Otherwise assume the worst. 9294 return false; 9295 } 9296 9297 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9298 const SCEV *&L, const SCEV *&R, 9299 SCEV::NoWrapFlags &Flags) { 9300 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9301 if (!AE || AE->getNumOperands() != 2) 9302 return false; 9303 9304 L = AE->getOperand(0); 9305 R = AE->getOperand(1); 9306 Flags = AE->getNoWrapFlags(); 9307 return true; 9308 } 9309 9310 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9311 const SCEV *Less) { 9312 // We avoid subtracting expressions here because this function is usually 9313 // fairly deep in the call stack (i.e. is called many times). 9314 9315 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9316 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9317 const auto *MAR = cast<SCEVAddRecExpr>(More); 9318 9319 if (LAR->getLoop() != MAR->getLoop()) 9320 return None; 9321 9322 // We look at affine expressions only; not for correctness but to keep 9323 // getStepRecurrence cheap. 9324 if (!LAR->isAffine() || !MAR->isAffine()) 9325 return None; 9326 9327 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9328 return None; 9329 9330 Less = LAR->getStart(); 9331 More = MAR->getStart(); 9332 9333 // fall through 9334 } 9335 9336 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9337 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9338 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9339 return M - L; 9340 } 9341 9342 const SCEV *L, *R; 9343 SCEV::NoWrapFlags Flags; 9344 if (splitBinaryAdd(Less, L, R, Flags)) 9345 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9346 if (R == More) 9347 return -(LC->getAPInt()); 9348 9349 if (splitBinaryAdd(More, L, R, Flags)) 9350 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9351 if (R == Less) 9352 return LC->getAPInt(); 9353 9354 return None; 9355 } 9356 9357 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9358 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9359 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9360 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9361 return false; 9362 9363 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9364 if (!AddRecLHS) 9365 return false; 9366 9367 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9368 if (!AddRecFoundLHS) 9369 return false; 9370 9371 // We'd like to let SCEV reason about control dependencies, so we constrain 9372 // both the inequalities to be about add recurrences on the same loop. This 9373 // way we can use isLoopEntryGuardedByCond later. 9374 9375 const Loop *L = AddRecFoundLHS->getLoop(); 9376 if (L != AddRecLHS->getLoop()) 9377 return false; 9378 9379 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9380 // 9381 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9382 // ... (2) 9383 // 9384 // Informal proof for (2), assuming (1) [*]: 9385 // 9386 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9387 // 9388 // Then 9389 // 9390 // FoundLHS s< FoundRHS s< INT_MIN - C 9391 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9392 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9393 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9394 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9395 // <=> FoundLHS + C s< FoundRHS + C 9396 // 9397 // [*]: (1) can be proved by ruling out overflow. 9398 // 9399 // [**]: This can be proved by analyzing all the four possibilities: 9400 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9401 // (A s>= 0, B s>= 0). 9402 // 9403 // Note: 9404 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9405 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9406 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9407 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9408 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9409 // C)". 9410 9411 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9412 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9413 if (!LDiff || !RDiff || *LDiff != *RDiff) 9414 return false; 9415 9416 if (LDiff->isMinValue()) 9417 return true; 9418 9419 APInt FoundRHSLimit; 9420 9421 if (Pred == CmpInst::ICMP_ULT) { 9422 FoundRHSLimit = -(*RDiff); 9423 } else { 9424 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9425 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9426 } 9427 9428 // Try to prove (1) or (2), as needed. 9429 return isAvailableAtLoopEntry(FoundRHS, L) && 9430 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9431 getConstant(FoundRHSLimit)); 9432 } 9433 9434 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9435 const SCEV *LHS, const SCEV *RHS, 9436 const SCEV *FoundLHS, 9437 const SCEV *FoundRHS) { 9438 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9439 return true; 9440 9441 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9442 return true; 9443 9444 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9445 FoundLHS, FoundRHS) || 9446 // ~x < ~y --> x > y 9447 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9448 getNotSCEV(FoundRHS), 9449 getNotSCEV(FoundLHS)); 9450 } 9451 9452 /// If Expr computes ~A, return A else return nullptr 9453 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9454 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9455 if (!Add || Add->getNumOperands() != 2 || 9456 !Add->getOperand(0)->isAllOnesValue()) 9457 return nullptr; 9458 9459 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9460 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9461 !AddRHS->getOperand(0)->isAllOnesValue()) 9462 return nullptr; 9463 9464 return AddRHS->getOperand(1); 9465 } 9466 9467 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9468 template<typename MaxExprType> 9469 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9470 const SCEV *Candidate) { 9471 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9472 if (!MaxExpr) return false; 9473 9474 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9475 } 9476 9477 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9478 template<typename MaxExprType> 9479 static bool IsMinConsistingOf(ScalarEvolution &SE, 9480 const SCEV *MaybeMinExpr, 9481 const SCEV *Candidate) { 9482 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9483 if (!MaybeMaxExpr) 9484 return false; 9485 9486 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9487 } 9488 9489 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9490 ICmpInst::Predicate Pred, 9491 const SCEV *LHS, const SCEV *RHS) { 9492 // If both sides are affine addrecs for the same loop, with equal 9493 // steps, and we know the recurrences don't wrap, then we only 9494 // need to check the predicate on the starting values. 9495 9496 if (!ICmpInst::isRelational(Pred)) 9497 return false; 9498 9499 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9500 if (!LAR) 9501 return false; 9502 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9503 if (!RAR) 9504 return false; 9505 if (LAR->getLoop() != RAR->getLoop()) 9506 return false; 9507 if (!LAR->isAffine() || !RAR->isAffine()) 9508 return false; 9509 9510 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9511 return false; 9512 9513 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9514 SCEV::FlagNSW : SCEV::FlagNUW; 9515 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9516 return false; 9517 9518 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9519 } 9520 9521 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9522 /// expression? 9523 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9524 ICmpInst::Predicate Pred, 9525 const SCEV *LHS, const SCEV *RHS) { 9526 switch (Pred) { 9527 default: 9528 return false; 9529 9530 case ICmpInst::ICMP_SGE: 9531 std::swap(LHS, RHS); 9532 LLVM_FALLTHROUGH; 9533 case ICmpInst::ICMP_SLE: 9534 return 9535 // min(A, ...) <= A 9536 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9537 // A <= max(A, ...) 9538 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9539 9540 case ICmpInst::ICMP_UGE: 9541 std::swap(LHS, RHS); 9542 LLVM_FALLTHROUGH; 9543 case ICmpInst::ICMP_ULE: 9544 return 9545 // min(A, ...) <= A 9546 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9547 // A <= max(A, ...) 9548 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9549 } 9550 9551 llvm_unreachable("covered switch fell through?!"); 9552 } 9553 9554 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9555 const SCEV *LHS, const SCEV *RHS, 9556 const SCEV *FoundLHS, 9557 const SCEV *FoundRHS, 9558 unsigned Depth) { 9559 assert(getTypeSizeInBits(LHS->getType()) == 9560 getTypeSizeInBits(RHS->getType()) && 9561 "LHS and RHS have different sizes?"); 9562 assert(getTypeSizeInBits(FoundLHS->getType()) == 9563 getTypeSizeInBits(FoundRHS->getType()) && 9564 "FoundLHS and FoundRHS have different sizes?"); 9565 // We want to avoid hurting the compile time with analysis of too big trees. 9566 if (Depth > MaxSCEVOperationsImplicationDepth) 9567 return false; 9568 // We only want to work with ICMP_SGT comparison so far. 9569 // TODO: Extend to ICMP_UGT? 9570 if (Pred == ICmpInst::ICMP_SLT) { 9571 Pred = ICmpInst::ICMP_SGT; 9572 std::swap(LHS, RHS); 9573 std::swap(FoundLHS, FoundRHS); 9574 } 9575 if (Pred != ICmpInst::ICMP_SGT) 9576 return false; 9577 9578 auto GetOpFromSExt = [&](const SCEV *S) { 9579 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9580 return Ext->getOperand(); 9581 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9582 // the constant in some cases. 9583 return S; 9584 }; 9585 9586 // Acquire values from extensions. 9587 auto *OrigFoundLHS = FoundLHS; 9588 LHS = GetOpFromSExt(LHS); 9589 FoundLHS = GetOpFromSExt(FoundLHS); 9590 9591 // Is the SGT predicate can be proved trivially or using the found context. 9592 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9593 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9594 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9595 FoundRHS, Depth + 1); 9596 }; 9597 9598 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9599 // We want to avoid creation of any new non-constant SCEV. Since we are 9600 // going to compare the operands to RHS, we should be certain that we don't 9601 // need any size extensions for this. So let's decline all cases when the 9602 // sizes of types of LHS and RHS do not match. 9603 // TODO: Maybe try to get RHS from sext to catch more cases? 9604 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9605 return false; 9606 9607 // Should not overflow. 9608 if (!LHSAddExpr->hasNoSignedWrap()) 9609 return false; 9610 9611 auto *LL = LHSAddExpr->getOperand(0); 9612 auto *LR = LHSAddExpr->getOperand(1); 9613 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9614 9615 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9616 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9617 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9618 }; 9619 // Try to prove the following rule: 9620 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9621 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9622 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9623 return true; 9624 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9625 Value *LL, *LR; 9626 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9627 9628 using namespace llvm::PatternMatch; 9629 9630 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9631 // Rules for division. 9632 // We are going to perform some comparisons with Denominator and its 9633 // derivative expressions. In general case, creating a SCEV for it may 9634 // lead to a complex analysis of the entire graph, and in particular it 9635 // can request trip count recalculation for the same loop. This would 9636 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9637 // this, we only want to create SCEVs that are constants in this section. 9638 // So we bail if Denominator is not a constant. 9639 if (!isa<ConstantInt>(LR)) 9640 return false; 9641 9642 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9643 9644 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9645 // then a SCEV for the numerator already exists and matches with FoundLHS. 9646 auto *Numerator = getExistingSCEV(LL); 9647 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9648 return false; 9649 9650 // Make sure that the numerator matches with FoundLHS and the denominator 9651 // is positive. 9652 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9653 return false; 9654 9655 auto *DTy = Denominator->getType(); 9656 auto *FRHSTy = FoundRHS->getType(); 9657 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9658 // One of types is a pointer and another one is not. We cannot extend 9659 // them properly to a wider type, so let us just reject this case. 9660 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9661 // to avoid this check. 9662 return false; 9663 9664 // Given that: 9665 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9666 auto *WTy = getWiderType(DTy, FRHSTy); 9667 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9668 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9669 9670 // Try to prove the following rule: 9671 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9672 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9673 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9674 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9675 if (isKnownNonPositive(RHS) && 9676 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9677 return true; 9678 9679 // Try to prove the following rule: 9680 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9681 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9682 // If we divide it by Denominator > 2, then: 9683 // 1. If FoundLHS is negative, then the result is 0. 9684 // 2. If FoundLHS is non-negative, then the result is non-negative. 9685 // Anyways, the result is non-negative. 9686 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9687 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9688 if (isKnownNegative(RHS) && 9689 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9690 return true; 9691 } 9692 } 9693 9694 return false; 9695 } 9696 9697 bool 9698 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 9699 const SCEV *LHS, const SCEV *RHS) { 9700 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9701 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9702 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9703 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9704 } 9705 9706 bool 9707 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9708 const SCEV *LHS, const SCEV *RHS, 9709 const SCEV *FoundLHS, 9710 const SCEV *FoundRHS) { 9711 switch (Pred) { 9712 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9713 case ICmpInst::ICMP_EQ: 9714 case ICmpInst::ICMP_NE: 9715 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9716 return true; 9717 break; 9718 case ICmpInst::ICMP_SLT: 9719 case ICmpInst::ICMP_SLE: 9720 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9721 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9722 return true; 9723 break; 9724 case ICmpInst::ICMP_SGT: 9725 case ICmpInst::ICMP_SGE: 9726 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9727 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9728 return true; 9729 break; 9730 case ICmpInst::ICMP_ULT: 9731 case ICmpInst::ICMP_ULE: 9732 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9733 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9734 return true; 9735 break; 9736 case ICmpInst::ICMP_UGT: 9737 case ICmpInst::ICMP_UGE: 9738 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9739 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9740 return true; 9741 break; 9742 } 9743 9744 // Maybe it can be proved via operations? 9745 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9746 return true; 9747 9748 return false; 9749 } 9750 9751 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9752 const SCEV *LHS, 9753 const SCEV *RHS, 9754 const SCEV *FoundLHS, 9755 const SCEV *FoundRHS) { 9756 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9757 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9758 // reduce the compile time impact of this optimization. 9759 return false; 9760 9761 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9762 if (!Addend) 9763 return false; 9764 9765 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9766 9767 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9768 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9769 ConstantRange FoundLHSRange = 9770 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9771 9772 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9773 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9774 9775 // We can also compute the range of values for `LHS` that satisfy the 9776 // consequent, "`LHS` `Pred` `RHS`": 9777 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9778 ConstantRange SatisfyingLHSRange = 9779 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9780 9781 // The antecedent implies the consequent if every value of `LHS` that 9782 // satisfies the antecedent also satisfies the consequent. 9783 return SatisfyingLHSRange.contains(LHSRange); 9784 } 9785 9786 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9787 bool IsSigned, bool NoWrap) { 9788 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9789 9790 if (NoWrap) return false; 9791 9792 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9793 const SCEV *One = getOne(Stride->getType()); 9794 9795 if (IsSigned) { 9796 APInt MaxRHS = getSignedRangeMax(RHS); 9797 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9798 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9799 9800 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9801 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9802 } 9803 9804 APInt MaxRHS = getUnsignedRangeMax(RHS); 9805 APInt MaxValue = APInt::getMaxValue(BitWidth); 9806 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9807 9808 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9809 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9810 } 9811 9812 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9813 bool IsSigned, bool NoWrap) { 9814 if (NoWrap) return false; 9815 9816 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9817 const SCEV *One = getOne(Stride->getType()); 9818 9819 if (IsSigned) { 9820 APInt MinRHS = getSignedRangeMin(RHS); 9821 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9822 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9823 9824 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9825 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9826 } 9827 9828 APInt MinRHS = getUnsignedRangeMin(RHS); 9829 APInt MinValue = APInt::getMinValue(BitWidth); 9830 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9831 9832 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9833 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9834 } 9835 9836 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9837 bool Equality) { 9838 const SCEV *One = getOne(Step->getType()); 9839 Delta = Equality ? getAddExpr(Delta, Step) 9840 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9841 return getUDivExpr(Delta, Step); 9842 } 9843 9844 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 9845 const SCEV *Stride, 9846 const SCEV *End, 9847 unsigned BitWidth, 9848 bool IsSigned) { 9849 9850 assert(!isKnownNonPositive(Stride) && 9851 "Stride is expected strictly positive!"); 9852 // Calculate the maximum backedge count based on the range of values 9853 // permitted by Start, End, and Stride. 9854 const SCEV *MaxBECount; 9855 APInt MinStart = 9856 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 9857 9858 APInt StrideForMaxBECount = 9859 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 9860 9861 // We already know that the stride is positive, so we paper over conservatism 9862 // in our range computation by forcing StrideForMaxBECount to be at least one. 9863 // In theory this is unnecessary, but we expect MaxBECount to be a 9864 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 9865 // is nothing to constant fold it to). 9866 APInt One(BitWidth, 1, IsSigned); 9867 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 9868 9869 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 9870 : APInt::getMaxValue(BitWidth); 9871 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 9872 9873 // Although End can be a MAX expression we estimate MaxEnd considering only 9874 // the case End = RHS of the loop termination condition. This is safe because 9875 // in the other case (End - Start) is zero, leading to a zero maximum backedge 9876 // taken count. 9877 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 9878 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 9879 9880 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 9881 getConstant(StrideForMaxBECount) /* Step */, 9882 false /* Equality */); 9883 9884 return MaxBECount; 9885 } 9886 9887 ScalarEvolution::ExitLimit 9888 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9889 const Loop *L, bool IsSigned, 9890 bool ControlsExit, bool AllowPredicates) { 9891 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9892 9893 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9894 bool PredicatedIV = false; 9895 9896 if (!IV && AllowPredicates) { 9897 // Try to make this an AddRec using runtime tests, in the first X 9898 // iterations of this loop, where X is the SCEV expression found by the 9899 // algorithm below. 9900 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9901 PredicatedIV = true; 9902 } 9903 9904 // Avoid weird loops 9905 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9906 return getCouldNotCompute(); 9907 9908 bool NoWrap = ControlsExit && 9909 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9910 9911 const SCEV *Stride = IV->getStepRecurrence(*this); 9912 9913 bool PositiveStride = isKnownPositive(Stride); 9914 9915 // Avoid negative or zero stride values. 9916 if (!PositiveStride) { 9917 // We can compute the correct backedge taken count for loops with unknown 9918 // strides if we can prove that the loop is not an infinite loop with side 9919 // effects. Here's the loop structure we are trying to handle - 9920 // 9921 // i = start 9922 // do { 9923 // A[i] = i; 9924 // i += s; 9925 // } while (i < end); 9926 // 9927 // The backedge taken count for such loops is evaluated as - 9928 // (max(end, start + stride) - start - 1) /u stride 9929 // 9930 // The additional preconditions that we need to check to prove correctness 9931 // of the above formula is as follows - 9932 // 9933 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9934 // NoWrap flag). 9935 // b) loop is single exit with no side effects. 9936 // 9937 // 9938 // Precondition a) implies that if the stride is negative, this is a single 9939 // trip loop. The backedge taken count formula reduces to zero in this case. 9940 // 9941 // Precondition b) implies that the unknown stride cannot be zero otherwise 9942 // we have UB. 9943 // 9944 // The positive stride case is the same as isKnownPositive(Stride) returning 9945 // true (original behavior of the function). 9946 // 9947 // We want to make sure that the stride is truly unknown as there are edge 9948 // cases where ScalarEvolution propagates no wrap flags to the 9949 // post-increment/decrement IV even though the increment/decrement operation 9950 // itself is wrapping. The computed backedge taken count may be wrong in 9951 // such cases. This is prevented by checking that the stride is not known to 9952 // be either positive or non-positive. For example, no wrap flags are 9953 // propagated to the post-increment IV of this loop with a trip count of 2 - 9954 // 9955 // unsigned char i; 9956 // for(i=127; i<128; i+=129) 9957 // A[i] = i; 9958 // 9959 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9960 !loopHasNoSideEffects(L)) 9961 return getCouldNotCompute(); 9962 } else if (!Stride->isOne() && 9963 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9964 // Avoid proven overflow cases: this will ensure that the backedge taken 9965 // count will not generate any unsigned overflow. Relaxed no-overflow 9966 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9967 // undefined behaviors like the case of C language. 9968 return getCouldNotCompute(); 9969 9970 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9971 : ICmpInst::ICMP_ULT; 9972 const SCEV *Start = IV->getStart(); 9973 const SCEV *End = RHS; 9974 // When the RHS is not invariant, we do not know the end bound of the loop and 9975 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 9976 // calculate the MaxBECount, given the start, stride and max value for the end 9977 // bound of the loop (RHS), and the fact that IV does not overflow (which is 9978 // checked above). 9979 if (!isLoopInvariant(RHS, L)) { 9980 const SCEV *MaxBECount = computeMaxBECountForLT( 9981 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 9982 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 9983 false /*MaxOrZero*/, Predicates); 9984 } 9985 // If the backedge is taken at least once, then it will be taken 9986 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9987 // is the LHS value of the less-than comparison the first time it is evaluated 9988 // and End is the RHS. 9989 const SCEV *BECountIfBackedgeTaken = 9990 computeBECount(getMinusSCEV(End, Start), Stride, false); 9991 // If the loop entry is guarded by the result of the backedge test of the 9992 // first loop iteration, then we know the backedge will be taken at least 9993 // once and so the backedge taken count is as above. If not then we use the 9994 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9995 // as if the backedge is taken at least once max(End,Start) is End and so the 9996 // result is as above, and if not max(End,Start) is Start so we get a backedge 9997 // count of zero. 9998 const SCEV *BECount; 9999 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10000 BECount = BECountIfBackedgeTaken; 10001 else { 10002 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10003 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10004 } 10005 10006 const SCEV *MaxBECount; 10007 bool MaxOrZero = false; 10008 if (isa<SCEVConstant>(BECount)) 10009 MaxBECount = BECount; 10010 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10011 // If we know exactly how many times the backedge will be taken if it's 10012 // taken at least once, then the backedge count will either be that or 10013 // zero. 10014 MaxBECount = BECountIfBackedgeTaken; 10015 MaxOrZero = true; 10016 } else { 10017 MaxBECount = computeMaxBECountForLT( 10018 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10019 } 10020 10021 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10022 !isa<SCEVCouldNotCompute>(BECount)) 10023 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10024 10025 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10026 } 10027 10028 ScalarEvolution::ExitLimit 10029 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10030 const Loop *L, bool IsSigned, 10031 bool ControlsExit, bool AllowPredicates) { 10032 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10033 // We handle only IV > Invariant 10034 if (!isLoopInvariant(RHS, L)) 10035 return getCouldNotCompute(); 10036 10037 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10038 if (!IV && AllowPredicates) 10039 // Try to make this an AddRec using runtime tests, in the first X 10040 // iterations of this loop, where X is the SCEV expression found by the 10041 // algorithm below. 10042 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10043 10044 // Avoid weird loops 10045 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10046 return getCouldNotCompute(); 10047 10048 bool NoWrap = ControlsExit && 10049 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10050 10051 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10052 10053 // Avoid negative or zero stride values 10054 if (!isKnownPositive(Stride)) 10055 return getCouldNotCompute(); 10056 10057 // Avoid proven overflow cases: this will ensure that the backedge taken count 10058 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10059 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10060 // behaviors like the case of C language. 10061 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10062 return getCouldNotCompute(); 10063 10064 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10065 : ICmpInst::ICMP_UGT; 10066 10067 const SCEV *Start = IV->getStart(); 10068 const SCEV *End = RHS; 10069 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10070 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10071 10072 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10073 10074 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10075 : getUnsignedRangeMax(Start); 10076 10077 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10078 : getUnsignedRangeMin(Stride); 10079 10080 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10081 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10082 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10083 10084 // Although End can be a MIN expression we estimate MinEnd considering only 10085 // the case End = RHS. This is safe because in the other case (Start - End) 10086 // is zero, leading to a zero maximum backedge taken count. 10087 APInt MinEnd = 10088 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10089 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10090 10091 10092 const SCEV *MaxBECount = getCouldNotCompute(); 10093 if (isa<SCEVConstant>(BECount)) 10094 MaxBECount = BECount; 10095 else 10096 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10097 getConstant(MinStride), false); 10098 10099 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10100 MaxBECount = BECount; 10101 10102 return ExitLimit(BECount, MaxBECount, false, Predicates); 10103 } 10104 10105 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10106 ScalarEvolution &SE) const { 10107 if (Range.isFullSet()) // Infinite loop. 10108 return SE.getCouldNotCompute(); 10109 10110 // If the start is a non-zero constant, shift the range to simplify things. 10111 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10112 if (!SC->getValue()->isZero()) { 10113 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10114 Operands[0] = SE.getZero(SC->getType()); 10115 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10116 getNoWrapFlags(FlagNW)); 10117 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10118 return ShiftedAddRec->getNumIterationsInRange( 10119 Range.subtract(SC->getAPInt()), SE); 10120 // This is strange and shouldn't happen. 10121 return SE.getCouldNotCompute(); 10122 } 10123 10124 // The only time we can solve this is when we have all constant indices. 10125 // Otherwise, we cannot determine the overflow conditions. 10126 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10127 return SE.getCouldNotCompute(); 10128 10129 // Okay at this point we know that all elements of the chrec are constants and 10130 // that the start element is zero. 10131 10132 // First check to see if the range contains zero. If not, the first 10133 // iteration exits. 10134 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10135 if (!Range.contains(APInt(BitWidth, 0))) 10136 return SE.getZero(getType()); 10137 10138 if (isAffine()) { 10139 // If this is an affine expression then we have this situation: 10140 // Solve {0,+,A} in Range === Ax in Range 10141 10142 // We know that zero is in the range. If A is positive then we know that 10143 // the upper value of the range must be the first possible exit value. 10144 // If A is negative then the lower of the range is the last possible loop 10145 // value. Also note that we already checked for a full range. 10146 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10147 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10148 10149 // The exit value should be (End+A)/A. 10150 APInt ExitVal = (End + A).udiv(A); 10151 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10152 10153 // Evaluate at the exit value. If we really did fall out of the valid 10154 // range, then we computed our trip count, otherwise wrap around or other 10155 // things must have happened. 10156 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10157 if (Range.contains(Val->getValue())) 10158 return SE.getCouldNotCompute(); // Something strange happened 10159 10160 // Ensure that the previous value is in the range. This is a sanity check. 10161 assert(Range.contains( 10162 EvaluateConstantChrecAtConstant(this, 10163 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10164 "Linear scev computation is off in a bad way!"); 10165 return SE.getConstant(ExitValue); 10166 } else if (isQuadratic()) { 10167 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10168 // quadratic equation to solve it. To do this, we must frame our problem in 10169 // terms of figuring out when zero is crossed, instead of when 10170 // Range.getUpper() is crossed. 10171 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10172 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10173 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10174 10175 // Next, solve the constructed addrec 10176 if (auto Roots = 10177 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10178 const SCEVConstant *R1 = Roots->first; 10179 const SCEVConstant *R2 = Roots->second; 10180 // Pick the smallest positive root value. 10181 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10182 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10183 if (!CB->getZExtValue()) 10184 std::swap(R1, R2); // R1 is the minimum root now. 10185 10186 // Make sure the root is not off by one. The returned iteration should 10187 // not be in the range, but the previous one should be. When solving 10188 // for "X*X < 5", for example, we should not return a root of 2. 10189 ConstantInt *R1Val = 10190 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10191 if (Range.contains(R1Val->getValue())) { 10192 // The next iteration must be out of the range... 10193 ConstantInt *NextVal = 10194 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10195 10196 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10197 if (!Range.contains(R1Val->getValue())) 10198 return SE.getConstant(NextVal); 10199 return SE.getCouldNotCompute(); // Something strange happened 10200 } 10201 10202 // If R1 was not in the range, then it is a good return value. Make 10203 // sure that R1-1 WAS in the range though, just in case. 10204 ConstantInt *NextVal = 10205 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10206 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10207 if (Range.contains(R1Val->getValue())) 10208 return R1; 10209 return SE.getCouldNotCompute(); // Something strange happened 10210 } 10211 } 10212 } 10213 10214 return SE.getCouldNotCompute(); 10215 } 10216 10217 // Return true when S contains at least an undef value. 10218 static inline bool containsUndefs(const SCEV *S) { 10219 return SCEVExprContains(S, [](const SCEV *S) { 10220 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10221 return isa<UndefValue>(SU->getValue()); 10222 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10223 return isa<UndefValue>(SC->getValue()); 10224 return false; 10225 }); 10226 } 10227 10228 namespace { 10229 10230 // Collect all steps of SCEV expressions. 10231 struct SCEVCollectStrides { 10232 ScalarEvolution &SE; 10233 SmallVectorImpl<const SCEV *> &Strides; 10234 10235 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10236 : SE(SE), Strides(S) {} 10237 10238 bool follow(const SCEV *S) { 10239 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10240 Strides.push_back(AR->getStepRecurrence(SE)); 10241 return true; 10242 } 10243 10244 bool isDone() const { return false; } 10245 }; 10246 10247 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10248 struct SCEVCollectTerms { 10249 SmallVectorImpl<const SCEV *> &Terms; 10250 10251 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10252 10253 bool follow(const SCEV *S) { 10254 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10255 isa<SCEVSignExtendExpr>(S)) { 10256 if (!containsUndefs(S)) 10257 Terms.push_back(S); 10258 10259 // Stop recursion: once we collected a term, do not walk its operands. 10260 return false; 10261 } 10262 10263 // Keep looking. 10264 return true; 10265 } 10266 10267 bool isDone() const { return false; } 10268 }; 10269 10270 // Check if a SCEV contains an AddRecExpr. 10271 struct SCEVHasAddRec { 10272 bool &ContainsAddRec; 10273 10274 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10275 ContainsAddRec = false; 10276 } 10277 10278 bool follow(const SCEV *S) { 10279 if (isa<SCEVAddRecExpr>(S)) { 10280 ContainsAddRec = true; 10281 10282 // Stop recursion: once we collected a term, do not walk its operands. 10283 return false; 10284 } 10285 10286 // Keep looking. 10287 return true; 10288 } 10289 10290 bool isDone() const { return false; } 10291 }; 10292 10293 // Find factors that are multiplied with an expression that (possibly as a 10294 // subexpression) contains an AddRecExpr. In the expression: 10295 // 10296 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10297 // 10298 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10299 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10300 // parameters as they form a product with an induction variable. 10301 // 10302 // This collector expects all array size parameters to be in the same MulExpr. 10303 // It might be necessary to later add support for collecting parameters that are 10304 // spread over different nested MulExpr. 10305 struct SCEVCollectAddRecMultiplies { 10306 SmallVectorImpl<const SCEV *> &Terms; 10307 ScalarEvolution &SE; 10308 10309 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10310 : Terms(T), SE(SE) {} 10311 10312 bool follow(const SCEV *S) { 10313 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10314 bool HasAddRec = false; 10315 SmallVector<const SCEV *, 0> Operands; 10316 for (auto Op : Mul->operands()) { 10317 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10318 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10319 Operands.push_back(Op); 10320 } else if (Unknown) { 10321 HasAddRec = true; 10322 } else { 10323 bool ContainsAddRec; 10324 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10325 visitAll(Op, ContiansAddRec); 10326 HasAddRec |= ContainsAddRec; 10327 } 10328 } 10329 if (Operands.size() == 0) 10330 return true; 10331 10332 if (!HasAddRec) 10333 return false; 10334 10335 Terms.push_back(SE.getMulExpr(Operands)); 10336 // Stop recursion: once we collected a term, do not walk its operands. 10337 return false; 10338 } 10339 10340 // Keep looking. 10341 return true; 10342 } 10343 10344 bool isDone() const { return false; } 10345 }; 10346 10347 } // end anonymous namespace 10348 10349 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10350 /// two places: 10351 /// 1) The strides of AddRec expressions. 10352 /// 2) Unknowns that are multiplied with AddRec expressions. 10353 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10354 SmallVectorImpl<const SCEV *> &Terms) { 10355 SmallVector<const SCEV *, 4> Strides; 10356 SCEVCollectStrides StrideCollector(*this, Strides); 10357 visitAll(Expr, StrideCollector); 10358 10359 DEBUG({ 10360 dbgs() << "Strides:\n"; 10361 for (const SCEV *S : Strides) 10362 dbgs() << *S << "\n"; 10363 }); 10364 10365 for (const SCEV *S : Strides) { 10366 SCEVCollectTerms TermCollector(Terms); 10367 visitAll(S, TermCollector); 10368 } 10369 10370 DEBUG({ 10371 dbgs() << "Terms:\n"; 10372 for (const SCEV *T : Terms) 10373 dbgs() << *T << "\n"; 10374 }); 10375 10376 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10377 visitAll(Expr, MulCollector); 10378 } 10379 10380 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10381 SmallVectorImpl<const SCEV *> &Terms, 10382 SmallVectorImpl<const SCEV *> &Sizes) { 10383 int Last = Terms.size() - 1; 10384 const SCEV *Step = Terms[Last]; 10385 10386 // End of recursion. 10387 if (Last == 0) { 10388 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10389 SmallVector<const SCEV *, 2> Qs; 10390 for (const SCEV *Op : M->operands()) 10391 if (!isa<SCEVConstant>(Op)) 10392 Qs.push_back(Op); 10393 10394 Step = SE.getMulExpr(Qs); 10395 } 10396 10397 Sizes.push_back(Step); 10398 return true; 10399 } 10400 10401 for (const SCEV *&Term : Terms) { 10402 // Normalize the terms before the next call to findArrayDimensionsRec. 10403 const SCEV *Q, *R; 10404 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10405 10406 // Bail out when GCD does not evenly divide one of the terms. 10407 if (!R->isZero()) 10408 return false; 10409 10410 Term = Q; 10411 } 10412 10413 // Remove all SCEVConstants. 10414 Terms.erase( 10415 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10416 Terms.end()); 10417 10418 if (Terms.size() > 0) 10419 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10420 return false; 10421 10422 Sizes.push_back(Step); 10423 return true; 10424 } 10425 10426 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10427 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10428 for (const SCEV *T : Terms) 10429 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10430 return true; 10431 return false; 10432 } 10433 10434 // Return the number of product terms in S. 10435 static inline int numberOfTerms(const SCEV *S) { 10436 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10437 return Expr->getNumOperands(); 10438 return 1; 10439 } 10440 10441 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10442 if (isa<SCEVConstant>(T)) 10443 return nullptr; 10444 10445 if (isa<SCEVUnknown>(T)) 10446 return T; 10447 10448 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10449 SmallVector<const SCEV *, 2> Factors; 10450 for (const SCEV *Op : M->operands()) 10451 if (!isa<SCEVConstant>(Op)) 10452 Factors.push_back(Op); 10453 10454 return SE.getMulExpr(Factors); 10455 } 10456 10457 return T; 10458 } 10459 10460 /// Return the size of an element read or written by Inst. 10461 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10462 Type *Ty; 10463 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10464 Ty = Store->getValueOperand()->getType(); 10465 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10466 Ty = Load->getType(); 10467 else 10468 return nullptr; 10469 10470 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10471 return getSizeOfExpr(ETy, Ty); 10472 } 10473 10474 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10475 SmallVectorImpl<const SCEV *> &Sizes, 10476 const SCEV *ElementSize) { 10477 if (Terms.size() < 1 || !ElementSize) 10478 return; 10479 10480 // Early return when Terms do not contain parameters: we do not delinearize 10481 // non parametric SCEVs. 10482 if (!containsParameters(Terms)) 10483 return; 10484 10485 DEBUG({ 10486 dbgs() << "Terms:\n"; 10487 for (const SCEV *T : Terms) 10488 dbgs() << *T << "\n"; 10489 }); 10490 10491 // Remove duplicates. 10492 array_pod_sort(Terms.begin(), Terms.end()); 10493 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10494 10495 // Put larger terms first. 10496 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10497 return numberOfTerms(LHS) > numberOfTerms(RHS); 10498 }); 10499 10500 // Try to divide all terms by the element size. If term is not divisible by 10501 // element size, proceed with the original term. 10502 for (const SCEV *&Term : Terms) { 10503 const SCEV *Q, *R; 10504 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10505 if (!Q->isZero()) 10506 Term = Q; 10507 } 10508 10509 SmallVector<const SCEV *, 4> NewTerms; 10510 10511 // Remove constant factors. 10512 for (const SCEV *T : Terms) 10513 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10514 NewTerms.push_back(NewT); 10515 10516 DEBUG({ 10517 dbgs() << "Terms after sorting:\n"; 10518 for (const SCEV *T : NewTerms) 10519 dbgs() << *T << "\n"; 10520 }); 10521 10522 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10523 Sizes.clear(); 10524 return; 10525 } 10526 10527 // The last element to be pushed into Sizes is the size of an element. 10528 Sizes.push_back(ElementSize); 10529 10530 DEBUG({ 10531 dbgs() << "Sizes:\n"; 10532 for (const SCEV *S : Sizes) 10533 dbgs() << *S << "\n"; 10534 }); 10535 } 10536 10537 void ScalarEvolution::computeAccessFunctions( 10538 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10539 SmallVectorImpl<const SCEV *> &Sizes) { 10540 // Early exit in case this SCEV is not an affine multivariate function. 10541 if (Sizes.empty()) 10542 return; 10543 10544 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10545 if (!AR->isAffine()) 10546 return; 10547 10548 const SCEV *Res = Expr; 10549 int Last = Sizes.size() - 1; 10550 for (int i = Last; i >= 0; i--) { 10551 const SCEV *Q, *R; 10552 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10553 10554 DEBUG({ 10555 dbgs() << "Res: " << *Res << "\n"; 10556 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10557 dbgs() << "Res divided by Sizes[i]:\n"; 10558 dbgs() << "Quotient: " << *Q << "\n"; 10559 dbgs() << "Remainder: " << *R << "\n"; 10560 }); 10561 10562 Res = Q; 10563 10564 // Do not record the last subscript corresponding to the size of elements in 10565 // the array. 10566 if (i == Last) { 10567 10568 // Bail out if the remainder is too complex. 10569 if (isa<SCEVAddRecExpr>(R)) { 10570 Subscripts.clear(); 10571 Sizes.clear(); 10572 return; 10573 } 10574 10575 continue; 10576 } 10577 10578 // Record the access function for the current subscript. 10579 Subscripts.push_back(R); 10580 } 10581 10582 // Also push in last position the remainder of the last division: it will be 10583 // the access function of the innermost dimension. 10584 Subscripts.push_back(Res); 10585 10586 std::reverse(Subscripts.begin(), Subscripts.end()); 10587 10588 DEBUG({ 10589 dbgs() << "Subscripts:\n"; 10590 for (const SCEV *S : Subscripts) 10591 dbgs() << *S << "\n"; 10592 }); 10593 } 10594 10595 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10596 /// sizes of an array access. Returns the remainder of the delinearization that 10597 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10598 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10599 /// expressions in the stride and base of a SCEV corresponding to the 10600 /// computation of a GCD (greatest common divisor) of base and stride. When 10601 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10602 /// 10603 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10604 /// 10605 /// void foo(long n, long m, long o, double A[n][m][o]) { 10606 /// 10607 /// for (long i = 0; i < n; i++) 10608 /// for (long j = 0; j < m; j++) 10609 /// for (long k = 0; k < o; k++) 10610 /// A[i][j][k] = 1.0; 10611 /// } 10612 /// 10613 /// the delinearization input is the following AddRec SCEV: 10614 /// 10615 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10616 /// 10617 /// From this SCEV, we are able to say that the base offset of the access is %A 10618 /// because it appears as an offset that does not divide any of the strides in 10619 /// the loops: 10620 /// 10621 /// CHECK: Base offset: %A 10622 /// 10623 /// and then SCEV->delinearize determines the size of some of the dimensions of 10624 /// the array as these are the multiples by which the strides are happening: 10625 /// 10626 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10627 /// 10628 /// Note that the outermost dimension remains of UnknownSize because there are 10629 /// no strides that would help identifying the size of the last dimension: when 10630 /// the array has been statically allocated, one could compute the size of that 10631 /// dimension by dividing the overall size of the array by the size of the known 10632 /// dimensions: %m * %o * 8. 10633 /// 10634 /// Finally delinearize provides the access functions for the array reference 10635 /// that does correspond to A[i][j][k] of the above C testcase: 10636 /// 10637 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10638 /// 10639 /// The testcases are checking the output of a function pass: 10640 /// DelinearizationPass that walks through all loads and stores of a function 10641 /// asking for the SCEV of the memory access with respect to all enclosing 10642 /// loops, calling SCEV->delinearize on that and printing the results. 10643 void ScalarEvolution::delinearize(const SCEV *Expr, 10644 SmallVectorImpl<const SCEV *> &Subscripts, 10645 SmallVectorImpl<const SCEV *> &Sizes, 10646 const SCEV *ElementSize) { 10647 // First step: collect parametric terms. 10648 SmallVector<const SCEV *, 4> Terms; 10649 collectParametricTerms(Expr, Terms); 10650 10651 if (Terms.empty()) 10652 return; 10653 10654 // Second step: find subscript sizes. 10655 findArrayDimensions(Terms, Sizes, ElementSize); 10656 10657 if (Sizes.empty()) 10658 return; 10659 10660 // Third step: compute the access functions for each subscript. 10661 computeAccessFunctions(Expr, Subscripts, Sizes); 10662 10663 if (Subscripts.empty()) 10664 return; 10665 10666 DEBUG({ 10667 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10668 dbgs() << "ArrayDecl[UnknownSize]"; 10669 for (const SCEV *S : Sizes) 10670 dbgs() << "[" << *S << "]"; 10671 10672 dbgs() << "\nArrayRef"; 10673 for (const SCEV *S : Subscripts) 10674 dbgs() << "[" << *S << "]"; 10675 dbgs() << "\n"; 10676 }); 10677 } 10678 10679 //===----------------------------------------------------------------------===// 10680 // SCEVCallbackVH Class Implementation 10681 //===----------------------------------------------------------------------===// 10682 10683 void ScalarEvolution::SCEVCallbackVH::deleted() { 10684 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10685 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10686 SE->ConstantEvolutionLoopExitValue.erase(PN); 10687 SE->eraseValueFromMap(getValPtr()); 10688 // this now dangles! 10689 } 10690 10691 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10692 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10693 10694 // Forget all the expressions associated with users of the old value, 10695 // so that future queries will recompute the expressions using the new 10696 // value. 10697 Value *Old = getValPtr(); 10698 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10699 SmallPtrSet<User *, 8> Visited; 10700 while (!Worklist.empty()) { 10701 User *U = Worklist.pop_back_val(); 10702 // Deleting the Old value will cause this to dangle. Postpone 10703 // that until everything else is done. 10704 if (U == Old) 10705 continue; 10706 if (!Visited.insert(U).second) 10707 continue; 10708 if (PHINode *PN = dyn_cast<PHINode>(U)) 10709 SE->ConstantEvolutionLoopExitValue.erase(PN); 10710 SE->eraseValueFromMap(U); 10711 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10712 } 10713 // Delete the Old value. 10714 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10715 SE->ConstantEvolutionLoopExitValue.erase(PN); 10716 SE->eraseValueFromMap(Old); 10717 // this now dangles! 10718 } 10719 10720 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10721 : CallbackVH(V), SE(se) {} 10722 10723 //===----------------------------------------------------------------------===// 10724 // ScalarEvolution Class Implementation 10725 //===----------------------------------------------------------------------===// 10726 10727 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10728 AssumptionCache &AC, DominatorTree &DT, 10729 LoopInfo &LI) 10730 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10731 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 10732 LoopDispositions(64), BlockDispositions(64) { 10733 // To use guards for proving predicates, we need to scan every instruction in 10734 // relevant basic blocks, and not just terminators. Doing this is a waste of 10735 // time if the IR does not actually contain any calls to 10736 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10737 // 10738 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10739 // to _add_ guards to the module when there weren't any before, and wants 10740 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10741 // efficient in lieu of being smart in that rather obscure case. 10742 10743 auto *GuardDecl = F.getParent()->getFunction( 10744 Intrinsic::getName(Intrinsic::experimental_guard)); 10745 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10746 } 10747 10748 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10749 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10750 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10751 ValueExprMap(std::move(Arg.ValueExprMap)), 10752 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10753 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10754 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10755 PredicatedBackedgeTakenCounts( 10756 std::move(Arg.PredicatedBackedgeTakenCounts)), 10757 ConstantEvolutionLoopExitValue( 10758 std::move(Arg.ConstantEvolutionLoopExitValue)), 10759 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10760 LoopDispositions(std::move(Arg.LoopDispositions)), 10761 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10762 BlockDispositions(std::move(Arg.BlockDispositions)), 10763 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10764 SignedRanges(std::move(Arg.SignedRanges)), 10765 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10766 UniquePreds(std::move(Arg.UniquePreds)), 10767 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10768 LoopUsers(std::move(Arg.LoopUsers)), 10769 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10770 FirstUnknown(Arg.FirstUnknown) { 10771 Arg.FirstUnknown = nullptr; 10772 } 10773 10774 ScalarEvolution::~ScalarEvolution() { 10775 // Iterate through all the SCEVUnknown instances and call their 10776 // destructors, so that they release their references to their values. 10777 for (SCEVUnknown *U = FirstUnknown; U;) { 10778 SCEVUnknown *Tmp = U; 10779 U = U->Next; 10780 Tmp->~SCEVUnknown(); 10781 } 10782 FirstUnknown = nullptr; 10783 10784 ExprValueMap.clear(); 10785 ValueExprMap.clear(); 10786 HasRecMap.clear(); 10787 10788 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10789 // that a loop had multiple computable exits. 10790 for (auto &BTCI : BackedgeTakenCounts) 10791 BTCI.second.clear(); 10792 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10793 BTCI.second.clear(); 10794 10795 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10796 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10797 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10798 } 10799 10800 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10801 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10802 } 10803 10804 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10805 const Loop *L) { 10806 // Print all inner loops first 10807 for (Loop *I : *L) 10808 PrintLoopInfo(OS, SE, I); 10809 10810 OS << "Loop "; 10811 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10812 OS << ": "; 10813 10814 SmallVector<BasicBlock *, 8> ExitBlocks; 10815 L->getExitBlocks(ExitBlocks); 10816 if (ExitBlocks.size() != 1) 10817 OS << "<multiple exits> "; 10818 10819 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10820 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10821 } else { 10822 OS << "Unpredictable backedge-taken count. "; 10823 } 10824 10825 OS << "\n" 10826 "Loop "; 10827 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10828 OS << ": "; 10829 10830 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10831 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10832 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10833 OS << ", actual taken count either this or zero."; 10834 } else { 10835 OS << "Unpredictable max backedge-taken count. "; 10836 } 10837 10838 OS << "\n" 10839 "Loop "; 10840 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10841 OS << ": "; 10842 10843 SCEVUnionPredicate Pred; 10844 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10845 if (!isa<SCEVCouldNotCompute>(PBT)) { 10846 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10847 OS << " Predicates:\n"; 10848 Pred.print(OS, 4); 10849 } else { 10850 OS << "Unpredictable predicated backedge-taken count. "; 10851 } 10852 OS << "\n"; 10853 10854 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10855 OS << "Loop "; 10856 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10857 OS << ": "; 10858 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10859 } 10860 } 10861 10862 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 10863 switch (LD) { 10864 case ScalarEvolution::LoopVariant: 10865 return "Variant"; 10866 case ScalarEvolution::LoopInvariant: 10867 return "Invariant"; 10868 case ScalarEvolution::LoopComputable: 10869 return "Computable"; 10870 } 10871 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 10872 } 10873 10874 void ScalarEvolution::print(raw_ostream &OS) const { 10875 // ScalarEvolution's implementation of the print method is to print 10876 // out SCEV values of all instructions that are interesting. Doing 10877 // this potentially causes it to create new SCEV objects though, 10878 // which technically conflicts with the const qualifier. This isn't 10879 // observable from outside the class though, so casting away the 10880 // const isn't dangerous. 10881 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10882 10883 OS << "Classifying expressions for: "; 10884 F.printAsOperand(OS, /*PrintType=*/false); 10885 OS << "\n"; 10886 for (Instruction &I : instructions(F)) 10887 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 10888 OS << I << '\n'; 10889 OS << " --> "; 10890 const SCEV *SV = SE.getSCEV(&I); 10891 SV->print(OS); 10892 if (!isa<SCEVCouldNotCompute>(SV)) { 10893 OS << " U: "; 10894 SE.getUnsignedRange(SV).print(OS); 10895 OS << " S: "; 10896 SE.getSignedRange(SV).print(OS); 10897 } 10898 10899 const Loop *L = LI.getLoopFor(I.getParent()); 10900 10901 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10902 if (AtUse != SV) { 10903 OS << " --> "; 10904 AtUse->print(OS); 10905 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10906 OS << " U: "; 10907 SE.getUnsignedRange(AtUse).print(OS); 10908 OS << " S: "; 10909 SE.getSignedRange(AtUse).print(OS); 10910 } 10911 } 10912 10913 if (L) { 10914 OS << "\t\t" "Exits: "; 10915 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10916 if (!SE.isLoopInvariant(ExitValue, L)) { 10917 OS << "<<Unknown>>"; 10918 } else { 10919 OS << *ExitValue; 10920 } 10921 10922 bool First = true; 10923 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10924 if (First) { 10925 OS << "\t\t" "LoopDispositions: { "; 10926 First = false; 10927 } else { 10928 OS << ", "; 10929 } 10930 10931 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10932 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10933 } 10934 10935 for (auto *InnerL : depth_first(L)) { 10936 if (InnerL == L) 10937 continue; 10938 if (First) { 10939 OS << "\t\t" "LoopDispositions: { "; 10940 First = false; 10941 } else { 10942 OS << ", "; 10943 } 10944 10945 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10946 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10947 } 10948 10949 OS << " }"; 10950 } 10951 10952 OS << "\n"; 10953 } 10954 10955 OS << "Determining loop execution counts for: "; 10956 F.printAsOperand(OS, /*PrintType=*/false); 10957 OS << "\n"; 10958 for (Loop *I : LI) 10959 PrintLoopInfo(OS, &SE, I); 10960 } 10961 10962 ScalarEvolution::LoopDisposition 10963 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10964 auto &Values = LoopDispositions[S]; 10965 for (auto &V : Values) { 10966 if (V.getPointer() == L) 10967 return V.getInt(); 10968 } 10969 Values.emplace_back(L, LoopVariant); 10970 LoopDisposition D = computeLoopDisposition(S, L); 10971 auto &Values2 = LoopDispositions[S]; 10972 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10973 if (V.getPointer() == L) { 10974 V.setInt(D); 10975 break; 10976 } 10977 } 10978 return D; 10979 } 10980 10981 ScalarEvolution::LoopDisposition 10982 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10983 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10984 case scConstant: 10985 return LoopInvariant; 10986 case scTruncate: 10987 case scZeroExtend: 10988 case scSignExtend: 10989 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10990 case scAddRecExpr: { 10991 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10992 10993 // If L is the addrec's loop, it's computable. 10994 if (AR->getLoop() == L) 10995 return LoopComputable; 10996 10997 // Add recurrences are never invariant in the function-body (null loop). 10998 if (!L) 10999 return LoopVariant; 11000 11001 // Everything that is not defined at loop entry is variant. 11002 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11003 return LoopVariant; 11004 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11005 " dominate the contained loop's header?"); 11006 11007 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11008 if (AR->getLoop()->contains(L)) 11009 return LoopInvariant; 11010 11011 // This recurrence is variant w.r.t. L if any of its operands 11012 // are variant. 11013 for (auto *Op : AR->operands()) 11014 if (!isLoopInvariant(Op, L)) 11015 return LoopVariant; 11016 11017 // Otherwise it's loop-invariant. 11018 return LoopInvariant; 11019 } 11020 case scAddExpr: 11021 case scMulExpr: 11022 case scUMaxExpr: 11023 case scSMaxExpr: { 11024 bool HasVarying = false; 11025 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11026 LoopDisposition D = getLoopDisposition(Op, L); 11027 if (D == LoopVariant) 11028 return LoopVariant; 11029 if (D == LoopComputable) 11030 HasVarying = true; 11031 } 11032 return HasVarying ? LoopComputable : LoopInvariant; 11033 } 11034 case scUDivExpr: { 11035 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11036 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11037 if (LD == LoopVariant) 11038 return LoopVariant; 11039 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11040 if (RD == LoopVariant) 11041 return LoopVariant; 11042 return (LD == LoopInvariant && RD == LoopInvariant) ? 11043 LoopInvariant : LoopComputable; 11044 } 11045 case scUnknown: 11046 // All non-instruction values are loop invariant. All instructions are loop 11047 // invariant if they are not contained in the specified loop. 11048 // Instructions are never considered invariant in the function body 11049 // (null loop) because they are defined within the "loop". 11050 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11051 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11052 return LoopInvariant; 11053 case scCouldNotCompute: 11054 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11055 } 11056 llvm_unreachable("Unknown SCEV kind!"); 11057 } 11058 11059 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11060 return getLoopDisposition(S, L) == LoopInvariant; 11061 } 11062 11063 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11064 return getLoopDisposition(S, L) == LoopComputable; 11065 } 11066 11067 ScalarEvolution::BlockDisposition 11068 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11069 auto &Values = BlockDispositions[S]; 11070 for (auto &V : Values) { 11071 if (V.getPointer() == BB) 11072 return V.getInt(); 11073 } 11074 Values.emplace_back(BB, DoesNotDominateBlock); 11075 BlockDisposition D = computeBlockDisposition(S, BB); 11076 auto &Values2 = BlockDispositions[S]; 11077 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11078 if (V.getPointer() == BB) { 11079 V.setInt(D); 11080 break; 11081 } 11082 } 11083 return D; 11084 } 11085 11086 ScalarEvolution::BlockDisposition 11087 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11088 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11089 case scConstant: 11090 return ProperlyDominatesBlock; 11091 case scTruncate: 11092 case scZeroExtend: 11093 case scSignExtend: 11094 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11095 case scAddRecExpr: { 11096 // This uses a "dominates" query instead of "properly dominates" query 11097 // to test for proper dominance too, because the instruction which 11098 // produces the addrec's value is a PHI, and a PHI effectively properly 11099 // dominates its entire containing block. 11100 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11101 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11102 return DoesNotDominateBlock; 11103 11104 // Fall through into SCEVNAryExpr handling. 11105 LLVM_FALLTHROUGH; 11106 } 11107 case scAddExpr: 11108 case scMulExpr: 11109 case scUMaxExpr: 11110 case scSMaxExpr: { 11111 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11112 bool Proper = true; 11113 for (const SCEV *NAryOp : NAry->operands()) { 11114 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11115 if (D == DoesNotDominateBlock) 11116 return DoesNotDominateBlock; 11117 if (D == DominatesBlock) 11118 Proper = false; 11119 } 11120 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11121 } 11122 case scUDivExpr: { 11123 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11124 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11125 BlockDisposition LD = getBlockDisposition(LHS, BB); 11126 if (LD == DoesNotDominateBlock) 11127 return DoesNotDominateBlock; 11128 BlockDisposition RD = getBlockDisposition(RHS, BB); 11129 if (RD == DoesNotDominateBlock) 11130 return DoesNotDominateBlock; 11131 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11132 ProperlyDominatesBlock : DominatesBlock; 11133 } 11134 case scUnknown: 11135 if (Instruction *I = 11136 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11137 if (I->getParent() == BB) 11138 return DominatesBlock; 11139 if (DT.properlyDominates(I->getParent(), BB)) 11140 return ProperlyDominatesBlock; 11141 return DoesNotDominateBlock; 11142 } 11143 return ProperlyDominatesBlock; 11144 case scCouldNotCompute: 11145 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11146 } 11147 llvm_unreachable("Unknown SCEV kind!"); 11148 } 11149 11150 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11151 return getBlockDisposition(S, BB) >= DominatesBlock; 11152 } 11153 11154 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11155 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11156 } 11157 11158 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11159 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11160 } 11161 11162 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11163 auto IsS = [&](const SCEV *X) { return S == X; }; 11164 auto ContainsS = [&](const SCEV *X) { 11165 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11166 }; 11167 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11168 } 11169 11170 void 11171 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11172 ValuesAtScopes.erase(S); 11173 LoopDispositions.erase(S); 11174 BlockDispositions.erase(S); 11175 UnsignedRanges.erase(S); 11176 SignedRanges.erase(S); 11177 ExprValueMap.erase(S); 11178 HasRecMap.erase(S); 11179 MinTrailingZerosCache.erase(S); 11180 11181 for (auto I = PredicatedSCEVRewrites.begin(); 11182 I != PredicatedSCEVRewrites.end();) { 11183 std::pair<const SCEV *, const Loop *> Entry = I->first; 11184 if (Entry.first == S) 11185 PredicatedSCEVRewrites.erase(I++); 11186 else 11187 ++I; 11188 } 11189 11190 auto RemoveSCEVFromBackedgeMap = 11191 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11192 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11193 BackedgeTakenInfo &BEInfo = I->second; 11194 if (BEInfo.hasOperand(S, this)) { 11195 BEInfo.clear(); 11196 Map.erase(I++); 11197 } else 11198 ++I; 11199 } 11200 }; 11201 11202 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11203 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11204 } 11205 11206 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11207 struct FindUsedLoops { 11208 SmallPtrSet<const Loop *, 8> LoopsUsed; 11209 bool follow(const SCEV *S) { 11210 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11211 LoopsUsed.insert(AR->getLoop()); 11212 return true; 11213 } 11214 11215 bool isDone() const { return false; } 11216 }; 11217 11218 FindUsedLoops F; 11219 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11220 11221 for (auto *L : F.LoopsUsed) 11222 LoopUsers[L].push_back(S); 11223 } 11224 11225 void ScalarEvolution::verify() const { 11226 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11227 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11228 11229 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11230 11231 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11232 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11233 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11234 11235 const SCEV *visitConstant(const SCEVConstant *Constant) { 11236 return SE.getConstant(Constant->getAPInt()); 11237 } 11238 11239 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11240 return SE.getUnknown(Expr->getValue()); 11241 } 11242 11243 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11244 return SE.getCouldNotCompute(); 11245 } 11246 }; 11247 11248 SCEVMapper SCM(SE2); 11249 11250 while (!LoopStack.empty()) { 11251 auto *L = LoopStack.pop_back_val(); 11252 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11253 11254 auto *CurBECount = SCM.visit( 11255 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11256 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11257 11258 if (CurBECount == SE2.getCouldNotCompute() || 11259 NewBECount == SE2.getCouldNotCompute()) { 11260 // NB! This situation is legal, but is very suspicious -- whatever pass 11261 // change the loop to make a trip count go from could not compute to 11262 // computable or vice-versa *should have* invalidated SCEV. However, we 11263 // choose not to assert here (for now) since we don't want false 11264 // positives. 11265 continue; 11266 } 11267 11268 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11269 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11270 // not propagate undef aggressively). This means we can (and do) fail 11271 // verification in cases where a transform makes the trip count of a loop 11272 // go from "undef" to "undef+1" (say). The transform is fine, since in 11273 // both cases the loop iterates "undef" times, but SCEV thinks we 11274 // increased the trip count of the loop by 1 incorrectly. 11275 continue; 11276 } 11277 11278 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11279 SE.getTypeSizeInBits(NewBECount->getType())) 11280 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11281 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11282 SE.getTypeSizeInBits(NewBECount->getType())) 11283 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11284 11285 auto *ConstantDelta = 11286 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11287 11288 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11289 dbgs() << "Trip Count Changed!\n"; 11290 dbgs() << "Old: " << *CurBECount << "\n"; 11291 dbgs() << "New: " << *NewBECount << "\n"; 11292 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11293 std::abort(); 11294 } 11295 } 11296 } 11297 11298 bool ScalarEvolution::invalidate( 11299 Function &F, const PreservedAnalyses &PA, 11300 FunctionAnalysisManager::Invalidator &Inv) { 11301 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11302 // of its dependencies is invalidated. 11303 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11304 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11305 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11306 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11307 Inv.invalidate<LoopAnalysis>(F, PA); 11308 } 11309 11310 AnalysisKey ScalarEvolutionAnalysis::Key; 11311 11312 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11313 FunctionAnalysisManager &AM) { 11314 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11315 AM.getResult<AssumptionAnalysis>(F), 11316 AM.getResult<DominatorTreeAnalysis>(F), 11317 AM.getResult<LoopAnalysis>(F)); 11318 } 11319 11320 PreservedAnalyses 11321 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11322 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11323 return PreservedAnalyses::all(); 11324 } 11325 11326 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11327 "Scalar Evolution Analysis", false, true) 11328 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11329 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11330 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11331 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11332 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11333 "Scalar Evolution Analysis", false, true) 11334 11335 char ScalarEvolutionWrapperPass::ID = 0; 11336 11337 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11338 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11339 } 11340 11341 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11342 SE.reset(new ScalarEvolution( 11343 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11344 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11345 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11346 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11347 return false; 11348 } 11349 11350 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11351 11352 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11353 SE->print(OS); 11354 } 11355 11356 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11357 if (!VerifySCEV) 11358 return; 11359 11360 SE->verify(); 11361 } 11362 11363 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11364 AU.setPreservesAll(); 11365 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11366 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11367 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11368 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11369 } 11370 11371 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11372 const SCEV *RHS) { 11373 FoldingSetNodeID ID; 11374 assert(LHS->getType() == RHS->getType() && 11375 "Type mismatch between LHS and RHS"); 11376 // Unique this node based on the arguments 11377 ID.AddInteger(SCEVPredicate::P_Equal); 11378 ID.AddPointer(LHS); 11379 ID.AddPointer(RHS); 11380 void *IP = nullptr; 11381 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11382 return S; 11383 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11384 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11385 UniquePreds.InsertNode(Eq, IP); 11386 return Eq; 11387 } 11388 11389 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11390 const SCEVAddRecExpr *AR, 11391 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11392 FoldingSetNodeID ID; 11393 // Unique this node based on the arguments 11394 ID.AddInteger(SCEVPredicate::P_Wrap); 11395 ID.AddPointer(AR); 11396 ID.AddInteger(AddedFlags); 11397 void *IP = nullptr; 11398 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11399 return S; 11400 auto *OF = new (SCEVAllocator) 11401 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11402 UniquePreds.InsertNode(OF, IP); 11403 return OF; 11404 } 11405 11406 namespace { 11407 11408 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11409 public: 11410 11411 /// Rewrites \p S in the context of a loop L and the SCEV predication 11412 /// infrastructure. 11413 /// 11414 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11415 /// equivalences present in \p Pred. 11416 /// 11417 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11418 /// \p NewPreds such that the result will be an AddRecExpr. 11419 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11420 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11421 SCEVUnionPredicate *Pred) { 11422 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11423 return Rewriter.visit(S); 11424 } 11425 11426 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11427 if (Pred) { 11428 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11429 for (auto *Pred : ExprPreds) 11430 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11431 if (IPred->getLHS() == Expr) 11432 return IPred->getRHS(); 11433 } 11434 return convertToAddRecWithPreds(Expr); 11435 } 11436 11437 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11438 const SCEV *Operand = visit(Expr->getOperand()); 11439 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11440 if (AR && AR->getLoop() == L && AR->isAffine()) { 11441 // This couldn't be folded because the operand didn't have the nuw 11442 // flag. Add the nusw flag as an assumption that we could make. 11443 const SCEV *Step = AR->getStepRecurrence(SE); 11444 Type *Ty = Expr->getType(); 11445 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11446 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11447 SE.getSignExtendExpr(Step, Ty), L, 11448 AR->getNoWrapFlags()); 11449 } 11450 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11451 } 11452 11453 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11454 const SCEV *Operand = visit(Expr->getOperand()); 11455 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11456 if (AR && AR->getLoop() == L && AR->isAffine()) { 11457 // This couldn't be folded because the operand didn't have the nsw 11458 // flag. Add the nssw flag as an assumption that we could make. 11459 const SCEV *Step = AR->getStepRecurrence(SE); 11460 Type *Ty = Expr->getType(); 11461 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11462 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11463 SE.getSignExtendExpr(Step, Ty), L, 11464 AR->getNoWrapFlags()); 11465 } 11466 return SE.getSignExtendExpr(Operand, Expr->getType()); 11467 } 11468 11469 private: 11470 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11471 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11472 SCEVUnionPredicate *Pred) 11473 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11474 11475 bool addOverflowAssumption(const SCEVPredicate *P) { 11476 if (!NewPreds) { 11477 // Check if we've already made this assumption. 11478 return Pred && Pred->implies(P); 11479 } 11480 NewPreds->insert(P); 11481 return true; 11482 } 11483 11484 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11485 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11486 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11487 return addOverflowAssumption(A); 11488 } 11489 11490 // If \p Expr represents a PHINode, we try to see if it can be represented 11491 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11492 // to add this predicate as a runtime overflow check, we return the AddRec. 11493 // If \p Expr does not meet these conditions (is not a PHI node, or we 11494 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11495 // return \p Expr. 11496 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11497 if (!isa<PHINode>(Expr->getValue())) 11498 return Expr; 11499 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11500 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11501 if (!PredicatedRewrite) 11502 return Expr; 11503 for (auto *P : PredicatedRewrite->second){ 11504 if (!addOverflowAssumption(P)) 11505 return Expr; 11506 } 11507 return PredicatedRewrite->first; 11508 } 11509 11510 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11511 SCEVUnionPredicate *Pred; 11512 const Loop *L; 11513 }; 11514 11515 } // end anonymous namespace 11516 11517 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11518 SCEVUnionPredicate &Preds) { 11519 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11520 } 11521 11522 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11523 const SCEV *S, const Loop *L, 11524 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11525 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11526 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11527 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11528 11529 if (!AddRec) 11530 return nullptr; 11531 11532 // Since the transformation was successful, we can now transfer the SCEV 11533 // predicates. 11534 for (auto *P : TransformPreds) 11535 Preds.insert(P); 11536 11537 return AddRec; 11538 } 11539 11540 /// SCEV predicates 11541 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11542 SCEVPredicateKind Kind) 11543 : FastID(ID), Kind(Kind) {} 11544 11545 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11546 const SCEV *LHS, const SCEV *RHS) 11547 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11548 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11549 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11550 } 11551 11552 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11553 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11554 11555 if (!Op) 11556 return false; 11557 11558 return Op->LHS == LHS && Op->RHS == RHS; 11559 } 11560 11561 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11562 11563 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11564 11565 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11566 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11567 } 11568 11569 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11570 const SCEVAddRecExpr *AR, 11571 IncrementWrapFlags Flags) 11572 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11573 11574 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11575 11576 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11577 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11578 11579 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11580 } 11581 11582 bool SCEVWrapPredicate::isAlwaysTrue() const { 11583 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11584 IncrementWrapFlags IFlags = Flags; 11585 11586 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11587 IFlags = clearFlags(IFlags, IncrementNSSW); 11588 11589 return IFlags == IncrementAnyWrap; 11590 } 11591 11592 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11593 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11594 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11595 OS << "<nusw>"; 11596 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11597 OS << "<nssw>"; 11598 OS << "\n"; 11599 } 11600 11601 SCEVWrapPredicate::IncrementWrapFlags 11602 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11603 ScalarEvolution &SE) { 11604 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11605 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11606 11607 // We can safely transfer the NSW flag as NSSW. 11608 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11609 ImpliedFlags = IncrementNSSW; 11610 11611 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11612 // If the increment is positive, the SCEV NUW flag will also imply the 11613 // WrapPredicate NUSW flag. 11614 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11615 if (Step->getValue()->getValue().isNonNegative()) 11616 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11617 } 11618 11619 return ImpliedFlags; 11620 } 11621 11622 /// Union predicates don't get cached so create a dummy set ID for it. 11623 SCEVUnionPredicate::SCEVUnionPredicate() 11624 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11625 11626 bool SCEVUnionPredicate::isAlwaysTrue() const { 11627 return all_of(Preds, 11628 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11629 } 11630 11631 ArrayRef<const SCEVPredicate *> 11632 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11633 auto I = SCEVToPreds.find(Expr); 11634 if (I == SCEVToPreds.end()) 11635 return ArrayRef<const SCEVPredicate *>(); 11636 return I->second; 11637 } 11638 11639 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11640 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11641 return all_of(Set->Preds, 11642 [this](const SCEVPredicate *I) { return this->implies(I); }); 11643 11644 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11645 if (ScevPredsIt == SCEVToPreds.end()) 11646 return false; 11647 auto &SCEVPreds = ScevPredsIt->second; 11648 11649 return any_of(SCEVPreds, 11650 [N](const SCEVPredicate *I) { return I->implies(N); }); 11651 } 11652 11653 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11654 11655 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11656 for (auto Pred : Preds) 11657 Pred->print(OS, Depth); 11658 } 11659 11660 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11661 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11662 for (auto Pred : Set->Preds) 11663 add(Pred); 11664 return; 11665 } 11666 11667 if (implies(N)) 11668 return; 11669 11670 const SCEV *Key = N->getExpr(); 11671 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11672 " associated expression!"); 11673 11674 SCEVToPreds[Key].push_back(N); 11675 Preds.push_back(N); 11676 } 11677 11678 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11679 Loop &L) 11680 : SE(SE), L(L) {} 11681 11682 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11683 const SCEV *Expr = SE.getSCEV(V); 11684 RewriteEntry &Entry = RewriteMap[Expr]; 11685 11686 // If we already have an entry and the version matches, return it. 11687 if (Entry.second && Generation == Entry.first) 11688 return Entry.second; 11689 11690 // We found an entry but it's stale. Rewrite the stale entry 11691 // according to the current predicate. 11692 if (Entry.second) 11693 Expr = Entry.second; 11694 11695 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11696 Entry = {Generation, NewSCEV}; 11697 11698 return NewSCEV; 11699 } 11700 11701 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11702 if (!BackedgeCount) { 11703 SCEVUnionPredicate BackedgePred; 11704 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11705 addPredicate(BackedgePred); 11706 } 11707 return BackedgeCount; 11708 } 11709 11710 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11711 if (Preds.implies(&Pred)) 11712 return; 11713 Preds.add(&Pred); 11714 updateGeneration(); 11715 } 11716 11717 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11718 return Preds; 11719 } 11720 11721 void PredicatedScalarEvolution::updateGeneration() { 11722 // If the generation number wrapped recompute everything. 11723 if (++Generation == 0) { 11724 for (auto &II : RewriteMap) { 11725 const SCEV *Rewritten = II.second.second; 11726 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11727 } 11728 } 11729 } 11730 11731 void PredicatedScalarEvolution::setNoOverflow( 11732 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11733 const SCEV *Expr = getSCEV(V); 11734 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11735 11736 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11737 11738 // Clear the statically implied flags. 11739 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11740 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11741 11742 auto II = FlagsMap.insert({V, Flags}); 11743 if (!II.second) 11744 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11745 } 11746 11747 bool PredicatedScalarEvolution::hasNoOverflow( 11748 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11749 const SCEV *Expr = getSCEV(V); 11750 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11751 11752 Flags = SCEVWrapPredicate::clearFlags( 11753 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11754 11755 auto II = FlagsMap.find(V); 11756 11757 if (II != FlagsMap.end()) 11758 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11759 11760 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11761 } 11762 11763 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11764 const SCEV *Expr = this->getSCEV(V); 11765 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11766 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11767 11768 if (!New) 11769 return nullptr; 11770 11771 for (auto *P : NewPreds) 11772 Preds.add(P); 11773 11774 updateGeneration(); 11775 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11776 return New; 11777 } 11778 11779 PredicatedScalarEvolution::PredicatedScalarEvolution( 11780 const PredicatedScalarEvolution &Init) 11781 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11782 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11783 for (const auto &I : Init.FlagsMap) 11784 FlagsMap.insert(I); 11785 } 11786 11787 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11788 // For each block. 11789 for (auto *BB : L.getBlocks()) 11790 for (auto &I : *BB) { 11791 if (!SE.isSCEVable(I.getType())) 11792 continue; 11793 11794 auto *Expr = SE.getSCEV(&I); 11795 auto II = RewriteMap.find(Expr); 11796 11797 if (II == RewriteMap.end()) 11798 continue; 11799 11800 // Don't print things that are not interesting. 11801 if (II->second.second == Expr) 11802 continue; 11803 11804 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11805 OS.indent(Depth + 2) << *Expr << "\n"; 11806 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11807 } 11808 } 11809