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 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3778 /// create a new one. 3779 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3780 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3781 3782 const SCEV *S = getExistingSCEV(V); 3783 if (S == nullptr) { 3784 S = createSCEV(V); 3785 // During PHI resolution, it is possible to create two SCEVs for the same 3786 // V, so it is needed to double check whether V->S is inserted into 3787 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3788 std::pair<ValueExprMapType::iterator, bool> Pair = 3789 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3790 if (Pair.second) { 3791 ExprValueMap[S].insert({V, nullptr}); 3792 3793 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3794 // ExprValueMap. 3795 const SCEV *Stripped = S; 3796 ConstantInt *Offset = nullptr; 3797 std::tie(Stripped, Offset) = splitAddExpr(S); 3798 // If stripped is SCEVUnknown, don't bother to save 3799 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3800 // increase the complexity of the expansion code. 3801 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3802 // because it may generate add/sub instead of GEP in SCEV expansion. 3803 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3804 !isa<GetElementPtrInst>(V)) 3805 ExprValueMap[Stripped].insert({V, Offset}); 3806 } 3807 } 3808 return S; 3809 } 3810 3811 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3812 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3813 3814 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3815 if (I != ValueExprMap.end()) { 3816 const SCEV *S = I->second; 3817 if (checkValidity(S)) 3818 return S; 3819 eraseValueFromMap(V); 3820 forgetMemoizedResults(S); 3821 } 3822 return nullptr; 3823 } 3824 3825 /// Return a SCEV corresponding to -V = -1*V 3826 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3827 SCEV::NoWrapFlags Flags) { 3828 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3829 return getConstant( 3830 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3831 3832 Type *Ty = V->getType(); 3833 Ty = getEffectiveSCEVType(Ty); 3834 return getMulExpr( 3835 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3836 } 3837 3838 /// Return a SCEV corresponding to ~V = -1-V 3839 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3840 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3841 return getConstant( 3842 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3843 3844 Type *Ty = V->getType(); 3845 Ty = getEffectiveSCEVType(Ty); 3846 const SCEV *AllOnes = 3847 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3848 return getMinusSCEV(AllOnes, V); 3849 } 3850 3851 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3852 SCEV::NoWrapFlags Flags, 3853 unsigned Depth) { 3854 // Fast path: X - X --> 0. 3855 if (LHS == RHS) 3856 return getZero(LHS->getType()); 3857 3858 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3859 // makes it so that we cannot make much use of NUW. 3860 auto AddFlags = SCEV::FlagAnyWrap; 3861 const bool RHSIsNotMinSigned = 3862 !getSignedRangeMin(RHS).isMinSignedValue(); 3863 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3864 // Let M be the minimum representable signed value. Then (-1)*RHS 3865 // signed-wraps if and only if RHS is M. That can happen even for 3866 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3867 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3868 // (-1)*RHS, we need to prove that RHS != M. 3869 // 3870 // If LHS is non-negative and we know that LHS - RHS does not 3871 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3872 // either by proving that RHS > M or that LHS >= 0. 3873 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3874 AddFlags = SCEV::FlagNSW; 3875 } 3876 } 3877 3878 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3879 // RHS is NSW and LHS >= 0. 3880 // 3881 // The difficulty here is that the NSW flag may have been proven 3882 // relative to a loop that is to be found in a recurrence in LHS and 3883 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3884 // larger scope than intended. 3885 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3886 3887 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3888 } 3889 3890 const SCEV * 3891 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3892 Type *SrcTy = V->getType(); 3893 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3894 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3895 "Cannot truncate or zero extend with non-integer arguments!"); 3896 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3897 return V; // No conversion 3898 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3899 return getTruncateExpr(V, Ty); 3900 return getZeroExtendExpr(V, Ty); 3901 } 3902 3903 const SCEV * 3904 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3905 Type *Ty) { 3906 Type *SrcTy = V->getType(); 3907 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3908 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3909 "Cannot truncate or zero extend with non-integer arguments!"); 3910 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3911 return V; // No conversion 3912 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3913 return getTruncateExpr(V, Ty); 3914 return getSignExtendExpr(V, Ty); 3915 } 3916 3917 const SCEV * 3918 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3919 Type *SrcTy = V->getType(); 3920 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3921 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3922 "Cannot noop or zero extend with non-integer arguments!"); 3923 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3924 "getNoopOrZeroExtend cannot truncate!"); 3925 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3926 return V; // No conversion 3927 return getZeroExtendExpr(V, Ty); 3928 } 3929 3930 const SCEV * 3931 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3932 Type *SrcTy = V->getType(); 3933 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3934 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3935 "Cannot noop or sign extend with non-integer arguments!"); 3936 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3937 "getNoopOrSignExtend cannot truncate!"); 3938 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3939 return V; // No conversion 3940 return getSignExtendExpr(V, Ty); 3941 } 3942 3943 const SCEV * 3944 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3945 Type *SrcTy = V->getType(); 3946 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3947 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3948 "Cannot noop or any extend with non-integer arguments!"); 3949 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3950 "getNoopOrAnyExtend cannot truncate!"); 3951 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3952 return V; // No conversion 3953 return getAnyExtendExpr(V, Ty); 3954 } 3955 3956 const SCEV * 3957 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3958 Type *SrcTy = V->getType(); 3959 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3960 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3961 "Cannot truncate or noop with non-integer arguments!"); 3962 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3963 "getTruncateOrNoop cannot extend!"); 3964 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3965 return V; // No conversion 3966 return getTruncateExpr(V, Ty); 3967 } 3968 3969 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3970 const SCEV *RHS) { 3971 const SCEV *PromotedLHS = LHS; 3972 const SCEV *PromotedRHS = RHS; 3973 3974 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3975 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3976 else 3977 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3978 3979 return getUMaxExpr(PromotedLHS, PromotedRHS); 3980 } 3981 3982 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3983 const SCEV *RHS) { 3984 const SCEV *PromotedLHS = LHS; 3985 const SCEV *PromotedRHS = RHS; 3986 3987 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3988 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3989 else 3990 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3991 3992 return getUMinExpr(PromotedLHS, PromotedRHS); 3993 } 3994 3995 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3996 // A pointer operand may evaluate to a nonpointer expression, such as null. 3997 if (!V->getType()->isPointerTy()) 3998 return V; 3999 4000 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4001 return getPointerBase(Cast->getOperand()); 4002 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4003 const SCEV *PtrOp = nullptr; 4004 for (const SCEV *NAryOp : NAry->operands()) { 4005 if (NAryOp->getType()->isPointerTy()) { 4006 // Cannot find the base of an expression with multiple pointer operands. 4007 if (PtrOp) 4008 return V; 4009 PtrOp = NAryOp; 4010 } 4011 } 4012 if (!PtrOp) 4013 return V; 4014 return getPointerBase(PtrOp); 4015 } 4016 return V; 4017 } 4018 4019 /// Push users of the given Instruction onto the given Worklist. 4020 static void 4021 PushDefUseChildren(Instruction *I, 4022 SmallVectorImpl<Instruction *> &Worklist) { 4023 // Push the def-use children onto the Worklist stack. 4024 for (User *U : I->users()) 4025 Worklist.push_back(cast<Instruction>(U)); 4026 } 4027 4028 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4029 SmallVector<Instruction *, 16> Worklist; 4030 PushDefUseChildren(PN, Worklist); 4031 4032 SmallPtrSet<Instruction *, 8> Visited; 4033 Visited.insert(PN); 4034 while (!Worklist.empty()) { 4035 Instruction *I = Worklist.pop_back_val(); 4036 if (!Visited.insert(I).second) 4037 continue; 4038 4039 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4040 if (It != ValueExprMap.end()) { 4041 const SCEV *Old = It->second; 4042 4043 // Short-circuit the def-use traversal if the symbolic name 4044 // ceases to appear in expressions. 4045 if (Old != SymName && !hasOperand(Old, SymName)) 4046 continue; 4047 4048 // SCEVUnknown for a PHI either means that it has an unrecognized 4049 // structure, it's a PHI that's in the progress of being computed 4050 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4051 // additional loop trip count information isn't going to change anything. 4052 // In the second case, createNodeForPHI will perform the necessary 4053 // updates on its own when it gets to that point. In the third, we do 4054 // want to forget the SCEVUnknown. 4055 if (!isa<PHINode>(I) || 4056 !isa<SCEVUnknown>(Old) || 4057 (I != PN && Old == SymName)) { 4058 eraseValueFromMap(It->first); 4059 forgetMemoizedResults(Old); 4060 } 4061 } 4062 4063 PushDefUseChildren(I, Worklist); 4064 } 4065 } 4066 4067 namespace { 4068 4069 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4070 public: 4071 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4072 ScalarEvolution &SE) { 4073 SCEVInitRewriter Rewriter(L, SE); 4074 const SCEV *Result = Rewriter.visit(S); 4075 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4076 } 4077 4078 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4079 if (!SE.isLoopInvariant(Expr, L)) 4080 Valid = false; 4081 return Expr; 4082 } 4083 4084 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4085 // Only allow AddRecExprs for this loop. 4086 if (Expr->getLoop() == L) 4087 return Expr->getStart(); 4088 Valid = false; 4089 return Expr; 4090 } 4091 4092 bool isValid() { return Valid; } 4093 4094 private: 4095 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4096 : SCEVRewriteVisitor(SE), L(L) {} 4097 4098 const Loop *L; 4099 bool Valid = true; 4100 }; 4101 4102 /// This class evaluates the compare condition by matching it against the 4103 /// condition of loop latch. If there is a match we assume a true value 4104 /// for the condition while building SCEV nodes. 4105 class SCEVBackedgeConditionFolder 4106 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4107 public: 4108 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4109 ScalarEvolution &SE) { 4110 bool IsPosBECond = false; 4111 Value *BECond = nullptr; 4112 if (BasicBlock *Latch = L->getLoopLatch()) { 4113 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4114 if (BI && BI->isConditional()) { 4115 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4116 "Both outgoing branches should not target same header!"); 4117 BECond = BI->getCondition(); 4118 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4119 } else { 4120 return S; 4121 } 4122 } 4123 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4124 return Rewriter.visit(S); 4125 } 4126 4127 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4128 const SCEV *Result = Expr; 4129 bool InvariantF = SE.isLoopInvariant(Expr, L); 4130 4131 if (!InvariantF) { 4132 Instruction *I = cast<Instruction>(Expr->getValue()); 4133 switch (I->getOpcode()) { 4134 case Instruction::Select: { 4135 SelectInst *SI = cast<SelectInst>(I); 4136 Optional<const SCEV *> Res = 4137 compareWithBackedgeCondition(SI->getCondition()); 4138 if (Res.hasValue()) { 4139 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4140 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4141 } 4142 break; 4143 } 4144 default: { 4145 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4146 if (Res.hasValue()) 4147 Result = Res.getValue(); 4148 break; 4149 } 4150 } 4151 } 4152 return Result; 4153 } 4154 4155 private: 4156 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4157 bool IsPosBECond, ScalarEvolution &SE) 4158 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4159 IsPositiveBECond(IsPosBECond) {} 4160 4161 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4162 4163 const Loop *L; 4164 /// Loop back condition. 4165 Value *BackedgeCond = nullptr; 4166 /// Set to true if loop back is on positive branch condition. 4167 bool IsPositiveBECond; 4168 }; 4169 4170 Optional<const SCEV *> 4171 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4172 4173 // If value matches the backedge condition for loop latch, 4174 // then return a constant evolution node based on loopback 4175 // branch taken. 4176 if (BackedgeCond == IC) 4177 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4178 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4179 return None; 4180 } 4181 4182 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4183 public: 4184 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4185 ScalarEvolution &SE) { 4186 SCEVShiftRewriter Rewriter(L, SE); 4187 const SCEV *Result = Rewriter.visit(S); 4188 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4189 } 4190 4191 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4192 // Only allow AddRecExprs for this loop. 4193 if (!SE.isLoopInvariant(Expr, L)) 4194 Valid = false; 4195 return Expr; 4196 } 4197 4198 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4199 if (Expr->getLoop() == L && Expr->isAffine()) 4200 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4201 Valid = false; 4202 return Expr; 4203 } 4204 4205 bool isValid() { return Valid; } 4206 4207 private: 4208 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4209 : SCEVRewriteVisitor(SE), L(L) {} 4210 4211 const Loop *L; 4212 bool Valid = true; 4213 }; 4214 4215 } // end anonymous namespace 4216 4217 SCEV::NoWrapFlags 4218 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4219 if (!AR->isAffine()) 4220 return SCEV::FlagAnyWrap; 4221 4222 using OBO = OverflowingBinaryOperator; 4223 4224 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4225 4226 if (!AR->hasNoSignedWrap()) { 4227 ConstantRange AddRecRange = getSignedRange(AR); 4228 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4229 4230 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4231 Instruction::Add, IncRange, OBO::NoSignedWrap); 4232 if (NSWRegion.contains(AddRecRange)) 4233 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4234 } 4235 4236 if (!AR->hasNoUnsignedWrap()) { 4237 ConstantRange AddRecRange = getUnsignedRange(AR); 4238 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4239 4240 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4241 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4242 if (NUWRegion.contains(AddRecRange)) 4243 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4244 } 4245 4246 return Result; 4247 } 4248 4249 namespace { 4250 4251 /// Represents an abstract binary operation. This may exist as a 4252 /// normal instruction or constant expression, or may have been 4253 /// derived from an expression tree. 4254 struct BinaryOp { 4255 unsigned Opcode; 4256 Value *LHS; 4257 Value *RHS; 4258 bool IsNSW = false; 4259 bool IsNUW = false; 4260 4261 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4262 /// constant expression. 4263 Operator *Op = nullptr; 4264 4265 explicit BinaryOp(Operator *Op) 4266 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4267 Op(Op) { 4268 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4269 IsNSW = OBO->hasNoSignedWrap(); 4270 IsNUW = OBO->hasNoUnsignedWrap(); 4271 } 4272 } 4273 4274 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4275 bool IsNUW = false) 4276 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4277 }; 4278 4279 } // end anonymous namespace 4280 4281 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4282 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4283 auto *Op = dyn_cast<Operator>(V); 4284 if (!Op) 4285 return None; 4286 4287 // Implementation detail: all the cleverness here should happen without 4288 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4289 // SCEV expressions when possible, and we should not break that. 4290 4291 switch (Op->getOpcode()) { 4292 case Instruction::Add: 4293 case Instruction::Sub: 4294 case Instruction::Mul: 4295 case Instruction::UDiv: 4296 case Instruction::URem: 4297 case Instruction::And: 4298 case Instruction::Or: 4299 case Instruction::AShr: 4300 case Instruction::Shl: 4301 return BinaryOp(Op); 4302 4303 case Instruction::Xor: 4304 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4305 // If the RHS of the xor is a signmask, then this is just an add. 4306 // Instcombine turns add of signmask into xor as a strength reduction step. 4307 if (RHSC->getValue().isSignMask()) 4308 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4309 return BinaryOp(Op); 4310 4311 case Instruction::LShr: 4312 // Turn logical shift right of a constant into a unsigned divide. 4313 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4314 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4315 4316 // If the shift count is not less than the bitwidth, the result of 4317 // the shift is undefined. Don't try to analyze it, because the 4318 // resolution chosen here may differ from the resolution chosen in 4319 // other parts of the compiler. 4320 if (SA->getValue().ult(BitWidth)) { 4321 Constant *X = 4322 ConstantInt::get(SA->getContext(), 4323 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4324 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4325 } 4326 } 4327 return BinaryOp(Op); 4328 4329 case Instruction::ExtractValue: { 4330 auto *EVI = cast<ExtractValueInst>(Op); 4331 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4332 break; 4333 4334 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4335 if (!CI) 4336 break; 4337 4338 if (auto *F = CI->getCalledFunction()) 4339 switch (F->getIntrinsicID()) { 4340 case Intrinsic::sadd_with_overflow: 4341 case Intrinsic::uadd_with_overflow: 4342 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4343 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4344 CI->getArgOperand(1)); 4345 4346 // Now that we know that all uses of the arithmetic-result component of 4347 // CI are guarded by the overflow check, we can go ahead and pretend 4348 // that the arithmetic is non-overflowing. 4349 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4350 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4351 CI->getArgOperand(1), /* IsNSW = */ true, 4352 /* IsNUW = */ false); 4353 else 4354 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4355 CI->getArgOperand(1), /* IsNSW = */ false, 4356 /* IsNUW*/ true); 4357 case Intrinsic::ssub_with_overflow: 4358 case Intrinsic::usub_with_overflow: 4359 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4360 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4361 CI->getArgOperand(1)); 4362 4363 // The same reasoning as sadd/uadd above. 4364 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4365 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4366 CI->getArgOperand(1), /* IsNSW = */ true, 4367 /* IsNUW = */ false); 4368 else 4369 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4370 CI->getArgOperand(1), /* IsNSW = */ false, 4371 /* IsNUW = */ true); 4372 case Intrinsic::smul_with_overflow: 4373 case Intrinsic::umul_with_overflow: 4374 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4375 CI->getArgOperand(1)); 4376 default: 4377 break; 4378 } 4379 break; 4380 } 4381 4382 default: 4383 break; 4384 } 4385 4386 return None; 4387 } 4388 4389 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4390 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4391 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4392 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4393 /// follows one of the following patterns: 4394 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4395 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4396 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4397 /// we return the type of the truncation operation, and indicate whether the 4398 /// truncated type should be treated as signed/unsigned by setting 4399 /// \p Signed to true/false, respectively. 4400 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4401 bool &Signed, ScalarEvolution &SE) { 4402 // The case where Op == SymbolicPHI (that is, with no type conversions on 4403 // the way) is handled by the regular add recurrence creating logic and 4404 // would have already been triggered in createAddRecForPHI. Reaching it here 4405 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4406 // because one of the other operands of the SCEVAddExpr updating this PHI is 4407 // not invariant). 4408 // 4409 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4410 // this case predicates that allow us to prove that Op == SymbolicPHI will 4411 // be added. 4412 if (Op == SymbolicPHI) 4413 return nullptr; 4414 4415 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4416 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4417 if (SourceBits != NewBits) 4418 return nullptr; 4419 4420 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4421 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4422 if (!SExt && !ZExt) 4423 return nullptr; 4424 const SCEVTruncateExpr *Trunc = 4425 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4426 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4427 if (!Trunc) 4428 return nullptr; 4429 const SCEV *X = Trunc->getOperand(); 4430 if (X != SymbolicPHI) 4431 return nullptr; 4432 Signed = SExt != nullptr; 4433 return Trunc->getType(); 4434 } 4435 4436 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4437 if (!PN->getType()->isIntegerTy()) 4438 return nullptr; 4439 const Loop *L = LI.getLoopFor(PN->getParent()); 4440 if (!L || L->getHeader() != PN->getParent()) 4441 return nullptr; 4442 return L; 4443 } 4444 4445 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4446 // computation that updates the phi follows the following pattern: 4447 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4448 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4449 // If so, try to see if it can be rewritten as an AddRecExpr under some 4450 // Predicates. If successful, return them as a pair. Also cache the results 4451 // of the analysis. 4452 // 4453 // Example usage scenario: 4454 // Say the Rewriter is called for the following SCEV: 4455 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4456 // where: 4457 // %X = phi i64 (%Start, %BEValue) 4458 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4459 // and call this function with %SymbolicPHI = %X. 4460 // 4461 // The analysis will find that the value coming around the backedge has 4462 // the following SCEV: 4463 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4464 // Upon concluding that this matches the desired pattern, the function 4465 // will return the pair {NewAddRec, SmallPredsVec} where: 4466 // NewAddRec = {%Start,+,%Step} 4467 // SmallPredsVec = {P1, P2, P3} as follows: 4468 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4469 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4470 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4471 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4472 // under the predicates {P1,P2,P3}. 4473 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4474 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4475 // 4476 // TODO's: 4477 // 4478 // 1) Extend the Induction descriptor to also support inductions that involve 4479 // casts: When needed (namely, when we are called in the context of the 4480 // vectorizer induction analysis), a Set of cast instructions will be 4481 // populated by this method, and provided back to isInductionPHI. This is 4482 // needed to allow the vectorizer to properly record them to be ignored by 4483 // the cost model and to avoid vectorizing them (otherwise these casts, 4484 // which are redundant under the runtime overflow checks, will be 4485 // vectorized, which can be costly). 4486 // 4487 // 2) Support additional induction/PHISCEV patterns: We also want to support 4488 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4489 // after the induction update operation (the induction increment): 4490 // 4491 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4492 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4493 // 4494 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4495 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4496 // 4497 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4498 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4499 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4500 SmallVector<const SCEVPredicate *, 3> Predicates; 4501 4502 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4503 // return an AddRec expression under some predicate. 4504 4505 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4506 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4507 assert(L && "Expecting an integer loop header phi"); 4508 4509 // The loop may have multiple entrances or multiple exits; we can analyze 4510 // this phi as an addrec if it has a unique entry value and a unique 4511 // backedge value. 4512 Value *BEValueV = nullptr, *StartValueV = nullptr; 4513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4514 Value *V = PN->getIncomingValue(i); 4515 if (L->contains(PN->getIncomingBlock(i))) { 4516 if (!BEValueV) { 4517 BEValueV = V; 4518 } else if (BEValueV != V) { 4519 BEValueV = nullptr; 4520 break; 4521 } 4522 } else if (!StartValueV) { 4523 StartValueV = V; 4524 } else if (StartValueV != V) { 4525 StartValueV = nullptr; 4526 break; 4527 } 4528 } 4529 if (!BEValueV || !StartValueV) 4530 return None; 4531 4532 const SCEV *BEValue = getSCEV(BEValueV); 4533 4534 // If the value coming around the backedge is an add with the symbolic 4535 // value we just inserted, possibly with casts that we can ignore under 4536 // an appropriate runtime guard, then we found a simple induction variable! 4537 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4538 if (!Add) 4539 return None; 4540 4541 // If there is a single occurrence of the symbolic value, possibly 4542 // casted, replace it with a recurrence. 4543 unsigned FoundIndex = Add->getNumOperands(); 4544 Type *TruncTy = nullptr; 4545 bool Signed; 4546 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4547 if ((TruncTy = 4548 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4549 if (FoundIndex == e) { 4550 FoundIndex = i; 4551 break; 4552 } 4553 4554 if (FoundIndex == Add->getNumOperands()) 4555 return None; 4556 4557 // Create an add with everything but the specified operand. 4558 SmallVector<const SCEV *, 8> Ops; 4559 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4560 if (i != FoundIndex) 4561 Ops.push_back(Add->getOperand(i)); 4562 const SCEV *Accum = getAddExpr(Ops); 4563 4564 // The runtime checks will not be valid if the step amount is 4565 // varying inside the loop. 4566 if (!isLoopInvariant(Accum, L)) 4567 return None; 4568 4569 // *** Part2: Create the predicates 4570 4571 // Analysis was successful: we have a phi-with-cast pattern for which we 4572 // can return an AddRec expression under the following predicates: 4573 // 4574 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4575 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4576 // P2: An Equal predicate that guarantees that 4577 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4578 // P3: An Equal predicate that guarantees that 4579 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4580 // 4581 // As we next prove, the above predicates guarantee that: 4582 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4583 // 4584 // 4585 // More formally, we want to prove that: 4586 // Expr(i+1) = Start + (i+1) * Accum 4587 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4588 // 4589 // Given that: 4590 // 1) Expr(0) = Start 4591 // 2) Expr(1) = Start + Accum 4592 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4593 // 3) Induction hypothesis (step i): 4594 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4595 // 4596 // Proof: 4597 // Expr(i+1) = 4598 // = Start + (i+1)*Accum 4599 // = (Start + i*Accum) + Accum 4600 // = Expr(i) + Accum 4601 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4602 // :: from step i 4603 // 4604 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4605 // 4606 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4607 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4608 // + Accum :: from P3 4609 // 4610 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4611 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4612 // 4613 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4614 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4615 // 4616 // By induction, the same applies to all iterations 1<=i<n: 4617 // 4618 4619 // Create a truncated addrec for which we will add a no overflow check (P1). 4620 const SCEV *StartVal = getSCEV(StartValueV); 4621 const SCEV *PHISCEV = 4622 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4623 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4624 4625 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4626 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4627 // will be constant. 4628 // 4629 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4630 // add P1. 4631 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4632 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4633 Signed ? SCEVWrapPredicate::IncrementNSSW 4634 : SCEVWrapPredicate::IncrementNUSW; 4635 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4636 Predicates.push_back(AddRecPred); 4637 } 4638 4639 // Create the Equal Predicates P2,P3: 4640 4641 // It is possible that the predicates P2 and/or P3 are computable at 4642 // compile time due to StartVal and/or Accum being constants. 4643 // If either one is, then we can check that now and escape if either P2 4644 // or P3 is false. 4645 4646 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4647 // for each of StartVal and Accum 4648 auto getExtendedExpr = [&](const SCEV *Expr, 4649 bool CreateSignExtend) -> const SCEV * { 4650 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4651 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4652 const SCEV *ExtendedExpr = 4653 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4654 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4655 return ExtendedExpr; 4656 }; 4657 4658 // Given: 4659 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4660 // = getExtendedExpr(Expr) 4661 // Determine whether the predicate P: Expr == ExtendedExpr 4662 // is known to be false at compile time 4663 auto PredIsKnownFalse = [&](const SCEV *Expr, 4664 const SCEV *ExtendedExpr) -> bool { 4665 return Expr != ExtendedExpr && 4666 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4667 }; 4668 4669 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4670 if (PredIsKnownFalse(StartVal, StartExtended)) { 4671 DEBUG(dbgs() << "P2 is compile-time false\n";); 4672 return None; 4673 } 4674 4675 // The Step is always Signed (because the overflow checks are either 4676 // NSSW or NUSW) 4677 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4678 if (PredIsKnownFalse(Accum, AccumExtended)) { 4679 DEBUG(dbgs() << "P3 is compile-time false\n";); 4680 return None; 4681 } 4682 4683 auto AppendPredicate = [&](const SCEV *Expr, 4684 const SCEV *ExtendedExpr) -> void { 4685 if (Expr != ExtendedExpr && 4686 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4687 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4688 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4689 Predicates.push_back(Pred); 4690 } 4691 }; 4692 4693 AppendPredicate(StartVal, StartExtended); 4694 AppendPredicate(Accum, AccumExtended); 4695 4696 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4697 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4698 // into NewAR if it will also add the runtime overflow checks specified in 4699 // Predicates. 4700 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4701 4702 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4703 std::make_pair(NewAR, Predicates); 4704 // Remember the result of the analysis for this SCEV at this locayyytion. 4705 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4706 return PredRewrite; 4707 } 4708 4709 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4710 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4711 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4712 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4713 if (!L) 4714 return None; 4715 4716 // Check to see if we already analyzed this PHI. 4717 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4718 if (I != PredicatedSCEVRewrites.end()) { 4719 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4720 I->second; 4721 // Analysis was done before and failed to create an AddRec: 4722 if (Rewrite.first == SymbolicPHI) 4723 return None; 4724 // Analysis was done before and succeeded to create an AddRec under 4725 // a predicate: 4726 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4727 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4728 return Rewrite; 4729 } 4730 4731 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4732 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4733 4734 // Record in the cache that the analysis failed 4735 if (!Rewrite) { 4736 SmallVector<const SCEVPredicate *, 3> Predicates; 4737 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4738 return None; 4739 } 4740 4741 return Rewrite; 4742 } 4743 4744 // FIXME: This utility is currently required because the Rewriter currently 4745 // does not rewrite this expression: 4746 // {0, +, (sext ix (trunc iy to ix) to iy)} 4747 // into {0, +, %step}, 4748 // even when the following Equal predicate exists: 4749 // "%step == (sext ix (trunc iy to ix) to iy)". 4750 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4751 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4752 if (AR1 == AR2) 4753 return true; 4754 4755 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4756 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4757 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4758 return false; 4759 return true; 4760 }; 4761 4762 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4763 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4764 return false; 4765 return true; 4766 } 4767 4768 /// A helper function for createAddRecFromPHI to handle simple cases. 4769 /// 4770 /// This function tries to find an AddRec expression for the simplest (yet most 4771 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4772 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4773 /// technique for finding the AddRec expression. 4774 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4775 Value *BEValueV, 4776 Value *StartValueV) { 4777 const Loop *L = LI.getLoopFor(PN->getParent()); 4778 assert(L && L->getHeader() == PN->getParent()); 4779 assert(BEValueV && StartValueV); 4780 4781 auto BO = MatchBinaryOp(BEValueV, DT); 4782 if (!BO) 4783 return nullptr; 4784 4785 if (BO->Opcode != Instruction::Add) 4786 return nullptr; 4787 4788 const SCEV *Accum = nullptr; 4789 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4790 Accum = getSCEV(BO->RHS); 4791 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4792 Accum = getSCEV(BO->LHS); 4793 4794 if (!Accum) 4795 return nullptr; 4796 4797 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4798 if (BO->IsNUW) 4799 Flags = setFlags(Flags, SCEV::FlagNUW); 4800 if (BO->IsNSW) 4801 Flags = setFlags(Flags, SCEV::FlagNSW); 4802 4803 const SCEV *StartVal = getSCEV(StartValueV); 4804 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4805 4806 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4807 4808 // We can add Flags to the post-inc expression only if we 4809 // know that it is *undefined behavior* for BEValueV to 4810 // overflow. 4811 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4812 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4813 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4814 4815 return PHISCEV; 4816 } 4817 4818 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4819 const Loop *L = LI.getLoopFor(PN->getParent()); 4820 if (!L || L->getHeader() != PN->getParent()) 4821 return nullptr; 4822 4823 // The loop may have multiple entrances or multiple exits; we can analyze 4824 // this phi as an addrec if it has a unique entry value and a unique 4825 // backedge value. 4826 Value *BEValueV = nullptr, *StartValueV = nullptr; 4827 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4828 Value *V = PN->getIncomingValue(i); 4829 if (L->contains(PN->getIncomingBlock(i))) { 4830 if (!BEValueV) { 4831 BEValueV = V; 4832 } else if (BEValueV != V) { 4833 BEValueV = nullptr; 4834 break; 4835 } 4836 } else if (!StartValueV) { 4837 StartValueV = V; 4838 } else if (StartValueV != V) { 4839 StartValueV = nullptr; 4840 break; 4841 } 4842 } 4843 if (!BEValueV || !StartValueV) 4844 return nullptr; 4845 4846 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4847 "PHI node already processed?"); 4848 4849 // First, try to find AddRec expression without creating a fictituos symbolic 4850 // value for PN. 4851 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4852 return S; 4853 4854 // Handle PHI node value symbolically. 4855 const SCEV *SymbolicName = getUnknown(PN); 4856 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4857 4858 // Using this symbolic name for the PHI, analyze the value coming around 4859 // the back-edge. 4860 const SCEV *BEValue = getSCEV(BEValueV); 4861 4862 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4863 // has a special value for the first iteration of the loop. 4864 4865 // If the value coming around the backedge is an add with the symbolic 4866 // value we just inserted, then we found a simple induction variable! 4867 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4868 // If there is a single occurrence of the symbolic value, replace it 4869 // with a recurrence. 4870 unsigned FoundIndex = Add->getNumOperands(); 4871 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4872 if (Add->getOperand(i) == SymbolicName) 4873 if (FoundIndex == e) { 4874 FoundIndex = i; 4875 break; 4876 } 4877 4878 if (FoundIndex != Add->getNumOperands()) { 4879 // Create an add with everything but the specified operand. 4880 SmallVector<const SCEV *, 8> Ops; 4881 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4882 if (i != FoundIndex) 4883 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4884 L, *this)); 4885 const SCEV *Accum = getAddExpr(Ops); 4886 4887 // This is not a valid addrec if the step amount is varying each 4888 // loop iteration, but is not itself an addrec in this loop. 4889 if (isLoopInvariant(Accum, L) || 4890 (isa<SCEVAddRecExpr>(Accum) && 4891 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4892 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4893 4894 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4895 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4896 if (BO->IsNUW) 4897 Flags = setFlags(Flags, SCEV::FlagNUW); 4898 if (BO->IsNSW) 4899 Flags = setFlags(Flags, SCEV::FlagNSW); 4900 } 4901 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4902 // If the increment is an inbounds GEP, then we know the address 4903 // space cannot be wrapped around. We cannot make any guarantee 4904 // about signed or unsigned overflow because pointers are 4905 // unsigned but we may have a negative index from the base 4906 // pointer. We can guarantee that no unsigned wrap occurs if the 4907 // indices form a positive value. 4908 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4909 Flags = setFlags(Flags, SCEV::FlagNW); 4910 4911 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4912 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4913 Flags = setFlags(Flags, SCEV::FlagNUW); 4914 } 4915 4916 // We cannot transfer nuw and nsw flags from subtraction 4917 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4918 // for instance. 4919 } 4920 4921 const SCEV *StartVal = getSCEV(StartValueV); 4922 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4923 4924 // Okay, for the entire analysis of this edge we assumed the PHI 4925 // to be symbolic. We now need to go back and purge all of the 4926 // entries for the scalars that use the symbolic expression. 4927 forgetSymbolicName(PN, SymbolicName); 4928 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4929 4930 // We can add Flags to the post-inc expression only if we 4931 // know that it is *undefined behavior* for BEValueV to 4932 // overflow. 4933 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4934 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4935 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4936 4937 return PHISCEV; 4938 } 4939 } 4940 } else { 4941 // Otherwise, this could be a loop like this: 4942 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4943 // In this case, j = {1,+,1} and BEValue is j. 4944 // Because the other in-value of i (0) fits the evolution of BEValue 4945 // i really is an addrec evolution. 4946 // 4947 // We can generalize this saying that i is the shifted value of BEValue 4948 // by one iteration: 4949 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4950 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4951 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4952 if (Shifted != getCouldNotCompute() && 4953 Start != getCouldNotCompute()) { 4954 const SCEV *StartVal = getSCEV(StartValueV); 4955 if (Start == StartVal) { 4956 // Okay, for the entire analysis of this edge we assumed the PHI 4957 // to be symbolic. We now need to go back and purge all of the 4958 // entries for the scalars that use the symbolic expression. 4959 forgetSymbolicName(PN, SymbolicName); 4960 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4961 return Shifted; 4962 } 4963 } 4964 } 4965 4966 // Remove the temporary PHI node SCEV that has been inserted while intending 4967 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4968 // as it will prevent later (possibly simpler) SCEV expressions to be added 4969 // to the ValueExprMap. 4970 eraseValueFromMap(PN); 4971 4972 return nullptr; 4973 } 4974 4975 // Checks if the SCEV S is available at BB. S is considered available at BB 4976 // if S can be materialized at BB without introducing a fault. 4977 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4978 BasicBlock *BB) { 4979 struct CheckAvailable { 4980 bool TraversalDone = false; 4981 bool Available = true; 4982 4983 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4984 BasicBlock *BB = nullptr; 4985 DominatorTree &DT; 4986 4987 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4988 : L(L), BB(BB), DT(DT) {} 4989 4990 bool setUnavailable() { 4991 TraversalDone = true; 4992 Available = false; 4993 return false; 4994 } 4995 4996 bool follow(const SCEV *S) { 4997 switch (S->getSCEVType()) { 4998 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4999 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5000 // These expressions are available if their operand(s) is/are. 5001 return true; 5002 5003 case scAddRecExpr: { 5004 // We allow add recurrences that are on the loop BB is in, or some 5005 // outer loop. This guarantees availability because the value of the 5006 // add recurrence at BB is simply the "current" value of the induction 5007 // variable. We can relax this in the future; for instance an add 5008 // recurrence on a sibling dominating loop is also available at BB. 5009 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5010 if (L && (ARLoop == L || ARLoop->contains(L))) 5011 return true; 5012 5013 return setUnavailable(); 5014 } 5015 5016 case scUnknown: { 5017 // For SCEVUnknown, we check for simple dominance. 5018 const auto *SU = cast<SCEVUnknown>(S); 5019 Value *V = SU->getValue(); 5020 5021 if (isa<Argument>(V)) 5022 return false; 5023 5024 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5025 return false; 5026 5027 return setUnavailable(); 5028 } 5029 5030 case scUDivExpr: 5031 case scCouldNotCompute: 5032 // We do not try to smart about these at all. 5033 return setUnavailable(); 5034 } 5035 llvm_unreachable("switch should be fully covered!"); 5036 } 5037 5038 bool isDone() { return TraversalDone; } 5039 }; 5040 5041 CheckAvailable CA(L, BB, DT); 5042 SCEVTraversal<CheckAvailable> ST(CA); 5043 5044 ST.visitAll(S); 5045 return CA.Available; 5046 } 5047 5048 // Try to match a control flow sequence that branches out at BI and merges back 5049 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5050 // match. 5051 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5052 Value *&C, Value *&LHS, Value *&RHS) { 5053 C = BI->getCondition(); 5054 5055 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5056 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5057 5058 if (!LeftEdge.isSingleEdge()) 5059 return false; 5060 5061 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5062 5063 Use &LeftUse = Merge->getOperandUse(0); 5064 Use &RightUse = Merge->getOperandUse(1); 5065 5066 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5067 LHS = LeftUse; 5068 RHS = RightUse; 5069 return true; 5070 } 5071 5072 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5073 LHS = RightUse; 5074 RHS = LeftUse; 5075 return true; 5076 } 5077 5078 return false; 5079 } 5080 5081 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5082 auto IsReachable = 5083 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5084 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5085 const Loop *L = LI.getLoopFor(PN->getParent()); 5086 5087 // We don't want to break LCSSA, even in a SCEV expression tree. 5088 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5089 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5090 return nullptr; 5091 5092 // Try to match 5093 // 5094 // br %cond, label %left, label %right 5095 // left: 5096 // br label %merge 5097 // right: 5098 // br label %merge 5099 // merge: 5100 // V = phi [ %x, %left ], [ %y, %right ] 5101 // 5102 // as "select %cond, %x, %y" 5103 5104 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5105 assert(IDom && "At least the entry block should dominate PN"); 5106 5107 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5108 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5109 5110 if (BI && BI->isConditional() && 5111 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5112 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5113 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5114 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5115 } 5116 5117 return nullptr; 5118 } 5119 5120 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5121 if (const SCEV *S = createAddRecFromPHI(PN)) 5122 return S; 5123 5124 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5125 return S; 5126 5127 // If the PHI has a single incoming value, follow that value, unless the 5128 // PHI's incoming blocks are in a different loop, in which case doing so 5129 // risks breaking LCSSA form. Instcombine would normally zap these, but 5130 // it doesn't have DominatorTree information, so it may miss cases. 5131 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5132 if (LI.replacementPreservesLCSSAForm(PN, V)) 5133 return getSCEV(V); 5134 5135 // If it's not a loop phi, we can't handle it yet. 5136 return getUnknown(PN); 5137 } 5138 5139 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5140 Value *Cond, 5141 Value *TrueVal, 5142 Value *FalseVal) { 5143 // Handle "constant" branch or select. This can occur for instance when a 5144 // loop pass transforms an inner loop and moves on to process the outer loop. 5145 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5146 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5147 5148 // Try to match some simple smax or umax patterns. 5149 auto *ICI = dyn_cast<ICmpInst>(Cond); 5150 if (!ICI) 5151 return getUnknown(I); 5152 5153 Value *LHS = ICI->getOperand(0); 5154 Value *RHS = ICI->getOperand(1); 5155 5156 switch (ICI->getPredicate()) { 5157 case ICmpInst::ICMP_SLT: 5158 case ICmpInst::ICMP_SLE: 5159 std::swap(LHS, RHS); 5160 LLVM_FALLTHROUGH; 5161 case ICmpInst::ICMP_SGT: 5162 case ICmpInst::ICMP_SGE: 5163 // a >s b ? a+x : b+x -> smax(a, b)+x 5164 // a >s b ? b+x : a+x -> smin(a, b)+x 5165 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5166 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5167 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5168 const SCEV *LA = getSCEV(TrueVal); 5169 const SCEV *RA = getSCEV(FalseVal); 5170 const SCEV *LDiff = getMinusSCEV(LA, LS); 5171 const SCEV *RDiff = getMinusSCEV(RA, RS); 5172 if (LDiff == RDiff) 5173 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5174 LDiff = getMinusSCEV(LA, RS); 5175 RDiff = getMinusSCEV(RA, LS); 5176 if (LDiff == RDiff) 5177 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5178 } 5179 break; 5180 case ICmpInst::ICMP_ULT: 5181 case ICmpInst::ICMP_ULE: 5182 std::swap(LHS, RHS); 5183 LLVM_FALLTHROUGH; 5184 case ICmpInst::ICMP_UGT: 5185 case ICmpInst::ICMP_UGE: 5186 // a >u b ? a+x : b+x -> umax(a, b)+x 5187 // a >u b ? b+x : a+x -> umin(a, b)+x 5188 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5189 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5190 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5191 const SCEV *LA = getSCEV(TrueVal); 5192 const SCEV *RA = getSCEV(FalseVal); 5193 const SCEV *LDiff = getMinusSCEV(LA, LS); 5194 const SCEV *RDiff = getMinusSCEV(RA, RS); 5195 if (LDiff == RDiff) 5196 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5197 LDiff = getMinusSCEV(LA, RS); 5198 RDiff = getMinusSCEV(RA, LS); 5199 if (LDiff == RDiff) 5200 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5201 } 5202 break; 5203 case ICmpInst::ICMP_NE: 5204 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5205 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5206 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5207 const SCEV *One = getOne(I->getType()); 5208 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), 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, One); 5213 if (LDiff == RDiff) 5214 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5215 } 5216 break; 5217 case ICmpInst::ICMP_EQ: 5218 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5219 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5220 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5221 const SCEV *One = getOne(I->getType()); 5222 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5223 const SCEV *LA = getSCEV(TrueVal); 5224 const SCEV *RA = getSCEV(FalseVal); 5225 const SCEV *LDiff = getMinusSCEV(LA, One); 5226 const SCEV *RDiff = getMinusSCEV(RA, LS); 5227 if (LDiff == RDiff) 5228 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5229 } 5230 break; 5231 default: 5232 break; 5233 } 5234 5235 return getUnknown(I); 5236 } 5237 5238 /// Expand GEP instructions into add and multiply operations. This allows them 5239 /// to be analyzed by regular SCEV code. 5240 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5241 // Don't attempt to analyze GEPs over unsized objects. 5242 if (!GEP->getSourceElementType()->isSized()) 5243 return getUnknown(GEP); 5244 5245 SmallVector<const SCEV *, 4> IndexExprs; 5246 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5247 IndexExprs.push_back(getSCEV(*Index)); 5248 return getGEPExpr(GEP, IndexExprs); 5249 } 5250 5251 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5252 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5253 return C->getAPInt().countTrailingZeros(); 5254 5255 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5256 return std::min(GetMinTrailingZeros(T->getOperand()), 5257 (uint32_t)getTypeSizeInBits(T->getType())); 5258 5259 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5260 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5261 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5262 ? getTypeSizeInBits(E->getType()) 5263 : OpRes; 5264 } 5265 5266 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5267 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5268 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5269 ? getTypeSizeInBits(E->getType()) 5270 : OpRes; 5271 } 5272 5273 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5274 // The result is the min of all operands results. 5275 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5276 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5277 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5278 return MinOpRes; 5279 } 5280 5281 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5282 // The result is the sum of all operands results. 5283 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5284 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5285 for (unsigned i = 1, e = M->getNumOperands(); 5286 SumOpRes != BitWidth && i != e; ++i) 5287 SumOpRes = 5288 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5289 return SumOpRes; 5290 } 5291 5292 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5293 // The result is the min of all operands results. 5294 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5295 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5296 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5297 return MinOpRes; 5298 } 5299 5300 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5301 // The result is the min of all operands results. 5302 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5303 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5304 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5305 return MinOpRes; 5306 } 5307 5308 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5309 // The result is the min of all operands results. 5310 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5311 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5312 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5313 return MinOpRes; 5314 } 5315 5316 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5317 // For a SCEVUnknown, ask ValueTracking. 5318 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5319 return Known.countMinTrailingZeros(); 5320 } 5321 5322 // SCEVUDivExpr 5323 return 0; 5324 } 5325 5326 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5327 auto I = MinTrailingZerosCache.find(S); 5328 if (I != MinTrailingZerosCache.end()) 5329 return I->second; 5330 5331 uint32_t Result = GetMinTrailingZerosImpl(S); 5332 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5333 assert(InsertPair.second && "Should insert a new key"); 5334 return InsertPair.first->second; 5335 } 5336 5337 /// Helper method to assign a range to V from metadata present in the IR. 5338 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5339 if (Instruction *I = dyn_cast<Instruction>(V)) 5340 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5341 return getConstantRangeFromMetadata(*MD); 5342 5343 return None; 5344 } 5345 5346 /// Determine the range for a particular SCEV. If SignHint is 5347 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5348 /// with a "cleaner" unsigned (resp. signed) representation. 5349 const ConstantRange & 5350 ScalarEvolution::getRangeRef(const SCEV *S, 5351 ScalarEvolution::RangeSignHint SignHint) { 5352 DenseMap<const SCEV *, ConstantRange> &Cache = 5353 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5354 : SignedRanges; 5355 5356 // See if we've computed this range already. 5357 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5358 if (I != Cache.end()) 5359 return I->second; 5360 5361 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5362 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5363 5364 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5365 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5366 5367 // If the value has known zeros, the maximum value will have those known zeros 5368 // as well. 5369 uint32_t TZ = GetMinTrailingZeros(S); 5370 if (TZ != 0) { 5371 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5372 ConservativeResult = 5373 ConstantRange(APInt::getMinValue(BitWidth), 5374 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5375 else 5376 ConservativeResult = ConstantRange( 5377 APInt::getSignedMinValue(BitWidth), 5378 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5379 } 5380 5381 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5382 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5383 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5384 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5385 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5386 } 5387 5388 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5389 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5390 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5391 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5392 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5393 } 5394 5395 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5396 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5397 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5398 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5399 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5400 } 5401 5402 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5403 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5404 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5405 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5406 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5407 } 5408 5409 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5410 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5411 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5412 return setRange(UDiv, SignHint, 5413 ConservativeResult.intersectWith(X.udiv(Y))); 5414 } 5415 5416 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5417 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5418 return setRange(ZExt, SignHint, 5419 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5420 } 5421 5422 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5423 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5424 return setRange(SExt, SignHint, 5425 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5426 } 5427 5428 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5429 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5430 return setRange(Trunc, SignHint, 5431 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5432 } 5433 5434 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5435 // If there's no unsigned wrap, the value will never be less than its 5436 // initial value. 5437 if (AddRec->hasNoUnsignedWrap()) 5438 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5439 if (!C->getValue()->isZero()) 5440 ConservativeResult = ConservativeResult.intersectWith( 5441 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5442 5443 // If there's no signed wrap, and all the operands have the same sign or 5444 // zero, the value won't ever change sign. 5445 if (AddRec->hasNoSignedWrap()) { 5446 bool AllNonNeg = true; 5447 bool AllNonPos = true; 5448 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5449 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5450 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5451 } 5452 if (AllNonNeg) 5453 ConservativeResult = ConservativeResult.intersectWith( 5454 ConstantRange(APInt(BitWidth, 0), 5455 APInt::getSignedMinValue(BitWidth))); 5456 else if (AllNonPos) 5457 ConservativeResult = ConservativeResult.intersectWith( 5458 ConstantRange(APInt::getSignedMinValue(BitWidth), 5459 APInt(BitWidth, 1))); 5460 } 5461 5462 // TODO: non-affine addrec 5463 if (AddRec->isAffine()) { 5464 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5465 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5466 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5467 auto RangeFromAffine = getRangeForAffineAR( 5468 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5469 BitWidth); 5470 if (!RangeFromAffine.isFullSet()) 5471 ConservativeResult = 5472 ConservativeResult.intersectWith(RangeFromAffine); 5473 5474 auto RangeFromFactoring = getRangeViaFactoring( 5475 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5476 BitWidth); 5477 if (!RangeFromFactoring.isFullSet()) 5478 ConservativeResult = 5479 ConservativeResult.intersectWith(RangeFromFactoring); 5480 } 5481 } 5482 5483 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5484 } 5485 5486 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5487 // Check if the IR explicitly contains !range metadata. 5488 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5489 if (MDRange.hasValue()) 5490 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5491 5492 // Split here to avoid paying the compile-time cost of calling both 5493 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5494 // if needed. 5495 const DataLayout &DL = getDataLayout(); 5496 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5497 // For a SCEVUnknown, ask ValueTracking. 5498 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5499 if (Known.One != ~Known.Zero + 1) 5500 ConservativeResult = 5501 ConservativeResult.intersectWith(ConstantRange(Known.One, 5502 ~Known.Zero + 1)); 5503 } else { 5504 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5505 "generalize as needed!"); 5506 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5507 if (NS > 1) 5508 ConservativeResult = ConservativeResult.intersectWith( 5509 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5510 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5511 } 5512 5513 return setRange(U, SignHint, std::move(ConservativeResult)); 5514 } 5515 5516 return setRange(S, SignHint, std::move(ConservativeResult)); 5517 } 5518 5519 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5520 // values that the expression can take. Initially, the expression has a value 5521 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5522 // argument defines if we treat Step as signed or unsigned. 5523 static ConstantRange getRangeForAffineARHelper(APInt Step, 5524 const ConstantRange &StartRange, 5525 const APInt &MaxBECount, 5526 unsigned BitWidth, bool Signed) { 5527 // If either Step or MaxBECount is 0, then the expression won't change, and we 5528 // just need to return the initial range. 5529 if (Step == 0 || MaxBECount == 0) 5530 return StartRange; 5531 5532 // If we don't know anything about the initial value (i.e. StartRange is 5533 // FullRange), then we don't know anything about the final range either. 5534 // Return FullRange. 5535 if (StartRange.isFullSet()) 5536 return ConstantRange(BitWidth, /* isFullSet = */ true); 5537 5538 // If Step is signed and negative, then we use its absolute value, but we also 5539 // note that we're moving in the opposite direction. 5540 bool Descending = Signed && Step.isNegative(); 5541 5542 if (Signed) 5543 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5544 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5545 // This equations hold true due to the well-defined wrap-around behavior of 5546 // APInt. 5547 Step = Step.abs(); 5548 5549 // Check if Offset is more than full span of BitWidth. If it is, the 5550 // expression is guaranteed to overflow. 5551 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5552 return ConstantRange(BitWidth, /* isFullSet = */ true); 5553 5554 // Offset is by how much the expression can change. Checks above guarantee no 5555 // overflow here. 5556 APInt Offset = Step * MaxBECount; 5557 5558 // Minimum value of the final range will match the minimal value of StartRange 5559 // if the expression is increasing and will be decreased by Offset otherwise. 5560 // Maximum value of the final range will match the maximal value of StartRange 5561 // if the expression is decreasing and will be increased by Offset otherwise. 5562 APInt StartLower = StartRange.getLower(); 5563 APInt StartUpper = StartRange.getUpper() - 1; 5564 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5565 : (StartUpper + std::move(Offset)); 5566 5567 // It's possible that the new minimum/maximum value will fall into the initial 5568 // range (due to wrap around). This means that the expression can take any 5569 // value in this bitwidth, and we have to return full range. 5570 if (StartRange.contains(MovedBoundary)) 5571 return ConstantRange(BitWidth, /* isFullSet = */ true); 5572 5573 APInt NewLower = 5574 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5575 APInt NewUpper = 5576 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5577 NewUpper += 1; 5578 5579 // If we end up with full range, return a proper full range. 5580 if (NewLower == NewUpper) 5581 return ConstantRange(BitWidth, /* isFullSet = */ true); 5582 5583 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5584 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5585 } 5586 5587 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5588 const SCEV *Step, 5589 const SCEV *MaxBECount, 5590 unsigned BitWidth) { 5591 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5592 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5593 "Precondition!"); 5594 5595 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5596 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5597 5598 // First, consider step signed. 5599 ConstantRange StartSRange = getSignedRange(Start); 5600 ConstantRange StepSRange = getSignedRange(Step); 5601 5602 // If Step can be both positive and negative, we need to find ranges for the 5603 // maximum absolute step values in both directions and union them. 5604 ConstantRange SR = 5605 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5606 MaxBECountValue, BitWidth, /* Signed = */ true); 5607 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5608 StartSRange, MaxBECountValue, 5609 BitWidth, /* Signed = */ true)); 5610 5611 // Next, consider step unsigned. 5612 ConstantRange UR = getRangeForAffineARHelper( 5613 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5614 MaxBECountValue, BitWidth, /* Signed = */ false); 5615 5616 // Finally, intersect signed and unsigned ranges. 5617 return SR.intersectWith(UR); 5618 } 5619 5620 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5621 const SCEV *Step, 5622 const SCEV *MaxBECount, 5623 unsigned BitWidth) { 5624 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5625 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5626 5627 struct SelectPattern { 5628 Value *Condition = nullptr; 5629 APInt TrueValue; 5630 APInt FalseValue; 5631 5632 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5633 const SCEV *S) { 5634 Optional<unsigned> CastOp; 5635 APInt Offset(BitWidth, 0); 5636 5637 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5638 "Should be!"); 5639 5640 // Peel off a constant offset: 5641 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5642 // In the future we could consider being smarter here and handle 5643 // {Start+Step,+,Step} too. 5644 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5645 return; 5646 5647 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5648 S = SA->getOperand(1); 5649 } 5650 5651 // Peel off a cast operation 5652 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5653 CastOp = SCast->getSCEVType(); 5654 S = SCast->getOperand(); 5655 } 5656 5657 using namespace llvm::PatternMatch; 5658 5659 auto *SU = dyn_cast<SCEVUnknown>(S); 5660 const APInt *TrueVal, *FalseVal; 5661 if (!SU || 5662 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5663 m_APInt(FalseVal)))) { 5664 Condition = nullptr; 5665 return; 5666 } 5667 5668 TrueValue = *TrueVal; 5669 FalseValue = *FalseVal; 5670 5671 // Re-apply the cast we peeled off earlier 5672 if (CastOp.hasValue()) 5673 switch (*CastOp) { 5674 default: 5675 llvm_unreachable("Unknown SCEV cast type!"); 5676 5677 case scTruncate: 5678 TrueValue = TrueValue.trunc(BitWidth); 5679 FalseValue = FalseValue.trunc(BitWidth); 5680 break; 5681 case scZeroExtend: 5682 TrueValue = TrueValue.zext(BitWidth); 5683 FalseValue = FalseValue.zext(BitWidth); 5684 break; 5685 case scSignExtend: 5686 TrueValue = TrueValue.sext(BitWidth); 5687 FalseValue = FalseValue.sext(BitWidth); 5688 break; 5689 } 5690 5691 // Re-apply the constant offset we peeled off earlier 5692 TrueValue += Offset; 5693 FalseValue += Offset; 5694 } 5695 5696 bool isRecognized() { return Condition != nullptr; } 5697 }; 5698 5699 SelectPattern StartPattern(*this, BitWidth, Start); 5700 if (!StartPattern.isRecognized()) 5701 return ConstantRange(BitWidth, /* isFullSet = */ true); 5702 5703 SelectPattern StepPattern(*this, BitWidth, Step); 5704 if (!StepPattern.isRecognized()) 5705 return ConstantRange(BitWidth, /* isFullSet = */ true); 5706 5707 if (StartPattern.Condition != StepPattern.Condition) { 5708 // We don't handle this case today; but we could, by considering four 5709 // possibilities below instead of two. I'm not sure if there are cases where 5710 // that will help over what getRange already does, though. 5711 return ConstantRange(BitWidth, /* isFullSet = */ true); 5712 } 5713 5714 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5715 // construct arbitrary general SCEV expressions here. This function is called 5716 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5717 // say) can end up caching a suboptimal value. 5718 5719 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5720 // C2352 and C2512 (otherwise it isn't needed). 5721 5722 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5723 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5724 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5725 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5726 5727 ConstantRange TrueRange = 5728 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5729 ConstantRange FalseRange = 5730 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5731 5732 return TrueRange.unionWith(FalseRange); 5733 } 5734 5735 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5736 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5737 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5738 5739 // Return early if there are no flags to propagate to the SCEV. 5740 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5741 if (BinOp->hasNoUnsignedWrap()) 5742 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5743 if (BinOp->hasNoSignedWrap()) 5744 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5745 if (Flags == SCEV::FlagAnyWrap) 5746 return SCEV::FlagAnyWrap; 5747 5748 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5749 } 5750 5751 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5752 // Here we check that I is in the header of the innermost loop containing I, 5753 // since we only deal with instructions in the loop header. The actual loop we 5754 // need to check later will come from an add recurrence, but getting that 5755 // requires computing the SCEV of the operands, which can be expensive. This 5756 // check we can do cheaply to rule out some cases early. 5757 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5758 if (InnermostContainingLoop == nullptr || 5759 InnermostContainingLoop->getHeader() != I->getParent()) 5760 return false; 5761 5762 // Only proceed if we can prove that I does not yield poison. 5763 if (!programUndefinedIfFullPoison(I)) 5764 return false; 5765 5766 // At this point we know that if I is executed, then it does not wrap 5767 // according to at least one of NSW or NUW. If I is not executed, then we do 5768 // not know if the calculation that I represents would wrap. Multiple 5769 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5770 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5771 // derived from other instructions that map to the same SCEV. We cannot make 5772 // that guarantee for cases where I is not executed. So we need to find the 5773 // loop that I is considered in relation to and prove that I is executed for 5774 // every iteration of that loop. That implies that the value that I 5775 // calculates does not wrap anywhere in the loop, so then we can apply the 5776 // flags to the SCEV. 5777 // 5778 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5779 // from different loops, so that we know which loop to prove that I is 5780 // executed in. 5781 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5782 // I could be an extractvalue from a call to an overflow intrinsic. 5783 // TODO: We can do better here in some cases. 5784 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5785 return false; 5786 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5787 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5788 bool AllOtherOpsLoopInvariant = true; 5789 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5790 ++OtherOpIndex) { 5791 if (OtherOpIndex != OpIndex) { 5792 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5793 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5794 AllOtherOpsLoopInvariant = false; 5795 break; 5796 } 5797 } 5798 } 5799 if (AllOtherOpsLoopInvariant && 5800 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5801 return true; 5802 } 5803 } 5804 return false; 5805 } 5806 5807 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5808 // If we know that \c I can never be poison period, then that's enough. 5809 if (isSCEVExprNeverPoison(I)) 5810 return true; 5811 5812 // For an add recurrence specifically, we assume that infinite loops without 5813 // side effects are undefined behavior, and then reason as follows: 5814 // 5815 // If the add recurrence is poison in any iteration, it is poison on all 5816 // future iterations (since incrementing poison yields poison). If the result 5817 // of the add recurrence is fed into the loop latch condition and the loop 5818 // does not contain any throws or exiting blocks other than the latch, we now 5819 // have the ability to "choose" whether the backedge is taken or not (by 5820 // choosing a sufficiently evil value for the poison feeding into the branch) 5821 // for every iteration including and after the one in which \p I first became 5822 // poison. There are two possibilities (let's call the iteration in which \p 5823 // I first became poison as K): 5824 // 5825 // 1. In the set of iterations including and after K, the loop body executes 5826 // no side effects. In this case executing the backege an infinte number 5827 // of times will yield undefined behavior. 5828 // 5829 // 2. In the set of iterations including and after K, the loop body executes 5830 // at least one side effect. In this case, that specific instance of side 5831 // effect is control dependent on poison, which also yields undefined 5832 // behavior. 5833 5834 auto *ExitingBB = L->getExitingBlock(); 5835 auto *LatchBB = L->getLoopLatch(); 5836 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5837 return false; 5838 5839 SmallPtrSet<const Instruction *, 16> Pushed; 5840 SmallVector<const Instruction *, 8> PoisonStack; 5841 5842 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5843 // things that are known to be fully poison under that assumption go on the 5844 // PoisonStack. 5845 Pushed.insert(I); 5846 PoisonStack.push_back(I); 5847 5848 bool LatchControlDependentOnPoison = false; 5849 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5850 const Instruction *Poison = PoisonStack.pop_back_val(); 5851 5852 for (auto *PoisonUser : Poison->users()) { 5853 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5854 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5855 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5856 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5857 assert(BI->isConditional() && "Only possibility!"); 5858 if (BI->getParent() == LatchBB) { 5859 LatchControlDependentOnPoison = true; 5860 break; 5861 } 5862 } 5863 } 5864 } 5865 5866 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5867 } 5868 5869 ScalarEvolution::LoopProperties 5870 ScalarEvolution::getLoopProperties(const Loop *L) { 5871 using LoopProperties = ScalarEvolution::LoopProperties; 5872 5873 auto Itr = LoopPropertiesCache.find(L); 5874 if (Itr == LoopPropertiesCache.end()) { 5875 auto HasSideEffects = [](Instruction *I) { 5876 if (auto *SI = dyn_cast<StoreInst>(I)) 5877 return !SI->isSimple(); 5878 5879 return I->mayHaveSideEffects(); 5880 }; 5881 5882 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5883 /*HasNoSideEffects*/ true}; 5884 5885 for (auto *BB : L->getBlocks()) 5886 for (auto &I : *BB) { 5887 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5888 LP.HasNoAbnormalExits = false; 5889 if (HasSideEffects(&I)) 5890 LP.HasNoSideEffects = false; 5891 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5892 break; // We're already as pessimistic as we can get. 5893 } 5894 5895 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5896 assert(InsertPair.second && "We just checked!"); 5897 Itr = InsertPair.first; 5898 } 5899 5900 return Itr->second; 5901 } 5902 5903 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5904 if (!isSCEVable(V->getType())) 5905 return getUnknown(V); 5906 5907 if (Instruction *I = dyn_cast<Instruction>(V)) { 5908 // Don't attempt to analyze instructions in blocks that aren't 5909 // reachable. Such instructions don't matter, and they aren't required 5910 // to obey basic rules for definitions dominating uses which this 5911 // analysis depends on. 5912 if (!DT.isReachableFromEntry(I->getParent())) 5913 return getUnknown(V); 5914 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5915 return getConstant(CI); 5916 else if (isa<ConstantPointerNull>(V)) 5917 return getZero(V->getType()); 5918 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5919 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5920 else if (!isa<ConstantExpr>(V)) 5921 return getUnknown(V); 5922 5923 Operator *U = cast<Operator>(V); 5924 if (auto BO = MatchBinaryOp(U, DT)) { 5925 switch (BO->Opcode) { 5926 case Instruction::Add: { 5927 // The simple thing to do would be to just call getSCEV on both operands 5928 // and call getAddExpr with the result. However if we're looking at a 5929 // bunch of things all added together, this can be quite inefficient, 5930 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5931 // Instead, gather up all the operands and make a single getAddExpr call. 5932 // LLVM IR canonical form means we need only traverse the left operands. 5933 SmallVector<const SCEV *, 4> AddOps; 5934 do { 5935 if (BO->Op) { 5936 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5937 AddOps.push_back(OpSCEV); 5938 break; 5939 } 5940 5941 // If a NUW or NSW flag can be applied to the SCEV for this 5942 // addition, then compute the SCEV for this addition by itself 5943 // with a separate call to getAddExpr. We need to do that 5944 // instead of pushing the operands of the addition onto AddOps, 5945 // since the flags are only known to apply to this particular 5946 // addition - they may not apply to other additions that can be 5947 // formed with operands from AddOps. 5948 const SCEV *RHS = getSCEV(BO->RHS); 5949 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5950 if (Flags != SCEV::FlagAnyWrap) { 5951 const SCEV *LHS = getSCEV(BO->LHS); 5952 if (BO->Opcode == Instruction::Sub) 5953 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5954 else 5955 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5956 break; 5957 } 5958 } 5959 5960 if (BO->Opcode == Instruction::Sub) 5961 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5962 else 5963 AddOps.push_back(getSCEV(BO->RHS)); 5964 5965 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5966 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5967 NewBO->Opcode != Instruction::Sub)) { 5968 AddOps.push_back(getSCEV(BO->LHS)); 5969 break; 5970 } 5971 BO = NewBO; 5972 } while (true); 5973 5974 return getAddExpr(AddOps); 5975 } 5976 5977 case Instruction::Mul: { 5978 SmallVector<const SCEV *, 4> MulOps; 5979 do { 5980 if (BO->Op) { 5981 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5982 MulOps.push_back(OpSCEV); 5983 break; 5984 } 5985 5986 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5987 if (Flags != SCEV::FlagAnyWrap) { 5988 MulOps.push_back( 5989 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5990 break; 5991 } 5992 } 5993 5994 MulOps.push_back(getSCEV(BO->RHS)); 5995 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5996 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5997 MulOps.push_back(getSCEV(BO->LHS)); 5998 break; 5999 } 6000 BO = NewBO; 6001 } while (true); 6002 6003 return getMulExpr(MulOps); 6004 } 6005 case Instruction::UDiv: 6006 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6007 case Instruction::URem: 6008 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6009 case Instruction::Sub: { 6010 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6011 if (BO->Op) 6012 Flags = getNoWrapFlagsFromUB(BO->Op); 6013 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6014 } 6015 case Instruction::And: 6016 // For an expression like x&255 that merely masks off the high bits, 6017 // use zext(trunc(x)) as the SCEV expression. 6018 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6019 if (CI->isZero()) 6020 return getSCEV(BO->RHS); 6021 if (CI->isMinusOne()) 6022 return getSCEV(BO->LHS); 6023 const APInt &A = CI->getValue(); 6024 6025 // Instcombine's ShrinkDemandedConstant may strip bits out of 6026 // constants, obscuring what would otherwise be a low-bits mask. 6027 // Use computeKnownBits to compute what ShrinkDemandedConstant 6028 // knew about to reconstruct a low-bits mask value. 6029 unsigned LZ = A.countLeadingZeros(); 6030 unsigned TZ = A.countTrailingZeros(); 6031 unsigned BitWidth = A.getBitWidth(); 6032 KnownBits Known(BitWidth); 6033 computeKnownBits(BO->LHS, Known, getDataLayout(), 6034 0, &AC, nullptr, &DT); 6035 6036 APInt EffectiveMask = 6037 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6038 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6039 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6040 const SCEV *LHS = getSCEV(BO->LHS); 6041 const SCEV *ShiftedLHS = nullptr; 6042 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6043 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6044 // For an expression like (x * 8) & 8, simplify the multiply. 6045 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6046 unsigned GCD = std::min(MulZeros, TZ); 6047 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6048 SmallVector<const SCEV*, 4> MulOps; 6049 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6050 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6051 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6052 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6053 } 6054 } 6055 if (!ShiftedLHS) 6056 ShiftedLHS = getUDivExpr(LHS, MulCount); 6057 return getMulExpr( 6058 getZeroExtendExpr( 6059 getTruncateExpr(ShiftedLHS, 6060 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6061 BO->LHS->getType()), 6062 MulCount); 6063 } 6064 } 6065 break; 6066 6067 case Instruction::Or: 6068 // If the RHS of the Or is a constant, we may have something like: 6069 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6070 // optimizations will transparently handle this case. 6071 // 6072 // In order for this transformation to be safe, the LHS must be of the 6073 // form X*(2^n) and the Or constant must be less than 2^n. 6074 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6075 const SCEV *LHS = getSCEV(BO->LHS); 6076 const APInt &CIVal = CI->getValue(); 6077 if (GetMinTrailingZeros(LHS) >= 6078 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6079 // Build a plain add SCEV. 6080 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6081 // If the LHS of the add was an addrec and it has no-wrap flags, 6082 // transfer the no-wrap flags, since an or won't introduce a wrap. 6083 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6084 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6085 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6086 OldAR->getNoWrapFlags()); 6087 } 6088 return S; 6089 } 6090 } 6091 break; 6092 6093 case Instruction::Xor: 6094 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6095 // If the RHS of xor is -1, then this is a not operation. 6096 if (CI->isMinusOne()) 6097 return getNotSCEV(getSCEV(BO->LHS)); 6098 6099 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6100 // This is a variant of the check for xor with -1, and it handles 6101 // the case where instcombine has trimmed non-demanded bits out 6102 // of an xor with -1. 6103 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6104 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6105 if (LBO->getOpcode() == Instruction::And && 6106 LCI->getValue() == CI->getValue()) 6107 if (const SCEVZeroExtendExpr *Z = 6108 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6109 Type *UTy = BO->LHS->getType(); 6110 const SCEV *Z0 = Z->getOperand(); 6111 Type *Z0Ty = Z0->getType(); 6112 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6113 6114 // If C is a low-bits mask, the zero extend is serving to 6115 // mask off the high bits. Complement the operand and 6116 // re-apply the zext. 6117 if (CI->getValue().isMask(Z0TySize)) 6118 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6119 6120 // If C is a single bit, it may be in the sign-bit position 6121 // before the zero-extend. In this case, represent the xor 6122 // using an add, which is equivalent, and re-apply the zext. 6123 APInt Trunc = CI->getValue().trunc(Z0TySize); 6124 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6125 Trunc.isSignMask()) 6126 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6127 UTy); 6128 } 6129 } 6130 break; 6131 6132 case Instruction::Shl: 6133 // Turn shift left of a constant amount into a multiply. 6134 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6135 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6136 6137 // If the shift count is not less than the bitwidth, the result of 6138 // the shift is undefined. Don't try to analyze it, because the 6139 // resolution chosen here may differ from the resolution chosen in 6140 // other parts of the compiler. 6141 if (SA->getValue().uge(BitWidth)) 6142 break; 6143 6144 // It is currently not resolved how to interpret NSW for left 6145 // shift by BitWidth - 1, so we avoid applying flags in that 6146 // case. Remove this check (or this comment) once the situation 6147 // is resolved. See 6148 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6149 // and http://reviews.llvm.org/D8890 . 6150 auto Flags = SCEV::FlagAnyWrap; 6151 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6152 Flags = getNoWrapFlagsFromUB(BO->Op); 6153 6154 Constant *X = ConstantInt::get(getContext(), 6155 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6156 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6157 } 6158 break; 6159 6160 case Instruction::AShr: { 6161 // AShr X, C, where C is a constant. 6162 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6163 if (!CI) 6164 break; 6165 6166 Type *OuterTy = BO->LHS->getType(); 6167 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6168 // If the shift count is not less than the bitwidth, the result of 6169 // the shift is undefined. Don't try to analyze it, because the 6170 // resolution chosen here may differ from the resolution chosen in 6171 // other parts of the compiler. 6172 if (CI->getValue().uge(BitWidth)) 6173 break; 6174 6175 if (CI->isZero()) 6176 return getSCEV(BO->LHS); // shift by zero --> noop 6177 6178 uint64_t AShrAmt = CI->getZExtValue(); 6179 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6180 6181 Operator *L = dyn_cast<Operator>(BO->LHS); 6182 if (L && L->getOpcode() == Instruction::Shl) { 6183 // X = Shl A, n 6184 // Y = AShr X, m 6185 // Both n and m are constant. 6186 6187 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6188 if (L->getOperand(1) == BO->RHS) 6189 // For a two-shift sext-inreg, i.e. n = m, 6190 // use sext(trunc(x)) as the SCEV expression. 6191 return getSignExtendExpr( 6192 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6193 6194 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6195 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6196 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6197 if (ShlAmt > AShrAmt) { 6198 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6199 // expression. We already checked that ShlAmt < BitWidth, so 6200 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6201 // ShlAmt - AShrAmt < Amt. 6202 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6203 ShlAmt - AShrAmt); 6204 return getSignExtendExpr( 6205 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6206 getConstant(Mul)), OuterTy); 6207 } 6208 } 6209 } 6210 break; 6211 } 6212 } 6213 } 6214 6215 switch (U->getOpcode()) { 6216 case Instruction::Trunc: 6217 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6218 6219 case Instruction::ZExt: 6220 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6221 6222 case Instruction::SExt: 6223 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6224 // The NSW flag of a subtract does not always survive the conversion to 6225 // A + (-1)*B. By pushing sign extension onto its operands we are much 6226 // more likely to preserve NSW and allow later AddRec optimisations. 6227 // 6228 // NOTE: This is effectively duplicating this logic from getSignExtend: 6229 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6230 // but by that point the NSW information has potentially been lost. 6231 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6232 Type *Ty = U->getType(); 6233 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6234 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6235 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6236 } 6237 } 6238 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6239 6240 case Instruction::BitCast: 6241 // BitCasts are no-op casts so we just eliminate the cast. 6242 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6243 return getSCEV(U->getOperand(0)); 6244 break; 6245 6246 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6247 // lead to pointer expressions which cannot safely be expanded to GEPs, 6248 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6249 // simplifying integer expressions. 6250 6251 case Instruction::GetElementPtr: 6252 return createNodeForGEP(cast<GEPOperator>(U)); 6253 6254 case Instruction::PHI: 6255 return createNodeForPHI(cast<PHINode>(U)); 6256 6257 case Instruction::Select: 6258 // U can also be a select constant expr, which let fall through. Since 6259 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6260 // constant expressions cannot have instructions as operands, we'd have 6261 // returned getUnknown for a select constant expressions anyway. 6262 if (isa<Instruction>(U)) 6263 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6264 U->getOperand(1), U->getOperand(2)); 6265 break; 6266 6267 case Instruction::Call: 6268 case Instruction::Invoke: 6269 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6270 return getSCEV(RV); 6271 break; 6272 } 6273 6274 return getUnknown(V); 6275 } 6276 6277 //===----------------------------------------------------------------------===// 6278 // Iteration Count Computation Code 6279 // 6280 6281 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6282 if (!ExitCount) 6283 return 0; 6284 6285 ConstantInt *ExitConst = ExitCount->getValue(); 6286 6287 // Guard against huge trip counts. 6288 if (ExitConst->getValue().getActiveBits() > 32) 6289 return 0; 6290 6291 // In case of integer overflow, this returns 0, which is correct. 6292 return ((unsigned)ExitConst->getZExtValue()) + 1; 6293 } 6294 6295 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6296 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6297 return getSmallConstantTripCount(L, ExitingBB); 6298 6299 // No trip count information for multiple exits. 6300 return 0; 6301 } 6302 6303 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6304 BasicBlock *ExitingBlock) { 6305 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6306 assert(L->isLoopExiting(ExitingBlock) && 6307 "Exiting block must actually branch out of the loop!"); 6308 const SCEVConstant *ExitCount = 6309 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6310 return getConstantTripCount(ExitCount); 6311 } 6312 6313 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6314 const auto *MaxExitCount = 6315 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6316 return getConstantTripCount(MaxExitCount); 6317 } 6318 6319 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6320 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6321 return getSmallConstantTripMultiple(L, ExitingBB); 6322 6323 // No trip multiple information for multiple exits. 6324 return 0; 6325 } 6326 6327 /// Returns the largest constant divisor of the trip count of this loop as a 6328 /// normal unsigned value, if possible. This means that the actual trip count is 6329 /// always a multiple of the returned value (don't forget the trip count could 6330 /// very well be zero as well!). 6331 /// 6332 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6333 /// multiple of a constant (which is also the case if the trip count is simply 6334 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6335 /// if the trip count is very large (>= 2^32). 6336 /// 6337 /// As explained in the comments for getSmallConstantTripCount, this assumes 6338 /// that control exits the loop via ExitingBlock. 6339 unsigned 6340 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6341 BasicBlock *ExitingBlock) { 6342 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6343 assert(L->isLoopExiting(ExitingBlock) && 6344 "Exiting block must actually branch out of the loop!"); 6345 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6346 if (ExitCount == getCouldNotCompute()) 6347 return 1; 6348 6349 // Get the trip count from the BE count by adding 1. 6350 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6351 6352 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6353 if (!TC) 6354 // Attempt to factor more general cases. Returns the greatest power of 6355 // two divisor. If overflow happens, the trip count expression is still 6356 // divisible by the greatest power of 2 divisor returned. 6357 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6358 6359 ConstantInt *Result = TC->getValue(); 6360 6361 // Guard against huge trip counts (this requires checking 6362 // for zero to handle the case where the trip count == -1 and the 6363 // addition wraps). 6364 if (!Result || Result->getValue().getActiveBits() > 32 || 6365 Result->getValue().getActiveBits() == 0) 6366 return 1; 6367 6368 return (unsigned)Result->getZExtValue(); 6369 } 6370 6371 /// Get the expression for the number of loop iterations for which this loop is 6372 /// guaranteed not to exit via ExitingBlock. Otherwise return 6373 /// SCEVCouldNotCompute. 6374 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6375 BasicBlock *ExitingBlock) { 6376 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6377 } 6378 6379 const SCEV * 6380 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6381 SCEVUnionPredicate &Preds) { 6382 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6383 } 6384 6385 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6386 return getBackedgeTakenInfo(L).getExact(this); 6387 } 6388 6389 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6390 /// known never to be less than the actual backedge taken count. 6391 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6392 return getBackedgeTakenInfo(L).getMax(this); 6393 } 6394 6395 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6396 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6397 } 6398 6399 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6400 static void 6401 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6402 BasicBlock *Header = L->getHeader(); 6403 6404 // Push all Loop-header PHIs onto the Worklist stack. 6405 for (PHINode &PN : Header->phis()) 6406 Worklist.push_back(&PN); 6407 } 6408 6409 const ScalarEvolution::BackedgeTakenInfo & 6410 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6411 auto &BTI = getBackedgeTakenInfo(L); 6412 if (BTI.hasFullInfo()) 6413 return BTI; 6414 6415 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6416 6417 if (!Pair.second) 6418 return Pair.first->second; 6419 6420 BackedgeTakenInfo Result = 6421 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6422 6423 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6424 } 6425 6426 const ScalarEvolution::BackedgeTakenInfo & 6427 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6428 // Initially insert an invalid entry for this loop. If the insertion 6429 // succeeds, proceed to actually compute a backedge-taken count and 6430 // update the value. The temporary CouldNotCompute value tells SCEV 6431 // code elsewhere that it shouldn't attempt to request a new 6432 // backedge-taken count, which could result in infinite recursion. 6433 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6434 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6435 if (!Pair.second) 6436 return Pair.first->second; 6437 6438 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6439 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6440 // must be cleared in this scope. 6441 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6442 6443 if (Result.getExact(this) != getCouldNotCompute()) { 6444 assert(isLoopInvariant(Result.getExact(this), L) && 6445 isLoopInvariant(Result.getMax(this), L) && 6446 "Computed backedge-taken count isn't loop invariant for loop!"); 6447 ++NumTripCountsComputed; 6448 } 6449 else if (Result.getMax(this) == getCouldNotCompute() && 6450 isa<PHINode>(L->getHeader()->begin())) { 6451 // Only count loops that have phi nodes as not being computable. 6452 ++NumTripCountsNotComputed; 6453 } 6454 6455 // Now that we know more about the trip count for this loop, forget any 6456 // existing SCEV values for PHI nodes in this loop since they are only 6457 // conservative estimates made without the benefit of trip count 6458 // information. This is similar to the code in forgetLoop, except that 6459 // it handles SCEVUnknown PHI nodes specially. 6460 if (Result.hasAnyInfo()) { 6461 SmallVector<Instruction *, 16> Worklist; 6462 PushLoopPHIs(L, Worklist); 6463 6464 SmallPtrSet<Instruction *, 8> Discovered; 6465 while (!Worklist.empty()) { 6466 Instruction *I = Worklist.pop_back_val(); 6467 6468 ValueExprMapType::iterator It = 6469 ValueExprMap.find_as(static_cast<Value *>(I)); 6470 if (It != ValueExprMap.end()) { 6471 const SCEV *Old = It->second; 6472 6473 // SCEVUnknown for a PHI either means that it has an unrecognized 6474 // structure, or it's a PHI that's in the progress of being computed 6475 // by createNodeForPHI. In the former case, additional loop trip 6476 // count information isn't going to change anything. In the later 6477 // case, createNodeForPHI will perform the necessary updates on its 6478 // own when it gets to that point. 6479 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6480 eraseValueFromMap(It->first); 6481 forgetMemoizedResults(Old); 6482 } 6483 if (PHINode *PN = dyn_cast<PHINode>(I)) 6484 ConstantEvolutionLoopExitValue.erase(PN); 6485 } 6486 6487 // Since we don't need to invalidate anything for correctness and we're 6488 // only invalidating to make SCEV's results more precise, we get to stop 6489 // early to avoid invalidating too much. This is especially important in 6490 // cases like: 6491 // 6492 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6493 // loop0: 6494 // %pn0 = phi 6495 // ... 6496 // loop1: 6497 // %pn1 = phi 6498 // ... 6499 // 6500 // where both loop0 and loop1's backedge taken count uses the SCEV 6501 // expression for %v. If we don't have the early stop below then in cases 6502 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6503 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6504 // count for loop1, effectively nullifying SCEV's trip count cache. 6505 for (auto *U : I->users()) 6506 if (auto *I = dyn_cast<Instruction>(U)) { 6507 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6508 if (LoopForUser && L->contains(LoopForUser) && 6509 Discovered.insert(I).second) 6510 Worklist.push_back(I); 6511 } 6512 } 6513 } 6514 6515 // Re-lookup the insert position, since the call to 6516 // computeBackedgeTakenCount above could result in a 6517 // recusive call to getBackedgeTakenInfo (on a different 6518 // loop), which would invalidate the iterator computed 6519 // earlier. 6520 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6521 } 6522 6523 void ScalarEvolution::forgetLoop(const Loop *L) { 6524 // Drop any stored trip count value. 6525 auto RemoveLoopFromBackedgeMap = 6526 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6527 auto BTCPos = Map.find(L); 6528 if (BTCPos != Map.end()) { 6529 BTCPos->second.clear(); 6530 Map.erase(BTCPos); 6531 } 6532 }; 6533 6534 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6535 SmallVector<Instruction *, 32> Worklist; 6536 SmallPtrSet<Instruction *, 16> Visited; 6537 6538 // Iterate over all the loops and sub-loops to drop SCEV information. 6539 while (!LoopWorklist.empty()) { 6540 auto *CurrL = LoopWorklist.pop_back_val(); 6541 6542 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6543 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6544 6545 // Drop information about predicated SCEV rewrites for this loop. 6546 for (auto I = PredicatedSCEVRewrites.begin(); 6547 I != PredicatedSCEVRewrites.end();) { 6548 std::pair<const SCEV *, const Loop *> Entry = I->first; 6549 if (Entry.second == CurrL) 6550 PredicatedSCEVRewrites.erase(I++); 6551 else 6552 ++I; 6553 } 6554 6555 auto LoopUsersItr = LoopUsers.find(CurrL); 6556 if (LoopUsersItr != LoopUsers.end()) { 6557 for (auto *S : LoopUsersItr->second) 6558 forgetMemoizedResults(S); 6559 LoopUsers.erase(LoopUsersItr); 6560 } 6561 6562 // Drop information about expressions based on loop-header PHIs. 6563 PushLoopPHIs(CurrL, Worklist); 6564 6565 while (!Worklist.empty()) { 6566 Instruction *I = Worklist.pop_back_val(); 6567 if (!Visited.insert(I).second) 6568 continue; 6569 6570 ValueExprMapType::iterator It = 6571 ValueExprMap.find_as(static_cast<Value *>(I)); 6572 if (It != ValueExprMap.end()) { 6573 eraseValueFromMap(It->first); 6574 forgetMemoizedResults(It->second); 6575 if (PHINode *PN = dyn_cast<PHINode>(I)) 6576 ConstantEvolutionLoopExitValue.erase(PN); 6577 } 6578 6579 PushDefUseChildren(I, Worklist); 6580 } 6581 6582 LoopPropertiesCache.erase(CurrL); 6583 // Forget all contained loops too, to avoid dangling entries in the 6584 // ValuesAtScopes map. 6585 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6586 } 6587 } 6588 6589 void ScalarEvolution::forgetValue(Value *V) { 6590 Instruction *I = dyn_cast<Instruction>(V); 6591 if (!I) return; 6592 6593 // Drop information about expressions based on loop-header PHIs. 6594 SmallVector<Instruction *, 16> Worklist; 6595 Worklist.push_back(I); 6596 6597 SmallPtrSet<Instruction *, 8> Visited; 6598 while (!Worklist.empty()) { 6599 I = Worklist.pop_back_val(); 6600 if (!Visited.insert(I).second) 6601 continue; 6602 6603 ValueExprMapType::iterator It = 6604 ValueExprMap.find_as(static_cast<Value *>(I)); 6605 if (It != ValueExprMap.end()) { 6606 eraseValueFromMap(It->first); 6607 forgetMemoizedResults(It->second); 6608 if (PHINode *PN = dyn_cast<PHINode>(I)) 6609 ConstantEvolutionLoopExitValue.erase(PN); 6610 } 6611 6612 PushDefUseChildren(I, Worklist); 6613 } 6614 } 6615 6616 /// Get the exact loop backedge taken count considering all loop exits. A 6617 /// computable result can only be returned for loops with a single exit. 6618 /// Returning the minimum taken count among all exits is incorrect because one 6619 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6620 /// the limit of each loop test is never skipped. This is a valid assumption as 6621 /// long as the loop exits via that test. For precise results, it is the 6622 /// caller's responsibility to specify the relevant loop exit using 6623 /// getExact(ExitingBlock, SE). 6624 const SCEV * 6625 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6626 SCEVUnionPredicate *Preds) const { 6627 // If any exits were not computable, the loop is not computable. 6628 if (!isComplete() || ExitNotTaken.empty()) 6629 return SE->getCouldNotCompute(); 6630 6631 const SCEV *BECount = nullptr; 6632 for (auto &ENT : ExitNotTaken) { 6633 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6634 6635 if (!BECount) 6636 BECount = ENT.ExactNotTaken; 6637 else if (BECount != ENT.ExactNotTaken) 6638 return SE->getCouldNotCompute(); 6639 if (Preds && !ENT.hasAlwaysTruePredicate()) 6640 Preds->add(ENT.Predicate.get()); 6641 6642 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6643 "Predicate should be always true!"); 6644 } 6645 6646 assert(BECount && "Invalid not taken count for loop exit"); 6647 return BECount; 6648 } 6649 6650 /// Get the exact not taken count for this loop exit. 6651 const SCEV * 6652 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6653 ScalarEvolution *SE) const { 6654 for (auto &ENT : ExitNotTaken) 6655 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6656 return ENT.ExactNotTaken; 6657 6658 return SE->getCouldNotCompute(); 6659 } 6660 6661 /// getMax - Get the max backedge taken count for the loop. 6662 const SCEV * 6663 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6664 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6665 return !ENT.hasAlwaysTruePredicate(); 6666 }; 6667 6668 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6669 return SE->getCouldNotCompute(); 6670 6671 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6672 "No point in having a non-constant max backedge taken count!"); 6673 return getMax(); 6674 } 6675 6676 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6677 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6678 return !ENT.hasAlwaysTruePredicate(); 6679 }; 6680 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6681 } 6682 6683 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6684 ScalarEvolution *SE) const { 6685 if (getMax() && getMax() != SE->getCouldNotCompute() && 6686 SE->hasOperand(getMax(), S)) 6687 return true; 6688 6689 for (auto &ENT : ExitNotTaken) 6690 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6691 SE->hasOperand(ENT.ExactNotTaken, S)) 6692 return true; 6693 6694 return false; 6695 } 6696 6697 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6698 : ExactNotTaken(E), MaxNotTaken(E) { 6699 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6700 isa<SCEVConstant>(MaxNotTaken)) && 6701 "No point in having a non-constant max backedge taken count!"); 6702 } 6703 6704 ScalarEvolution::ExitLimit::ExitLimit( 6705 const SCEV *E, const SCEV *M, bool MaxOrZero, 6706 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6707 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6708 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6709 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6710 "Exact is not allowed to be less precise than Max"); 6711 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6712 isa<SCEVConstant>(MaxNotTaken)) && 6713 "No point in having a non-constant max backedge taken count!"); 6714 for (auto *PredSet : PredSetList) 6715 for (auto *P : *PredSet) 6716 addPredicate(P); 6717 } 6718 6719 ScalarEvolution::ExitLimit::ExitLimit( 6720 const SCEV *E, const SCEV *M, bool MaxOrZero, 6721 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6722 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6723 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6724 isa<SCEVConstant>(MaxNotTaken)) && 6725 "No point in having a non-constant max backedge taken count!"); 6726 } 6727 6728 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6729 bool MaxOrZero) 6730 : ExitLimit(E, M, MaxOrZero, None) { 6731 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6732 isa<SCEVConstant>(MaxNotTaken)) && 6733 "No point in having a non-constant max backedge taken count!"); 6734 } 6735 6736 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6737 /// computable exit into a persistent ExitNotTakenInfo array. 6738 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6739 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6740 &&ExitCounts, 6741 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6742 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6743 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6744 6745 ExitNotTaken.reserve(ExitCounts.size()); 6746 std::transform( 6747 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6748 [&](const EdgeExitInfo &EEI) { 6749 BasicBlock *ExitBB = EEI.first; 6750 const ExitLimit &EL = EEI.second; 6751 if (EL.Predicates.empty()) 6752 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6753 6754 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6755 for (auto *Pred : EL.Predicates) 6756 Predicate->add(Pred); 6757 6758 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6759 }); 6760 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6761 "No point in having a non-constant max backedge taken count!"); 6762 } 6763 6764 /// Invalidate this result and free the ExitNotTakenInfo array. 6765 void ScalarEvolution::BackedgeTakenInfo::clear() { 6766 ExitNotTaken.clear(); 6767 } 6768 6769 /// Compute the number of times the backedge of the specified loop will execute. 6770 ScalarEvolution::BackedgeTakenInfo 6771 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6772 bool AllowPredicates) { 6773 SmallVector<BasicBlock *, 8> ExitingBlocks; 6774 L->getExitingBlocks(ExitingBlocks); 6775 6776 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6777 6778 SmallVector<EdgeExitInfo, 4> ExitCounts; 6779 bool CouldComputeBECount = true; 6780 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6781 const SCEV *MustExitMaxBECount = nullptr; 6782 const SCEV *MayExitMaxBECount = nullptr; 6783 bool MustExitMaxOrZero = false; 6784 6785 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6786 // and compute maxBECount. 6787 // Do a union of all the predicates here. 6788 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6789 BasicBlock *ExitBB = ExitingBlocks[i]; 6790 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6791 6792 assert((AllowPredicates || EL.Predicates.empty()) && 6793 "Predicated exit limit when predicates are not allowed!"); 6794 6795 // 1. For each exit that can be computed, add an entry to ExitCounts. 6796 // CouldComputeBECount is true only if all exits can be computed. 6797 if (EL.ExactNotTaken == getCouldNotCompute()) 6798 // We couldn't compute an exact value for this exit, so 6799 // we won't be able to compute an exact value for the loop. 6800 CouldComputeBECount = false; 6801 else 6802 ExitCounts.emplace_back(ExitBB, EL); 6803 6804 // 2. Derive the loop's MaxBECount from each exit's max number of 6805 // non-exiting iterations. Partition the loop exits into two kinds: 6806 // LoopMustExits and LoopMayExits. 6807 // 6808 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6809 // is a LoopMayExit. If any computable LoopMustExit is found, then 6810 // MaxBECount is the minimum EL.MaxNotTaken of computable 6811 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6812 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6813 // computable EL.MaxNotTaken. 6814 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6815 DT.dominates(ExitBB, Latch)) { 6816 if (!MustExitMaxBECount) { 6817 MustExitMaxBECount = EL.MaxNotTaken; 6818 MustExitMaxOrZero = EL.MaxOrZero; 6819 } else { 6820 MustExitMaxBECount = 6821 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6822 } 6823 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6824 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6825 MayExitMaxBECount = EL.MaxNotTaken; 6826 else { 6827 MayExitMaxBECount = 6828 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6829 } 6830 } 6831 } 6832 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6833 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6834 // The loop backedge will be taken the maximum or zero times if there's 6835 // a single exit that must be taken the maximum or zero times. 6836 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6837 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6838 MaxBECount, MaxOrZero); 6839 } 6840 6841 ScalarEvolution::ExitLimit 6842 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6843 bool AllowPredicates) { 6844 // Okay, we've chosen an exiting block. See what condition causes us to exit 6845 // at this block and remember the exit block and whether all other targets 6846 // lead to the loop header. 6847 bool MustExecuteLoopHeader = true; 6848 BasicBlock *Exit = nullptr; 6849 for (auto *SBB : successors(ExitingBlock)) 6850 if (!L->contains(SBB)) { 6851 if (Exit) // Multiple exit successors. 6852 return getCouldNotCompute(); 6853 Exit = SBB; 6854 } else if (SBB != L->getHeader()) { 6855 MustExecuteLoopHeader = false; 6856 } 6857 6858 // At this point, we know we have a conditional branch that determines whether 6859 // the loop is exited. However, we don't know if the branch is executed each 6860 // time through the loop. If not, then the execution count of the branch will 6861 // not be equal to the trip count of the loop. 6862 // 6863 // Currently we check for this by checking to see if the Exit branch goes to 6864 // the loop header. If so, we know it will always execute the same number of 6865 // times as the loop. We also handle the case where the exit block *is* the 6866 // loop header. This is common for un-rotated loops. 6867 // 6868 // If both of those tests fail, walk up the unique predecessor chain to the 6869 // header, stopping if there is an edge that doesn't exit the loop. If the 6870 // header is reached, the execution count of the branch will be equal to the 6871 // trip count of the loop. 6872 // 6873 // More extensive analysis could be done to handle more cases here. 6874 // 6875 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6876 // The simple checks failed, try climbing the unique predecessor chain 6877 // up to the header. 6878 bool Ok = false; 6879 for (BasicBlock *BB = ExitingBlock; BB; ) { 6880 BasicBlock *Pred = BB->getUniquePredecessor(); 6881 if (!Pred) 6882 return getCouldNotCompute(); 6883 TerminatorInst *PredTerm = Pred->getTerminator(); 6884 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6885 if (PredSucc == BB) 6886 continue; 6887 // If the predecessor has a successor that isn't BB and isn't 6888 // outside the loop, assume the worst. 6889 if (L->contains(PredSucc)) 6890 return getCouldNotCompute(); 6891 } 6892 if (Pred == L->getHeader()) { 6893 Ok = true; 6894 break; 6895 } 6896 BB = Pred; 6897 } 6898 if (!Ok) 6899 return getCouldNotCompute(); 6900 } 6901 6902 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6903 TerminatorInst *Term = ExitingBlock->getTerminator(); 6904 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6905 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6906 // Proceed to the next level to examine the exit condition expression. 6907 return computeExitLimitFromCond( 6908 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 6909 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6910 } 6911 6912 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6913 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6914 /*ControlsExit=*/IsOnlyExit); 6915 6916 return getCouldNotCompute(); 6917 } 6918 6919 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6920 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB, 6921 bool ControlsExit, bool AllowPredicates) { 6922 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates); 6923 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB, 6924 ControlsExit, AllowPredicates); 6925 } 6926 6927 Optional<ScalarEvolution::ExitLimit> 6928 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6929 BasicBlock *TBB, BasicBlock *FBB, 6930 bool ControlsExit, bool AllowPredicates) { 6931 (void)this->L; 6932 (void)this->TBB; 6933 (void)this->FBB; 6934 (void)this->AllowPredicates; 6935 6936 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6937 this->AllowPredicates == AllowPredicates && 6938 "Variance in assumed invariant key components!"); 6939 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6940 if (Itr == TripCountMap.end()) 6941 return None; 6942 return Itr->second; 6943 } 6944 6945 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6946 BasicBlock *TBB, BasicBlock *FBB, 6947 bool ControlsExit, 6948 bool AllowPredicates, 6949 const ExitLimit &EL) { 6950 assert(this->L == L && this->TBB == TBB && this->FBB == FBB && 6951 this->AllowPredicates == AllowPredicates && 6952 "Variance in assumed invariant key components!"); 6953 6954 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6955 assert(InsertResult.second && "Expected successful insertion!"); 6956 (void)InsertResult; 6957 } 6958 6959 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 6960 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6961 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6962 6963 if (auto MaybeEL = 6964 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates)) 6965 return *MaybeEL; 6966 6967 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB, 6968 ControlsExit, AllowPredicates); 6969 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL); 6970 return EL; 6971 } 6972 6973 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 6974 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB, 6975 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) { 6976 // Check if the controlling expression for this loop is an And or Or. 6977 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 6978 if (BO->getOpcode() == Instruction::And) { 6979 // Recurse on the operands of the and. 6980 bool EitherMayExit = L->contains(TBB); 6981 ExitLimit EL0 = computeExitLimitFromCondCached( 6982 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 6983 AllowPredicates); 6984 ExitLimit EL1 = computeExitLimitFromCondCached( 6985 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 6986 AllowPredicates); 6987 const SCEV *BECount = getCouldNotCompute(); 6988 const SCEV *MaxBECount = getCouldNotCompute(); 6989 if (EitherMayExit) { 6990 // Both conditions must be true for the loop to continue executing. 6991 // Choose the less conservative count. 6992 if (EL0.ExactNotTaken == getCouldNotCompute() || 6993 EL1.ExactNotTaken == getCouldNotCompute()) 6994 BECount = getCouldNotCompute(); 6995 else 6996 BECount = 6997 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 6998 if (EL0.MaxNotTaken == getCouldNotCompute()) 6999 MaxBECount = EL1.MaxNotTaken; 7000 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7001 MaxBECount = EL0.MaxNotTaken; 7002 else 7003 MaxBECount = 7004 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7005 } else { 7006 // Both conditions must be true at the same time for the loop to exit. 7007 // For now, be conservative. 7008 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 7009 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7010 MaxBECount = EL0.MaxNotTaken; 7011 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7012 BECount = EL0.ExactNotTaken; 7013 } 7014 7015 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7016 // to be more aggressive when computing BECount than when computing 7017 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7018 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7019 // to not. 7020 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7021 !isa<SCEVCouldNotCompute>(BECount)) 7022 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7023 7024 return ExitLimit(BECount, MaxBECount, false, 7025 {&EL0.Predicates, &EL1.Predicates}); 7026 } 7027 if (BO->getOpcode() == Instruction::Or) { 7028 // Recurse on the operands of the or. 7029 bool EitherMayExit = L->contains(FBB); 7030 ExitLimit EL0 = computeExitLimitFromCondCached( 7031 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit, 7032 AllowPredicates); 7033 ExitLimit EL1 = computeExitLimitFromCondCached( 7034 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit, 7035 AllowPredicates); 7036 const SCEV *BECount = getCouldNotCompute(); 7037 const SCEV *MaxBECount = getCouldNotCompute(); 7038 if (EitherMayExit) { 7039 // Both conditions must be false for the loop to continue executing. 7040 // Choose the less conservative count. 7041 if (EL0.ExactNotTaken == getCouldNotCompute() || 7042 EL1.ExactNotTaken == getCouldNotCompute()) 7043 BECount = getCouldNotCompute(); 7044 else 7045 BECount = 7046 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7047 if (EL0.MaxNotTaken == getCouldNotCompute()) 7048 MaxBECount = EL1.MaxNotTaken; 7049 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7050 MaxBECount = EL0.MaxNotTaken; 7051 else 7052 MaxBECount = 7053 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7054 } else { 7055 // Both conditions must be false at the same time for the loop to exit. 7056 // For now, be conservative. 7057 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 7058 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7059 MaxBECount = EL0.MaxNotTaken; 7060 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7061 BECount = EL0.ExactNotTaken; 7062 } 7063 7064 return ExitLimit(BECount, MaxBECount, false, 7065 {&EL0.Predicates, &EL1.Predicates}); 7066 } 7067 } 7068 7069 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7070 // Proceed to the next level to examine the icmp. 7071 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7072 ExitLimit EL = 7073 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 7074 if (EL.hasFullInfo() || !AllowPredicates) 7075 return EL; 7076 7077 // Try again, but use SCEV predicates this time. 7078 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 7079 /*AllowPredicates=*/true); 7080 } 7081 7082 // Check for a constant condition. These are normally stripped out by 7083 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7084 // preserve the CFG and is temporarily leaving constant conditions 7085 // in place. 7086 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7087 if (L->contains(FBB) == !CI->getZExtValue()) 7088 // The backedge is always taken. 7089 return getCouldNotCompute(); 7090 else 7091 // The backedge is never taken. 7092 return getZero(CI->getType()); 7093 } 7094 7095 // If it's not an integer or pointer comparison then compute it the hard way. 7096 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 7097 } 7098 7099 ScalarEvolution::ExitLimit 7100 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7101 ICmpInst *ExitCond, 7102 BasicBlock *TBB, 7103 BasicBlock *FBB, 7104 bool ControlsExit, 7105 bool AllowPredicates) { 7106 // If the condition was exit on true, convert the condition to exit on false 7107 ICmpInst::Predicate Pred; 7108 if (!L->contains(FBB)) 7109 Pred = ExitCond->getPredicate(); 7110 else 7111 Pred = ExitCond->getInversePredicate(); 7112 const ICmpInst::Predicate OriginalPred = Pred; 7113 7114 // Handle common loops like: for (X = "string"; *X; ++X) 7115 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7116 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7117 ExitLimit ItCnt = 7118 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7119 if (ItCnt.hasAnyInfo()) 7120 return ItCnt; 7121 } 7122 7123 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7124 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7125 7126 // Try to evaluate any dependencies out of the loop. 7127 LHS = getSCEVAtScope(LHS, L); 7128 RHS = getSCEVAtScope(RHS, L); 7129 7130 // At this point, we would like to compute how many iterations of the 7131 // loop the predicate will return true for these inputs. 7132 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7133 // If there is a loop-invariant, force it into the RHS. 7134 std::swap(LHS, RHS); 7135 Pred = ICmpInst::getSwappedPredicate(Pred); 7136 } 7137 7138 // Simplify the operands before analyzing them. 7139 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7140 7141 // If we have a comparison of a chrec against a constant, try to use value 7142 // ranges to answer this query. 7143 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7144 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7145 if (AddRec->getLoop() == L) { 7146 // Form the constant range. 7147 ConstantRange CompRange = 7148 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7149 7150 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7151 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7152 } 7153 7154 switch (Pred) { 7155 case ICmpInst::ICMP_NE: { // while (X != Y) 7156 // Convert to: while (X-Y != 0) 7157 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7158 AllowPredicates); 7159 if (EL.hasAnyInfo()) return EL; 7160 break; 7161 } 7162 case ICmpInst::ICMP_EQ: { // while (X == Y) 7163 // Convert to: while (X-Y == 0) 7164 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7165 if (EL.hasAnyInfo()) return EL; 7166 break; 7167 } 7168 case ICmpInst::ICMP_SLT: 7169 case ICmpInst::ICMP_ULT: { // while (X < Y) 7170 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7171 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7172 AllowPredicates); 7173 if (EL.hasAnyInfo()) return EL; 7174 break; 7175 } 7176 case ICmpInst::ICMP_SGT: 7177 case ICmpInst::ICMP_UGT: { // while (X > Y) 7178 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7179 ExitLimit EL = 7180 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7181 AllowPredicates); 7182 if (EL.hasAnyInfo()) return EL; 7183 break; 7184 } 7185 default: 7186 break; 7187 } 7188 7189 auto *ExhaustiveCount = 7190 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 7191 7192 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7193 return ExhaustiveCount; 7194 7195 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7196 ExitCond->getOperand(1), L, OriginalPred); 7197 } 7198 7199 ScalarEvolution::ExitLimit 7200 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7201 SwitchInst *Switch, 7202 BasicBlock *ExitingBlock, 7203 bool ControlsExit) { 7204 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7205 7206 // Give up if the exit is the default dest of a switch. 7207 if (Switch->getDefaultDest() == ExitingBlock) 7208 return getCouldNotCompute(); 7209 7210 assert(L->contains(Switch->getDefaultDest()) && 7211 "Default case must not exit the loop!"); 7212 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7213 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7214 7215 // while (X != Y) --> while (X-Y != 0) 7216 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7217 if (EL.hasAnyInfo()) 7218 return EL; 7219 7220 return getCouldNotCompute(); 7221 } 7222 7223 static ConstantInt * 7224 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7225 ScalarEvolution &SE) { 7226 const SCEV *InVal = SE.getConstant(C); 7227 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7228 assert(isa<SCEVConstant>(Val) && 7229 "Evaluation of SCEV at constant didn't fold correctly?"); 7230 return cast<SCEVConstant>(Val)->getValue(); 7231 } 7232 7233 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7234 /// compute the backedge execution count. 7235 ScalarEvolution::ExitLimit 7236 ScalarEvolution::computeLoadConstantCompareExitLimit( 7237 LoadInst *LI, 7238 Constant *RHS, 7239 const Loop *L, 7240 ICmpInst::Predicate predicate) { 7241 if (LI->isVolatile()) return getCouldNotCompute(); 7242 7243 // Check to see if the loaded pointer is a getelementptr of a global. 7244 // TODO: Use SCEV instead of manually grubbing with GEPs. 7245 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7246 if (!GEP) return getCouldNotCompute(); 7247 7248 // Make sure that it is really a constant global we are gepping, with an 7249 // initializer, and make sure the first IDX is really 0. 7250 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7251 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7252 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7253 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7254 return getCouldNotCompute(); 7255 7256 // Okay, we allow one non-constant index into the GEP instruction. 7257 Value *VarIdx = nullptr; 7258 std::vector<Constant*> Indexes; 7259 unsigned VarIdxNum = 0; 7260 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7261 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7262 Indexes.push_back(CI); 7263 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7264 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7265 VarIdx = GEP->getOperand(i); 7266 VarIdxNum = i-2; 7267 Indexes.push_back(nullptr); 7268 } 7269 7270 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7271 if (!VarIdx) 7272 return getCouldNotCompute(); 7273 7274 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7275 // Check to see if X is a loop variant variable value now. 7276 const SCEV *Idx = getSCEV(VarIdx); 7277 Idx = getSCEVAtScope(Idx, L); 7278 7279 // We can only recognize very limited forms of loop index expressions, in 7280 // particular, only affine AddRec's like {C1,+,C2}. 7281 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7282 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7283 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7284 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7285 return getCouldNotCompute(); 7286 7287 unsigned MaxSteps = MaxBruteForceIterations; 7288 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7289 ConstantInt *ItCst = ConstantInt::get( 7290 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7291 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7292 7293 // Form the GEP offset. 7294 Indexes[VarIdxNum] = Val; 7295 7296 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7297 Indexes); 7298 if (!Result) break; // Cannot compute! 7299 7300 // Evaluate the condition for this iteration. 7301 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7302 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7303 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7304 ++NumArrayLenItCounts; 7305 return getConstant(ItCst); // Found terminating iteration! 7306 } 7307 } 7308 return getCouldNotCompute(); 7309 } 7310 7311 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7312 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7313 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7314 if (!RHS) 7315 return getCouldNotCompute(); 7316 7317 const BasicBlock *Latch = L->getLoopLatch(); 7318 if (!Latch) 7319 return getCouldNotCompute(); 7320 7321 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7322 if (!Predecessor) 7323 return getCouldNotCompute(); 7324 7325 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7326 // Return LHS in OutLHS and shift_opt in OutOpCode. 7327 auto MatchPositiveShift = 7328 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7329 7330 using namespace PatternMatch; 7331 7332 ConstantInt *ShiftAmt; 7333 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7334 OutOpCode = Instruction::LShr; 7335 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7336 OutOpCode = Instruction::AShr; 7337 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7338 OutOpCode = Instruction::Shl; 7339 else 7340 return false; 7341 7342 return ShiftAmt->getValue().isStrictlyPositive(); 7343 }; 7344 7345 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7346 // 7347 // loop: 7348 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7349 // %iv.shifted = lshr i32 %iv, <positive constant> 7350 // 7351 // Return true on a successful match. Return the corresponding PHI node (%iv 7352 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7353 auto MatchShiftRecurrence = 7354 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7355 Optional<Instruction::BinaryOps> PostShiftOpCode; 7356 7357 { 7358 Instruction::BinaryOps OpC; 7359 Value *V; 7360 7361 // If we encounter a shift instruction, "peel off" the shift operation, 7362 // and remember that we did so. Later when we inspect %iv's backedge 7363 // value, we will make sure that the backedge value uses the same 7364 // operation. 7365 // 7366 // Note: the peeled shift operation does not have to be the same 7367 // instruction as the one feeding into the PHI's backedge value. We only 7368 // really care about it being the same *kind* of shift instruction -- 7369 // that's all that is required for our later inferences to hold. 7370 if (MatchPositiveShift(LHS, V, OpC)) { 7371 PostShiftOpCode = OpC; 7372 LHS = V; 7373 } 7374 } 7375 7376 PNOut = dyn_cast<PHINode>(LHS); 7377 if (!PNOut || PNOut->getParent() != L->getHeader()) 7378 return false; 7379 7380 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7381 Value *OpLHS; 7382 7383 return 7384 // The backedge value for the PHI node must be a shift by a positive 7385 // amount 7386 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7387 7388 // of the PHI node itself 7389 OpLHS == PNOut && 7390 7391 // and the kind of shift should be match the kind of shift we peeled 7392 // off, if any. 7393 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7394 }; 7395 7396 PHINode *PN; 7397 Instruction::BinaryOps OpCode; 7398 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7399 return getCouldNotCompute(); 7400 7401 const DataLayout &DL = getDataLayout(); 7402 7403 // The key rationale for this optimization is that for some kinds of shift 7404 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7405 // within a finite number of iterations. If the condition guarding the 7406 // backedge (in the sense that the backedge is taken if the condition is true) 7407 // is false for the value the shift recurrence stabilizes to, then we know 7408 // that the backedge is taken only a finite number of times. 7409 7410 ConstantInt *StableValue = nullptr; 7411 switch (OpCode) { 7412 default: 7413 llvm_unreachable("Impossible case!"); 7414 7415 case Instruction::AShr: { 7416 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7417 // bitwidth(K) iterations. 7418 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7419 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7420 Predecessor->getTerminator(), &DT); 7421 auto *Ty = cast<IntegerType>(RHS->getType()); 7422 if (Known.isNonNegative()) 7423 StableValue = ConstantInt::get(Ty, 0); 7424 else if (Known.isNegative()) 7425 StableValue = ConstantInt::get(Ty, -1, true); 7426 else 7427 return getCouldNotCompute(); 7428 7429 break; 7430 } 7431 case Instruction::LShr: 7432 case Instruction::Shl: 7433 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7434 // stabilize to 0 in at most bitwidth(K) iterations. 7435 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7436 break; 7437 } 7438 7439 auto *Result = 7440 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7441 assert(Result->getType()->isIntegerTy(1) && 7442 "Otherwise cannot be an operand to a branch instruction"); 7443 7444 if (Result->isZeroValue()) { 7445 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7446 const SCEV *UpperBound = 7447 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7448 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7449 } 7450 7451 return getCouldNotCompute(); 7452 } 7453 7454 /// Return true if we can constant fold an instruction of the specified type, 7455 /// assuming that all operands were constants. 7456 static bool CanConstantFold(const Instruction *I) { 7457 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7458 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7459 isa<LoadInst>(I)) 7460 return true; 7461 7462 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7463 if (const Function *F = CI->getCalledFunction()) 7464 return canConstantFoldCallTo(CI, F); 7465 return false; 7466 } 7467 7468 /// Determine whether this instruction can constant evolve within this loop 7469 /// assuming its operands can all constant evolve. 7470 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7471 // An instruction outside of the loop can't be derived from a loop PHI. 7472 if (!L->contains(I)) return false; 7473 7474 if (isa<PHINode>(I)) { 7475 // We don't currently keep track of the control flow needed to evaluate 7476 // PHIs, so we cannot handle PHIs inside of loops. 7477 return L->getHeader() == I->getParent(); 7478 } 7479 7480 // If we won't be able to constant fold this expression even if the operands 7481 // are constants, bail early. 7482 return CanConstantFold(I); 7483 } 7484 7485 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7486 /// recursing through each instruction operand until reaching a loop header phi. 7487 static PHINode * 7488 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7489 DenseMap<Instruction *, PHINode *> &PHIMap, 7490 unsigned Depth) { 7491 if (Depth > MaxConstantEvolvingDepth) 7492 return nullptr; 7493 7494 // Otherwise, we can evaluate this instruction if all of its operands are 7495 // constant or derived from a PHI node themselves. 7496 PHINode *PHI = nullptr; 7497 for (Value *Op : UseInst->operands()) { 7498 if (isa<Constant>(Op)) continue; 7499 7500 Instruction *OpInst = dyn_cast<Instruction>(Op); 7501 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7502 7503 PHINode *P = dyn_cast<PHINode>(OpInst); 7504 if (!P) 7505 // If this operand is already visited, reuse the prior result. 7506 // We may have P != PHI if this is the deepest point at which the 7507 // inconsistent paths meet. 7508 P = PHIMap.lookup(OpInst); 7509 if (!P) { 7510 // Recurse and memoize the results, whether a phi is found or not. 7511 // This recursive call invalidates pointers into PHIMap. 7512 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7513 PHIMap[OpInst] = P; 7514 } 7515 if (!P) 7516 return nullptr; // Not evolving from PHI 7517 if (PHI && PHI != P) 7518 return nullptr; // Evolving from multiple different PHIs. 7519 PHI = P; 7520 } 7521 // This is a expression evolving from a constant PHI! 7522 return PHI; 7523 } 7524 7525 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7526 /// in the loop that V is derived from. We allow arbitrary operations along the 7527 /// way, but the operands of an operation must either be constants or a value 7528 /// derived from a constant PHI. If this expression does not fit with these 7529 /// constraints, return null. 7530 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7531 Instruction *I = dyn_cast<Instruction>(V); 7532 if (!I || !canConstantEvolve(I, L)) return nullptr; 7533 7534 if (PHINode *PN = dyn_cast<PHINode>(I)) 7535 return PN; 7536 7537 // Record non-constant instructions contained by the loop. 7538 DenseMap<Instruction *, PHINode *> PHIMap; 7539 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7540 } 7541 7542 /// EvaluateExpression - Given an expression that passes the 7543 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7544 /// in the loop has the value PHIVal. If we can't fold this expression for some 7545 /// reason, return null. 7546 static Constant *EvaluateExpression(Value *V, const Loop *L, 7547 DenseMap<Instruction *, Constant *> &Vals, 7548 const DataLayout &DL, 7549 const TargetLibraryInfo *TLI) { 7550 // Convenient constant check, but redundant for recursive calls. 7551 if (Constant *C = dyn_cast<Constant>(V)) return C; 7552 Instruction *I = dyn_cast<Instruction>(V); 7553 if (!I) return nullptr; 7554 7555 if (Constant *C = Vals.lookup(I)) return C; 7556 7557 // An instruction inside the loop depends on a value outside the loop that we 7558 // weren't given a mapping for, or a value such as a call inside the loop. 7559 if (!canConstantEvolve(I, L)) return nullptr; 7560 7561 // An unmapped PHI can be due to a branch or another loop inside this loop, 7562 // or due to this not being the initial iteration through a loop where we 7563 // couldn't compute the evolution of this particular PHI last time. 7564 if (isa<PHINode>(I)) return nullptr; 7565 7566 std::vector<Constant*> Operands(I->getNumOperands()); 7567 7568 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7569 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7570 if (!Operand) { 7571 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7572 if (!Operands[i]) return nullptr; 7573 continue; 7574 } 7575 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7576 Vals[Operand] = C; 7577 if (!C) return nullptr; 7578 Operands[i] = C; 7579 } 7580 7581 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7582 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7583 Operands[1], DL, TLI); 7584 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7585 if (!LI->isVolatile()) 7586 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7587 } 7588 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7589 } 7590 7591 7592 // If every incoming value to PN except the one for BB is a specific Constant, 7593 // return that, else return nullptr. 7594 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7595 Constant *IncomingVal = nullptr; 7596 7597 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7598 if (PN->getIncomingBlock(i) == BB) 7599 continue; 7600 7601 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7602 if (!CurrentVal) 7603 return nullptr; 7604 7605 if (IncomingVal != CurrentVal) { 7606 if (IncomingVal) 7607 return nullptr; 7608 IncomingVal = CurrentVal; 7609 } 7610 } 7611 7612 return IncomingVal; 7613 } 7614 7615 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7616 /// in the header of its containing loop, we know the loop executes a 7617 /// constant number of times, and the PHI node is just a recurrence 7618 /// involving constants, fold it. 7619 Constant * 7620 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7621 const APInt &BEs, 7622 const Loop *L) { 7623 auto I = ConstantEvolutionLoopExitValue.find(PN); 7624 if (I != ConstantEvolutionLoopExitValue.end()) 7625 return I->second; 7626 7627 if (BEs.ugt(MaxBruteForceIterations)) 7628 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7629 7630 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7631 7632 DenseMap<Instruction *, Constant *> CurrentIterVals; 7633 BasicBlock *Header = L->getHeader(); 7634 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7635 7636 BasicBlock *Latch = L->getLoopLatch(); 7637 if (!Latch) 7638 return nullptr; 7639 7640 for (PHINode &PHI : Header->phis()) { 7641 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7642 CurrentIterVals[&PHI] = StartCST; 7643 } 7644 if (!CurrentIterVals.count(PN)) 7645 return RetVal = nullptr; 7646 7647 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7648 7649 // Execute the loop symbolically to determine the exit value. 7650 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7651 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7652 7653 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7654 unsigned IterationNum = 0; 7655 const DataLayout &DL = getDataLayout(); 7656 for (; ; ++IterationNum) { 7657 if (IterationNum == NumIterations) 7658 return RetVal = CurrentIterVals[PN]; // Got exit value! 7659 7660 // Compute the value of the PHIs for the next iteration. 7661 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7662 DenseMap<Instruction *, Constant *> NextIterVals; 7663 Constant *NextPHI = 7664 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7665 if (!NextPHI) 7666 return nullptr; // Couldn't evaluate! 7667 NextIterVals[PN] = NextPHI; 7668 7669 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7670 7671 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7672 // cease to be able to evaluate one of them or if they stop evolving, 7673 // because that doesn't necessarily prevent us from computing PN. 7674 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7675 for (const auto &I : CurrentIterVals) { 7676 PHINode *PHI = dyn_cast<PHINode>(I.first); 7677 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7678 PHIsToCompute.emplace_back(PHI, I.second); 7679 } 7680 // We use two distinct loops because EvaluateExpression may invalidate any 7681 // iterators into CurrentIterVals. 7682 for (const auto &I : PHIsToCompute) { 7683 PHINode *PHI = I.first; 7684 Constant *&NextPHI = NextIterVals[PHI]; 7685 if (!NextPHI) { // Not already computed. 7686 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7687 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7688 } 7689 if (NextPHI != I.second) 7690 StoppedEvolving = false; 7691 } 7692 7693 // If all entries in CurrentIterVals == NextIterVals then we can stop 7694 // iterating, the loop can't continue to change. 7695 if (StoppedEvolving) 7696 return RetVal = CurrentIterVals[PN]; 7697 7698 CurrentIterVals.swap(NextIterVals); 7699 } 7700 } 7701 7702 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7703 Value *Cond, 7704 bool ExitWhen) { 7705 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7706 if (!PN) return getCouldNotCompute(); 7707 7708 // If the loop is canonicalized, the PHI will have exactly two entries. 7709 // That's the only form we support here. 7710 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7711 7712 DenseMap<Instruction *, Constant *> CurrentIterVals; 7713 BasicBlock *Header = L->getHeader(); 7714 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7715 7716 BasicBlock *Latch = L->getLoopLatch(); 7717 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7718 7719 for (PHINode &PHI : Header->phis()) { 7720 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7721 CurrentIterVals[&PHI] = StartCST; 7722 } 7723 if (!CurrentIterVals.count(PN)) 7724 return getCouldNotCompute(); 7725 7726 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7727 // the loop symbolically to determine when the condition gets a value of 7728 // "ExitWhen". 7729 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7730 const DataLayout &DL = getDataLayout(); 7731 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7732 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7733 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7734 7735 // Couldn't symbolically evaluate. 7736 if (!CondVal) return getCouldNotCompute(); 7737 7738 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7739 ++NumBruteForceTripCountsComputed; 7740 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7741 } 7742 7743 // Update all the PHI nodes for the next iteration. 7744 DenseMap<Instruction *, Constant *> NextIterVals; 7745 7746 // Create a list of which PHIs we need to compute. We want to do this before 7747 // calling EvaluateExpression on them because that may invalidate iterators 7748 // into CurrentIterVals. 7749 SmallVector<PHINode *, 8> PHIsToCompute; 7750 for (const auto &I : CurrentIterVals) { 7751 PHINode *PHI = dyn_cast<PHINode>(I.first); 7752 if (!PHI || PHI->getParent() != Header) continue; 7753 PHIsToCompute.push_back(PHI); 7754 } 7755 for (PHINode *PHI : PHIsToCompute) { 7756 Constant *&NextPHI = NextIterVals[PHI]; 7757 if (NextPHI) continue; // Already computed! 7758 7759 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7760 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7761 } 7762 CurrentIterVals.swap(NextIterVals); 7763 } 7764 7765 // Too many iterations were needed to evaluate. 7766 return getCouldNotCompute(); 7767 } 7768 7769 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7770 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7771 ValuesAtScopes[V]; 7772 // Check to see if we've folded this expression at this loop before. 7773 for (auto &LS : Values) 7774 if (LS.first == L) 7775 return LS.second ? LS.second : V; 7776 7777 Values.emplace_back(L, nullptr); 7778 7779 // Otherwise compute it. 7780 const SCEV *C = computeSCEVAtScope(V, L); 7781 for (auto &LS : reverse(ValuesAtScopes[V])) 7782 if (LS.first == L) { 7783 LS.second = C; 7784 break; 7785 } 7786 return C; 7787 } 7788 7789 /// This builds up a Constant using the ConstantExpr interface. That way, we 7790 /// will return Constants for objects which aren't represented by a 7791 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7792 /// Returns NULL if the SCEV isn't representable as a Constant. 7793 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7794 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7795 case scCouldNotCompute: 7796 case scAddRecExpr: 7797 break; 7798 case scConstant: 7799 return cast<SCEVConstant>(V)->getValue(); 7800 case scUnknown: 7801 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7802 case scSignExtend: { 7803 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7804 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7805 return ConstantExpr::getSExt(CastOp, SS->getType()); 7806 break; 7807 } 7808 case scZeroExtend: { 7809 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7810 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7811 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7812 break; 7813 } 7814 case scTruncate: { 7815 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7816 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7817 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7818 break; 7819 } 7820 case scAddExpr: { 7821 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7822 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7823 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7824 unsigned AS = PTy->getAddressSpace(); 7825 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7826 C = ConstantExpr::getBitCast(C, DestPtrTy); 7827 } 7828 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7829 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7830 if (!C2) return nullptr; 7831 7832 // First pointer! 7833 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7834 unsigned AS = C2->getType()->getPointerAddressSpace(); 7835 std::swap(C, C2); 7836 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7837 // The offsets have been converted to bytes. We can add bytes to an 7838 // i8* by GEP with the byte count in the first index. 7839 C = ConstantExpr::getBitCast(C, DestPtrTy); 7840 } 7841 7842 // Don't bother trying to sum two pointers. We probably can't 7843 // statically compute a load that results from it anyway. 7844 if (C2->getType()->isPointerTy()) 7845 return nullptr; 7846 7847 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7848 if (PTy->getElementType()->isStructTy()) 7849 C2 = ConstantExpr::getIntegerCast( 7850 C2, Type::getInt32Ty(C->getContext()), true); 7851 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7852 } else 7853 C = ConstantExpr::getAdd(C, C2); 7854 } 7855 return C; 7856 } 7857 break; 7858 } 7859 case scMulExpr: { 7860 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7861 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7862 // Don't bother with pointers at all. 7863 if (C->getType()->isPointerTy()) return nullptr; 7864 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7865 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7866 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7867 C = ConstantExpr::getMul(C, C2); 7868 } 7869 return C; 7870 } 7871 break; 7872 } 7873 case scUDivExpr: { 7874 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7875 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7876 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7877 if (LHS->getType() == RHS->getType()) 7878 return ConstantExpr::getUDiv(LHS, RHS); 7879 break; 7880 } 7881 case scSMaxExpr: 7882 case scUMaxExpr: 7883 break; // TODO: smax, umax. 7884 } 7885 return nullptr; 7886 } 7887 7888 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7889 if (isa<SCEVConstant>(V)) return V; 7890 7891 // If this instruction is evolved from a constant-evolving PHI, compute the 7892 // exit value from the loop without using SCEVs. 7893 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7894 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7895 const Loop *LI = this->LI[I->getParent()]; 7896 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7897 if (PHINode *PN = dyn_cast<PHINode>(I)) 7898 if (PN->getParent() == LI->getHeader()) { 7899 // Okay, there is no closed form solution for the PHI node. Check 7900 // to see if the loop that contains it has a known backedge-taken 7901 // count. If so, we may be able to force computation of the exit 7902 // value. 7903 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7904 if (const SCEVConstant *BTCC = 7905 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7906 7907 // This trivial case can show up in some degenerate cases where 7908 // the incoming IR has not yet been fully simplified. 7909 if (BTCC->getValue()->isZero()) { 7910 Value *InitValue = nullptr; 7911 bool MultipleInitValues = false; 7912 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 7913 if (!LI->contains(PN->getIncomingBlock(i))) { 7914 if (!InitValue) 7915 InitValue = PN->getIncomingValue(i); 7916 else if (InitValue != PN->getIncomingValue(i)) { 7917 MultipleInitValues = true; 7918 break; 7919 } 7920 } 7921 if (!MultipleInitValues && InitValue) 7922 return getSCEV(InitValue); 7923 } 7924 } 7925 // Okay, we know how many times the containing loop executes. If 7926 // this is a constant evolving PHI node, get the final value at 7927 // the specified iteration number. 7928 Constant *RV = 7929 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7930 if (RV) return getSCEV(RV); 7931 } 7932 } 7933 7934 // Okay, this is an expression that we cannot symbolically evaluate 7935 // into a SCEV. Check to see if it's possible to symbolically evaluate 7936 // the arguments into constants, and if so, try to constant propagate the 7937 // result. This is particularly useful for computing loop exit values. 7938 if (CanConstantFold(I)) { 7939 SmallVector<Constant *, 4> Operands; 7940 bool MadeImprovement = false; 7941 for (Value *Op : I->operands()) { 7942 if (Constant *C = dyn_cast<Constant>(Op)) { 7943 Operands.push_back(C); 7944 continue; 7945 } 7946 7947 // If any of the operands is non-constant and if they are 7948 // non-integer and non-pointer, don't even try to analyze them 7949 // with scev techniques. 7950 if (!isSCEVable(Op->getType())) 7951 return V; 7952 7953 const SCEV *OrigV = getSCEV(Op); 7954 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7955 MadeImprovement |= OrigV != OpV; 7956 7957 Constant *C = BuildConstantFromSCEV(OpV); 7958 if (!C) return V; 7959 if (C->getType() != Op->getType()) 7960 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 7961 Op->getType(), 7962 false), 7963 C, Op->getType()); 7964 Operands.push_back(C); 7965 } 7966 7967 // Check to see if getSCEVAtScope actually made an improvement. 7968 if (MadeImprovement) { 7969 Constant *C = nullptr; 7970 const DataLayout &DL = getDataLayout(); 7971 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 7972 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7973 Operands[1], DL, &TLI); 7974 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 7975 if (!LI->isVolatile()) 7976 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7977 } else 7978 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 7979 if (!C) return V; 7980 return getSCEV(C); 7981 } 7982 } 7983 } 7984 7985 // This is some other type of SCEVUnknown, just return it. 7986 return V; 7987 } 7988 7989 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 7990 // Avoid performing the look-up in the common case where the specified 7991 // expression has no loop-variant portions. 7992 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 7993 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 7994 if (OpAtScope != Comm->getOperand(i)) { 7995 // Okay, at least one of these operands is loop variant but might be 7996 // foldable. Build a new instance of the folded commutative expression. 7997 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 7998 Comm->op_begin()+i); 7999 NewOps.push_back(OpAtScope); 8000 8001 for (++i; i != e; ++i) { 8002 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8003 NewOps.push_back(OpAtScope); 8004 } 8005 if (isa<SCEVAddExpr>(Comm)) 8006 return getAddExpr(NewOps); 8007 if (isa<SCEVMulExpr>(Comm)) 8008 return getMulExpr(NewOps); 8009 if (isa<SCEVSMaxExpr>(Comm)) 8010 return getSMaxExpr(NewOps); 8011 if (isa<SCEVUMaxExpr>(Comm)) 8012 return getUMaxExpr(NewOps); 8013 llvm_unreachable("Unknown commutative SCEV type!"); 8014 } 8015 } 8016 // If we got here, all operands are loop invariant. 8017 return Comm; 8018 } 8019 8020 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8021 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8022 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8023 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8024 return Div; // must be loop invariant 8025 return getUDivExpr(LHS, RHS); 8026 } 8027 8028 // If this is a loop recurrence for a loop that does not contain L, then we 8029 // are dealing with the final value computed by the loop. 8030 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8031 // First, attempt to evaluate each operand. 8032 // Avoid performing the look-up in the common case where the specified 8033 // expression has no loop-variant portions. 8034 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8035 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8036 if (OpAtScope == AddRec->getOperand(i)) 8037 continue; 8038 8039 // Okay, at least one of these operands is loop variant but might be 8040 // foldable. Build a new instance of the folded commutative expression. 8041 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8042 AddRec->op_begin()+i); 8043 NewOps.push_back(OpAtScope); 8044 for (++i; i != e; ++i) 8045 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8046 8047 const SCEV *FoldedRec = 8048 getAddRecExpr(NewOps, AddRec->getLoop(), 8049 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8050 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8051 // The addrec may be folded to a nonrecurrence, for example, if the 8052 // induction variable is multiplied by zero after constant folding. Go 8053 // ahead and return the folded value. 8054 if (!AddRec) 8055 return FoldedRec; 8056 break; 8057 } 8058 8059 // If the scope is outside the addrec's loop, evaluate it by using the 8060 // loop exit value of the addrec. 8061 if (!AddRec->getLoop()->contains(L)) { 8062 // To evaluate this recurrence, we need to know how many times the AddRec 8063 // loop iterates. Compute this now. 8064 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8065 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8066 8067 // Then, evaluate the AddRec. 8068 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8069 } 8070 8071 return AddRec; 8072 } 8073 8074 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8075 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8076 if (Op == Cast->getOperand()) 8077 return Cast; // must be loop invariant 8078 return getZeroExtendExpr(Op, Cast->getType()); 8079 } 8080 8081 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8082 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8083 if (Op == Cast->getOperand()) 8084 return Cast; // must be loop invariant 8085 return getSignExtendExpr(Op, Cast->getType()); 8086 } 8087 8088 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8089 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8090 if (Op == Cast->getOperand()) 8091 return Cast; // must be loop invariant 8092 return getTruncateExpr(Op, Cast->getType()); 8093 } 8094 8095 llvm_unreachable("Unknown SCEV type!"); 8096 } 8097 8098 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8099 return getSCEVAtScope(getSCEV(V), L); 8100 } 8101 8102 /// Finds the minimum unsigned root of the following equation: 8103 /// 8104 /// A * X = B (mod N) 8105 /// 8106 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8107 /// A and B isn't important. 8108 /// 8109 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8110 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8111 ScalarEvolution &SE) { 8112 uint32_t BW = A.getBitWidth(); 8113 assert(BW == SE.getTypeSizeInBits(B->getType())); 8114 assert(A != 0 && "A must be non-zero."); 8115 8116 // 1. D = gcd(A, N) 8117 // 8118 // The gcd of A and N may have only one prime factor: 2. The number of 8119 // trailing zeros in A is its multiplicity 8120 uint32_t Mult2 = A.countTrailingZeros(); 8121 // D = 2^Mult2 8122 8123 // 2. Check if B is divisible by D. 8124 // 8125 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8126 // is not less than multiplicity of this prime factor for D. 8127 if (SE.GetMinTrailingZeros(B) < Mult2) 8128 return SE.getCouldNotCompute(); 8129 8130 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8131 // modulo (N / D). 8132 // 8133 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8134 // (N / D) in general. The inverse itself always fits into BW bits, though, 8135 // so we immediately truncate it. 8136 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8137 APInt Mod(BW + 1, 0); 8138 Mod.setBit(BW - Mult2); // Mod = N / D 8139 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8140 8141 // 4. Compute the minimum unsigned root of the equation: 8142 // I * (B / D) mod (N / D) 8143 // To simplify the computation, we factor out the divide by D: 8144 // (I * B mod N) / D 8145 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8146 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8147 } 8148 8149 /// Find the roots of the quadratic equation for the given quadratic chrec 8150 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8151 /// two SCEVCouldNotCompute objects. 8152 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8153 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8154 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8155 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8156 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8157 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8158 8159 // We currently can only solve this if the coefficients are constants. 8160 if (!LC || !MC || !NC) 8161 return None; 8162 8163 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8164 const APInt &L = LC->getAPInt(); 8165 const APInt &M = MC->getAPInt(); 8166 const APInt &N = NC->getAPInt(); 8167 APInt Two(BitWidth, 2); 8168 8169 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8170 8171 // The A coefficient is N/2 8172 APInt A = N.sdiv(Two); 8173 8174 // The B coefficient is M-N/2 8175 APInt B = M; 8176 B -= A; // A is the same as N/2. 8177 8178 // The C coefficient is L. 8179 const APInt& C = L; 8180 8181 // Compute the B^2-4ac term. 8182 APInt SqrtTerm = B; 8183 SqrtTerm *= B; 8184 SqrtTerm -= 4 * (A * C); 8185 8186 if (SqrtTerm.isNegative()) { 8187 // The loop is provably infinite. 8188 return None; 8189 } 8190 8191 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8192 // integer value or else APInt::sqrt() will assert. 8193 APInt SqrtVal = SqrtTerm.sqrt(); 8194 8195 // Compute the two solutions for the quadratic formula. 8196 // The divisions must be performed as signed divisions. 8197 APInt NegB = -std::move(B); 8198 APInt TwoA = std::move(A); 8199 TwoA <<= 1; 8200 if (TwoA.isNullValue()) 8201 return None; 8202 8203 LLVMContext &Context = SE.getContext(); 8204 8205 ConstantInt *Solution1 = 8206 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8207 ConstantInt *Solution2 = 8208 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8209 8210 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8211 cast<SCEVConstant>(SE.getConstant(Solution2))); 8212 } 8213 8214 ScalarEvolution::ExitLimit 8215 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8216 bool AllowPredicates) { 8217 8218 // This is only used for loops with a "x != y" exit test. The exit condition 8219 // is now expressed as a single expression, V = x-y. So the exit test is 8220 // effectively V != 0. We know and take advantage of the fact that this 8221 // expression only being used in a comparison by zero context. 8222 8223 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8224 // If the value is a constant 8225 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8226 // If the value is already zero, the branch will execute zero times. 8227 if (C->getValue()->isZero()) return C; 8228 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8229 } 8230 8231 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 8232 if (!AddRec && AllowPredicates) 8233 // Try to make this an AddRec using runtime tests, in the first X 8234 // iterations of this loop, where X is the SCEV expression found by the 8235 // algorithm below. 8236 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8237 8238 if (!AddRec || AddRec->getLoop() != L) 8239 return getCouldNotCompute(); 8240 8241 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8242 // the quadratic equation to solve it. 8243 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8244 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8245 const SCEVConstant *R1 = Roots->first; 8246 const SCEVConstant *R2 = Roots->second; 8247 // Pick the smallest positive root value. 8248 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8249 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8250 if (!CB->getZExtValue()) 8251 std::swap(R1, R2); // R1 is the minimum root now. 8252 8253 // We can only use this value if the chrec ends up with an exact zero 8254 // value at this index. When solving for "X*X != 5", for example, we 8255 // should not accept a root of 2. 8256 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8257 if (Val->isZero()) 8258 // We found a quadratic root! 8259 return ExitLimit(R1, R1, false, Predicates); 8260 } 8261 } 8262 return getCouldNotCompute(); 8263 } 8264 8265 // Otherwise we can only handle this if it is affine. 8266 if (!AddRec->isAffine()) 8267 return getCouldNotCompute(); 8268 8269 // If this is an affine expression, the execution count of this branch is 8270 // the minimum unsigned root of the following equation: 8271 // 8272 // Start + Step*N = 0 (mod 2^BW) 8273 // 8274 // equivalent to: 8275 // 8276 // Step*N = -Start (mod 2^BW) 8277 // 8278 // where BW is the common bit width of Start and Step. 8279 8280 // Get the initial value for the loop. 8281 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8282 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8283 8284 // For now we handle only constant steps. 8285 // 8286 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8287 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8288 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8289 // We have not yet seen any such cases. 8290 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8291 if (!StepC || StepC->getValue()->isZero()) 8292 return getCouldNotCompute(); 8293 8294 // For positive steps (counting up until unsigned overflow): 8295 // N = -Start/Step (as unsigned) 8296 // For negative steps (counting down to zero): 8297 // N = Start/-Step 8298 // First compute the unsigned distance from zero in the direction of Step. 8299 bool CountDown = StepC->getAPInt().isNegative(); 8300 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8301 8302 // Handle unitary steps, which cannot wraparound. 8303 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8304 // N = Distance (as unsigned) 8305 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8306 APInt MaxBECount = getUnsignedRangeMax(Distance); 8307 8308 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8309 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8310 // case, and see if we can improve the bound. 8311 // 8312 // Explicitly handling this here is necessary because getUnsignedRange 8313 // isn't context-sensitive; it doesn't know that we only care about the 8314 // range inside the loop. 8315 const SCEV *Zero = getZero(Distance->getType()); 8316 const SCEV *One = getOne(Distance->getType()); 8317 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8318 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8319 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8320 // as "unsigned_max(Distance + 1) - 1". 8321 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8322 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8323 } 8324 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8325 } 8326 8327 // If the condition controls loop exit (the loop exits only if the expression 8328 // is true) and the addition is no-wrap we can use unsigned divide to 8329 // compute the backedge count. In this case, the step may not divide the 8330 // distance, but we don't care because if the condition is "missed" the loop 8331 // will have undefined behavior due to wrapping. 8332 if (ControlsExit && AddRec->hasNoSelfWrap() && 8333 loopHasNoAbnormalExits(AddRec->getLoop())) { 8334 const SCEV *Exact = 8335 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8336 const SCEV *Max = 8337 Exact == getCouldNotCompute() 8338 ? Exact 8339 : getConstant(getUnsignedRangeMax(Exact)); 8340 return ExitLimit(Exact, Max, false, Predicates); 8341 } 8342 8343 // Solve the general equation. 8344 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8345 getNegativeSCEV(Start), *this); 8346 const SCEV *M = E == getCouldNotCompute() 8347 ? E 8348 : getConstant(getUnsignedRangeMax(E)); 8349 return ExitLimit(E, M, false, Predicates); 8350 } 8351 8352 ScalarEvolution::ExitLimit 8353 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8354 // Loops that look like: while (X == 0) are very strange indeed. We don't 8355 // handle them yet except for the trivial case. This could be expanded in the 8356 // future as needed. 8357 8358 // If the value is a constant, check to see if it is known to be non-zero 8359 // already. If so, the backedge will execute zero times. 8360 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8361 if (!C->getValue()->isZero()) 8362 return getZero(C->getType()); 8363 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8364 } 8365 8366 // We could implement others, but I really doubt anyone writes loops like 8367 // this, and if they did, they would already be constant folded. 8368 return getCouldNotCompute(); 8369 } 8370 8371 std::pair<BasicBlock *, BasicBlock *> 8372 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8373 // If the block has a unique predecessor, then there is no path from the 8374 // predecessor to the block that does not go through the direct edge 8375 // from the predecessor to the block. 8376 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8377 return {Pred, BB}; 8378 8379 // A loop's header is defined to be a block that dominates the loop. 8380 // If the header has a unique predecessor outside the loop, it must be 8381 // a block that has exactly one successor that can reach the loop. 8382 if (Loop *L = LI.getLoopFor(BB)) 8383 return {L->getLoopPredecessor(), L->getHeader()}; 8384 8385 return {nullptr, nullptr}; 8386 } 8387 8388 /// SCEV structural equivalence is usually sufficient for testing whether two 8389 /// expressions are equal, however for the purposes of looking for a condition 8390 /// guarding a loop, it can be useful to be a little more general, since a 8391 /// front-end may have replicated the controlling expression. 8392 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8393 // Quick check to see if they are the same SCEV. 8394 if (A == B) return true; 8395 8396 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8397 // Not all instructions that are "identical" compute the same value. For 8398 // instance, two distinct alloca instructions allocating the same type are 8399 // identical and do not read memory; but compute distinct values. 8400 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8401 }; 8402 8403 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8404 // two different instructions with the same value. Check for this case. 8405 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8406 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8407 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8408 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8409 if (ComputesEqualValues(AI, BI)) 8410 return true; 8411 8412 // Otherwise assume they may have a different value. 8413 return false; 8414 } 8415 8416 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8417 const SCEV *&LHS, const SCEV *&RHS, 8418 unsigned Depth) { 8419 bool Changed = false; 8420 8421 // If we hit the max recursion limit bail out. 8422 if (Depth >= 3) 8423 return false; 8424 8425 // Canonicalize a constant to the right side. 8426 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8427 // Check for both operands constant. 8428 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8429 if (ConstantExpr::getICmp(Pred, 8430 LHSC->getValue(), 8431 RHSC->getValue())->isNullValue()) 8432 goto trivially_false; 8433 else 8434 goto trivially_true; 8435 } 8436 // Otherwise swap the operands to put the constant on the right. 8437 std::swap(LHS, RHS); 8438 Pred = ICmpInst::getSwappedPredicate(Pred); 8439 Changed = true; 8440 } 8441 8442 // If we're comparing an addrec with a value which is loop-invariant in the 8443 // addrec's loop, put the addrec on the left. Also make a dominance check, 8444 // as both operands could be addrecs loop-invariant in each other's loop. 8445 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8446 const Loop *L = AR->getLoop(); 8447 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8448 std::swap(LHS, RHS); 8449 Pred = ICmpInst::getSwappedPredicate(Pred); 8450 Changed = true; 8451 } 8452 } 8453 8454 // If there's a constant operand, canonicalize comparisons with boundary 8455 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8456 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8457 const APInt &RA = RC->getAPInt(); 8458 8459 bool SimplifiedByConstantRange = false; 8460 8461 if (!ICmpInst::isEquality(Pred)) { 8462 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8463 if (ExactCR.isFullSet()) 8464 goto trivially_true; 8465 else if (ExactCR.isEmptySet()) 8466 goto trivially_false; 8467 8468 APInt NewRHS; 8469 CmpInst::Predicate NewPred; 8470 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8471 ICmpInst::isEquality(NewPred)) { 8472 // We were able to convert an inequality to an equality. 8473 Pred = NewPred; 8474 RHS = getConstant(NewRHS); 8475 Changed = SimplifiedByConstantRange = true; 8476 } 8477 } 8478 8479 if (!SimplifiedByConstantRange) { 8480 switch (Pred) { 8481 default: 8482 break; 8483 case ICmpInst::ICMP_EQ: 8484 case ICmpInst::ICMP_NE: 8485 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8486 if (!RA) 8487 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8488 if (const SCEVMulExpr *ME = 8489 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8490 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8491 ME->getOperand(0)->isAllOnesValue()) { 8492 RHS = AE->getOperand(1); 8493 LHS = ME->getOperand(1); 8494 Changed = true; 8495 } 8496 break; 8497 8498 8499 // The "Should have been caught earlier!" messages refer to the fact 8500 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8501 // should have fired on the corresponding cases, and canonicalized the 8502 // check to trivially_true or trivially_false. 8503 8504 case ICmpInst::ICMP_UGE: 8505 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8506 Pred = ICmpInst::ICMP_UGT; 8507 RHS = getConstant(RA - 1); 8508 Changed = true; 8509 break; 8510 case ICmpInst::ICMP_ULE: 8511 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8512 Pred = ICmpInst::ICMP_ULT; 8513 RHS = getConstant(RA + 1); 8514 Changed = true; 8515 break; 8516 case ICmpInst::ICMP_SGE: 8517 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8518 Pred = ICmpInst::ICMP_SGT; 8519 RHS = getConstant(RA - 1); 8520 Changed = true; 8521 break; 8522 case ICmpInst::ICMP_SLE: 8523 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8524 Pred = ICmpInst::ICMP_SLT; 8525 RHS = getConstant(RA + 1); 8526 Changed = true; 8527 break; 8528 } 8529 } 8530 } 8531 8532 // Check for obvious equality. 8533 if (HasSameValue(LHS, RHS)) { 8534 if (ICmpInst::isTrueWhenEqual(Pred)) 8535 goto trivially_true; 8536 if (ICmpInst::isFalseWhenEqual(Pred)) 8537 goto trivially_false; 8538 } 8539 8540 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8541 // adding or subtracting 1 from one of the operands. 8542 switch (Pred) { 8543 case ICmpInst::ICMP_SLE: 8544 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8545 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8546 SCEV::FlagNSW); 8547 Pred = ICmpInst::ICMP_SLT; 8548 Changed = true; 8549 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8550 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8551 SCEV::FlagNSW); 8552 Pred = ICmpInst::ICMP_SLT; 8553 Changed = true; 8554 } 8555 break; 8556 case ICmpInst::ICMP_SGE: 8557 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8558 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8559 SCEV::FlagNSW); 8560 Pred = ICmpInst::ICMP_SGT; 8561 Changed = true; 8562 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8563 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8564 SCEV::FlagNSW); 8565 Pred = ICmpInst::ICMP_SGT; 8566 Changed = true; 8567 } 8568 break; 8569 case ICmpInst::ICMP_ULE: 8570 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8571 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8572 SCEV::FlagNUW); 8573 Pred = ICmpInst::ICMP_ULT; 8574 Changed = true; 8575 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8576 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8577 Pred = ICmpInst::ICMP_ULT; 8578 Changed = true; 8579 } 8580 break; 8581 case ICmpInst::ICMP_UGE: 8582 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8583 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8584 Pred = ICmpInst::ICMP_UGT; 8585 Changed = true; 8586 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8587 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8588 SCEV::FlagNUW); 8589 Pred = ICmpInst::ICMP_UGT; 8590 Changed = true; 8591 } 8592 break; 8593 default: 8594 break; 8595 } 8596 8597 // TODO: More simplifications are possible here. 8598 8599 // Recursively simplify until we either hit a recursion limit or nothing 8600 // changes. 8601 if (Changed) 8602 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8603 8604 return Changed; 8605 8606 trivially_true: 8607 // Return 0 == 0. 8608 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8609 Pred = ICmpInst::ICMP_EQ; 8610 return true; 8611 8612 trivially_false: 8613 // Return 0 != 0. 8614 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8615 Pred = ICmpInst::ICMP_NE; 8616 return true; 8617 } 8618 8619 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8620 return getSignedRangeMax(S).isNegative(); 8621 } 8622 8623 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8624 return getSignedRangeMin(S).isStrictlyPositive(); 8625 } 8626 8627 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8628 return !getSignedRangeMin(S).isNegative(); 8629 } 8630 8631 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8632 return !getSignedRangeMax(S).isStrictlyPositive(); 8633 } 8634 8635 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8636 return isKnownNegative(S) || isKnownPositive(S); 8637 } 8638 8639 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8640 const SCEV *LHS, const SCEV *RHS) { 8641 // Canonicalize the inputs first. 8642 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8643 8644 // If LHS or RHS is an addrec, check to see if the condition is true in 8645 // every iteration of the loop. 8646 // If LHS and RHS are both addrec, both conditions must be true in 8647 // every iteration of the loop. 8648 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8649 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8650 bool LeftGuarded = false; 8651 bool RightGuarded = false; 8652 if (LAR) { 8653 const Loop *L = LAR->getLoop(); 8654 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 8655 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 8656 if (!RAR) return true; 8657 LeftGuarded = true; 8658 } 8659 } 8660 if (RAR) { 8661 const Loop *L = RAR->getLoop(); 8662 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 8663 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 8664 if (!LAR) return true; 8665 RightGuarded = true; 8666 } 8667 } 8668 if (LeftGuarded && RightGuarded) 8669 return true; 8670 8671 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8672 return true; 8673 8674 // Otherwise see what can be done with known constant ranges. 8675 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 8676 } 8677 8678 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8679 ICmpInst::Predicate Pred, 8680 bool &Increasing) { 8681 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8682 8683 #ifndef NDEBUG 8684 // Verify an invariant: inverting the predicate should turn a monotonically 8685 // increasing change to a monotonically decreasing one, and vice versa. 8686 bool IncreasingSwapped; 8687 bool ResultSwapped = isMonotonicPredicateImpl( 8688 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8689 8690 assert(Result == ResultSwapped && "should be able to analyze both!"); 8691 if (ResultSwapped) 8692 assert(Increasing == !IncreasingSwapped && 8693 "monotonicity should flip as we flip the predicate"); 8694 #endif 8695 8696 return Result; 8697 } 8698 8699 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8700 ICmpInst::Predicate Pred, 8701 bool &Increasing) { 8702 8703 // A zero step value for LHS means the induction variable is essentially a 8704 // loop invariant value. We don't really depend on the predicate actually 8705 // flipping from false to true (for increasing predicates, and the other way 8706 // around for decreasing predicates), all we care about is that *if* the 8707 // predicate changes then it only changes from false to true. 8708 // 8709 // A zero step value in itself is not very useful, but there may be places 8710 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8711 // as general as possible. 8712 8713 switch (Pred) { 8714 default: 8715 return false; // Conservative answer 8716 8717 case ICmpInst::ICMP_UGT: 8718 case ICmpInst::ICMP_UGE: 8719 case ICmpInst::ICMP_ULT: 8720 case ICmpInst::ICMP_ULE: 8721 if (!LHS->hasNoUnsignedWrap()) 8722 return false; 8723 8724 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8725 return true; 8726 8727 case ICmpInst::ICMP_SGT: 8728 case ICmpInst::ICMP_SGE: 8729 case ICmpInst::ICMP_SLT: 8730 case ICmpInst::ICMP_SLE: { 8731 if (!LHS->hasNoSignedWrap()) 8732 return false; 8733 8734 const SCEV *Step = LHS->getStepRecurrence(*this); 8735 8736 if (isKnownNonNegative(Step)) { 8737 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8738 return true; 8739 } 8740 8741 if (isKnownNonPositive(Step)) { 8742 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8743 return true; 8744 } 8745 8746 return false; 8747 } 8748 8749 } 8750 8751 llvm_unreachable("switch has default clause!"); 8752 } 8753 8754 bool ScalarEvolution::isLoopInvariantPredicate( 8755 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8756 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8757 const SCEV *&InvariantRHS) { 8758 8759 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8760 if (!isLoopInvariant(RHS, L)) { 8761 if (!isLoopInvariant(LHS, L)) 8762 return false; 8763 8764 std::swap(LHS, RHS); 8765 Pred = ICmpInst::getSwappedPredicate(Pred); 8766 } 8767 8768 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8769 if (!ArLHS || ArLHS->getLoop() != L) 8770 return false; 8771 8772 bool Increasing; 8773 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8774 return false; 8775 8776 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8777 // true as the loop iterates, and the backedge is control dependent on 8778 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8779 // 8780 // * if the predicate was false in the first iteration then the predicate 8781 // is never evaluated again, since the loop exits without taking the 8782 // backedge. 8783 // * if the predicate was true in the first iteration then it will 8784 // continue to be true for all future iterations since it is 8785 // monotonically increasing. 8786 // 8787 // For both the above possibilities, we can replace the loop varying 8788 // predicate with its value on the first iteration of the loop (which is 8789 // loop invariant). 8790 // 8791 // A similar reasoning applies for a monotonically decreasing predicate, by 8792 // replacing true with false and false with true in the above two bullets. 8793 8794 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8795 8796 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8797 return false; 8798 8799 InvariantPred = Pred; 8800 InvariantLHS = ArLHS->getStart(); 8801 InvariantRHS = RHS; 8802 return true; 8803 } 8804 8805 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8806 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8807 if (HasSameValue(LHS, RHS)) 8808 return ICmpInst::isTrueWhenEqual(Pred); 8809 8810 // This code is split out from isKnownPredicate because it is called from 8811 // within isLoopEntryGuardedByCond. 8812 8813 auto CheckRanges = 8814 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8815 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8816 .contains(RangeLHS); 8817 }; 8818 8819 // The check at the top of the function catches the case where the values are 8820 // known to be equal. 8821 if (Pred == CmpInst::ICMP_EQ) 8822 return false; 8823 8824 if (Pred == CmpInst::ICMP_NE) 8825 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8826 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8827 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8828 8829 if (CmpInst::isSigned(Pred)) 8830 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8831 8832 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8833 } 8834 8835 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8836 const SCEV *LHS, 8837 const SCEV *RHS) { 8838 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8839 // Return Y via OutY. 8840 auto MatchBinaryAddToConst = 8841 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8842 SCEV::NoWrapFlags ExpectedFlags) { 8843 const SCEV *NonConstOp, *ConstOp; 8844 SCEV::NoWrapFlags FlagsPresent; 8845 8846 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8847 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8848 return false; 8849 8850 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8851 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8852 }; 8853 8854 APInt C; 8855 8856 switch (Pred) { 8857 default: 8858 break; 8859 8860 case ICmpInst::ICMP_SGE: 8861 std::swap(LHS, RHS); 8862 LLVM_FALLTHROUGH; 8863 case ICmpInst::ICMP_SLE: 8864 // X s<= (X + C)<nsw> if C >= 0 8865 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8866 return true; 8867 8868 // (X + C)<nsw> s<= X if C <= 0 8869 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8870 !C.isStrictlyPositive()) 8871 return true; 8872 break; 8873 8874 case ICmpInst::ICMP_SGT: 8875 std::swap(LHS, RHS); 8876 LLVM_FALLTHROUGH; 8877 case ICmpInst::ICMP_SLT: 8878 // X s< (X + C)<nsw> if C > 0 8879 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8880 C.isStrictlyPositive()) 8881 return true; 8882 8883 // (X + C)<nsw> s< X if C < 0 8884 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8885 return true; 8886 break; 8887 } 8888 8889 return false; 8890 } 8891 8892 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8893 const SCEV *LHS, 8894 const SCEV *RHS) { 8895 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8896 return false; 8897 8898 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8899 // the stack can result in exponential time complexity. 8900 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8901 8902 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8903 // 8904 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8905 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8906 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8907 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8908 // use isKnownPredicate later if needed. 8909 return isKnownNonNegative(RHS) && 8910 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8911 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8912 } 8913 8914 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8915 ICmpInst::Predicate Pred, 8916 const SCEV *LHS, const SCEV *RHS) { 8917 // No need to even try if we know the module has no guards. 8918 if (!HasGuards) 8919 return false; 8920 8921 return any_of(*BB, [&](Instruction &I) { 8922 using namespace llvm::PatternMatch; 8923 8924 Value *Condition; 8925 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 8926 m_Value(Condition))) && 8927 isImpliedCond(Pred, LHS, RHS, Condition, false); 8928 }); 8929 } 8930 8931 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 8932 /// protected by a conditional between LHS and RHS. This is used to 8933 /// to eliminate casts. 8934 bool 8935 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 8936 ICmpInst::Predicate Pred, 8937 const SCEV *LHS, const SCEV *RHS) { 8938 // Interpret a null as meaning no loop, where there is obviously no guard 8939 // (interprocedural conditions notwithstanding). 8940 if (!L) return true; 8941 8942 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8943 return true; 8944 8945 BasicBlock *Latch = L->getLoopLatch(); 8946 if (!Latch) 8947 return false; 8948 8949 BranchInst *LoopContinuePredicate = 8950 dyn_cast<BranchInst>(Latch->getTerminator()); 8951 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 8952 isImpliedCond(Pred, LHS, RHS, 8953 LoopContinuePredicate->getCondition(), 8954 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 8955 return true; 8956 8957 // We don't want more than one activation of the following loops on the stack 8958 // -- that can lead to O(n!) time complexity. 8959 if (WalkingBEDominatingConds) 8960 return false; 8961 8962 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 8963 8964 // See if we can exploit a trip count to prove the predicate. 8965 const auto &BETakenInfo = getBackedgeTakenInfo(L); 8966 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 8967 if (LatchBECount != getCouldNotCompute()) { 8968 // We know that Latch branches back to the loop header exactly 8969 // LatchBECount times. This means the backdege condition at Latch is 8970 // equivalent to "{0,+,1} u< LatchBECount". 8971 Type *Ty = LatchBECount->getType(); 8972 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 8973 const SCEV *LoopCounter = 8974 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 8975 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 8976 LatchBECount)) 8977 return true; 8978 } 8979 8980 // Check conditions due to any @llvm.assume intrinsics. 8981 for (auto &AssumeVH : AC.assumptions()) { 8982 if (!AssumeVH) 8983 continue; 8984 auto *CI = cast<CallInst>(AssumeVH); 8985 if (!DT.dominates(CI, Latch->getTerminator())) 8986 continue; 8987 8988 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8989 return true; 8990 } 8991 8992 // If the loop is not reachable from the entry block, we risk running into an 8993 // infinite loop as we walk up into the dom tree. These loops do not matter 8994 // anyway, so we just return a conservative answer when we see them. 8995 if (!DT.isReachableFromEntry(L->getHeader())) 8996 return false; 8997 8998 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8999 return true; 9000 9001 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9002 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9003 assert(DTN && "should reach the loop header before reaching the root!"); 9004 9005 BasicBlock *BB = DTN->getBlock(); 9006 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9007 return true; 9008 9009 BasicBlock *PBB = BB->getSinglePredecessor(); 9010 if (!PBB) 9011 continue; 9012 9013 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9014 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9015 continue; 9016 9017 Value *Condition = ContinuePredicate->getCondition(); 9018 9019 // If we have an edge `E` within the loop body that dominates the only 9020 // latch, the condition guarding `E` also guards the backedge. This 9021 // reasoning works only for loops with a single latch. 9022 9023 BasicBlockEdge DominatingEdge(PBB, BB); 9024 if (DominatingEdge.isSingleEdge()) { 9025 // We're constructively (and conservatively) enumerating edges within the 9026 // loop body that dominate the latch. The dominator tree better agree 9027 // with us on this: 9028 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9029 9030 if (isImpliedCond(Pred, LHS, RHS, Condition, 9031 BB != ContinuePredicate->getSuccessor(0))) 9032 return true; 9033 } 9034 } 9035 9036 return false; 9037 } 9038 9039 bool 9040 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9041 ICmpInst::Predicate Pred, 9042 const SCEV *LHS, const SCEV *RHS) { 9043 // Interpret a null as meaning no loop, where there is obviously no guard 9044 // (interprocedural conditions notwithstanding). 9045 if (!L) return false; 9046 9047 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 9048 return true; 9049 9050 // Starting at the loop predecessor, climb up the predecessor chain, as long 9051 // as there are predecessors that can be found that have unique successors 9052 // leading to the original header. 9053 for (std::pair<BasicBlock *, BasicBlock *> 9054 Pair(L->getLoopPredecessor(), L->getHeader()); 9055 Pair.first; 9056 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9057 9058 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 9059 return true; 9060 9061 BranchInst *LoopEntryPredicate = 9062 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9063 if (!LoopEntryPredicate || 9064 LoopEntryPredicate->isUnconditional()) 9065 continue; 9066 9067 if (isImpliedCond(Pred, LHS, RHS, 9068 LoopEntryPredicate->getCondition(), 9069 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9070 return true; 9071 } 9072 9073 // Check conditions due to any @llvm.assume intrinsics. 9074 for (auto &AssumeVH : AC.assumptions()) { 9075 if (!AssumeVH) 9076 continue; 9077 auto *CI = cast<CallInst>(AssumeVH); 9078 if (!DT.dominates(CI, L->getHeader())) 9079 continue; 9080 9081 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9082 return true; 9083 } 9084 9085 return false; 9086 } 9087 9088 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9089 const SCEV *LHS, const SCEV *RHS, 9090 Value *FoundCondValue, 9091 bool Inverse) { 9092 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9093 return false; 9094 9095 auto ClearOnExit = 9096 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9097 9098 // Recursively handle And and Or conditions. 9099 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9100 if (BO->getOpcode() == Instruction::And) { 9101 if (!Inverse) 9102 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9103 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9104 } else if (BO->getOpcode() == Instruction::Or) { 9105 if (Inverse) 9106 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9107 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9108 } 9109 } 9110 9111 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9112 if (!ICI) return false; 9113 9114 // Now that we found a conditional branch that dominates the loop or controls 9115 // the loop latch. Check to see if it is the comparison we are looking for. 9116 ICmpInst::Predicate FoundPred; 9117 if (Inverse) 9118 FoundPred = ICI->getInversePredicate(); 9119 else 9120 FoundPred = ICI->getPredicate(); 9121 9122 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9123 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9124 9125 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9126 } 9127 9128 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9129 const SCEV *RHS, 9130 ICmpInst::Predicate FoundPred, 9131 const SCEV *FoundLHS, 9132 const SCEV *FoundRHS) { 9133 // Balance the types. 9134 if (getTypeSizeInBits(LHS->getType()) < 9135 getTypeSizeInBits(FoundLHS->getType())) { 9136 if (CmpInst::isSigned(Pred)) { 9137 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9138 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9139 } else { 9140 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9141 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9142 } 9143 } else if (getTypeSizeInBits(LHS->getType()) > 9144 getTypeSizeInBits(FoundLHS->getType())) { 9145 if (CmpInst::isSigned(FoundPred)) { 9146 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9147 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9148 } else { 9149 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9150 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9151 } 9152 } 9153 9154 // Canonicalize the query to match the way instcombine will have 9155 // canonicalized the comparison. 9156 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9157 if (LHS == RHS) 9158 return CmpInst::isTrueWhenEqual(Pred); 9159 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9160 if (FoundLHS == FoundRHS) 9161 return CmpInst::isFalseWhenEqual(FoundPred); 9162 9163 // Check to see if we can make the LHS or RHS match. 9164 if (LHS == FoundRHS || RHS == FoundLHS) { 9165 if (isa<SCEVConstant>(RHS)) { 9166 std::swap(FoundLHS, FoundRHS); 9167 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9168 } else { 9169 std::swap(LHS, RHS); 9170 Pred = ICmpInst::getSwappedPredicate(Pred); 9171 } 9172 } 9173 9174 // Check whether the found predicate is the same as the desired predicate. 9175 if (FoundPred == Pred) 9176 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9177 9178 // Check whether swapping the found predicate makes it the same as the 9179 // desired predicate. 9180 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9181 if (isa<SCEVConstant>(RHS)) 9182 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9183 else 9184 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9185 RHS, LHS, FoundLHS, FoundRHS); 9186 } 9187 9188 // Unsigned comparison is the same as signed comparison when both the operands 9189 // are non-negative. 9190 if (CmpInst::isUnsigned(FoundPred) && 9191 CmpInst::getSignedPredicate(FoundPred) == Pred && 9192 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9193 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9194 9195 // Check if we can make progress by sharpening ranges. 9196 if (FoundPred == ICmpInst::ICMP_NE && 9197 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9198 9199 const SCEVConstant *C = nullptr; 9200 const SCEV *V = nullptr; 9201 9202 if (isa<SCEVConstant>(FoundLHS)) { 9203 C = cast<SCEVConstant>(FoundLHS); 9204 V = FoundRHS; 9205 } else { 9206 C = cast<SCEVConstant>(FoundRHS); 9207 V = FoundLHS; 9208 } 9209 9210 // The guarding predicate tells us that C != V. If the known range 9211 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9212 // range we consider has to correspond to same signedness as the 9213 // predicate we're interested in folding. 9214 9215 APInt Min = ICmpInst::isSigned(Pred) ? 9216 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9217 9218 if (Min == C->getAPInt()) { 9219 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9220 // This is true even if (Min + 1) wraps around -- in case of 9221 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9222 9223 APInt SharperMin = Min + 1; 9224 9225 switch (Pred) { 9226 case ICmpInst::ICMP_SGE: 9227 case ICmpInst::ICMP_UGE: 9228 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9229 // RHS, we're done. 9230 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9231 getConstant(SharperMin))) 9232 return true; 9233 LLVM_FALLTHROUGH; 9234 9235 case ICmpInst::ICMP_SGT: 9236 case ICmpInst::ICMP_UGT: 9237 // We know from the range information that (V `Pred` Min || 9238 // V == Min). We know from the guarding condition that !(V 9239 // == Min). This gives us 9240 // 9241 // V `Pred` Min || V == Min && !(V == Min) 9242 // => V `Pred` Min 9243 // 9244 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9245 9246 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9247 return true; 9248 LLVM_FALLTHROUGH; 9249 9250 default: 9251 // No change 9252 break; 9253 } 9254 } 9255 } 9256 9257 // Check whether the actual condition is beyond sufficient. 9258 if (FoundPred == ICmpInst::ICMP_EQ) 9259 if (ICmpInst::isTrueWhenEqual(Pred)) 9260 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9261 return true; 9262 if (Pred == ICmpInst::ICMP_NE) 9263 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9264 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9265 return true; 9266 9267 // Otherwise assume the worst. 9268 return false; 9269 } 9270 9271 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9272 const SCEV *&L, const SCEV *&R, 9273 SCEV::NoWrapFlags &Flags) { 9274 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9275 if (!AE || AE->getNumOperands() != 2) 9276 return false; 9277 9278 L = AE->getOperand(0); 9279 R = AE->getOperand(1); 9280 Flags = AE->getNoWrapFlags(); 9281 return true; 9282 } 9283 9284 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9285 const SCEV *Less) { 9286 // We avoid subtracting expressions here because this function is usually 9287 // fairly deep in the call stack (i.e. is called many times). 9288 9289 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9290 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9291 const auto *MAR = cast<SCEVAddRecExpr>(More); 9292 9293 if (LAR->getLoop() != MAR->getLoop()) 9294 return None; 9295 9296 // We look at affine expressions only; not for correctness but to keep 9297 // getStepRecurrence cheap. 9298 if (!LAR->isAffine() || !MAR->isAffine()) 9299 return None; 9300 9301 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9302 return None; 9303 9304 Less = LAR->getStart(); 9305 More = MAR->getStart(); 9306 9307 // fall through 9308 } 9309 9310 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9311 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9312 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9313 return M - L; 9314 } 9315 9316 const SCEV *L, *R; 9317 SCEV::NoWrapFlags Flags; 9318 if (splitBinaryAdd(Less, L, R, Flags)) 9319 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9320 if (R == More) 9321 return -(LC->getAPInt()); 9322 9323 if (splitBinaryAdd(More, L, R, Flags)) 9324 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9325 if (R == Less) 9326 return LC->getAPInt(); 9327 9328 return None; 9329 } 9330 9331 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9332 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9333 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9334 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9335 return false; 9336 9337 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9338 if (!AddRecLHS) 9339 return false; 9340 9341 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9342 if (!AddRecFoundLHS) 9343 return false; 9344 9345 // We'd like to let SCEV reason about control dependencies, so we constrain 9346 // both the inequalities to be about add recurrences on the same loop. This 9347 // way we can use isLoopEntryGuardedByCond later. 9348 9349 const Loop *L = AddRecFoundLHS->getLoop(); 9350 if (L != AddRecLHS->getLoop()) 9351 return false; 9352 9353 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9354 // 9355 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9356 // ... (2) 9357 // 9358 // Informal proof for (2), assuming (1) [*]: 9359 // 9360 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9361 // 9362 // Then 9363 // 9364 // FoundLHS s< FoundRHS s< INT_MIN - C 9365 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9366 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9367 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9368 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9369 // <=> FoundLHS + C s< FoundRHS + C 9370 // 9371 // [*]: (1) can be proved by ruling out overflow. 9372 // 9373 // [**]: This can be proved by analyzing all the four possibilities: 9374 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9375 // (A s>= 0, B s>= 0). 9376 // 9377 // Note: 9378 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9379 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9380 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9381 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9382 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9383 // C)". 9384 9385 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9386 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9387 if (!LDiff || !RDiff || *LDiff != *RDiff) 9388 return false; 9389 9390 if (LDiff->isMinValue()) 9391 return true; 9392 9393 APInt FoundRHSLimit; 9394 9395 if (Pred == CmpInst::ICMP_ULT) { 9396 FoundRHSLimit = -(*RDiff); 9397 } else { 9398 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9399 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9400 } 9401 9402 // Try to prove (1) or (2), as needed. 9403 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9404 getConstant(FoundRHSLimit)); 9405 } 9406 9407 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9408 const SCEV *LHS, const SCEV *RHS, 9409 const SCEV *FoundLHS, 9410 const SCEV *FoundRHS) { 9411 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9412 return true; 9413 9414 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9415 return true; 9416 9417 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9418 FoundLHS, FoundRHS) || 9419 // ~x < ~y --> x > y 9420 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9421 getNotSCEV(FoundRHS), 9422 getNotSCEV(FoundLHS)); 9423 } 9424 9425 /// If Expr computes ~A, return A else return nullptr 9426 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9427 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9428 if (!Add || Add->getNumOperands() != 2 || 9429 !Add->getOperand(0)->isAllOnesValue()) 9430 return nullptr; 9431 9432 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9433 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9434 !AddRHS->getOperand(0)->isAllOnesValue()) 9435 return nullptr; 9436 9437 return AddRHS->getOperand(1); 9438 } 9439 9440 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9441 template<typename MaxExprType> 9442 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9443 const SCEV *Candidate) { 9444 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9445 if (!MaxExpr) return false; 9446 9447 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9448 } 9449 9450 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9451 template<typename MaxExprType> 9452 static bool IsMinConsistingOf(ScalarEvolution &SE, 9453 const SCEV *MaybeMinExpr, 9454 const SCEV *Candidate) { 9455 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9456 if (!MaybeMaxExpr) 9457 return false; 9458 9459 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9460 } 9461 9462 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9463 ICmpInst::Predicate Pred, 9464 const SCEV *LHS, const SCEV *RHS) { 9465 // If both sides are affine addrecs for the same loop, with equal 9466 // steps, and we know the recurrences don't wrap, then we only 9467 // need to check the predicate on the starting values. 9468 9469 if (!ICmpInst::isRelational(Pred)) 9470 return false; 9471 9472 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9473 if (!LAR) 9474 return false; 9475 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9476 if (!RAR) 9477 return false; 9478 if (LAR->getLoop() != RAR->getLoop()) 9479 return false; 9480 if (!LAR->isAffine() || !RAR->isAffine()) 9481 return false; 9482 9483 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9484 return false; 9485 9486 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9487 SCEV::FlagNSW : SCEV::FlagNUW; 9488 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9489 return false; 9490 9491 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9492 } 9493 9494 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9495 /// expression? 9496 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9497 ICmpInst::Predicate Pred, 9498 const SCEV *LHS, const SCEV *RHS) { 9499 switch (Pred) { 9500 default: 9501 return false; 9502 9503 case ICmpInst::ICMP_SGE: 9504 std::swap(LHS, RHS); 9505 LLVM_FALLTHROUGH; 9506 case ICmpInst::ICMP_SLE: 9507 return 9508 // min(A, ...) <= A 9509 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9510 // A <= max(A, ...) 9511 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9512 9513 case ICmpInst::ICMP_UGE: 9514 std::swap(LHS, RHS); 9515 LLVM_FALLTHROUGH; 9516 case ICmpInst::ICMP_ULE: 9517 return 9518 // min(A, ...) <= A 9519 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9520 // A <= max(A, ...) 9521 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9522 } 9523 9524 llvm_unreachable("covered switch fell through?!"); 9525 } 9526 9527 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9528 const SCEV *LHS, const SCEV *RHS, 9529 const SCEV *FoundLHS, 9530 const SCEV *FoundRHS, 9531 unsigned Depth) { 9532 assert(getTypeSizeInBits(LHS->getType()) == 9533 getTypeSizeInBits(RHS->getType()) && 9534 "LHS and RHS have different sizes?"); 9535 assert(getTypeSizeInBits(FoundLHS->getType()) == 9536 getTypeSizeInBits(FoundRHS->getType()) && 9537 "FoundLHS and FoundRHS have different sizes?"); 9538 // We want to avoid hurting the compile time with analysis of too big trees. 9539 if (Depth > MaxSCEVOperationsImplicationDepth) 9540 return false; 9541 // We only want to work with ICMP_SGT comparison so far. 9542 // TODO: Extend to ICMP_UGT? 9543 if (Pred == ICmpInst::ICMP_SLT) { 9544 Pred = ICmpInst::ICMP_SGT; 9545 std::swap(LHS, RHS); 9546 std::swap(FoundLHS, FoundRHS); 9547 } 9548 if (Pred != ICmpInst::ICMP_SGT) 9549 return false; 9550 9551 auto GetOpFromSExt = [&](const SCEV *S) { 9552 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9553 return Ext->getOperand(); 9554 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9555 // the constant in some cases. 9556 return S; 9557 }; 9558 9559 // Acquire values from extensions. 9560 auto *OrigFoundLHS = FoundLHS; 9561 LHS = GetOpFromSExt(LHS); 9562 FoundLHS = GetOpFromSExt(FoundLHS); 9563 9564 // Is the SGT predicate can be proved trivially or using the found context. 9565 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9566 return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9567 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9568 FoundRHS, Depth + 1); 9569 }; 9570 9571 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9572 // We want to avoid creation of any new non-constant SCEV. Since we are 9573 // going to compare the operands to RHS, we should be certain that we don't 9574 // need any size extensions for this. So let's decline all cases when the 9575 // sizes of types of LHS and RHS do not match. 9576 // TODO: Maybe try to get RHS from sext to catch more cases? 9577 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9578 return false; 9579 9580 // Should not overflow. 9581 if (!LHSAddExpr->hasNoSignedWrap()) 9582 return false; 9583 9584 auto *LL = LHSAddExpr->getOperand(0); 9585 auto *LR = LHSAddExpr->getOperand(1); 9586 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9587 9588 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9589 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9590 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9591 }; 9592 // Try to prove the following rule: 9593 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9594 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9595 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9596 return true; 9597 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9598 Value *LL, *LR; 9599 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9600 9601 using namespace llvm::PatternMatch; 9602 9603 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9604 // Rules for division. 9605 // We are going to perform some comparisons with Denominator and its 9606 // derivative expressions. In general case, creating a SCEV for it may 9607 // lead to a complex analysis of the entire graph, and in particular it 9608 // can request trip count recalculation for the same loop. This would 9609 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9610 // this, we only want to create SCEVs that are constants in this section. 9611 // So we bail if Denominator is not a constant. 9612 if (!isa<ConstantInt>(LR)) 9613 return false; 9614 9615 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9616 9617 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9618 // then a SCEV for the numerator already exists and matches with FoundLHS. 9619 auto *Numerator = getExistingSCEV(LL); 9620 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9621 return false; 9622 9623 // Make sure that the numerator matches with FoundLHS and the denominator 9624 // is positive. 9625 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9626 return false; 9627 9628 auto *DTy = Denominator->getType(); 9629 auto *FRHSTy = FoundRHS->getType(); 9630 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9631 // One of types is a pointer and another one is not. We cannot extend 9632 // them properly to a wider type, so let us just reject this case. 9633 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9634 // to avoid this check. 9635 return false; 9636 9637 // Given that: 9638 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9639 auto *WTy = getWiderType(DTy, FRHSTy); 9640 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9641 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9642 9643 // Try to prove the following rule: 9644 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9645 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9646 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9647 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9648 if (isKnownNonPositive(RHS) && 9649 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9650 return true; 9651 9652 // Try to prove the following rule: 9653 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9654 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9655 // If we divide it by Denominator > 2, then: 9656 // 1. If FoundLHS is negative, then the result is 0. 9657 // 2. If FoundLHS is non-negative, then the result is non-negative. 9658 // Anyways, the result is non-negative. 9659 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9660 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9661 if (isKnownNegative(RHS) && 9662 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9663 return true; 9664 } 9665 } 9666 9667 return false; 9668 } 9669 9670 bool 9671 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred, 9672 const SCEV *LHS, const SCEV *RHS) { 9673 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9674 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9675 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9676 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9677 } 9678 9679 bool 9680 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9681 const SCEV *LHS, const SCEV *RHS, 9682 const SCEV *FoundLHS, 9683 const SCEV *FoundRHS) { 9684 switch (Pred) { 9685 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9686 case ICmpInst::ICMP_EQ: 9687 case ICmpInst::ICMP_NE: 9688 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9689 return true; 9690 break; 9691 case ICmpInst::ICMP_SLT: 9692 case ICmpInst::ICMP_SLE: 9693 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9694 isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9695 return true; 9696 break; 9697 case ICmpInst::ICMP_SGT: 9698 case ICmpInst::ICMP_SGE: 9699 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9700 isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9701 return true; 9702 break; 9703 case ICmpInst::ICMP_ULT: 9704 case ICmpInst::ICMP_ULE: 9705 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9706 isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9707 return true; 9708 break; 9709 case ICmpInst::ICMP_UGT: 9710 case ICmpInst::ICMP_UGE: 9711 if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9712 isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9713 return true; 9714 break; 9715 } 9716 9717 // Maybe it can be proved via operations? 9718 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9719 return true; 9720 9721 return false; 9722 } 9723 9724 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9725 const SCEV *LHS, 9726 const SCEV *RHS, 9727 const SCEV *FoundLHS, 9728 const SCEV *FoundRHS) { 9729 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9730 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9731 // reduce the compile time impact of this optimization. 9732 return false; 9733 9734 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9735 if (!Addend) 9736 return false; 9737 9738 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9739 9740 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9741 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9742 ConstantRange FoundLHSRange = 9743 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9744 9745 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9746 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9747 9748 // We can also compute the range of values for `LHS` that satisfy the 9749 // consequent, "`LHS` `Pred` `RHS`": 9750 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9751 ConstantRange SatisfyingLHSRange = 9752 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9753 9754 // The antecedent implies the consequent if every value of `LHS` that 9755 // satisfies the antecedent also satisfies the consequent. 9756 return SatisfyingLHSRange.contains(LHSRange); 9757 } 9758 9759 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9760 bool IsSigned, bool NoWrap) { 9761 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9762 9763 if (NoWrap) return false; 9764 9765 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9766 const SCEV *One = getOne(Stride->getType()); 9767 9768 if (IsSigned) { 9769 APInt MaxRHS = getSignedRangeMax(RHS); 9770 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9771 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9772 9773 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9774 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9775 } 9776 9777 APInt MaxRHS = getUnsignedRangeMax(RHS); 9778 APInt MaxValue = APInt::getMaxValue(BitWidth); 9779 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9780 9781 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9782 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9783 } 9784 9785 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9786 bool IsSigned, bool NoWrap) { 9787 if (NoWrap) return false; 9788 9789 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9790 const SCEV *One = getOne(Stride->getType()); 9791 9792 if (IsSigned) { 9793 APInt MinRHS = getSignedRangeMin(RHS); 9794 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9795 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9796 9797 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9798 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9799 } 9800 9801 APInt MinRHS = getUnsignedRangeMin(RHS); 9802 APInt MinValue = APInt::getMinValue(BitWidth); 9803 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9804 9805 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9806 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9807 } 9808 9809 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9810 bool Equality) { 9811 const SCEV *One = getOne(Step->getType()); 9812 Delta = Equality ? getAddExpr(Delta, Step) 9813 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9814 return getUDivExpr(Delta, Step); 9815 } 9816 9817 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 9818 const SCEV *Stride, 9819 const SCEV *End, 9820 unsigned BitWidth, 9821 bool IsSigned) { 9822 9823 assert(!isKnownNonPositive(Stride) && 9824 "Stride is expected strictly positive!"); 9825 // Calculate the maximum backedge count based on the range of values 9826 // permitted by Start, End, and Stride. 9827 const SCEV *MaxBECount; 9828 APInt MinStart = 9829 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 9830 9831 APInt StrideForMaxBECount = 9832 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 9833 9834 // We already know that the stride is positive, so we paper over conservatism 9835 // in our range computation by forcing StrideForMaxBECount to be at least one. 9836 // In theory this is unnecessary, but we expect MaxBECount to be a 9837 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 9838 // is nothing to constant fold it to). 9839 APInt One(BitWidth, 1, IsSigned); 9840 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 9841 9842 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 9843 : APInt::getMaxValue(BitWidth); 9844 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 9845 9846 // Although End can be a MAX expression we estimate MaxEnd considering only 9847 // the case End = RHS of the loop termination condition. This is safe because 9848 // in the other case (End - Start) is zero, leading to a zero maximum backedge 9849 // taken count. 9850 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 9851 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 9852 9853 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 9854 getConstant(StrideForMaxBECount) /* Step */, 9855 false /* Equality */); 9856 9857 return MaxBECount; 9858 } 9859 9860 ScalarEvolution::ExitLimit 9861 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 9862 const Loop *L, bool IsSigned, 9863 bool ControlsExit, bool AllowPredicates) { 9864 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9865 9866 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 9867 bool PredicatedIV = false; 9868 9869 if (!IV && AllowPredicates) { 9870 // Try to make this an AddRec using runtime tests, in the first X 9871 // iterations of this loop, where X is the SCEV expression found by the 9872 // algorithm below. 9873 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 9874 PredicatedIV = true; 9875 } 9876 9877 // Avoid weird loops 9878 if (!IV || IV->getLoop() != L || !IV->isAffine()) 9879 return getCouldNotCompute(); 9880 9881 bool NoWrap = ControlsExit && 9882 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 9883 9884 const SCEV *Stride = IV->getStepRecurrence(*this); 9885 9886 bool PositiveStride = isKnownPositive(Stride); 9887 9888 // Avoid negative or zero stride values. 9889 if (!PositiveStride) { 9890 // We can compute the correct backedge taken count for loops with unknown 9891 // strides if we can prove that the loop is not an infinite loop with side 9892 // effects. Here's the loop structure we are trying to handle - 9893 // 9894 // i = start 9895 // do { 9896 // A[i] = i; 9897 // i += s; 9898 // } while (i < end); 9899 // 9900 // The backedge taken count for such loops is evaluated as - 9901 // (max(end, start + stride) - start - 1) /u stride 9902 // 9903 // The additional preconditions that we need to check to prove correctness 9904 // of the above formula is as follows - 9905 // 9906 // a) IV is either nuw or nsw depending upon signedness (indicated by the 9907 // NoWrap flag). 9908 // b) loop is single exit with no side effects. 9909 // 9910 // 9911 // Precondition a) implies that if the stride is negative, this is a single 9912 // trip loop. The backedge taken count formula reduces to zero in this case. 9913 // 9914 // Precondition b) implies that the unknown stride cannot be zero otherwise 9915 // we have UB. 9916 // 9917 // The positive stride case is the same as isKnownPositive(Stride) returning 9918 // true (original behavior of the function). 9919 // 9920 // We want to make sure that the stride is truly unknown as there are edge 9921 // cases where ScalarEvolution propagates no wrap flags to the 9922 // post-increment/decrement IV even though the increment/decrement operation 9923 // itself is wrapping. The computed backedge taken count may be wrong in 9924 // such cases. This is prevented by checking that the stride is not known to 9925 // be either positive or non-positive. For example, no wrap flags are 9926 // propagated to the post-increment IV of this loop with a trip count of 2 - 9927 // 9928 // unsigned char i; 9929 // for(i=127; i<128; i+=129) 9930 // A[i] = i; 9931 // 9932 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 9933 !loopHasNoSideEffects(L)) 9934 return getCouldNotCompute(); 9935 } else if (!Stride->isOne() && 9936 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 9937 // Avoid proven overflow cases: this will ensure that the backedge taken 9938 // count will not generate any unsigned overflow. Relaxed no-overflow 9939 // conditions exploit NoWrapFlags, allowing to optimize in presence of 9940 // undefined behaviors like the case of C language. 9941 return getCouldNotCompute(); 9942 9943 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 9944 : ICmpInst::ICMP_ULT; 9945 const SCEV *Start = IV->getStart(); 9946 const SCEV *End = RHS; 9947 // When the RHS is not invariant, we do not know the end bound of the loop and 9948 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 9949 // calculate the MaxBECount, given the start, stride and max value for the end 9950 // bound of the loop (RHS), and the fact that IV does not overflow (which is 9951 // checked above). 9952 if (!isLoopInvariant(RHS, L)) { 9953 const SCEV *MaxBECount = computeMaxBECountForLT( 9954 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 9955 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 9956 false /*MaxOrZero*/, Predicates); 9957 } 9958 // If the backedge is taken at least once, then it will be taken 9959 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 9960 // is the LHS value of the less-than comparison the first time it is evaluated 9961 // and End is the RHS. 9962 const SCEV *BECountIfBackedgeTaken = 9963 computeBECount(getMinusSCEV(End, Start), Stride, false); 9964 // If the loop entry is guarded by the result of the backedge test of the 9965 // first loop iteration, then we know the backedge will be taken at least 9966 // once and so the backedge taken count is as above. If not then we use the 9967 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 9968 // as if the backedge is taken at least once max(End,Start) is End and so the 9969 // result is as above, and if not max(End,Start) is Start so we get a backedge 9970 // count of zero. 9971 const SCEV *BECount; 9972 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 9973 BECount = BECountIfBackedgeTaken; 9974 else { 9975 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 9976 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 9977 } 9978 9979 const SCEV *MaxBECount; 9980 bool MaxOrZero = false; 9981 if (isa<SCEVConstant>(BECount)) 9982 MaxBECount = BECount; 9983 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 9984 // If we know exactly how many times the backedge will be taken if it's 9985 // taken at least once, then the backedge count will either be that or 9986 // zero. 9987 MaxBECount = BECountIfBackedgeTaken; 9988 MaxOrZero = true; 9989 } else { 9990 MaxBECount = computeMaxBECountForLT( 9991 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 9992 } 9993 9994 if (isa<SCEVCouldNotCompute>(MaxBECount) && 9995 !isa<SCEVCouldNotCompute>(BECount)) 9996 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 9997 9998 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 9999 } 10000 10001 ScalarEvolution::ExitLimit 10002 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10003 const Loop *L, bool IsSigned, 10004 bool ControlsExit, bool AllowPredicates) { 10005 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10006 // We handle only IV > Invariant 10007 if (!isLoopInvariant(RHS, L)) 10008 return getCouldNotCompute(); 10009 10010 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10011 if (!IV && AllowPredicates) 10012 // Try to make this an AddRec using runtime tests, in the first X 10013 // iterations of this loop, where X is the SCEV expression found by the 10014 // algorithm below. 10015 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10016 10017 // Avoid weird loops 10018 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10019 return getCouldNotCompute(); 10020 10021 bool NoWrap = ControlsExit && 10022 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10023 10024 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10025 10026 // Avoid negative or zero stride values 10027 if (!isKnownPositive(Stride)) 10028 return getCouldNotCompute(); 10029 10030 // Avoid proven overflow cases: this will ensure that the backedge taken count 10031 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10032 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10033 // behaviors like the case of C language. 10034 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10035 return getCouldNotCompute(); 10036 10037 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10038 : ICmpInst::ICMP_UGT; 10039 10040 const SCEV *Start = IV->getStart(); 10041 const SCEV *End = RHS; 10042 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10043 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10044 10045 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10046 10047 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10048 : getUnsignedRangeMax(Start); 10049 10050 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10051 : getUnsignedRangeMin(Stride); 10052 10053 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10054 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10055 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10056 10057 // Although End can be a MIN expression we estimate MinEnd considering only 10058 // the case End = RHS. This is safe because in the other case (Start - End) 10059 // is zero, leading to a zero maximum backedge taken count. 10060 APInt MinEnd = 10061 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10062 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10063 10064 10065 const SCEV *MaxBECount = getCouldNotCompute(); 10066 if (isa<SCEVConstant>(BECount)) 10067 MaxBECount = BECount; 10068 else 10069 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10070 getConstant(MinStride), false); 10071 10072 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10073 MaxBECount = BECount; 10074 10075 return ExitLimit(BECount, MaxBECount, false, Predicates); 10076 } 10077 10078 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10079 ScalarEvolution &SE) const { 10080 if (Range.isFullSet()) // Infinite loop. 10081 return SE.getCouldNotCompute(); 10082 10083 // If the start is a non-zero constant, shift the range to simplify things. 10084 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10085 if (!SC->getValue()->isZero()) { 10086 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10087 Operands[0] = SE.getZero(SC->getType()); 10088 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10089 getNoWrapFlags(FlagNW)); 10090 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10091 return ShiftedAddRec->getNumIterationsInRange( 10092 Range.subtract(SC->getAPInt()), SE); 10093 // This is strange and shouldn't happen. 10094 return SE.getCouldNotCompute(); 10095 } 10096 10097 // The only time we can solve this is when we have all constant indices. 10098 // Otherwise, we cannot determine the overflow conditions. 10099 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10100 return SE.getCouldNotCompute(); 10101 10102 // Okay at this point we know that all elements of the chrec are constants and 10103 // that the start element is zero. 10104 10105 // First check to see if the range contains zero. If not, the first 10106 // iteration exits. 10107 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10108 if (!Range.contains(APInt(BitWidth, 0))) 10109 return SE.getZero(getType()); 10110 10111 if (isAffine()) { 10112 // If this is an affine expression then we have this situation: 10113 // Solve {0,+,A} in Range === Ax in Range 10114 10115 // We know that zero is in the range. If A is positive then we know that 10116 // the upper value of the range must be the first possible exit value. 10117 // If A is negative then the lower of the range is the last possible loop 10118 // value. Also note that we already checked for a full range. 10119 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10120 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10121 10122 // The exit value should be (End+A)/A. 10123 APInt ExitVal = (End + A).udiv(A); 10124 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10125 10126 // Evaluate at the exit value. If we really did fall out of the valid 10127 // range, then we computed our trip count, otherwise wrap around or other 10128 // things must have happened. 10129 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10130 if (Range.contains(Val->getValue())) 10131 return SE.getCouldNotCompute(); // Something strange happened 10132 10133 // Ensure that the previous value is in the range. This is a sanity check. 10134 assert(Range.contains( 10135 EvaluateConstantChrecAtConstant(this, 10136 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10137 "Linear scev computation is off in a bad way!"); 10138 return SE.getConstant(ExitValue); 10139 } else if (isQuadratic()) { 10140 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10141 // quadratic equation to solve it. To do this, we must frame our problem in 10142 // terms of figuring out when zero is crossed, instead of when 10143 // Range.getUpper() is crossed. 10144 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10145 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10146 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10147 10148 // Next, solve the constructed addrec 10149 if (auto Roots = 10150 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10151 const SCEVConstant *R1 = Roots->first; 10152 const SCEVConstant *R2 = Roots->second; 10153 // Pick the smallest positive root value. 10154 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10155 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10156 if (!CB->getZExtValue()) 10157 std::swap(R1, R2); // R1 is the minimum root now. 10158 10159 // Make sure the root is not off by one. The returned iteration should 10160 // not be in the range, but the previous one should be. When solving 10161 // for "X*X < 5", for example, we should not return a root of 2. 10162 ConstantInt *R1Val = 10163 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10164 if (Range.contains(R1Val->getValue())) { 10165 // The next iteration must be out of the range... 10166 ConstantInt *NextVal = 10167 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10168 10169 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10170 if (!Range.contains(R1Val->getValue())) 10171 return SE.getConstant(NextVal); 10172 return SE.getCouldNotCompute(); // Something strange happened 10173 } 10174 10175 // If R1 was not in the range, then it is a good return value. Make 10176 // sure that R1-1 WAS in the range though, just in case. 10177 ConstantInt *NextVal = 10178 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10179 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10180 if (Range.contains(R1Val->getValue())) 10181 return R1; 10182 return SE.getCouldNotCompute(); // Something strange happened 10183 } 10184 } 10185 } 10186 10187 return SE.getCouldNotCompute(); 10188 } 10189 10190 // Return true when S contains at least an undef value. 10191 static inline bool containsUndefs(const SCEV *S) { 10192 return SCEVExprContains(S, [](const SCEV *S) { 10193 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10194 return isa<UndefValue>(SU->getValue()); 10195 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10196 return isa<UndefValue>(SC->getValue()); 10197 return false; 10198 }); 10199 } 10200 10201 namespace { 10202 10203 // Collect all steps of SCEV expressions. 10204 struct SCEVCollectStrides { 10205 ScalarEvolution &SE; 10206 SmallVectorImpl<const SCEV *> &Strides; 10207 10208 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10209 : SE(SE), Strides(S) {} 10210 10211 bool follow(const SCEV *S) { 10212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10213 Strides.push_back(AR->getStepRecurrence(SE)); 10214 return true; 10215 } 10216 10217 bool isDone() const { return false; } 10218 }; 10219 10220 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10221 struct SCEVCollectTerms { 10222 SmallVectorImpl<const SCEV *> &Terms; 10223 10224 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10225 10226 bool follow(const SCEV *S) { 10227 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10228 isa<SCEVSignExtendExpr>(S)) { 10229 if (!containsUndefs(S)) 10230 Terms.push_back(S); 10231 10232 // Stop recursion: once we collected a term, do not walk its operands. 10233 return false; 10234 } 10235 10236 // Keep looking. 10237 return true; 10238 } 10239 10240 bool isDone() const { return false; } 10241 }; 10242 10243 // Check if a SCEV contains an AddRecExpr. 10244 struct SCEVHasAddRec { 10245 bool &ContainsAddRec; 10246 10247 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10248 ContainsAddRec = false; 10249 } 10250 10251 bool follow(const SCEV *S) { 10252 if (isa<SCEVAddRecExpr>(S)) { 10253 ContainsAddRec = true; 10254 10255 // Stop recursion: once we collected a term, do not walk its operands. 10256 return false; 10257 } 10258 10259 // Keep looking. 10260 return true; 10261 } 10262 10263 bool isDone() const { return false; } 10264 }; 10265 10266 // Find factors that are multiplied with an expression that (possibly as a 10267 // subexpression) contains an AddRecExpr. In the expression: 10268 // 10269 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10270 // 10271 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10272 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10273 // parameters as they form a product with an induction variable. 10274 // 10275 // This collector expects all array size parameters to be in the same MulExpr. 10276 // It might be necessary to later add support for collecting parameters that are 10277 // spread over different nested MulExpr. 10278 struct SCEVCollectAddRecMultiplies { 10279 SmallVectorImpl<const SCEV *> &Terms; 10280 ScalarEvolution &SE; 10281 10282 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10283 : Terms(T), SE(SE) {} 10284 10285 bool follow(const SCEV *S) { 10286 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10287 bool HasAddRec = false; 10288 SmallVector<const SCEV *, 0> Operands; 10289 for (auto Op : Mul->operands()) { 10290 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10291 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10292 Operands.push_back(Op); 10293 } else if (Unknown) { 10294 HasAddRec = true; 10295 } else { 10296 bool ContainsAddRec; 10297 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10298 visitAll(Op, ContiansAddRec); 10299 HasAddRec |= ContainsAddRec; 10300 } 10301 } 10302 if (Operands.size() == 0) 10303 return true; 10304 10305 if (!HasAddRec) 10306 return false; 10307 10308 Terms.push_back(SE.getMulExpr(Operands)); 10309 // Stop recursion: once we collected a term, do not walk its operands. 10310 return false; 10311 } 10312 10313 // Keep looking. 10314 return true; 10315 } 10316 10317 bool isDone() const { return false; } 10318 }; 10319 10320 } // end anonymous namespace 10321 10322 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10323 /// two places: 10324 /// 1) The strides of AddRec expressions. 10325 /// 2) Unknowns that are multiplied with AddRec expressions. 10326 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10327 SmallVectorImpl<const SCEV *> &Terms) { 10328 SmallVector<const SCEV *, 4> Strides; 10329 SCEVCollectStrides StrideCollector(*this, Strides); 10330 visitAll(Expr, StrideCollector); 10331 10332 DEBUG({ 10333 dbgs() << "Strides:\n"; 10334 for (const SCEV *S : Strides) 10335 dbgs() << *S << "\n"; 10336 }); 10337 10338 for (const SCEV *S : Strides) { 10339 SCEVCollectTerms TermCollector(Terms); 10340 visitAll(S, TermCollector); 10341 } 10342 10343 DEBUG({ 10344 dbgs() << "Terms:\n"; 10345 for (const SCEV *T : Terms) 10346 dbgs() << *T << "\n"; 10347 }); 10348 10349 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10350 visitAll(Expr, MulCollector); 10351 } 10352 10353 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10354 SmallVectorImpl<const SCEV *> &Terms, 10355 SmallVectorImpl<const SCEV *> &Sizes) { 10356 int Last = Terms.size() - 1; 10357 const SCEV *Step = Terms[Last]; 10358 10359 // End of recursion. 10360 if (Last == 0) { 10361 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10362 SmallVector<const SCEV *, 2> Qs; 10363 for (const SCEV *Op : M->operands()) 10364 if (!isa<SCEVConstant>(Op)) 10365 Qs.push_back(Op); 10366 10367 Step = SE.getMulExpr(Qs); 10368 } 10369 10370 Sizes.push_back(Step); 10371 return true; 10372 } 10373 10374 for (const SCEV *&Term : Terms) { 10375 // Normalize the terms before the next call to findArrayDimensionsRec. 10376 const SCEV *Q, *R; 10377 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10378 10379 // Bail out when GCD does not evenly divide one of the terms. 10380 if (!R->isZero()) 10381 return false; 10382 10383 Term = Q; 10384 } 10385 10386 // Remove all SCEVConstants. 10387 Terms.erase( 10388 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10389 Terms.end()); 10390 10391 if (Terms.size() > 0) 10392 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10393 return false; 10394 10395 Sizes.push_back(Step); 10396 return true; 10397 } 10398 10399 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10400 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10401 for (const SCEV *T : Terms) 10402 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10403 return true; 10404 return false; 10405 } 10406 10407 // Return the number of product terms in S. 10408 static inline int numberOfTerms(const SCEV *S) { 10409 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10410 return Expr->getNumOperands(); 10411 return 1; 10412 } 10413 10414 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10415 if (isa<SCEVConstant>(T)) 10416 return nullptr; 10417 10418 if (isa<SCEVUnknown>(T)) 10419 return T; 10420 10421 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10422 SmallVector<const SCEV *, 2> Factors; 10423 for (const SCEV *Op : M->operands()) 10424 if (!isa<SCEVConstant>(Op)) 10425 Factors.push_back(Op); 10426 10427 return SE.getMulExpr(Factors); 10428 } 10429 10430 return T; 10431 } 10432 10433 /// Return the size of an element read or written by Inst. 10434 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10435 Type *Ty; 10436 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10437 Ty = Store->getValueOperand()->getType(); 10438 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10439 Ty = Load->getType(); 10440 else 10441 return nullptr; 10442 10443 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10444 return getSizeOfExpr(ETy, Ty); 10445 } 10446 10447 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10448 SmallVectorImpl<const SCEV *> &Sizes, 10449 const SCEV *ElementSize) { 10450 if (Terms.size() < 1 || !ElementSize) 10451 return; 10452 10453 // Early return when Terms do not contain parameters: we do not delinearize 10454 // non parametric SCEVs. 10455 if (!containsParameters(Terms)) 10456 return; 10457 10458 DEBUG({ 10459 dbgs() << "Terms:\n"; 10460 for (const SCEV *T : Terms) 10461 dbgs() << *T << "\n"; 10462 }); 10463 10464 // Remove duplicates. 10465 array_pod_sort(Terms.begin(), Terms.end()); 10466 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10467 10468 // Put larger terms first. 10469 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10470 return numberOfTerms(LHS) > numberOfTerms(RHS); 10471 }); 10472 10473 // Try to divide all terms by the element size. If term is not divisible by 10474 // element size, proceed with the original term. 10475 for (const SCEV *&Term : Terms) { 10476 const SCEV *Q, *R; 10477 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10478 if (!Q->isZero()) 10479 Term = Q; 10480 } 10481 10482 SmallVector<const SCEV *, 4> NewTerms; 10483 10484 // Remove constant factors. 10485 for (const SCEV *T : Terms) 10486 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10487 NewTerms.push_back(NewT); 10488 10489 DEBUG({ 10490 dbgs() << "Terms after sorting:\n"; 10491 for (const SCEV *T : NewTerms) 10492 dbgs() << *T << "\n"; 10493 }); 10494 10495 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10496 Sizes.clear(); 10497 return; 10498 } 10499 10500 // The last element to be pushed into Sizes is the size of an element. 10501 Sizes.push_back(ElementSize); 10502 10503 DEBUG({ 10504 dbgs() << "Sizes:\n"; 10505 for (const SCEV *S : Sizes) 10506 dbgs() << *S << "\n"; 10507 }); 10508 } 10509 10510 void ScalarEvolution::computeAccessFunctions( 10511 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10512 SmallVectorImpl<const SCEV *> &Sizes) { 10513 // Early exit in case this SCEV is not an affine multivariate function. 10514 if (Sizes.empty()) 10515 return; 10516 10517 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10518 if (!AR->isAffine()) 10519 return; 10520 10521 const SCEV *Res = Expr; 10522 int Last = Sizes.size() - 1; 10523 for (int i = Last; i >= 0; i--) { 10524 const SCEV *Q, *R; 10525 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10526 10527 DEBUG({ 10528 dbgs() << "Res: " << *Res << "\n"; 10529 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10530 dbgs() << "Res divided by Sizes[i]:\n"; 10531 dbgs() << "Quotient: " << *Q << "\n"; 10532 dbgs() << "Remainder: " << *R << "\n"; 10533 }); 10534 10535 Res = Q; 10536 10537 // Do not record the last subscript corresponding to the size of elements in 10538 // the array. 10539 if (i == Last) { 10540 10541 // Bail out if the remainder is too complex. 10542 if (isa<SCEVAddRecExpr>(R)) { 10543 Subscripts.clear(); 10544 Sizes.clear(); 10545 return; 10546 } 10547 10548 continue; 10549 } 10550 10551 // Record the access function for the current subscript. 10552 Subscripts.push_back(R); 10553 } 10554 10555 // Also push in last position the remainder of the last division: it will be 10556 // the access function of the innermost dimension. 10557 Subscripts.push_back(Res); 10558 10559 std::reverse(Subscripts.begin(), Subscripts.end()); 10560 10561 DEBUG({ 10562 dbgs() << "Subscripts:\n"; 10563 for (const SCEV *S : Subscripts) 10564 dbgs() << *S << "\n"; 10565 }); 10566 } 10567 10568 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10569 /// sizes of an array access. Returns the remainder of the delinearization that 10570 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10571 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10572 /// expressions in the stride and base of a SCEV corresponding to the 10573 /// computation of a GCD (greatest common divisor) of base and stride. When 10574 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10575 /// 10576 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10577 /// 10578 /// void foo(long n, long m, long o, double A[n][m][o]) { 10579 /// 10580 /// for (long i = 0; i < n; i++) 10581 /// for (long j = 0; j < m; j++) 10582 /// for (long k = 0; k < o; k++) 10583 /// A[i][j][k] = 1.0; 10584 /// } 10585 /// 10586 /// the delinearization input is the following AddRec SCEV: 10587 /// 10588 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10589 /// 10590 /// From this SCEV, we are able to say that the base offset of the access is %A 10591 /// because it appears as an offset that does not divide any of the strides in 10592 /// the loops: 10593 /// 10594 /// CHECK: Base offset: %A 10595 /// 10596 /// and then SCEV->delinearize determines the size of some of the dimensions of 10597 /// the array as these are the multiples by which the strides are happening: 10598 /// 10599 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10600 /// 10601 /// Note that the outermost dimension remains of UnknownSize because there are 10602 /// no strides that would help identifying the size of the last dimension: when 10603 /// the array has been statically allocated, one could compute the size of that 10604 /// dimension by dividing the overall size of the array by the size of the known 10605 /// dimensions: %m * %o * 8. 10606 /// 10607 /// Finally delinearize provides the access functions for the array reference 10608 /// that does correspond to A[i][j][k] of the above C testcase: 10609 /// 10610 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10611 /// 10612 /// The testcases are checking the output of a function pass: 10613 /// DelinearizationPass that walks through all loads and stores of a function 10614 /// asking for the SCEV of the memory access with respect to all enclosing 10615 /// loops, calling SCEV->delinearize on that and printing the results. 10616 void ScalarEvolution::delinearize(const SCEV *Expr, 10617 SmallVectorImpl<const SCEV *> &Subscripts, 10618 SmallVectorImpl<const SCEV *> &Sizes, 10619 const SCEV *ElementSize) { 10620 // First step: collect parametric terms. 10621 SmallVector<const SCEV *, 4> Terms; 10622 collectParametricTerms(Expr, Terms); 10623 10624 if (Terms.empty()) 10625 return; 10626 10627 // Second step: find subscript sizes. 10628 findArrayDimensions(Terms, Sizes, ElementSize); 10629 10630 if (Sizes.empty()) 10631 return; 10632 10633 // Third step: compute the access functions for each subscript. 10634 computeAccessFunctions(Expr, Subscripts, Sizes); 10635 10636 if (Subscripts.empty()) 10637 return; 10638 10639 DEBUG({ 10640 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10641 dbgs() << "ArrayDecl[UnknownSize]"; 10642 for (const SCEV *S : Sizes) 10643 dbgs() << "[" << *S << "]"; 10644 10645 dbgs() << "\nArrayRef"; 10646 for (const SCEV *S : Subscripts) 10647 dbgs() << "[" << *S << "]"; 10648 dbgs() << "\n"; 10649 }); 10650 } 10651 10652 //===----------------------------------------------------------------------===// 10653 // SCEVCallbackVH Class Implementation 10654 //===----------------------------------------------------------------------===// 10655 10656 void ScalarEvolution::SCEVCallbackVH::deleted() { 10657 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10658 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10659 SE->ConstantEvolutionLoopExitValue.erase(PN); 10660 SE->eraseValueFromMap(getValPtr()); 10661 // this now dangles! 10662 } 10663 10664 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10665 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10666 10667 // Forget all the expressions associated with users of the old value, 10668 // so that future queries will recompute the expressions using the new 10669 // value. 10670 Value *Old = getValPtr(); 10671 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10672 SmallPtrSet<User *, 8> Visited; 10673 while (!Worklist.empty()) { 10674 User *U = Worklist.pop_back_val(); 10675 // Deleting the Old value will cause this to dangle. Postpone 10676 // that until everything else is done. 10677 if (U == Old) 10678 continue; 10679 if (!Visited.insert(U).second) 10680 continue; 10681 if (PHINode *PN = dyn_cast<PHINode>(U)) 10682 SE->ConstantEvolutionLoopExitValue.erase(PN); 10683 SE->eraseValueFromMap(U); 10684 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10685 } 10686 // Delete the Old value. 10687 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10688 SE->ConstantEvolutionLoopExitValue.erase(PN); 10689 SE->eraseValueFromMap(Old); 10690 // this now dangles! 10691 } 10692 10693 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10694 : CallbackVH(V), SE(se) {} 10695 10696 //===----------------------------------------------------------------------===// 10697 // ScalarEvolution Class Implementation 10698 //===----------------------------------------------------------------------===// 10699 10700 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10701 AssumptionCache &AC, DominatorTree &DT, 10702 LoopInfo &LI) 10703 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10704 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 10705 LoopDispositions(64), BlockDispositions(64) { 10706 // To use guards for proving predicates, we need to scan every instruction in 10707 // relevant basic blocks, and not just terminators. Doing this is a waste of 10708 // time if the IR does not actually contain any calls to 10709 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10710 // 10711 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10712 // to _add_ guards to the module when there weren't any before, and wants 10713 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10714 // efficient in lieu of being smart in that rather obscure case. 10715 10716 auto *GuardDecl = F.getParent()->getFunction( 10717 Intrinsic::getName(Intrinsic::experimental_guard)); 10718 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10719 } 10720 10721 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10722 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10723 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10724 ValueExprMap(std::move(Arg.ValueExprMap)), 10725 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10726 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10727 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10728 PredicatedBackedgeTakenCounts( 10729 std::move(Arg.PredicatedBackedgeTakenCounts)), 10730 ConstantEvolutionLoopExitValue( 10731 std::move(Arg.ConstantEvolutionLoopExitValue)), 10732 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10733 LoopDispositions(std::move(Arg.LoopDispositions)), 10734 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10735 BlockDispositions(std::move(Arg.BlockDispositions)), 10736 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10737 SignedRanges(std::move(Arg.SignedRanges)), 10738 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10739 UniquePreds(std::move(Arg.UniquePreds)), 10740 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10741 LoopUsers(std::move(Arg.LoopUsers)), 10742 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10743 FirstUnknown(Arg.FirstUnknown) { 10744 Arg.FirstUnknown = nullptr; 10745 } 10746 10747 ScalarEvolution::~ScalarEvolution() { 10748 // Iterate through all the SCEVUnknown instances and call their 10749 // destructors, so that they release their references to their values. 10750 for (SCEVUnknown *U = FirstUnknown; U;) { 10751 SCEVUnknown *Tmp = U; 10752 U = U->Next; 10753 Tmp->~SCEVUnknown(); 10754 } 10755 FirstUnknown = nullptr; 10756 10757 ExprValueMap.clear(); 10758 ValueExprMap.clear(); 10759 HasRecMap.clear(); 10760 10761 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10762 // that a loop had multiple computable exits. 10763 for (auto &BTCI : BackedgeTakenCounts) 10764 BTCI.second.clear(); 10765 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10766 BTCI.second.clear(); 10767 10768 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10769 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10770 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10771 } 10772 10773 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10774 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10775 } 10776 10777 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10778 const Loop *L) { 10779 // Print all inner loops first 10780 for (Loop *I : *L) 10781 PrintLoopInfo(OS, SE, I); 10782 10783 OS << "Loop "; 10784 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10785 OS << ": "; 10786 10787 SmallVector<BasicBlock *, 8> ExitBlocks; 10788 L->getExitBlocks(ExitBlocks); 10789 if (ExitBlocks.size() != 1) 10790 OS << "<multiple exits> "; 10791 10792 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10793 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10794 } else { 10795 OS << "Unpredictable backedge-taken count. "; 10796 } 10797 10798 OS << "\n" 10799 "Loop "; 10800 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10801 OS << ": "; 10802 10803 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10804 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10805 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10806 OS << ", actual taken count either this or zero."; 10807 } else { 10808 OS << "Unpredictable max backedge-taken count. "; 10809 } 10810 10811 OS << "\n" 10812 "Loop "; 10813 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10814 OS << ": "; 10815 10816 SCEVUnionPredicate Pred; 10817 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10818 if (!isa<SCEVCouldNotCompute>(PBT)) { 10819 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10820 OS << " Predicates:\n"; 10821 Pred.print(OS, 4); 10822 } else { 10823 OS << "Unpredictable predicated backedge-taken count. "; 10824 } 10825 OS << "\n"; 10826 10827 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10828 OS << "Loop "; 10829 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10830 OS << ": "; 10831 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 10832 } 10833 } 10834 10835 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 10836 switch (LD) { 10837 case ScalarEvolution::LoopVariant: 10838 return "Variant"; 10839 case ScalarEvolution::LoopInvariant: 10840 return "Invariant"; 10841 case ScalarEvolution::LoopComputable: 10842 return "Computable"; 10843 } 10844 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 10845 } 10846 10847 void ScalarEvolution::print(raw_ostream &OS) const { 10848 // ScalarEvolution's implementation of the print method is to print 10849 // out SCEV values of all instructions that are interesting. Doing 10850 // this potentially causes it to create new SCEV objects though, 10851 // which technically conflicts with the const qualifier. This isn't 10852 // observable from outside the class though, so casting away the 10853 // const isn't dangerous. 10854 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10855 10856 OS << "Classifying expressions for: "; 10857 F.printAsOperand(OS, /*PrintType=*/false); 10858 OS << "\n"; 10859 for (Instruction &I : instructions(F)) 10860 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 10861 OS << I << '\n'; 10862 OS << " --> "; 10863 const SCEV *SV = SE.getSCEV(&I); 10864 SV->print(OS); 10865 if (!isa<SCEVCouldNotCompute>(SV)) { 10866 OS << " U: "; 10867 SE.getUnsignedRange(SV).print(OS); 10868 OS << " S: "; 10869 SE.getSignedRange(SV).print(OS); 10870 } 10871 10872 const Loop *L = LI.getLoopFor(I.getParent()); 10873 10874 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 10875 if (AtUse != SV) { 10876 OS << " --> "; 10877 AtUse->print(OS); 10878 if (!isa<SCEVCouldNotCompute>(AtUse)) { 10879 OS << " U: "; 10880 SE.getUnsignedRange(AtUse).print(OS); 10881 OS << " S: "; 10882 SE.getSignedRange(AtUse).print(OS); 10883 } 10884 } 10885 10886 if (L) { 10887 OS << "\t\t" "Exits: "; 10888 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 10889 if (!SE.isLoopInvariant(ExitValue, L)) { 10890 OS << "<<Unknown>>"; 10891 } else { 10892 OS << *ExitValue; 10893 } 10894 10895 bool First = true; 10896 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 10897 if (First) { 10898 OS << "\t\t" "LoopDispositions: { "; 10899 First = false; 10900 } else { 10901 OS << ", "; 10902 } 10903 10904 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10905 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 10906 } 10907 10908 for (auto *InnerL : depth_first(L)) { 10909 if (InnerL == L) 10910 continue; 10911 if (First) { 10912 OS << "\t\t" "LoopDispositions: { "; 10913 First = false; 10914 } else { 10915 OS << ", "; 10916 } 10917 10918 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10919 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 10920 } 10921 10922 OS << " }"; 10923 } 10924 10925 OS << "\n"; 10926 } 10927 10928 OS << "Determining loop execution counts for: "; 10929 F.printAsOperand(OS, /*PrintType=*/false); 10930 OS << "\n"; 10931 for (Loop *I : LI) 10932 PrintLoopInfo(OS, &SE, I); 10933 } 10934 10935 ScalarEvolution::LoopDisposition 10936 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 10937 auto &Values = LoopDispositions[S]; 10938 for (auto &V : Values) { 10939 if (V.getPointer() == L) 10940 return V.getInt(); 10941 } 10942 Values.emplace_back(L, LoopVariant); 10943 LoopDisposition D = computeLoopDisposition(S, L); 10944 auto &Values2 = LoopDispositions[S]; 10945 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 10946 if (V.getPointer() == L) { 10947 V.setInt(D); 10948 break; 10949 } 10950 } 10951 return D; 10952 } 10953 10954 ScalarEvolution::LoopDisposition 10955 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 10956 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 10957 case scConstant: 10958 return LoopInvariant; 10959 case scTruncate: 10960 case scZeroExtend: 10961 case scSignExtend: 10962 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 10963 case scAddRecExpr: { 10964 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 10965 10966 // If L is the addrec's loop, it's computable. 10967 if (AR->getLoop() == L) 10968 return LoopComputable; 10969 10970 // Add recurrences are never invariant in the function-body (null loop). 10971 if (!L) 10972 return LoopVariant; 10973 10974 // Everything that is not defined at loop entry is variant. 10975 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 10976 return LoopVariant; 10977 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 10978 " dominate the contained loop's header?"); 10979 10980 // This recurrence is invariant w.r.t. L if AR's loop contains L. 10981 if (AR->getLoop()->contains(L)) 10982 return LoopInvariant; 10983 10984 // This recurrence is variant w.r.t. L if any of its operands 10985 // are variant. 10986 for (auto *Op : AR->operands()) 10987 if (!isLoopInvariant(Op, L)) 10988 return LoopVariant; 10989 10990 // Otherwise it's loop-invariant. 10991 return LoopInvariant; 10992 } 10993 case scAddExpr: 10994 case scMulExpr: 10995 case scUMaxExpr: 10996 case scSMaxExpr: { 10997 bool HasVarying = false; 10998 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 10999 LoopDisposition D = getLoopDisposition(Op, L); 11000 if (D == LoopVariant) 11001 return LoopVariant; 11002 if (D == LoopComputable) 11003 HasVarying = true; 11004 } 11005 return HasVarying ? LoopComputable : LoopInvariant; 11006 } 11007 case scUDivExpr: { 11008 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11009 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11010 if (LD == LoopVariant) 11011 return LoopVariant; 11012 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11013 if (RD == LoopVariant) 11014 return LoopVariant; 11015 return (LD == LoopInvariant && RD == LoopInvariant) ? 11016 LoopInvariant : LoopComputable; 11017 } 11018 case scUnknown: 11019 // All non-instruction values are loop invariant. All instructions are loop 11020 // invariant if they are not contained in the specified loop. 11021 // Instructions are never considered invariant in the function body 11022 // (null loop) because they are defined within the "loop". 11023 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11024 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11025 return LoopInvariant; 11026 case scCouldNotCompute: 11027 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11028 } 11029 llvm_unreachable("Unknown SCEV kind!"); 11030 } 11031 11032 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11033 return getLoopDisposition(S, L) == LoopInvariant; 11034 } 11035 11036 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11037 return getLoopDisposition(S, L) == LoopComputable; 11038 } 11039 11040 ScalarEvolution::BlockDisposition 11041 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11042 auto &Values = BlockDispositions[S]; 11043 for (auto &V : Values) { 11044 if (V.getPointer() == BB) 11045 return V.getInt(); 11046 } 11047 Values.emplace_back(BB, DoesNotDominateBlock); 11048 BlockDisposition D = computeBlockDisposition(S, BB); 11049 auto &Values2 = BlockDispositions[S]; 11050 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11051 if (V.getPointer() == BB) { 11052 V.setInt(D); 11053 break; 11054 } 11055 } 11056 return D; 11057 } 11058 11059 ScalarEvolution::BlockDisposition 11060 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11061 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11062 case scConstant: 11063 return ProperlyDominatesBlock; 11064 case scTruncate: 11065 case scZeroExtend: 11066 case scSignExtend: 11067 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11068 case scAddRecExpr: { 11069 // This uses a "dominates" query instead of "properly dominates" query 11070 // to test for proper dominance too, because the instruction which 11071 // produces the addrec's value is a PHI, and a PHI effectively properly 11072 // dominates its entire containing block. 11073 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11074 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11075 return DoesNotDominateBlock; 11076 11077 // Fall through into SCEVNAryExpr handling. 11078 LLVM_FALLTHROUGH; 11079 } 11080 case scAddExpr: 11081 case scMulExpr: 11082 case scUMaxExpr: 11083 case scSMaxExpr: { 11084 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11085 bool Proper = true; 11086 for (const SCEV *NAryOp : NAry->operands()) { 11087 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11088 if (D == DoesNotDominateBlock) 11089 return DoesNotDominateBlock; 11090 if (D == DominatesBlock) 11091 Proper = false; 11092 } 11093 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11094 } 11095 case scUDivExpr: { 11096 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11097 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11098 BlockDisposition LD = getBlockDisposition(LHS, BB); 11099 if (LD == DoesNotDominateBlock) 11100 return DoesNotDominateBlock; 11101 BlockDisposition RD = getBlockDisposition(RHS, BB); 11102 if (RD == DoesNotDominateBlock) 11103 return DoesNotDominateBlock; 11104 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11105 ProperlyDominatesBlock : DominatesBlock; 11106 } 11107 case scUnknown: 11108 if (Instruction *I = 11109 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11110 if (I->getParent() == BB) 11111 return DominatesBlock; 11112 if (DT.properlyDominates(I->getParent(), BB)) 11113 return ProperlyDominatesBlock; 11114 return DoesNotDominateBlock; 11115 } 11116 return ProperlyDominatesBlock; 11117 case scCouldNotCompute: 11118 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11119 } 11120 llvm_unreachable("Unknown SCEV kind!"); 11121 } 11122 11123 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11124 return getBlockDisposition(S, BB) >= DominatesBlock; 11125 } 11126 11127 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11128 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11129 } 11130 11131 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11132 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11133 } 11134 11135 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11136 auto IsS = [&](const SCEV *X) { return S == X; }; 11137 auto ContainsS = [&](const SCEV *X) { 11138 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11139 }; 11140 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11141 } 11142 11143 void 11144 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11145 ValuesAtScopes.erase(S); 11146 LoopDispositions.erase(S); 11147 BlockDispositions.erase(S); 11148 UnsignedRanges.erase(S); 11149 SignedRanges.erase(S); 11150 ExprValueMap.erase(S); 11151 HasRecMap.erase(S); 11152 MinTrailingZerosCache.erase(S); 11153 11154 for (auto I = PredicatedSCEVRewrites.begin(); 11155 I != PredicatedSCEVRewrites.end();) { 11156 std::pair<const SCEV *, const Loop *> Entry = I->first; 11157 if (Entry.first == S) 11158 PredicatedSCEVRewrites.erase(I++); 11159 else 11160 ++I; 11161 } 11162 11163 auto RemoveSCEVFromBackedgeMap = 11164 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11165 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11166 BackedgeTakenInfo &BEInfo = I->second; 11167 if (BEInfo.hasOperand(S, this)) { 11168 BEInfo.clear(); 11169 Map.erase(I++); 11170 } else 11171 ++I; 11172 } 11173 }; 11174 11175 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11176 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11177 } 11178 11179 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11180 struct FindUsedLoops { 11181 SmallPtrSet<const Loop *, 8> LoopsUsed; 11182 bool follow(const SCEV *S) { 11183 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11184 LoopsUsed.insert(AR->getLoop()); 11185 return true; 11186 } 11187 11188 bool isDone() const { return false; } 11189 }; 11190 11191 FindUsedLoops F; 11192 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11193 11194 for (auto *L : F.LoopsUsed) 11195 LoopUsers[L].push_back(S); 11196 } 11197 11198 void ScalarEvolution::verify() const { 11199 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11200 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11201 11202 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11203 11204 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11205 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11206 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11207 11208 const SCEV *visitConstant(const SCEVConstant *Constant) { 11209 return SE.getConstant(Constant->getAPInt()); 11210 } 11211 11212 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11213 return SE.getUnknown(Expr->getValue()); 11214 } 11215 11216 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11217 return SE.getCouldNotCompute(); 11218 } 11219 }; 11220 11221 SCEVMapper SCM(SE2); 11222 11223 while (!LoopStack.empty()) { 11224 auto *L = LoopStack.pop_back_val(); 11225 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11226 11227 auto *CurBECount = SCM.visit( 11228 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11229 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11230 11231 if (CurBECount == SE2.getCouldNotCompute() || 11232 NewBECount == SE2.getCouldNotCompute()) { 11233 // NB! This situation is legal, but is very suspicious -- whatever pass 11234 // change the loop to make a trip count go from could not compute to 11235 // computable or vice-versa *should have* invalidated SCEV. However, we 11236 // choose not to assert here (for now) since we don't want false 11237 // positives. 11238 continue; 11239 } 11240 11241 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11242 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11243 // not propagate undef aggressively). This means we can (and do) fail 11244 // verification in cases where a transform makes the trip count of a loop 11245 // go from "undef" to "undef+1" (say). The transform is fine, since in 11246 // both cases the loop iterates "undef" times, but SCEV thinks we 11247 // increased the trip count of the loop by 1 incorrectly. 11248 continue; 11249 } 11250 11251 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11252 SE.getTypeSizeInBits(NewBECount->getType())) 11253 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11254 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11255 SE.getTypeSizeInBits(NewBECount->getType())) 11256 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11257 11258 auto *ConstantDelta = 11259 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11260 11261 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11262 dbgs() << "Trip Count Changed!\n"; 11263 dbgs() << "Old: " << *CurBECount << "\n"; 11264 dbgs() << "New: " << *NewBECount << "\n"; 11265 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11266 std::abort(); 11267 } 11268 } 11269 } 11270 11271 bool ScalarEvolution::invalidate( 11272 Function &F, const PreservedAnalyses &PA, 11273 FunctionAnalysisManager::Invalidator &Inv) { 11274 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11275 // of its dependencies is invalidated. 11276 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11277 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11278 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11279 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11280 Inv.invalidate<LoopAnalysis>(F, PA); 11281 } 11282 11283 AnalysisKey ScalarEvolutionAnalysis::Key; 11284 11285 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11286 FunctionAnalysisManager &AM) { 11287 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11288 AM.getResult<AssumptionAnalysis>(F), 11289 AM.getResult<DominatorTreeAnalysis>(F), 11290 AM.getResult<LoopAnalysis>(F)); 11291 } 11292 11293 PreservedAnalyses 11294 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11295 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11296 return PreservedAnalyses::all(); 11297 } 11298 11299 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11300 "Scalar Evolution Analysis", false, true) 11301 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11302 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11303 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11304 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11305 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11306 "Scalar Evolution Analysis", false, true) 11307 11308 char ScalarEvolutionWrapperPass::ID = 0; 11309 11310 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11311 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11312 } 11313 11314 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11315 SE.reset(new ScalarEvolution( 11316 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11317 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11318 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11319 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11320 return false; 11321 } 11322 11323 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11324 11325 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11326 SE->print(OS); 11327 } 11328 11329 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11330 if (!VerifySCEV) 11331 return; 11332 11333 SE->verify(); 11334 } 11335 11336 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11337 AU.setPreservesAll(); 11338 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11339 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11340 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11341 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11342 } 11343 11344 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11345 const SCEV *RHS) { 11346 FoldingSetNodeID ID; 11347 assert(LHS->getType() == RHS->getType() && 11348 "Type mismatch between LHS and RHS"); 11349 // Unique this node based on the arguments 11350 ID.AddInteger(SCEVPredicate::P_Equal); 11351 ID.AddPointer(LHS); 11352 ID.AddPointer(RHS); 11353 void *IP = nullptr; 11354 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11355 return S; 11356 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11357 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11358 UniquePreds.InsertNode(Eq, IP); 11359 return Eq; 11360 } 11361 11362 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11363 const SCEVAddRecExpr *AR, 11364 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11365 FoldingSetNodeID ID; 11366 // Unique this node based on the arguments 11367 ID.AddInteger(SCEVPredicate::P_Wrap); 11368 ID.AddPointer(AR); 11369 ID.AddInteger(AddedFlags); 11370 void *IP = nullptr; 11371 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11372 return S; 11373 auto *OF = new (SCEVAllocator) 11374 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11375 UniquePreds.InsertNode(OF, IP); 11376 return OF; 11377 } 11378 11379 namespace { 11380 11381 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11382 public: 11383 11384 /// Rewrites \p S in the context of a loop L and the SCEV predication 11385 /// infrastructure. 11386 /// 11387 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11388 /// equivalences present in \p Pred. 11389 /// 11390 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11391 /// \p NewPreds such that the result will be an AddRecExpr. 11392 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11393 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11394 SCEVUnionPredicate *Pred) { 11395 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11396 return Rewriter.visit(S); 11397 } 11398 11399 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11400 if (Pred) { 11401 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11402 for (auto *Pred : ExprPreds) 11403 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11404 if (IPred->getLHS() == Expr) 11405 return IPred->getRHS(); 11406 } 11407 return convertToAddRecWithPreds(Expr); 11408 } 11409 11410 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11411 const SCEV *Operand = visit(Expr->getOperand()); 11412 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11413 if (AR && AR->getLoop() == L && AR->isAffine()) { 11414 // This couldn't be folded because the operand didn't have the nuw 11415 // flag. Add the nusw flag as an assumption that we could make. 11416 const SCEV *Step = AR->getStepRecurrence(SE); 11417 Type *Ty = Expr->getType(); 11418 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11419 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11420 SE.getSignExtendExpr(Step, Ty), L, 11421 AR->getNoWrapFlags()); 11422 } 11423 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11424 } 11425 11426 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11427 const SCEV *Operand = visit(Expr->getOperand()); 11428 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11429 if (AR && AR->getLoop() == L && AR->isAffine()) { 11430 // This couldn't be folded because the operand didn't have the nsw 11431 // flag. Add the nssw flag as an assumption that we could make. 11432 const SCEV *Step = AR->getStepRecurrence(SE); 11433 Type *Ty = Expr->getType(); 11434 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11435 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11436 SE.getSignExtendExpr(Step, Ty), L, 11437 AR->getNoWrapFlags()); 11438 } 11439 return SE.getSignExtendExpr(Operand, Expr->getType()); 11440 } 11441 11442 private: 11443 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11444 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11445 SCEVUnionPredicate *Pred) 11446 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11447 11448 bool addOverflowAssumption(const SCEVPredicate *P) { 11449 if (!NewPreds) { 11450 // Check if we've already made this assumption. 11451 return Pred && Pred->implies(P); 11452 } 11453 NewPreds->insert(P); 11454 return true; 11455 } 11456 11457 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11458 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11459 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11460 return addOverflowAssumption(A); 11461 } 11462 11463 // If \p Expr represents a PHINode, we try to see if it can be represented 11464 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11465 // to add this predicate as a runtime overflow check, we return the AddRec. 11466 // If \p Expr does not meet these conditions (is not a PHI node, or we 11467 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11468 // return \p Expr. 11469 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11470 if (!isa<PHINode>(Expr->getValue())) 11471 return Expr; 11472 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11473 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11474 if (!PredicatedRewrite) 11475 return Expr; 11476 for (auto *P : PredicatedRewrite->second){ 11477 if (!addOverflowAssumption(P)) 11478 return Expr; 11479 } 11480 return PredicatedRewrite->first; 11481 } 11482 11483 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11484 SCEVUnionPredicate *Pred; 11485 const Loop *L; 11486 }; 11487 11488 } // end anonymous namespace 11489 11490 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11491 SCEVUnionPredicate &Preds) { 11492 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11493 } 11494 11495 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11496 const SCEV *S, const Loop *L, 11497 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11498 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11499 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11500 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11501 11502 if (!AddRec) 11503 return nullptr; 11504 11505 // Since the transformation was successful, we can now transfer the SCEV 11506 // predicates. 11507 for (auto *P : TransformPreds) 11508 Preds.insert(P); 11509 11510 return AddRec; 11511 } 11512 11513 /// SCEV predicates 11514 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11515 SCEVPredicateKind Kind) 11516 : FastID(ID), Kind(Kind) {} 11517 11518 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11519 const SCEV *LHS, const SCEV *RHS) 11520 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11521 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11522 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11523 } 11524 11525 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11526 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11527 11528 if (!Op) 11529 return false; 11530 11531 return Op->LHS == LHS && Op->RHS == RHS; 11532 } 11533 11534 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11535 11536 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11537 11538 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11539 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11540 } 11541 11542 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11543 const SCEVAddRecExpr *AR, 11544 IncrementWrapFlags Flags) 11545 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11546 11547 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11548 11549 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11550 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11551 11552 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11553 } 11554 11555 bool SCEVWrapPredicate::isAlwaysTrue() const { 11556 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11557 IncrementWrapFlags IFlags = Flags; 11558 11559 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11560 IFlags = clearFlags(IFlags, IncrementNSSW); 11561 11562 return IFlags == IncrementAnyWrap; 11563 } 11564 11565 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11566 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11567 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11568 OS << "<nusw>"; 11569 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11570 OS << "<nssw>"; 11571 OS << "\n"; 11572 } 11573 11574 SCEVWrapPredicate::IncrementWrapFlags 11575 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11576 ScalarEvolution &SE) { 11577 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11578 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11579 11580 // We can safely transfer the NSW flag as NSSW. 11581 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11582 ImpliedFlags = IncrementNSSW; 11583 11584 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11585 // If the increment is positive, the SCEV NUW flag will also imply the 11586 // WrapPredicate NUSW flag. 11587 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11588 if (Step->getValue()->getValue().isNonNegative()) 11589 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11590 } 11591 11592 return ImpliedFlags; 11593 } 11594 11595 /// Union predicates don't get cached so create a dummy set ID for it. 11596 SCEVUnionPredicate::SCEVUnionPredicate() 11597 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11598 11599 bool SCEVUnionPredicate::isAlwaysTrue() const { 11600 return all_of(Preds, 11601 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11602 } 11603 11604 ArrayRef<const SCEVPredicate *> 11605 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11606 auto I = SCEVToPreds.find(Expr); 11607 if (I == SCEVToPreds.end()) 11608 return ArrayRef<const SCEVPredicate *>(); 11609 return I->second; 11610 } 11611 11612 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11613 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11614 return all_of(Set->Preds, 11615 [this](const SCEVPredicate *I) { return this->implies(I); }); 11616 11617 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11618 if (ScevPredsIt == SCEVToPreds.end()) 11619 return false; 11620 auto &SCEVPreds = ScevPredsIt->second; 11621 11622 return any_of(SCEVPreds, 11623 [N](const SCEVPredicate *I) { return I->implies(N); }); 11624 } 11625 11626 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11627 11628 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11629 for (auto Pred : Preds) 11630 Pred->print(OS, Depth); 11631 } 11632 11633 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11634 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11635 for (auto Pred : Set->Preds) 11636 add(Pred); 11637 return; 11638 } 11639 11640 if (implies(N)) 11641 return; 11642 11643 const SCEV *Key = N->getExpr(); 11644 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11645 " associated expression!"); 11646 11647 SCEVToPreds[Key].push_back(N); 11648 Preds.push_back(N); 11649 } 11650 11651 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11652 Loop &L) 11653 : SE(SE), L(L) {} 11654 11655 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11656 const SCEV *Expr = SE.getSCEV(V); 11657 RewriteEntry &Entry = RewriteMap[Expr]; 11658 11659 // If we already have an entry and the version matches, return it. 11660 if (Entry.second && Generation == Entry.first) 11661 return Entry.second; 11662 11663 // We found an entry but it's stale. Rewrite the stale entry 11664 // according to the current predicate. 11665 if (Entry.second) 11666 Expr = Entry.second; 11667 11668 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11669 Entry = {Generation, NewSCEV}; 11670 11671 return NewSCEV; 11672 } 11673 11674 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11675 if (!BackedgeCount) { 11676 SCEVUnionPredicate BackedgePred; 11677 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11678 addPredicate(BackedgePred); 11679 } 11680 return BackedgeCount; 11681 } 11682 11683 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11684 if (Preds.implies(&Pred)) 11685 return; 11686 Preds.add(&Pred); 11687 updateGeneration(); 11688 } 11689 11690 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11691 return Preds; 11692 } 11693 11694 void PredicatedScalarEvolution::updateGeneration() { 11695 // If the generation number wrapped recompute everything. 11696 if (++Generation == 0) { 11697 for (auto &II : RewriteMap) { 11698 const SCEV *Rewritten = II.second.second; 11699 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11700 } 11701 } 11702 } 11703 11704 void PredicatedScalarEvolution::setNoOverflow( 11705 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11706 const SCEV *Expr = getSCEV(V); 11707 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11708 11709 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11710 11711 // Clear the statically implied flags. 11712 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11713 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11714 11715 auto II = FlagsMap.insert({V, Flags}); 11716 if (!II.second) 11717 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11718 } 11719 11720 bool PredicatedScalarEvolution::hasNoOverflow( 11721 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11722 const SCEV *Expr = getSCEV(V); 11723 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11724 11725 Flags = SCEVWrapPredicate::clearFlags( 11726 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11727 11728 auto II = FlagsMap.find(V); 11729 11730 if (II != FlagsMap.end()) 11731 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11732 11733 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11734 } 11735 11736 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11737 const SCEV *Expr = this->getSCEV(V); 11738 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11739 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11740 11741 if (!New) 11742 return nullptr; 11743 11744 for (auto *P : NewPreds) 11745 Preds.add(P); 11746 11747 updateGeneration(); 11748 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11749 return New; 11750 } 11751 11752 PredicatedScalarEvolution::PredicatedScalarEvolution( 11753 const PredicatedScalarEvolution &Init) 11754 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11755 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11756 for (const auto &I : Init.FlagsMap) 11757 FlagsMap.insert(I); 11758 } 11759 11760 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11761 // For each block. 11762 for (auto *BB : L.getBlocks()) 11763 for (auto &I : *BB) { 11764 if (!SE.isSCEVable(I.getType())) 11765 continue; 11766 11767 auto *Expr = SE.getSCEV(&I); 11768 auto II = RewriteMap.find(Expr); 11769 11770 if (II == RewriteMap.end()) 11771 continue; 11772 11773 // Don't print things that are not interesting. 11774 if (II->second.second == Expr) 11775 continue; 11776 11777 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11778 OS.indent(Depth + 2) << *Expr << "\n"; 11779 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11780 } 11781 } 11782