1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/SmallPtrSet.h" 66 #include "llvm/ADT/Statistic.h" 67 #include "llvm/Analysis/AssumptionCache.h" 68 #include "llvm/Analysis/ConstantFolding.h" 69 #include "llvm/Analysis/InstructionSimplify.h" 70 #include "llvm/Analysis/LoopInfo.h" 71 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 72 #include "llvm/Analysis/TargetLibraryInfo.h" 73 #include "llvm/Analysis/ValueTracking.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Dominators.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/GlobalAlias.h" 81 #include "llvm/IR/GlobalVariable.h" 82 #include "llvm/IR/InstIterator.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/LLVMContext.h" 85 #include "llvm/IR/Metadata.h" 86 #include "llvm/IR/Operator.h" 87 #include "llvm/IR/PatternMatch.h" 88 #include "llvm/Support/CommandLine.h" 89 #include "llvm/Support/Debug.h" 90 #include "llvm/Support/ErrorHandling.h" 91 #include "llvm/Support/MathExtras.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include "llvm/Support/SaveAndRestore.h" 94 #include <algorithm> 95 using namespace llvm; 96 97 #define DEBUG_TYPE "scalar-evolution" 98 99 STATISTIC(NumArrayLenItCounts, 100 "Number of trip counts computed with array length"); 101 STATISTIC(NumTripCountsComputed, 102 "Number of loops with predictable loop counts"); 103 STATISTIC(NumTripCountsNotComputed, 104 "Number of loops without predictable loop counts"); 105 STATISTIC(NumBruteForceTripCountsComputed, 106 "Number of loops with trip counts computed by force"); 107 108 static cl::opt<unsigned> 109 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 110 cl::desc("Maximum number of iterations SCEV will " 111 "symbolically execute a constant " 112 "derived loop"), 113 cl::init(100)); 114 115 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 116 static cl::opt<bool> 117 VerifySCEV("verify-scev", 118 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 119 static cl::opt<bool> 120 VerifySCEVMap("verify-scev-maps", 121 cl::desc("Verify no dangling value in ScalarEvolution's " 122 "ExprValueMap (slow)")); 123 124 static cl::opt<unsigned> MulOpsInlineThreshold( 125 "scev-mulops-inline-threshold", cl::Hidden, 126 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 127 cl::init(1000)); 128 129 //===----------------------------------------------------------------------===// 130 // SCEV class definitions 131 //===----------------------------------------------------------------------===// 132 133 //===----------------------------------------------------------------------===// 134 // Implementation of the SCEV class. 135 // 136 137 LLVM_DUMP_METHOD 138 void SCEV::dump() const { 139 print(dbgs()); 140 dbgs() << '\n'; 141 } 142 143 void SCEV::print(raw_ostream &OS) const { 144 switch (static_cast<SCEVTypes>(getSCEVType())) { 145 case scConstant: 146 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 147 return; 148 case scTruncate: { 149 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 150 const SCEV *Op = Trunc->getOperand(); 151 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 152 << *Trunc->getType() << ")"; 153 return; 154 } 155 case scZeroExtend: { 156 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 157 const SCEV *Op = ZExt->getOperand(); 158 OS << "(zext " << *Op->getType() << " " << *Op << " to " 159 << *ZExt->getType() << ")"; 160 return; 161 } 162 case scSignExtend: { 163 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 164 const SCEV *Op = SExt->getOperand(); 165 OS << "(sext " << *Op->getType() << " " << *Op << " to " 166 << *SExt->getType() << ")"; 167 return; 168 } 169 case scAddRecExpr: { 170 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 171 OS << "{" << *AR->getOperand(0); 172 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 173 OS << ",+," << *AR->getOperand(i); 174 OS << "}<"; 175 if (AR->hasNoUnsignedWrap()) 176 OS << "nuw><"; 177 if (AR->hasNoSignedWrap()) 178 OS << "nsw><"; 179 if (AR->hasNoSelfWrap() && 180 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 181 OS << "nw><"; 182 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 183 OS << ">"; 184 return; 185 } 186 case scAddExpr: 187 case scMulExpr: 188 case scUMaxExpr: 189 case scSMaxExpr: { 190 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 191 const char *OpStr = nullptr; 192 switch (NAry->getSCEVType()) { 193 case scAddExpr: OpStr = " + "; break; 194 case scMulExpr: OpStr = " * "; break; 195 case scUMaxExpr: OpStr = " umax "; break; 196 case scSMaxExpr: OpStr = " smax "; break; 197 } 198 OS << "("; 199 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 200 I != E; ++I) { 201 OS << **I; 202 if (std::next(I) != E) 203 OS << OpStr; 204 } 205 OS << ")"; 206 switch (NAry->getSCEVType()) { 207 case scAddExpr: 208 case scMulExpr: 209 if (NAry->hasNoUnsignedWrap()) 210 OS << "<nuw>"; 211 if (NAry->hasNoSignedWrap()) 212 OS << "<nsw>"; 213 } 214 return; 215 } 216 case scUDivExpr: { 217 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 218 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 219 return; 220 } 221 case scUnknown: { 222 const SCEVUnknown *U = cast<SCEVUnknown>(this); 223 Type *AllocTy; 224 if (U->isSizeOf(AllocTy)) { 225 OS << "sizeof(" << *AllocTy << ")"; 226 return; 227 } 228 if (U->isAlignOf(AllocTy)) { 229 OS << "alignof(" << *AllocTy << ")"; 230 return; 231 } 232 233 Type *CTy; 234 Constant *FieldNo; 235 if (U->isOffsetOf(CTy, FieldNo)) { 236 OS << "offsetof(" << *CTy << ", "; 237 FieldNo->printAsOperand(OS, false); 238 OS << ")"; 239 return; 240 } 241 242 // Otherwise just print it normally. 243 U->getValue()->printAsOperand(OS, false); 244 return; 245 } 246 case scCouldNotCompute: 247 OS << "***COULDNOTCOMPUTE***"; 248 return; 249 } 250 llvm_unreachable("Unknown SCEV kind!"); 251 } 252 253 Type *SCEV::getType() const { 254 switch (static_cast<SCEVTypes>(getSCEVType())) { 255 case scConstant: 256 return cast<SCEVConstant>(this)->getType(); 257 case scTruncate: 258 case scZeroExtend: 259 case scSignExtend: 260 return cast<SCEVCastExpr>(this)->getType(); 261 case scAddRecExpr: 262 case scMulExpr: 263 case scUMaxExpr: 264 case scSMaxExpr: 265 return cast<SCEVNAryExpr>(this)->getType(); 266 case scAddExpr: 267 return cast<SCEVAddExpr>(this)->getType(); 268 case scUDivExpr: 269 return cast<SCEVUDivExpr>(this)->getType(); 270 case scUnknown: 271 return cast<SCEVUnknown>(this)->getType(); 272 case scCouldNotCompute: 273 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 274 } 275 llvm_unreachable("Unknown SCEV kind!"); 276 } 277 278 bool SCEV::isZero() const { 279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 280 return SC->getValue()->isZero(); 281 return false; 282 } 283 284 bool SCEV::isOne() const { 285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 286 return SC->getValue()->isOne(); 287 return false; 288 } 289 290 bool SCEV::isAllOnesValue() const { 291 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 292 return SC->getValue()->isAllOnesValue(); 293 return false; 294 } 295 296 bool SCEV::isNonConstantNegative() const { 297 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 298 if (!Mul) return false; 299 300 // If there is a constant factor, it will be first. 301 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 302 if (!SC) return false; 303 304 // Return true if the value is negative, this matches things like (-42 * V). 305 return SC->getAPInt().isNegative(); 306 } 307 308 SCEVCouldNotCompute::SCEVCouldNotCompute() : 309 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 310 311 bool SCEVCouldNotCompute::classof(const SCEV *S) { 312 return S->getSCEVType() == scCouldNotCompute; 313 } 314 315 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 316 FoldingSetNodeID ID; 317 ID.AddInteger(scConstant); 318 ID.AddPointer(V); 319 void *IP = nullptr; 320 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 321 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 322 UniqueSCEVs.InsertNode(S, IP); 323 return S; 324 } 325 326 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 327 return getConstant(ConstantInt::get(getContext(), Val)); 328 } 329 330 const SCEV * 331 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 332 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 333 return getConstant(ConstantInt::get(ITy, V, isSigned)); 334 } 335 336 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 337 unsigned SCEVTy, const SCEV *op, Type *ty) 338 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 339 340 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 341 const SCEV *op, Type *ty) 342 : SCEVCastExpr(ID, scTruncate, op, ty) { 343 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 344 (Ty->isIntegerTy() || Ty->isPointerTy()) && 345 "Cannot truncate non-integer value!"); 346 } 347 348 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 349 const SCEV *op, Type *ty) 350 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 351 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 352 (Ty->isIntegerTy() || Ty->isPointerTy()) && 353 "Cannot zero extend non-integer value!"); 354 } 355 356 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 357 const SCEV *op, Type *ty) 358 : SCEVCastExpr(ID, scSignExtend, op, ty) { 359 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 360 (Ty->isIntegerTy() || Ty->isPointerTy()) && 361 "Cannot sign extend non-integer value!"); 362 } 363 364 void SCEVUnknown::deleted() { 365 // Clear this SCEVUnknown from various maps. 366 SE->forgetMemoizedResults(this); 367 368 // Remove this SCEVUnknown from the uniquing map. 369 SE->UniqueSCEVs.RemoveNode(this); 370 371 // Release the value. 372 setValPtr(nullptr); 373 } 374 375 void SCEVUnknown::allUsesReplacedWith(Value *New) { 376 // Clear this SCEVUnknown from various maps. 377 SE->forgetMemoizedResults(this); 378 379 // Remove this SCEVUnknown from the uniquing map. 380 SE->UniqueSCEVs.RemoveNode(this); 381 382 // Update this SCEVUnknown to point to the new value. This is needed 383 // because there may still be outstanding SCEVs which still point to 384 // this SCEVUnknown. 385 setValPtr(New); 386 } 387 388 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 389 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 390 if (VCE->getOpcode() == Instruction::PtrToInt) 391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 392 if (CE->getOpcode() == Instruction::GetElementPtr && 393 CE->getOperand(0)->isNullValue() && 394 CE->getNumOperands() == 2) 395 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 396 if (CI->isOne()) { 397 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 398 ->getElementType(); 399 return true; 400 } 401 402 return false; 403 } 404 405 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 406 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 407 if (VCE->getOpcode() == Instruction::PtrToInt) 408 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 409 if (CE->getOpcode() == Instruction::GetElementPtr && 410 CE->getOperand(0)->isNullValue()) { 411 Type *Ty = 412 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 413 if (StructType *STy = dyn_cast<StructType>(Ty)) 414 if (!STy->isPacked() && 415 CE->getNumOperands() == 3 && 416 CE->getOperand(1)->isNullValue()) { 417 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 418 if (CI->isOne() && 419 STy->getNumElements() == 2 && 420 STy->getElementType(0)->isIntegerTy(1)) { 421 AllocTy = STy->getElementType(1); 422 return true; 423 } 424 } 425 } 426 427 return false; 428 } 429 430 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 431 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 432 if (VCE->getOpcode() == Instruction::PtrToInt) 433 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 434 if (CE->getOpcode() == Instruction::GetElementPtr && 435 CE->getNumOperands() == 3 && 436 CE->getOperand(0)->isNullValue() && 437 CE->getOperand(1)->isNullValue()) { 438 Type *Ty = 439 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 440 // Ignore vector types here so that ScalarEvolutionExpander doesn't 441 // emit getelementptrs that index into vectors. 442 if (Ty->isStructTy() || Ty->isArrayTy()) { 443 CTy = Ty; 444 FieldNo = CE->getOperand(2); 445 return true; 446 } 447 } 448 449 return false; 450 } 451 452 //===----------------------------------------------------------------------===// 453 // SCEV Utilities 454 //===----------------------------------------------------------------------===// 455 456 static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, 457 Value *RV, unsigned DepthLeft = 2) { 458 if (DepthLeft == 0) 459 return 0; 460 461 // Order pointer values after integer values. This helps SCEVExpander form 462 // GEPs. 463 bool LIsPointer = LV->getType()->isPointerTy(), 464 RIsPointer = RV->getType()->isPointerTy(); 465 if (LIsPointer != RIsPointer) 466 return (int)LIsPointer - (int)RIsPointer; 467 468 // Compare getValueID values. 469 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 470 if (LID != RID) 471 return (int)LID - (int)RID; 472 473 // Sort arguments by their position. 474 if (const auto *LA = dyn_cast<Argument>(LV)) { 475 const auto *RA = cast<Argument>(RV); 476 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 477 return (int)LArgNo - (int)RArgNo; 478 } 479 480 // For instructions, compare their loop depth, and their operand count. This 481 // is pretty loose. 482 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 483 const auto *RInst = cast<Instruction>(RV); 484 485 // Compare loop depths. 486 const BasicBlock *LParent = LInst->getParent(), 487 *RParent = RInst->getParent(); 488 if (LParent != RParent) { 489 unsigned LDepth = LI->getLoopDepth(LParent), 490 RDepth = LI->getLoopDepth(RParent); 491 if (LDepth != RDepth) 492 return (int)LDepth - (int)RDepth; 493 } 494 495 // Compare the number of operands. 496 unsigned LNumOps = LInst->getNumOperands(), 497 RNumOps = RInst->getNumOperands(); 498 if (LNumOps != RNumOps || LNumOps != 1) 499 return (int)LNumOps - (int)RNumOps; 500 501 // We only bother "recursing" if we have one operand to look at (so we don't 502 // really recurse as much as we iterate). We can consider expanding this 503 // logic in the future. 504 return CompareValueComplexity(LI, LInst->getOperand(0), 505 RInst->getOperand(0), DepthLeft - 1); 506 } 507 508 return 0; 509 } 510 511 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 512 // than RHS, respectively. A three-way result allows recursive comparisons to be 513 // more efficient. 514 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, 515 const SCEV *RHS) { 516 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 517 if (LHS == RHS) 518 return 0; 519 520 // Primarily, sort the SCEVs by their getSCEVType(). 521 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 522 if (LType != RType) 523 return (int)LType - (int)RType; 524 525 // Aside from the getSCEVType() ordering, the particular ordering 526 // isn't very important except that it's beneficial to be consistent, 527 // so that (a + b) and (b + a) don't end up as different expressions. 528 switch (static_cast<SCEVTypes>(LType)) { 529 case scUnknown: { 530 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 531 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 532 533 return CompareValueComplexity(LI, LU->getValue(), RU->getValue()); 534 } 535 536 case scConstant: { 537 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 538 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 539 540 // Compare constant values. 541 const APInt &LA = LC->getAPInt(); 542 const APInt &RA = RC->getAPInt(); 543 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 544 if (LBitWidth != RBitWidth) 545 return (int)LBitWidth - (int)RBitWidth; 546 return LA.ult(RA) ? -1 : 1; 547 } 548 549 case scAddRecExpr: { 550 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 551 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 552 553 // Compare addrec loop depths. 554 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 555 if (LLoop != RLoop) { 556 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 557 if (LDepth != RDepth) 558 return (int)LDepth - (int)RDepth; 559 } 560 561 // Addrec complexity grows with operand count. 562 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 563 if (LNumOps != RNumOps) 564 return (int)LNumOps - (int)RNumOps; 565 566 // Lexicographically compare. 567 for (unsigned i = 0; i != LNumOps; ++i) { 568 long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i)); 569 if (X != 0) 570 return X; 571 } 572 573 return 0; 574 } 575 576 case scAddExpr: 577 case scMulExpr: 578 case scSMaxExpr: 579 case scUMaxExpr: { 580 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 581 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 582 583 // Lexicographically compare n-ary expressions. 584 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 585 if (LNumOps != RNumOps) 586 return (int)LNumOps - (int)RNumOps; 587 588 for (unsigned i = 0; i != LNumOps; ++i) { 589 if (i >= RNumOps) 590 return 1; 591 long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i)); 592 if (X != 0) 593 return X; 594 } 595 return (int)LNumOps - (int)RNumOps; 596 } 597 598 case scUDivExpr: { 599 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 601 602 // Lexicographically compare udiv expressions. 603 long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS()); 604 if (X != 0) 605 return X; 606 return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS()); 607 } 608 609 case scTruncate: 610 case scZeroExtend: 611 case scSignExtend: { 612 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 613 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 614 615 // Compare cast expressions by operand. 616 return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand()); 617 } 618 619 case scCouldNotCompute: 620 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 621 } 622 llvm_unreachable("Unknown SCEV kind!"); 623 } 624 625 /// Given a list of SCEV objects, order them by their complexity, and group 626 /// objects of the same complexity together by value. When this routine is 627 /// finished, we know that any duplicates in the vector are consecutive and that 628 /// complexity is monotonically increasing. 629 /// 630 /// Note that we go take special precautions to ensure that we get deterministic 631 /// results from this routine. In other words, we don't want the results of 632 /// this to depend on where the addresses of various SCEV objects happened to 633 /// land in memory. 634 /// 635 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 636 LoopInfo *LI) { 637 if (Ops.size() < 2) return; // Noop 638 if (Ops.size() == 2) { 639 // This is the common case, which also happens to be trivially simple. 640 // Special case it. 641 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 642 if (CompareSCEVComplexity(LI, RHS, LHS) < 0) 643 std::swap(LHS, RHS); 644 return; 645 } 646 647 // Do the rough sort by complexity. 648 std::stable_sort(Ops.begin(), Ops.end(), 649 [LI](const SCEV *LHS, const SCEV *RHS) { 650 return CompareSCEVComplexity(LI, LHS, RHS) < 0; 651 }); 652 653 // Now that we are sorted by complexity, group elements of the same 654 // complexity. Note that this is, at worst, N^2, but the vector is likely to 655 // be extremely short in practice. Note that we take this approach because we 656 // do not want to depend on the addresses of the objects we are grouping. 657 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 658 const SCEV *S = Ops[i]; 659 unsigned Complexity = S->getSCEVType(); 660 661 // If there are any objects of the same complexity and same value as this 662 // one, group them. 663 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 664 if (Ops[j] == S) { // Found a duplicate. 665 // Move it to immediately after i'th element. 666 std::swap(Ops[i+1], Ops[j]); 667 ++i; // no need to rescan it. 668 if (i == e-2) return; // Done! 669 } 670 } 671 } 672 } 673 674 // Returns the size of the SCEV S. 675 static inline int sizeOfSCEV(const SCEV *S) { 676 struct FindSCEVSize { 677 int Size; 678 FindSCEVSize() : Size(0) {} 679 680 bool follow(const SCEV *S) { 681 ++Size; 682 // Keep looking at all operands of S. 683 return true; 684 } 685 bool isDone() const { 686 return false; 687 } 688 }; 689 690 FindSCEVSize F; 691 SCEVTraversal<FindSCEVSize> ST(F); 692 ST.visitAll(S); 693 return F.Size; 694 } 695 696 namespace { 697 698 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 699 public: 700 // Computes the Quotient and Remainder of the division of Numerator by 701 // Denominator. 702 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 703 const SCEV *Denominator, const SCEV **Quotient, 704 const SCEV **Remainder) { 705 assert(Numerator && Denominator && "Uninitialized SCEV"); 706 707 SCEVDivision D(SE, Numerator, Denominator); 708 709 // Check for the trivial case here to avoid having to check for it in the 710 // rest of the code. 711 if (Numerator == Denominator) { 712 *Quotient = D.One; 713 *Remainder = D.Zero; 714 return; 715 } 716 717 if (Numerator->isZero()) { 718 *Quotient = D.Zero; 719 *Remainder = D.Zero; 720 return; 721 } 722 723 // A simple case when N/1. The quotient is N. 724 if (Denominator->isOne()) { 725 *Quotient = Numerator; 726 *Remainder = D.Zero; 727 return; 728 } 729 730 // Split the Denominator when it is a product. 731 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 732 const SCEV *Q, *R; 733 *Quotient = Numerator; 734 for (const SCEV *Op : T->operands()) { 735 divide(SE, *Quotient, Op, &Q, &R); 736 *Quotient = Q; 737 738 // Bail out when the Numerator is not divisible by one of the terms of 739 // the Denominator. 740 if (!R->isZero()) { 741 *Quotient = D.Zero; 742 *Remainder = Numerator; 743 return; 744 } 745 } 746 *Remainder = D.Zero; 747 return; 748 } 749 750 D.visit(Numerator); 751 *Quotient = D.Quotient; 752 *Remainder = D.Remainder; 753 } 754 755 // Except in the trivial case described above, we do not know how to divide 756 // Expr by Denominator for the following functions with empty implementation. 757 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 758 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 759 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 760 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 761 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 762 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 763 void visitUnknown(const SCEVUnknown *Numerator) {} 764 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 765 766 void visitConstant(const SCEVConstant *Numerator) { 767 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 768 APInt NumeratorVal = Numerator->getAPInt(); 769 APInt DenominatorVal = D->getAPInt(); 770 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 771 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 772 773 if (NumeratorBW > DenominatorBW) 774 DenominatorVal = DenominatorVal.sext(NumeratorBW); 775 else if (NumeratorBW < DenominatorBW) 776 NumeratorVal = NumeratorVal.sext(DenominatorBW); 777 778 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 779 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 780 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 781 Quotient = SE.getConstant(QuotientVal); 782 Remainder = SE.getConstant(RemainderVal); 783 return; 784 } 785 } 786 787 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 788 const SCEV *StartQ, *StartR, *StepQ, *StepR; 789 if (!Numerator->isAffine()) 790 return cannotDivide(Numerator); 791 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 792 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 793 // Bail out if the types do not match. 794 Type *Ty = Denominator->getType(); 795 if (Ty != StartQ->getType() || Ty != StartR->getType() || 796 Ty != StepQ->getType() || Ty != StepR->getType()) 797 return cannotDivide(Numerator); 798 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 799 Numerator->getNoWrapFlags()); 800 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 801 Numerator->getNoWrapFlags()); 802 } 803 804 void visitAddExpr(const SCEVAddExpr *Numerator) { 805 SmallVector<const SCEV *, 2> Qs, Rs; 806 Type *Ty = Denominator->getType(); 807 808 for (const SCEV *Op : Numerator->operands()) { 809 const SCEV *Q, *R; 810 divide(SE, Op, Denominator, &Q, &R); 811 812 // Bail out if types do not match. 813 if (Ty != Q->getType() || Ty != R->getType()) 814 return cannotDivide(Numerator); 815 816 Qs.push_back(Q); 817 Rs.push_back(R); 818 } 819 820 if (Qs.size() == 1) { 821 Quotient = Qs[0]; 822 Remainder = Rs[0]; 823 return; 824 } 825 826 Quotient = SE.getAddExpr(Qs); 827 Remainder = SE.getAddExpr(Rs); 828 } 829 830 void visitMulExpr(const SCEVMulExpr *Numerator) { 831 SmallVector<const SCEV *, 2> Qs; 832 Type *Ty = Denominator->getType(); 833 834 bool FoundDenominatorTerm = false; 835 for (const SCEV *Op : Numerator->operands()) { 836 // Bail out if types do not match. 837 if (Ty != Op->getType()) 838 return cannotDivide(Numerator); 839 840 if (FoundDenominatorTerm) { 841 Qs.push_back(Op); 842 continue; 843 } 844 845 // Check whether Denominator divides one of the product operands. 846 const SCEV *Q, *R; 847 divide(SE, Op, Denominator, &Q, &R); 848 if (!R->isZero()) { 849 Qs.push_back(Op); 850 continue; 851 } 852 853 // Bail out if types do not match. 854 if (Ty != Q->getType()) 855 return cannotDivide(Numerator); 856 857 FoundDenominatorTerm = true; 858 Qs.push_back(Q); 859 } 860 861 if (FoundDenominatorTerm) { 862 Remainder = Zero; 863 if (Qs.size() == 1) 864 Quotient = Qs[0]; 865 else 866 Quotient = SE.getMulExpr(Qs); 867 return; 868 } 869 870 if (!isa<SCEVUnknown>(Denominator)) 871 return cannotDivide(Numerator); 872 873 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 874 ValueToValueMap RewriteMap; 875 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 876 cast<SCEVConstant>(Zero)->getValue(); 877 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 878 879 if (Remainder->isZero()) { 880 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 881 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 882 cast<SCEVConstant>(One)->getValue(); 883 Quotient = 884 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 885 return; 886 } 887 888 // Quotient is (Numerator - Remainder) divided by Denominator. 889 const SCEV *Q, *R; 890 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 891 // This SCEV does not seem to simplify: fail the division here. 892 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 893 return cannotDivide(Numerator); 894 divide(SE, Diff, Denominator, &Q, &R); 895 if (R != Zero) 896 return cannotDivide(Numerator); 897 Quotient = Q; 898 } 899 900 private: 901 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 902 const SCEV *Denominator) 903 : SE(S), Denominator(Denominator) { 904 Zero = SE.getZero(Denominator->getType()); 905 One = SE.getOne(Denominator->getType()); 906 907 // We generally do not know how to divide Expr by Denominator. We 908 // initialize the division to a "cannot divide" state to simplify the rest 909 // of the code. 910 cannotDivide(Numerator); 911 } 912 913 // Convenience function for giving up on the division. We set the quotient to 914 // be equal to zero and the remainder to be equal to the numerator. 915 void cannotDivide(const SCEV *Numerator) { 916 Quotient = Zero; 917 Remainder = Numerator; 918 } 919 920 ScalarEvolution &SE; 921 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 922 }; 923 924 } 925 926 //===----------------------------------------------------------------------===// 927 // Simple SCEV method implementations 928 //===----------------------------------------------------------------------===// 929 930 /// Compute BC(It, K). The result has width W. Assume, K > 0. 931 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 932 ScalarEvolution &SE, 933 Type *ResultTy) { 934 // Handle the simplest case efficiently. 935 if (K == 1) 936 return SE.getTruncateOrZeroExtend(It, ResultTy); 937 938 // We are using the following formula for BC(It, K): 939 // 940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 941 // 942 // Suppose, W is the bitwidth of the return value. We must be prepared for 943 // overflow. Hence, we must assure that the result of our computation is 944 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 945 // safe in modular arithmetic. 946 // 947 // However, this code doesn't use exactly that formula; the formula it uses 948 // is something like the following, where T is the number of factors of 2 in 949 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 950 // exponentiation: 951 // 952 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 953 // 954 // This formula is trivially equivalent to the previous formula. However, 955 // this formula can be implemented much more efficiently. The trick is that 956 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 957 // arithmetic. To do exact division in modular arithmetic, all we have 958 // to do is multiply by the inverse. Therefore, this step can be done at 959 // width W. 960 // 961 // The next issue is how to safely do the division by 2^T. The way this 962 // is done is by doing the multiplication step at a width of at least W + T 963 // bits. This way, the bottom W+T bits of the product are accurate. Then, 964 // when we perform the division by 2^T (which is equivalent to a right shift 965 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 966 // truncated out after the division by 2^T. 967 // 968 // In comparison to just directly using the first formula, this technique 969 // is much more efficient; using the first formula requires W * K bits, 970 // but this formula less than W + K bits. Also, the first formula requires 971 // a division step, whereas this formula only requires multiplies and shifts. 972 // 973 // It doesn't matter whether the subtraction step is done in the calculation 974 // width or the input iteration count's width; if the subtraction overflows, 975 // the result must be zero anyway. We prefer here to do it in the width of 976 // the induction variable because it helps a lot for certain cases; CodeGen 977 // isn't smart enough to ignore the overflow, which leads to much less 978 // efficient code if the width of the subtraction is wider than the native 979 // register width. 980 // 981 // (It's possible to not widen at all by pulling out factors of 2 before 982 // the multiplication; for example, K=2 can be calculated as 983 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 984 // extra arithmetic, so it's not an obvious win, and it gets 985 // much more complicated for K > 3.) 986 987 // Protection from insane SCEVs; this bound is conservative, 988 // but it probably doesn't matter. 989 if (K > 1000) 990 return SE.getCouldNotCompute(); 991 992 unsigned W = SE.getTypeSizeInBits(ResultTy); 993 994 // Calculate K! / 2^T and T; we divide out the factors of two before 995 // multiplying for calculating K! / 2^T to avoid overflow. 996 // Other overflow doesn't matter because we only care about the bottom 997 // W bits of the result. 998 APInt OddFactorial(W, 1); 999 unsigned T = 1; 1000 for (unsigned i = 3; i <= K; ++i) { 1001 APInt Mult(W, i); 1002 unsigned TwoFactors = Mult.countTrailingZeros(); 1003 T += TwoFactors; 1004 Mult = Mult.lshr(TwoFactors); 1005 OddFactorial *= Mult; 1006 } 1007 1008 // We need at least W + T bits for the multiplication step 1009 unsigned CalculationBits = W + T; 1010 1011 // Calculate 2^T, at width T+W. 1012 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1013 1014 // Calculate the multiplicative inverse of K! / 2^T; 1015 // this multiplication factor will perform the exact division by 1016 // K! / 2^T. 1017 APInt Mod = APInt::getSignedMinValue(W+1); 1018 APInt MultiplyFactor = OddFactorial.zext(W+1); 1019 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1020 MultiplyFactor = MultiplyFactor.trunc(W); 1021 1022 // Calculate the product, at width T+W 1023 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1024 CalculationBits); 1025 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1026 for (unsigned i = 1; i != K; ++i) { 1027 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1028 Dividend = SE.getMulExpr(Dividend, 1029 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1030 } 1031 1032 // Divide by 2^T 1033 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1034 1035 // Truncate the result, and divide by K! / 2^T. 1036 1037 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1038 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1039 } 1040 1041 /// Return the value of this chain of recurrences at the specified iteration 1042 /// number. We can evaluate this recurrence by multiplying each element in the 1043 /// chain by the binomial coefficient corresponding to it. In other words, we 1044 /// can evaluate {A,+,B,+,C,+,D} as: 1045 /// 1046 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1047 /// 1048 /// where BC(It, k) stands for binomial coefficient. 1049 /// 1050 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1051 ScalarEvolution &SE) const { 1052 const SCEV *Result = getStart(); 1053 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1054 // The computation is correct in the face of overflow provided that the 1055 // multiplication is performed _after_ the evaluation of the binomial 1056 // coefficient. 1057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1058 if (isa<SCEVCouldNotCompute>(Coeff)) 1059 return Coeff; 1060 1061 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1062 } 1063 return Result; 1064 } 1065 1066 //===----------------------------------------------------------------------===// 1067 // SCEV Expression folder implementations 1068 //===----------------------------------------------------------------------===// 1069 1070 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1071 Type *Ty) { 1072 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1073 "This is not a truncating conversion!"); 1074 assert(isSCEVable(Ty) && 1075 "This is not a conversion to a SCEVable type!"); 1076 Ty = getEffectiveSCEVType(Ty); 1077 1078 FoldingSetNodeID ID; 1079 ID.AddInteger(scTruncate); 1080 ID.AddPointer(Op); 1081 ID.AddPointer(Ty); 1082 void *IP = nullptr; 1083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1084 1085 // Fold if the operand is constant. 1086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1087 return getConstant( 1088 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1089 1090 // trunc(trunc(x)) --> trunc(x) 1091 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1092 return getTruncateExpr(ST->getOperand(), Ty); 1093 1094 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1095 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1096 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1097 1098 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1099 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1100 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1101 1102 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1103 // eliminate all the truncates, or we replace other casts with truncates. 1104 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1105 SmallVector<const SCEV *, 4> Operands; 1106 bool hasTrunc = false; 1107 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1108 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1109 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1110 hasTrunc = isa<SCEVTruncateExpr>(S); 1111 Operands.push_back(S); 1112 } 1113 if (!hasTrunc) 1114 return getAddExpr(Operands); 1115 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1116 } 1117 1118 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1119 // eliminate all the truncates, or we replace other casts with truncates. 1120 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1121 SmallVector<const SCEV *, 4> Operands; 1122 bool hasTrunc = false; 1123 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1124 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1125 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1126 hasTrunc = isa<SCEVTruncateExpr>(S); 1127 Operands.push_back(S); 1128 } 1129 if (!hasTrunc) 1130 return getMulExpr(Operands); 1131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1132 } 1133 1134 // If the input value is a chrec scev, truncate the chrec's operands. 1135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1136 SmallVector<const SCEV *, 4> Operands; 1137 for (const SCEV *Op : AddRec->operands()) 1138 Operands.push_back(getTruncateExpr(Op, Ty)); 1139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1140 } 1141 1142 // The cast wasn't folded; create an explicit cast node. We can reuse 1143 // the existing insert position since if we get here, we won't have 1144 // made any changes which would invalidate it. 1145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1146 Op, Ty); 1147 UniqueSCEVs.InsertNode(S, IP); 1148 return S; 1149 } 1150 1151 // Get the limit of a recurrence such that incrementing by Step cannot cause 1152 // signed overflow as long as the value of the recurrence within the 1153 // loop does not exceed this limit before incrementing. 1154 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1155 ICmpInst::Predicate *Pred, 1156 ScalarEvolution *SE) { 1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1158 if (SE->isKnownPositive(Step)) { 1159 *Pred = ICmpInst::ICMP_SLT; 1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1161 SE->getSignedRange(Step).getSignedMax()); 1162 } 1163 if (SE->isKnownNegative(Step)) { 1164 *Pred = ICmpInst::ICMP_SGT; 1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1166 SE->getSignedRange(Step).getSignedMin()); 1167 } 1168 return nullptr; 1169 } 1170 1171 // Get the limit of a recurrence such that incrementing by Step cannot cause 1172 // unsigned overflow as long as the value of the recurrence within the loop does 1173 // not exceed this limit before incrementing. 1174 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1175 ICmpInst::Predicate *Pred, 1176 ScalarEvolution *SE) { 1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1178 *Pred = ICmpInst::ICMP_ULT; 1179 1180 return SE->getConstant(APInt::getMinValue(BitWidth) - 1181 SE->getUnsignedRange(Step).getUnsignedMax()); 1182 } 1183 1184 namespace { 1185 1186 struct ExtendOpTraitsBase { 1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1188 }; 1189 1190 // Used to make code generic over signed and unsigned overflow. 1191 template <typename ExtendOp> struct ExtendOpTraits { 1192 // Members present: 1193 // 1194 // static const SCEV::NoWrapFlags WrapType; 1195 // 1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1197 // 1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1199 // ICmpInst::Predicate *Pred, 1200 // ScalarEvolution *SE); 1201 }; 1202 1203 template <> 1204 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1206 1207 static const GetExtendExprTy GetExtendExpr; 1208 1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1210 ICmpInst::Predicate *Pred, 1211 ScalarEvolution *SE) { 1212 return getSignedOverflowLimitForStep(Step, Pred, SE); 1213 } 1214 }; 1215 1216 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1218 1219 template <> 1220 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1222 1223 static const GetExtendExprTy GetExtendExpr; 1224 1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1226 ICmpInst::Predicate *Pred, 1227 ScalarEvolution *SE) { 1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1229 } 1230 }; 1231 1232 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1234 } 1235 1236 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1237 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1238 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1239 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1240 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1241 // expression "Step + sext/zext(PreIncAR)" is congruent with 1242 // "sext/zext(PostIncAR)" 1243 template <typename ExtendOpTy> 1244 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1245 ScalarEvolution *SE) { 1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1248 1249 const Loop *L = AR->getLoop(); 1250 const SCEV *Start = AR->getStart(); 1251 const SCEV *Step = AR->getStepRecurrence(*SE); 1252 1253 // Check for a simple looking step prior to loop entry. 1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1255 if (!SA) 1256 return nullptr; 1257 1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1259 // subtraction is expensive. For this purpose, perform a quick and dirty 1260 // difference, by checking for Step in the operand list. 1261 SmallVector<const SCEV *, 4> DiffOps; 1262 for (const SCEV *Op : SA->operands()) 1263 if (Op != Step) 1264 DiffOps.push_back(Op); 1265 1266 if (DiffOps.size() == SA->getNumOperands()) 1267 return nullptr; 1268 1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1270 // `Step`: 1271 1272 // 1. NSW/NUW flags on the step increment. 1273 auto PreStartFlags = 1274 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1275 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1276 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1277 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1278 1279 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1280 // "S+X does not sign/unsign-overflow". 1281 // 1282 1283 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1284 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1285 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1286 return PreStart; 1287 1288 // 2. Direct overflow check on the step operation's expression. 1289 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1290 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1291 const SCEV *OperandExtendedStart = 1292 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1293 (SE->*GetExtendExpr)(Step, WideTy)); 1294 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1295 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1296 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1297 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1298 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1299 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1300 } 1301 return PreStart; 1302 } 1303 1304 // 3. Loop precondition. 1305 ICmpInst::Predicate Pred; 1306 const SCEV *OverflowLimit = 1307 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1308 1309 if (OverflowLimit && 1310 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1311 return PreStart; 1312 1313 return nullptr; 1314 } 1315 1316 // Get the normalized zero or sign extended expression for this AddRec's Start. 1317 template <typename ExtendOpTy> 1318 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1319 ScalarEvolution *SE) { 1320 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1321 1322 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1323 if (!PreStart) 1324 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1325 1326 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1327 (SE->*GetExtendExpr)(PreStart, Ty)); 1328 } 1329 1330 // Try to prove away overflow by looking at "nearby" add recurrences. A 1331 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1332 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1333 // 1334 // Formally: 1335 // 1336 // {S,+,X} == {S-T,+,X} + T 1337 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1338 // 1339 // If ({S-T,+,X} + T) does not overflow ... (1) 1340 // 1341 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1342 // 1343 // If {S-T,+,X} does not overflow ... (2) 1344 // 1345 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1346 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1347 // 1348 // If (S-T)+T does not overflow ... (3) 1349 // 1350 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1351 // == {Ext(S),+,Ext(X)} == LHS 1352 // 1353 // Thus, if (1), (2) and (3) are true for some T, then 1354 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1355 // 1356 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1357 // does not overflow" restricted to the 0th iteration. Therefore we only need 1358 // to check for (1) and (2). 1359 // 1360 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1361 // is `Delta` (defined below). 1362 // 1363 template <typename ExtendOpTy> 1364 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1365 const SCEV *Step, 1366 const Loop *L) { 1367 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1368 1369 // We restrict `Start` to a constant to prevent SCEV from spending too much 1370 // time here. It is correct (but more expensive) to continue with a 1371 // non-constant `Start` and do a general SCEV subtraction to compute 1372 // `PreStart` below. 1373 // 1374 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1375 if (!StartC) 1376 return false; 1377 1378 APInt StartAI = StartC->getAPInt(); 1379 1380 for (unsigned Delta : {-2, -1, 1, 2}) { 1381 const SCEV *PreStart = getConstant(StartAI - Delta); 1382 1383 FoldingSetNodeID ID; 1384 ID.AddInteger(scAddRecExpr); 1385 ID.AddPointer(PreStart); 1386 ID.AddPointer(Step); 1387 ID.AddPointer(L); 1388 void *IP = nullptr; 1389 const auto *PreAR = 1390 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1391 1392 // Give up if we don't already have the add recurrence we need because 1393 // actually constructing an add recurrence is relatively expensive. 1394 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1395 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1396 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1397 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1398 DeltaS, &Pred, this); 1399 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1400 return true; 1401 } 1402 } 1403 1404 return false; 1405 } 1406 1407 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1408 Type *Ty) { 1409 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1410 "This is not an extending conversion!"); 1411 assert(isSCEVable(Ty) && 1412 "This is not a conversion to a SCEVable type!"); 1413 Ty = getEffectiveSCEVType(Ty); 1414 1415 // Fold if the operand is constant. 1416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1417 return getConstant( 1418 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1419 1420 // zext(zext(x)) --> zext(x) 1421 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1422 return getZeroExtendExpr(SZ->getOperand(), Ty); 1423 1424 // Before doing any expensive analysis, check to see if we've already 1425 // computed a SCEV for this Op and Ty. 1426 FoldingSetNodeID ID; 1427 ID.AddInteger(scZeroExtend); 1428 ID.AddPointer(Op); 1429 ID.AddPointer(Ty); 1430 void *IP = nullptr; 1431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1432 1433 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1434 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1435 // It's possible the bits taken off by the truncate were all zero bits. If 1436 // so, we should be able to simplify this further. 1437 const SCEV *X = ST->getOperand(); 1438 ConstantRange CR = getUnsignedRange(X); 1439 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1440 unsigned NewBits = getTypeSizeInBits(Ty); 1441 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1442 CR.zextOrTrunc(NewBits))) 1443 return getTruncateOrZeroExtend(X, Ty); 1444 } 1445 1446 // If the input value is a chrec scev, and we can prove that the value 1447 // did not overflow the old, smaller, value, we can zero extend all of the 1448 // operands (often constants). This allows analysis of something like 1449 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1450 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1451 if (AR->isAffine()) { 1452 const SCEV *Start = AR->getStart(); 1453 const SCEV *Step = AR->getStepRecurrence(*this); 1454 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1455 const Loop *L = AR->getLoop(); 1456 1457 if (!AR->hasNoUnsignedWrap()) { 1458 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1459 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1460 } 1461 1462 // If we have special knowledge that this addrec won't overflow, 1463 // we don't need to do any further analysis. 1464 if (AR->hasNoUnsignedWrap()) 1465 return getAddRecExpr( 1466 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1467 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1468 1469 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1470 // Note that this serves two purposes: It filters out loops that are 1471 // simply not analyzable, and it covers the case where this code is 1472 // being called from within backedge-taken count analysis, such that 1473 // attempting to ask for the backedge-taken count would likely result 1474 // in infinite recursion. In the later case, the analysis code will 1475 // cope with a conservative value, and it will take care to purge 1476 // that value once it has finished. 1477 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1478 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1479 // Manually compute the final value for AR, checking for 1480 // overflow. 1481 1482 // Check whether the backedge-taken count can be losslessly casted to 1483 // the addrec's type. The count is always unsigned. 1484 const SCEV *CastedMaxBECount = 1485 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1486 const SCEV *RecastedMaxBECount = 1487 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1488 if (MaxBECount == RecastedMaxBECount) { 1489 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1490 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1491 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1492 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1493 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1494 const SCEV *WideMaxBECount = 1495 getZeroExtendExpr(CastedMaxBECount, WideTy); 1496 const SCEV *OperandExtendedAdd = 1497 getAddExpr(WideStart, 1498 getMulExpr(WideMaxBECount, 1499 getZeroExtendExpr(Step, WideTy))); 1500 if (ZAdd == OperandExtendedAdd) { 1501 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1502 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1503 // Return the expression with the addrec on the outside. 1504 return getAddRecExpr( 1505 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1506 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1507 } 1508 // Similar to above, only this time treat the step value as signed. 1509 // This covers loops that count down. 1510 OperandExtendedAdd = 1511 getAddExpr(WideStart, 1512 getMulExpr(WideMaxBECount, 1513 getSignExtendExpr(Step, WideTy))); 1514 if (ZAdd == OperandExtendedAdd) { 1515 // Cache knowledge of AR NW, which is propagated to this AddRec. 1516 // Negative step causes unsigned wrap, but it still can't self-wrap. 1517 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1518 // Return the expression with the addrec on the outside. 1519 return getAddRecExpr( 1520 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1521 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1522 } 1523 } 1524 } 1525 1526 // Normally, in the cases we can prove no-overflow via a 1527 // backedge guarding condition, we can also compute a backedge 1528 // taken count for the loop. The exceptions are assumptions and 1529 // guards present in the loop -- SCEV is not great at exploiting 1530 // these to compute max backedge taken counts, but can still use 1531 // these to prove lack of overflow. Use this fact to avoid 1532 // doing extra work that may not pay off. 1533 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1534 !AC.assumptions().empty()) { 1535 // If the backedge is guarded by a comparison with the pre-inc 1536 // value the addrec is safe. Also, if the entry is guarded by 1537 // a comparison with the start value and the backedge is 1538 // guarded by a comparison with the post-inc value, the addrec 1539 // is safe. 1540 if (isKnownPositive(Step)) { 1541 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1542 getUnsignedRange(Step).getUnsignedMax()); 1543 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1544 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1545 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1546 AR->getPostIncExpr(*this), N))) { 1547 // Cache knowledge of AR NUW, which is propagated to this 1548 // AddRec. 1549 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1550 // Return the expression with the addrec on the outside. 1551 return getAddRecExpr( 1552 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1553 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1554 } 1555 } else if (isKnownNegative(Step)) { 1556 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1557 getSignedRange(Step).getSignedMin()); 1558 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1559 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1560 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1561 AR->getPostIncExpr(*this), N))) { 1562 // Cache knowledge of AR NW, which is propagated to this 1563 // AddRec. Negative step causes unsigned wrap, but it 1564 // still can't self-wrap. 1565 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1566 // Return the expression with the addrec on the outside. 1567 return getAddRecExpr( 1568 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1569 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1570 } 1571 } 1572 } 1573 1574 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1575 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1576 return getAddRecExpr( 1577 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1578 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1579 } 1580 } 1581 1582 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1583 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1584 if (SA->hasNoUnsignedWrap()) { 1585 // If the addition does not unsign overflow then we can, by definition, 1586 // commute the zero extension with the addition operation. 1587 SmallVector<const SCEV *, 4> Ops; 1588 for (const auto *Op : SA->operands()) 1589 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1590 return getAddExpr(Ops, SCEV::FlagNUW); 1591 } 1592 } 1593 1594 // The cast wasn't folded; create an explicit cast node. 1595 // Recompute the insert position, as it may have been invalidated. 1596 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1597 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1598 Op, Ty); 1599 UniqueSCEVs.InsertNode(S, IP); 1600 return S; 1601 } 1602 1603 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1604 Type *Ty) { 1605 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1606 "This is not an extending conversion!"); 1607 assert(isSCEVable(Ty) && 1608 "This is not a conversion to a SCEVable type!"); 1609 Ty = getEffectiveSCEVType(Ty); 1610 1611 // Fold if the operand is constant. 1612 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1613 return getConstant( 1614 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1615 1616 // sext(sext(x)) --> sext(x) 1617 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1618 return getSignExtendExpr(SS->getOperand(), Ty); 1619 1620 // sext(zext(x)) --> zext(x) 1621 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1622 return getZeroExtendExpr(SZ->getOperand(), Ty); 1623 1624 // Before doing any expensive analysis, check to see if we've already 1625 // computed a SCEV for this Op and Ty. 1626 FoldingSetNodeID ID; 1627 ID.AddInteger(scSignExtend); 1628 ID.AddPointer(Op); 1629 ID.AddPointer(Ty); 1630 void *IP = nullptr; 1631 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1632 1633 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1634 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1635 // It's possible the bits taken off by the truncate were all sign bits. If 1636 // so, we should be able to simplify this further. 1637 const SCEV *X = ST->getOperand(); 1638 ConstantRange CR = getSignedRange(X); 1639 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1640 unsigned NewBits = getTypeSizeInBits(Ty); 1641 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1642 CR.sextOrTrunc(NewBits))) 1643 return getTruncateOrSignExtend(X, Ty); 1644 } 1645 1646 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1647 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1648 if (SA->getNumOperands() == 2) { 1649 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1650 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1651 if (SMul && SC1) { 1652 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1653 const APInt &C1 = SC1->getAPInt(); 1654 const APInt &C2 = SC2->getAPInt(); 1655 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1656 C2.ugt(C1) && C2.isPowerOf2()) 1657 return getAddExpr(getSignExtendExpr(SC1, Ty), 1658 getSignExtendExpr(SMul, Ty)); 1659 } 1660 } 1661 } 1662 1663 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1664 if (SA->hasNoSignedWrap()) { 1665 // If the addition does not sign overflow then we can, by definition, 1666 // commute the sign extension with the addition operation. 1667 SmallVector<const SCEV *, 4> Ops; 1668 for (const auto *Op : SA->operands()) 1669 Ops.push_back(getSignExtendExpr(Op, Ty)); 1670 return getAddExpr(Ops, SCEV::FlagNSW); 1671 } 1672 } 1673 // If the input value is a chrec scev, and we can prove that the value 1674 // did not overflow the old, smaller, value, we can sign extend all of the 1675 // operands (often constants). This allows analysis of something like 1676 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1677 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1678 if (AR->isAffine()) { 1679 const SCEV *Start = AR->getStart(); 1680 const SCEV *Step = AR->getStepRecurrence(*this); 1681 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1682 const Loop *L = AR->getLoop(); 1683 1684 if (!AR->hasNoSignedWrap()) { 1685 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1686 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1687 } 1688 1689 // If we have special knowledge that this addrec won't overflow, 1690 // we don't need to do any further analysis. 1691 if (AR->hasNoSignedWrap()) 1692 return getAddRecExpr( 1693 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1694 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1695 1696 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1697 // Note that this serves two purposes: It filters out loops that are 1698 // simply not analyzable, and it covers the case where this code is 1699 // being called from within backedge-taken count analysis, such that 1700 // attempting to ask for the backedge-taken count would likely result 1701 // in infinite recursion. In the later case, the analysis code will 1702 // cope with a conservative value, and it will take care to purge 1703 // that value once it has finished. 1704 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1705 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1706 // Manually compute the final value for AR, checking for 1707 // overflow. 1708 1709 // Check whether the backedge-taken count can be losslessly casted to 1710 // the addrec's type. The count is always unsigned. 1711 const SCEV *CastedMaxBECount = 1712 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1713 const SCEV *RecastedMaxBECount = 1714 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1715 if (MaxBECount == RecastedMaxBECount) { 1716 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1717 // Check whether Start+Step*MaxBECount has no signed overflow. 1718 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1719 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1720 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1721 const SCEV *WideMaxBECount = 1722 getZeroExtendExpr(CastedMaxBECount, WideTy); 1723 const SCEV *OperandExtendedAdd = 1724 getAddExpr(WideStart, 1725 getMulExpr(WideMaxBECount, 1726 getSignExtendExpr(Step, WideTy))); 1727 if (SAdd == OperandExtendedAdd) { 1728 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1729 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1730 // Return the expression with the addrec on the outside. 1731 return getAddRecExpr( 1732 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1733 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1734 } 1735 // Similar to above, only this time treat the step value as unsigned. 1736 // This covers loops that count up with an unsigned step. 1737 OperandExtendedAdd = 1738 getAddExpr(WideStart, 1739 getMulExpr(WideMaxBECount, 1740 getZeroExtendExpr(Step, WideTy))); 1741 if (SAdd == OperandExtendedAdd) { 1742 // If AR wraps around then 1743 // 1744 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1745 // => SAdd != OperandExtendedAdd 1746 // 1747 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1748 // (SAdd == OperandExtendedAdd => AR is NW) 1749 1750 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1751 1752 // Return the expression with the addrec on the outside. 1753 return getAddRecExpr( 1754 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1755 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1756 } 1757 } 1758 } 1759 1760 // Normally, in the cases we can prove no-overflow via a 1761 // backedge guarding condition, we can also compute a backedge 1762 // taken count for the loop. The exceptions are assumptions and 1763 // guards present in the loop -- SCEV is not great at exploiting 1764 // these to compute max backedge taken counts, but can still use 1765 // these to prove lack of overflow. Use this fact to avoid 1766 // doing extra work that may not pay off. 1767 1768 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1769 !AC.assumptions().empty()) { 1770 // If the backedge is guarded by a comparison with the pre-inc 1771 // value the addrec is safe. Also, if the entry is guarded by 1772 // a comparison with the start value and the backedge is 1773 // guarded by a comparison with the post-inc value, the addrec 1774 // is safe. 1775 ICmpInst::Predicate Pred; 1776 const SCEV *OverflowLimit = 1777 getSignedOverflowLimitForStep(Step, &Pred, this); 1778 if (OverflowLimit && 1779 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1780 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1781 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1782 OverflowLimit)))) { 1783 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1784 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1785 return getAddRecExpr( 1786 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1787 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1788 } 1789 } 1790 1791 // If Start and Step are constants, check if we can apply this 1792 // transformation: 1793 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1794 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1795 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1796 if (SC1 && SC2) { 1797 const APInt &C1 = SC1->getAPInt(); 1798 const APInt &C2 = SC2->getAPInt(); 1799 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1800 C2.isPowerOf2()) { 1801 Start = getSignExtendExpr(Start, Ty); 1802 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1803 AR->getNoWrapFlags()); 1804 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1805 } 1806 } 1807 1808 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1809 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1810 return getAddRecExpr( 1811 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1812 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1813 } 1814 } 1815 1816 // If the input value is provably positive and we could not simplify 1817 // away the sext build a zext instead. 1818 if (isKnownNonNegative(Op)) 1819 return getZeroExtendExpr(Op, Ty); 1820 1821 // The cast wasn't folded; create an explicit cast node. 1822 // Recompute the insert position, as it may have been invalidated. 1823 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1824 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1825 Op, Ty); 1826 UniqueSCEVs.InsertNode(S, IP); 1827 return S; 1828 } 1829 1830 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1831 /// unspecified bits out to the given type. 1832 /// 1833 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1834 Type *Ty) { 1835 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1836 "This is not an extending conversion!"); 1837 assert(isSCEVable(Ty) && 1838 "This is not a conversion to a SCEVable type!"); 1839 Ty = getEffectiveSCEVType(Ty); 1840 1841 // Sign-extend negative constants. 1842 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1843 if (SC->getAPInt().isNegative()) 1844 return getSignExtendExpr(Op, Ty); 1845 1846 // Peel off a truncate cast. 1847 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1848 const SCEV *NewOp = T->getOperand(); 1849 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1850 return getAnyExtendExpr(NewOp, Ty); 1851 return getTruncateOrNoop(NewOp, Ty); 1852 } 1853 1854 // Next try a zext cast. If the cast is folded, use it. 1855 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1856 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1857 return ZExt; 1858 1859 // Next try a sext cast. If the cast is folded, use it. 1860 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1861 if (!isa<SCEVSignExtendExpr>(SExt)) 1862 return SExt; 1863 1864 // Force the cast to be folded into the operands of an addrec. 1865 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1866 SmallVector<const SCEV *, 4> Ops; 1867 for (const SCEV *Op : AR->operands()) 1868 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1869 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1870 } 1871 1872 // If the expression is obviously signed, use the sext cast value. 1873 if (isa<SCEVSMaxExpr>(Op)) 1874 return SExt; 1875 1876 // Absent any other information, use the zext cast value. 1877 return ZExt; 1878 } 1879 1880 /// Process the given Ops list, which is a list of operands to be added under 1881 /// the given scale, update the given map. This is a helper function for 1882 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1883 /// that would form an add expression like this: 1884 /// 1885 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1886 /// 1887 /// where A and B are constants, update the map with these values: 1888 /// 1889 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1890 /// 1891 /// and add 13 + A*B*29 to AccumulatedConstant. 1892 /// This will allow getAddRecExpr to produce this: 1893 /// 1894 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1895 /// 1896 /// This form often exposes folding opportunities that are hidden in 1897 /// the original operand list. 1898 /// 1899 /// Return true iff it appears that any interesting folding opportunities 1900 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1901 /// the common case where no interesting opportunities are present, and 1902 /// is also used as a check to avoid infinite recursion. 1903 /// 1904 static bool 1905 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1906 SmallVectorImpl<const SCEV *> &NewOps, 1907 APInt &AccumulatedConstant, 1908 const SCEV *const *Ops, size_t NumOperands, 1909 const APInt &Scale, 1910 ScalarEvolution &SE) { 1911 bool Interesting = false; 1912 1913 // Iterate over the add operands. They are sorted, with constants first. 1914 unsigned i = 0; 1915 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1916 ++i; 1917 // Pull a buried constant out to the outside. 1918 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1919 Interesting = true; 1920 AccumulatedConstant += Scale * C->getAPInt(); 1921 } 1922 1923 // Next comes everything else. We're especially interested in multiplies 1924 // here, but they're in the middle, so just visit the rest with one loop. 1925 for (; i != NumOperands; ++i) { 1926 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1927 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1928 APInt NewScale = 1929 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1930 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1931 // A multiplication of a constant with another add; recurse. 1932 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1933 Interesting |= 1934 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1935 Add->op_begin(), Add->getNumOperands(), 1936 NewScale, SE); 1937 } else { 1938 // A multiplication of a constant with some other value. Update 1939 // the map. 1940 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1941 const SCEV *Key = SE.getMulExpr(MulOps); 1942 auto Pair = M.insert({Key, NewScale}); 1943 if (Pair.second) { 1944 NewOps.push_back(Pair.first->first); 1945 } else { 1946 Pair.first->second += NewScale; 1947 // The map already had an entry for this value, which may indicate 1948 // a folding opportunity. 1949 Interesting = true; 1950 } 1951 } 1952 } else { 1953 // An ordinary operand. Update the map. 1954 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1955 M.insert({Ops[i], Scale}); 1956 if (Pair.second) { 1957 NewOps.push_back(Pair.first->first); 1958 } else { 1959 Pair.first->second += Scale; 1960 // The map already had an entry for this value, which may indicate 1961 // a folding opportunity. 1962 Interesting = true; 1963 } 1964 } 1965 } 1966 1967 return Interesting; 1968 } 1969 1970 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 1971 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 1972 // can't-overflow flags for the operation if possible. 1973 static SCEV::NoWrapFlags 1974 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 1975 const SmallVectorImpl<const SCEV *> &Ops, 1976 SCEV::NoWrapFlags Flags) { 1977 using namespace std::placeholders; 1978 typedef OverflowingBinaryOperator OBO; 1979 1980 bool CanAnalyze = 1981 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 1982 (void)CanAnalyze; 1983 assert(CanAnalyze && "don't call from other places!"); 1984 1985 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1986 SCEV::NoWrapFlags SignOrUnsignWrap = 1987 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1988 1989 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1990 auto IsKnownNonNegative = [&](const SCEV *S) { 1991 return SE->isKnownNonNegative(S); 1992 }; 1993 1994 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 1995 Flags = 1996 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1997 1998 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1999 2000 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2001 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2002 2003 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2004 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2005 2006 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2007 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2008 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2009 Instruction::Add, C, OBO::NoSignedWrap); 2010 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2011 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2012 } 2013 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2014 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2015 Instruction::Add, C, OBO::NoUnsignedWrap); 2016 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2017 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2018 } 2019 } 2020 2021 return Flags; 2022 } 2023 2024 /// Get a canonical add expression, or something simpler if possible. 2025 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2026 SCEV::NoWrapFlags Flags) { 2027 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2028 "only nuw or nsw allowed"); 2029 assert(!Ops.empty() && "Cannot get empty add!"); 2030 if (Ops.size() == 1) return Ops[0]; 2031 #ifndef NDEBUG 2032 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2033 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2034 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2035 "SCEVAddExpr operand types don't match!"); 2036 #endif 2037 2038 // Sort by complexity, this groups all similar expression types together. 2039 GroupByComplexity(Ops, &LI); 2040 2041 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2042 2043 // If there are any constants, fold them together. 2044 unsigned Idx = 0; 2045 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2046 ++Idx; 2047 assert(Idx < Ops.size()); 2048 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2049 // We found two constants, fold them together! 2050 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2051 if (Ops.size() == 2) return Ops[0]; 2052 Ops.erase(Ops.begin()+1); // Erase the folded element 2053 LHSC = cast<SCEVConstant>(Ops[0]); 2054 } 2055 2056 // If we are left with a constant zero being added, strip it off. 2057 if (LHSC->getValue()->isZero()) { 2058 Ops.erase(Ops.begin()); 2059 --Idx; 2060 } 2061 2062 if (Ops.size() == 1) return Ops[0]; 2063 } 2064 2065 // Okay, check to see if the same value occurs in the operand list more than 2066 // once. If so, merge them together into an multiply expression. Since we 2067 // sorted the list, these values are required to be adjacent. 2068 Type *Ty = Ops[0]->getType(); 2069 bool FoundMatch = false; 2070 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2071 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2072 // Scan ahead to count how many equal operands there are. 2073 unsigned Count = 2; 2074 while (i+Count != e && Ops[i+Count] == Ops[i]) 2075 ++Count; 2076 // Merge the values into a multiply. 2077 const SCEV *Scale = getConstant(Ty, Count); 2078 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2079 if (Ops.size() == Count) 2080 return Mul; 2081 Ops[i] = Mul; 2082 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2083 --i; e -= Count - 1; 2084 FoundMatch = true; 2085 } 2086 if (FoundMatch) 2087 return getAddExpr(Ops, Flags); 2088 2089 // Check for truncates. If all the operands are truncated from the same 2090 // type, see if factoring out the truncate would permit the result to be 2091 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2092 // if the contents of the resulting outer trunc fold to something simple. 2093 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2094 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2095 Type *DstType = Trunc->getType(); 2096 Type *SrcType = Trunc->getOperand()->getType(); 2097 SmallVector<const SCEV *, 8> LargeOps; 2098 bool Ok = true; 2099 // Check all the operands to see if they can be represented in the 2100 // source type of the truncate. 2101 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2102 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2103 if (T->getOperand()->getType() != SrcType) { 2104 Ok = false; 2105 break; 2106 } 2107 LargeOps.push_back(T->getOperand()); 2108 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2109 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2110 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2111 SmallVector<const SCEV *, 8> LargeMulOps; 2112 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2113 if (const SCEVTruncateExpr *T = 2114 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2115 if (T->getOperand()->getType() != SrcType) { 2116 Ok = false; 2117 break; 2118 } 2119 LargeMulOps.push_back(T->getOperand()); 2120 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2121 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2122 } else { 2123 Ok = false; 2124 break; 2125 } 2126 } 2127 if (Ok) 2128 LargeOps.push_back(getMulExpr(LargeMulOps)); 2129 } else { 2130 Ok = false; 2131 break; 2132 } 2133 } 2134 if (Ok) { 2135 // Evaluate the expression in the larger type. 2136 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2137 // If it folds to something simple, use it. Otherwise, don't. 2138 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2139 return getTruncateExpr(Fold, DstType); 2140 } 2141 } 2142 2143 // Skip past any other cast SCEVs. 2144 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2145 ++Idx; 2146 2147 // If there are add operands they would be next. 2148 if (Idx < Ops.size()) { 2149 bool DeletedAdd = false; 2150 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2151 // If we have an add, expand the add operands onto the end of the operands 2152 // list. 2153 Ops.erase(Ops.begin()+Idx); 2154 Ops.append(Add->op_begin(), Add->op_end()); 2155 DeletedAdd = true; 2156 } 2157 2158 // If we deleted at least one add, we added operands to the end of the list, 2159 // and they are not necessarily sorted. Recurse to resort and resimplify 2160 // any operands we just acquired. 2161 if (DeletedAdd) 2162 return getAddExpr(Ops); 2163 } 2164 2165 // Skip over the add expression until we get to a multiply. 2166 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2167 ++Idx; 2168 2169 // Check to see if there are any folding opportunities present with 2170 // operands multiplied by constant values. 2171 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2172 uint64_t BitWidth = getTypeSizeInBits(Ty); 2173 DenseMap<const SCEV *, APInt> M; 2174 SmallVector<const SCEV *, 8> NewOps; 2175 APInt AccumulatedConstant(BitWidth, 0); 2176 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2177 Ops.data(), Ops.size(), 2178 APInt(BitWidth, 1), *this)) { 2179 struct APIntCompare { 2180 bool operator()(const APInt &LHS, const APInt &RHS) const { 2181 return LHS.ult(RHS); 2182 } 2183 }; 2184 2185 // Some interesting folding opportunity is present, so its worthwhile to 2186 // re-generate the operands list. Group the operands by constant scale, 2187 // to avoid multiplying by the same constant scale multiple times. 2188 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2189 for (const SCEV *NewOp : NewOps) 2190 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2191 // Re-generate the operands list. 2192 Ops.clear(); 2193 if (AccumulatedConstant != 0) 2194 Ops.push_back(getConstant(AccumulatedConstant)); 2195 for (auto &MulOp : MulOpLists) 2196 if (MulOp.first != 0) 2197 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2198 getAddExpr(MulOp.second))); 2199 if (Ops.empty()) 2200 return getZero(Ty); 2201 if (Ops.size() == 1) 2202 return Ops[0]; 2203 return getAddExpr(Ops); 2204 } 2205 } 2206 2207 // If we are adding something to a multiply expression, make sure the 2208 // something is not already an operand of the multiply. If so, merge it into 2209 // the multiply. 2210 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2211 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2212 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2213 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2214 if (isa<SCEVConstant>(MulOpSCEV)) 2215 continue; 2216 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2217 if (MulOpSCEV == Ops[AddOp]) { 2218 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2219 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2220 if (Mul->getNumOperands() != 2) { 2221 // If the multiply has more than two operands, we must get the 2222 // Y*Z term. 2223 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2224 Mul->op_begin()+MulOp); 2225 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2226 InnerMul = getMulExpr(MulOps); 2227 } 2228 const SCEV *One = getOne(Ty); 2229 const SCEV *AddOne = getAddExpr(One, InnerMul); 2230 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2231 if (Ops.size() == 2) return OuterMul; 2232 if (AddOp < Idx) { 2233 Ops.erase(Ops.begin()+AddOp); 2234 Ops.erase(Ops.begin()+Idx-1); 2235 } else { 2236 Ops.erase(Ops.begin()+Idx); 2237 Ops.erase(Ops.begin()+AddOp-1); 2238 } 2239 Ops.push_back(OuterMul); 2240 return getAddExpr(Ops); 2241 } 2242 2243 // Check this multiply against other multiplies being added together. 2244 for (unsigned OtherMulIdx = Idx+1; 2245 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2246 ++OtherMulIdx) { 2247 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2248 // If MulOp occurs in OtherMul, we can fold the two multiplies 2249 // together. 2250 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2251 OMulOp != e; ++OMulOp) 2252 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2253 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2254 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2255 if (Mul->getNumOperands() != 2) { 2256 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2257 Mul->op_begin()+MulOp); 2258 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2259 InnerMul1 = getMulExpr(MulOps); 2260 } 2261 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2262 if (OtherMul->getNumOperands() != 2) { 2263 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2264 OtherMul->op_begin()+OMulOp); 2265 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2266 InnerMul2 = getMulExpr(MulOps); 2267 } 2268 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2269 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2270 if (Ops.size() == 2) return OuterMul; 2271 Ops.erase(Ops.begin()+Idx); 2272 Ops.erase(Ops.begin()+OtherMulIdx-1); 2273 Ops.push_back(OuterMul); 2274 return getAddExpr(Ops); 2275 } 2276 } 2277 } 2278 } 2279 2280 // If there are any add recurrences in the operands list, see if any other 2281 // added values are loop invariant. If so, we can fold them into the 2282 // recurrence. 2283 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2284 ++Idx; 2285 2286 // Scan over all recurrences, trying to fold loop invariants into them. 2287 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2288 // Scan all of the other operands to this add and add them to the vector if 2289 // they are loop invariant w.r.t. the recurrence. 2290 SmallVector<const SCEV *, 8> LIOps; 2291 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2292 const Loop *AddRecLoop = AddRec->getLoop(); 2293 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2294 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2295 LIOps.push_back(Ops[i]); 2296 Ops.erase(Ops.begin()+i); 2297 --i; --e; 2298 } 2299 2300 // If we found some loop invariants, fold them into the recurrence. 2301 if (!LIOps.empty()) { 2302 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2303 LIOps.push_back(AddRec->getStart()); 2304 2305 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2306 AddRec->op_end()); 2307 // This follows from the fact that the no-wrap flags on the outer add 2308 // expression are applicable on the 0th iteration, when the add recurrence 2309 // will be equal to its start value. 2310 AddRecOps[0] = getAddExpr(LIOps, Flags); 2311 2312 // Build the new addrec. Propagate the NUW and NSW flags if both the 2313 // outer add and the inner addrec are guaranteed to have no overflow. 2314 // Always propagate NW. 2315 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2316 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2317 2318 // If all of the other operands were loop invariant, we are done. 2319 if (Ops.size() == 1) return NewRec; 2320 2321 // Otherwise, add the folded AddRec by the non-invariant parts. 2322 for (unsigned i = 0;; ++i) 2323 if (Ops[i] == AddRec) { 2324 Ops[i] = NewRec; 2325 break; 2326 } 2327 return getAddExpr(Ops); 2328 } 2329 2330 // Okay, if there weren't any loop invariants to be folded, check to see if 2331 // there are multiple AddRec's with the same loop induction variable being 2332 // added together. If so, we can fold them. 2333 for (unsigned OtherIdx = Idx+1; 2334 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2335 ++OtherIdx) 2336 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2337 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2338 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2339 AddRec->op_end()); 2340 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2341 ++OtherIdx) 2342 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2343 if (OtherAddRec->getLoop() == AddRecLoop) { 2344 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2345 i != e; ++i) { 2346 if (i >= AddRecOps.size()) { 2347 AddRecOps.append(OtherAddRec->op_begin()+i, 2348 OtherAddRec->op_end()); 2349 break; 2350 } 2351 AddRecOps[i] = getAddExpr(AddRecOps[i], 2352 OtherAddRec->getOperand(i)); 2353 } 2354 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2355 } 2356 // Step size has changed, so we cannot guarantee no self-wraparound. 2357 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2358 return getAddExpr(Ops); 2359 } 2360 2361 // Otherwise couldn't fold anything into this recurrence. Move onto the 2362 // next one. 2363 } 2364 2365 // Okay, it looks like we really DO need an add expr. Check to see if we 2366 // already have one, otherwise create a new one. 2367 FoldingSetNodeID ID; 2368 ID.AddInteger(scAddExpr); 2369 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2370 ID.AddPointer(Ops[i]); 2371 void *IP = nullptr; 2372 SCEVAddExpr *S = 2373 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2374 if (!S) { 2375 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2376 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2377 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2378 O, Ops.size()); 2379 UniqueSCEVs.InsertNode(S, IP); 2380 } 2381 S->setNoWrapFlags(Flags); 2382 return S; 2383 } 2384 2385 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2386 uint64_t k = i*j; 2387 if (j > 1 && k / j != i) Overflow = true; 2388 return k; 2389 } 2390 2391 /// Compute the result of "n choose k", the binomial coefficient. If an 2392 /// intermediate computation overflows, Overflow will be set and the return will 2393 /// be garbage. Overflow is not cleared on absence of overflow. 2394 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2395 // We use the multiplicative formula: 2396 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2397 // At each iteration, we take the n-th term of the numeral and divide by the 2398 // (k-n)th term of the denominator. This division will always produce an 2399 // integral result, and helps reduce the chance of overflow in the 2400 // intermediate computations. However, we can still overflow even when the 2401 // final result would fit. 2402 2403 if (n == 0 || n == k) return 1; 2404 if (k > n) return 0; 2405 2406 if (k > n/2) 2407 k = n-k; 2408 2409 uint64_t r = 1; 2410 for (uint64_t i = 1; i <= k; ++i) { 2411 r = umul_ov(r, n-(i-1), Overflow); 2412 r /= i; 2413 } 2414 return r; 2415 } 2416 2417 /// Determine if any of the operands in this SCEV are a constant or if 2418 /// any of the add or multiply expressions in this SCEV contain a constant. 2419 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2420 SmallVector<const SCEV *, 4> Ops; 2421 Ops.push_back(StartExpr); 2422 while (!Ops.empty()) { 2423 const SCEV *CurrentExpr = Ops.pop_back_val(); 2424 if (isa<SCEVConstant>(*CurrentExpr)) 2425 return true; 2426 2427 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2428 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2429 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2430 } 2431 } 2432 return false; 2433 } 2434 2435 /// Get a canonical multiply expression, or something simpler if possible. 2436 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2437 SCEV::NoWrapFlags Flags) { 2438 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2439 "only nuw or nsw allowed"); 2440 assert(!Ops.empty() && "Cannot get empty mul!"); 2441 if (Ops.size() == 1) return Ops[0]; 2442 #ifndef NDEBUG 2443 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2444 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2445 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2446 "SCEVMulExpr operand types don't match!"); 2447 #endif 2448 2449 // Sort by complexity, this groups all similar expression types together. 2450 GroupByComplexity(Ops, &LI); 2451 2452 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2453 2454 // If there are any constants, fold them together. 2455 unsigned Idx = 0; 2456 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2457 2458 // C1*(C2+V) -> C1*C2 + C1*V 2459 if (Ops.size() == 2) 2460 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2461 // If any of Add's ops are Adds or Muls with a constant, 2462 // apply this transformation as well. 2463 if (Add->getNumOperands() == 2) 2464 if (containsConstantSomewhere(Add)) 2465 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2466 getMulExpr(LHSC, Add->getOperand(1))); 2467 2468 ++Idx; 2469 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2470 // We found two constants, fold them together! 2471 ConstantInt *Fold = 2472 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2473 Ops[0] = getConstant(Fold); 2474 Ops.erase(Ops.begin()+1); // Erase the folded element 2475 if (Ops.size() == 1) return Ops[0]; 2476 LHSC = cast<SCEVConstant>(Ops[0]); 2477 } 2478 2479 // If we are left with a constant one being multiplied, strip it off. 2480 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2481 Ops.erase(Ops.begin()); 2482 --Idx; 2483 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2484 // If we have a multiply of zero, it will always be zero. 2485 return Ops[0]; 2486 } else if (Ops[0]->isAllOnesValue()) { 2487 // If we have a mul by -1 of an add, try distributing the -1 among the 2488 // add operands. 2489 if (Ops.size() == 2) { 2490 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2491 SmallVector<const SCEV *, 4> NewOps; 2492 bool AnyFolded = false; 2493 for (const SCEV *AddOp : Add->operands()) { 2494 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2495 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2496 NewOps.push_back(Mul); 2497 } 2498 if (AnyFolded) 2499 return getAddExpr(NewOps); 2500 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2501 // Negation preserves a recurrence's no self-wrap property. 2502 SmallVector<const SCEV *, 4> Operands; 2503 for (const SCEV *AddRecOp : AddRec->operands()) 2504 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2505 2506 return getAddRecExpr(Operands, AddRec->getLoop(), 2507 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2508 } 2509 } 2510 } 2511 2512 if (Ops.size() == 1) 2513 return Ops[0]; 2514 } 2515 2516 // Skip over the add expression until we get to a multiply. 2517 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2518 ++Idx; 2519 2520 // If there are mul operands inline them all into this expression. 2521 if (Idx < Ops.size()) { 2522 bool DeletedMul = false; 2523 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2524 if (Ops.size() > MulOpsInlineThreshold) 2525 break; 2526 // If we have an mul, expand the mul operands onto the end of the operands 2527 // list. 2528 Ops.erase(Ops.begin()+Idx); 2529 Ops.append(Mul->op_begin(), Mul->op_end()); 2530 DeletedMul = true; 2531 } 2532 2533 // If we deleted at least one mul, we added operands to the end of the list, 2534 // and they are not necessarily sorted. Recurse to resort and resimplify 2535 // any operands we just acquired. 2536 if (DeletedMul) 2537 return getMulExpr(Ops); 2538 } 2539 2540 // If there are any add recurrences in the operands list, see if any other 2541 // added values are loop invariant. If so, we can fold them into the 2542 // recurrence. 2543 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2544 ++Idx; 2545 2546 // Scan over all recurrences, trying to fold loop invariants into them. 2547 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2548 // Scan all of the other operands to this mul and add them to the vector if 2549 // they are loop invariant w.r.t. the recurrence. 2550 SmallVector<const SCEV *, 8> LIOps; 2551 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2552 const Loop *AddRecLoop = AddRec->getLoop(); 2553 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2554 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2555 LIOps.push_back(Ops[i]); 2556 Ops.erase(Ops.begin()+i); 2557 --i; --e; 2558 } 2559 2560 // If we found some loop invariants, fold them into the recurrence. 2561 if (!LIOps.empty()) { 2562 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2563 SmallVector<const SCEV *, 4> NewOps; 2564 NewOps.reserve(AddRec->getNumOperands()); 2565 const SCEV *Scale = getMulExpr(LIOps); 2566 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2567 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2568 2569 // Build the new addrec. Propagate the NUW and NSW flags if both the 2570 // outer mul and the inner addrec are guaranteed to have no overflow. 2571 // 2572 // No self-wrap cannot be guaranteed after changing the step size, but 2573 // will be inferred if either NUW or NSW is true. 2574 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2575 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2576 2577 // If all of the other operands were loop invariant, we are done. 2578 if (Ops.size() == 1) return NewRec; 2579 2580 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2581 for (unsigned i = 0;; ++i) 2582 if (Ops[i] == AddRec) { 2583 Ops[i] = NewRec; 2584 break; 2585 } 2586 return getMulExpr(Ops); 2587 } 2588 2589 // Okay, if there weren't any loop invariants to be folded, check to see if 2590 // there are multiple AddRec's with the same loop induction variable being 2591 // multiplied together. If so, we can fold them. 2592 2593 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2594 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2595 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2596 // ]]],+,...up to x=2n}. 2597 // Note that the arguments to choose() are always integers with values 2598 // known at compile time, never SCEV objects. 2599 // 2600 // The implementation avoids pointless extra computations when the two 2601 // addrec's are of different length (mathematically, it's equivalent to 2602 // an infinite stream of zeros on the right). 2603 bool OpsModified = false; 2604 for (unsigned OtherIdx = Idx+1; 2605 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2606 ++OtherIdx) { 2607 const SCEVAddRecExpr *OtherAddRec = 2608 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2609 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2610 continue; 2611 2612 bool Overflow = false; 2613 Type *Ty = AddRec->getType(); 2614 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2615 SmallVector<const SCEV*, 7> AddRecOps; 2616 for (int x = 0, xe = AddRec->getNumOperands() + 2617 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2618 const SCEV *Term = getZero(Ty); 2619 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2620 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2621 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2622 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2623 z < ze && !Overflow; ++z) { 2624 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2625 uint64_t Coeff; 2626 if (LargerThan64Bits) 2627 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2628 else 2629 Coeff = Coeff1*Coeff2; 2630 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2631 const SCEV *Term1 = AddRec->getOperand(y-z); 2632 const SCEV *Term2 = OtherAddRec->getOperand(z); 2633 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2634 } 2635 } 2636 AddRecOps.push_back(Term); 2637 } 2638 if (!Overflow) { 2639 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2640 SCEV::FlagAnyWrap); 2641 if (Ops.size() == 2) return NewAddRec; 2642 Ops[Idx] = NewAddRec; 2643 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2644 OpsModified = true; 2645 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2646 if (!AddRec) 2647 break; 2648 } 2649 } 2650 if (OpsModified) 2651 return getMulExpr(Ops); 2652 2653 // Otherwise couldn't fold anything into this recurrence. Move onto the 2654 // next one. 2655 } 2656 2657 // Okay, it looks like we really DO need an mul expr. Check to see if we 2658 // already have one, otherwise create a new one. 2659 FoldingSetNodeID ID; 2660 ID.AddInteger(scMulExpr); 2661 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2662 ID.AddPointer(Ops[i]); 2663 void *IP = nullptr; 2664 SCEVMulExpr *S = 2665 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2666 if (!S) { 2667 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2668 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2669 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2670 O, Ops.size()); 2671 UniqueSCEVs.InsertNode(S, IP); 2672 } 2673 S->setNoWrapFlags(Flags); 2674 return S; 2675 } 2676 2677 /// Get a canonical unsigned division expression, or something simpler if 2678 /// possible. 2679 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2680 const SCEV *RHS) { 2681 assert(getEffectiveSCEVType(LHS->getType()) == 2682 getEffectiveSCEVType(RHS->getType()) && 2683 "SCEVUDivExpr operand types don't match!"); 2684 2685 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2686 if (RHSC->getValue()->equalsInt(1)) 2687 return LHS; // X udiv 1 --> x 2688 // If the denominator is zero, the result of the udiv is undefined. Don't 2689 // try to analyze it, because the resolution chosen here may differ from 2690 // the resolution chosen in other parts of the compiler. 2691 if (!RHSC->getValue()->isZero()) { 2692 // Determine if the division can be folded into the operands of 2693 // its operands. 2694 // TODO: Generalize this to non-constants by using known-bits information. 2695 Type *Ty = LHS->getType(); 2696 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2697 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2698 // For non-power-of-two values, effectively round the value up to the 2699 // nearest power of two. 2700 if (!RHSC->getAPInt().isPowerOf2()) 2701 ++MaxShiftAmt; 2702 IntegerType *ExtTy = 2703 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2704 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2705 if (const SCEVConstant *Step = 2706 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2707 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2708 const APInt &StepInt = Step->getAPInt(); 2709 const APInt &DivInt = RHSC->getAPInt(); 2710 if (!StepInt.urem(DivInt) && 2711 getZeroExtendExpr(AR, ExtTy) == 2712 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2713 getZeroExtendExpr(Step, ExtTy), 2714 AR->getLoop(), SCEV::FlagAnyWrap)) { 2715 SmallVector<const SCEV *, 4> Operands; 2716 for (const SCEV *Op : AR->operands()) 2717 Operands.push_back(getUDivExpr(Op, RHS)); 2718 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2719 } 2720 /// Get a canonical UDivExpr for a recurrence. 2721 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2722 // We can currently only fold X%N if X is constant. 2723 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2724 if (StartC && !DivInt.urem(StepInt) && 2725 getZeroExtendExpr(AR, ExtTy) == 2726 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2727 getZeroExtendExpr(Step, ExtTy), 2728 AR->getLoop(), SCEV::FlagAnyWrap)) { 2729 const APInt &StartInt = StartC->getAPInt(); 2730 const APInt &StartRem = StartInt.urem(StepInt); 2731 if (StartRem != 0) 2732 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2733 AR->getLoop(), SCEV::FlagNW); 2734 } 2735 } 2736 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2737 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2738 SmallVector<const SCEV *, 4> Operands; 2739 for (const SCEV *Op : M->operands()) 2740 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2741 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2742 // Find an operand that's safely divisible. 2743 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2744 const SCEV *Op = M->getOperand(i); 2745 const SCEV *Div = getUDivExpr(Op, RHSC); 2746 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2747 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2748 M->op_end()); 2749 Operands[i] = Div; 2750 return getMulExpr(Operands); 2751 } 2752 } 2753 } 2754 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2755 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2756 SmallVector<const SCEV *, 4> Operands; 2757 for (const SCEV *Op : A->operands()) 2758 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2759 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2760 Operands.clear(); 2761 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2762 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2763 if (isa<SCEVUDivExpr>(Op) || 2764 getMulExpr(Op, RHS) != A->getOperand(i)) 2765 break; 2766 Operands.push_back(Op); 2767 } 2768 if (Operands.size() == A->getNumOperands()) 2769 return getAddExpr(Operands); 2770 } 2771 } 2772 2773 // Fold if both operands are constant. 2774 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2775 Constant *LHSCV = LHSC->getValue(); 2776 Constant *RHSCV = RHSC->getValue(); 2777 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2778 RHSCV))); 2779 } 2780 } 2781 } 2782 2783 FoldingSetNodeID ID; 2784 ID.AddInteger(scUDivExpr); 2785 ID.AddPointer(LHS); 2786 ID.AddPointer(RHS); 2787 void *IP = nullptr; 2788 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2789 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2790 LHS, RHS); 2791 UniqueSCEVs.InsertNode(S, IP); 2792 return S; 2793 } 2794 2795 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2796 APInt A = C1->getAPInt().abs(); 2797 APInt B = C2->getAPInt().abs(); 2798 uint32_t ABW = A.getBitWidth(); 2799 uint32_t BBW = B.getBitWidth(); 2800 2801 if (ABW > BBW) 2802 B = B.zext(ABW); 2803 else if (ABW < BBW) 2804 A = A.zext(BBW); 2805 2806 return APIntOps::GreatestCommonDivisor(A, B); 2807 } 2808 2809 /// Get a canonical unsigned division expression, or something simpler if 2810 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2811 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2812 /// it's not exact because the udiv may be clearing bits. 2813 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2814 const SCEV *RHS) { 2815 // TODO: we could try to find factors in all sorts of things, but for now we 2816 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2817 // end of this file for inspiration. 2818 2819 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2820 if (!Mul) 2821 return getUDivExpr(LHS, RHS); 2822 2823 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2824 // If the mulexpr multiplies by a constant, then that constant must be the 2825 // first element of the mulexpr. 2826 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2827 if (LHSCst == RHSCst) { 2828 SmallVector<const SCEV *, 2> Operands; 2829 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2830 return getMulExpr(Operands); 2831 } 2832 2833 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2834 // that there's a factor provided by one of the other terms. We need to 2835 // check. 2836 APInt Factor = gcd(LHSCst, RHSCst); 2837 if (!Factor.isIntN(1)) { 2838 LHSCst = 2839 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2840 RHSCst = 2841 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2842 SmallVector<const SCEV *, 2> Operands; 2843 Operands.push_back(LHSCst); 2844 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2845 LHS = getMulExpr(Operands); 2846 RHS = RHSCst; 2847 Mul = dyn_cast<SCEVMulExpr>(LHS); 2848 if (!Mul) 2849 return getUDivExactExpr(LHS, RHS); 2850 } 2851 } 2852 } 2853 2854 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2855 if (Mul->getOperand(i) == RHS) { 2856 SmallVector<const SCEV *, 2> Operands; 2857 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2858 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2859 return getMulExpr(Operands); 2860 } 2861 } 2862 2863 return getUDivExpr(LHS, RHS); 2864 } 2865 2866 /// Get an add recurrence expression for the specified loop. Simplify the 2867 /// expression as much as possible. 2868 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2869 const Loop *L, 2870 SCEV::NoWrapFlags Flags) { 2871 SmallVector<const SCEV *, 4> Operands; 2872 Operands.push_back(Start); 2873 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2874 if (StepChrec->getLoop() == L) { 2875 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2876 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2877 } 2878 2879 Operands.push_back(Step); 2880 return getAddRecExpr(Operands, L, Flags); 2881 } 2882 2883 /// Get an add recurrence expression for the specified loop. Simplify the 2884 /// expression as much as possible. 2885 const SCEV * 2886 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2887 const Loop *L, SCEV::NoWrapFlags Flags) { 2888 if (Operands.size() == 1) return Operands[0]; 2889 #ifndef NDEBUG 2890 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2891 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2892 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2893 "SCEVAddRecExpr operand types don't match!"); 2894 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2895 assert(isLoopInvariant(Operands[i], L) && 2896 "SCEVAddRecExpr operand is not loop-invariant!"); 2897 #endif 2898 2899 if (Operands.back()->isZero()) { 2900 Operands.pop_back(); 2901 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2902 } 2903 2904 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2905 // use that information to infer NUW and NSW flags. However, computing a 2906 // BE count requires calling getAddRecExpr, so we may not yet have a 2907 // meaningful BE count at this point (and if we don't, we'd be stuck 2908 // with a SCEVCouldNotCompute as the cached BE count). 2909 2910 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2911 2912 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2913 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2914 const Loop *NestedLoop = NestedAR->getLoop(); 2915 if (L->contains(NestedLoop) 2916 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2917 : (!NestedLoop->contains(L) && 2918 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2919 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2920 NestedAR->op_end()); 2921 Operands[0] = NestedAR->getStart(); 2922 // AddRecs require their operands be loop-invariant with respect to their 2923 // loops. Don't perform this transformation if it would break this 2924 // requirement. 2925 bool AllInvariant = all_of( 2926 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2927 2928 if (AllInvariant) { 2929 // Create a recurrence for the outer loop with the same step size. 2930 // 2931 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2932 // inner recurrence has the same property. 2933 SCEV::NoWrapFlags OuterFlags = 2934 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2935 2936 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2937 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2938 return isLoopInvariant(Op, NestedLoop); 2939 }); 2940 2941 if (AllInvariant) { 2942 // Ok, both add recurrences are valid after the transformation. 2943 // 2944 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2945 // the outer recurrence has the same property. 2946 SCEV::NoWrapFlags InnerFlags = 2947 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2948 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2949 } 2950 } 2951 // Reset Operands to its original state. 2952 Operands[0] = NestedAR; 2953 } 2954 } 2955 2956 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2957 // already have one, otherwise create a new one. 2958 FoldingSetNodeID ID; 2959 ID.AddInteger(scAddRecExpr); 2960 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2961 ID.AddPointer(Operands[i]); 2962 ID.AddPointer(L); 2963 void *IP = nullptr; 2964 SCEVAddRecExpr *S = 2965 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2966 if (!S) { 2967 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2968 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2969 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2970 O, Operands.size(), L); 2971 UniqueSCEVs.InsertNode(S, IP); 2972 } 2973 S->setNoWrapFlags(Flags); 2974 return S; 2975 } 2976 2977 const SCEV * 2978 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 2979 const SmallVectorImpl<const SCEV *> &IndexExprs, 2980 bool InBounds) { 2981 // getSCEV(Base)->getType() has the same address space as Base->getType() 2982 // because SCEV::getType() preserves the address space. 2983 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 2984 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 2985 // instruction to its SCEV, because the Instruction may be guarded by control 2986 // flow and the no-overflow bits may not be valid for the expression in any 2987 // context. This can be fixed similarly to how these flags are handled for 2988 // adds. 2989 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 2990 2991 const SCEV *TotalOffset = getZero(IntPtrTy); 2992 // The address space is unimportant. The first thing we do on CurTy is getting 2993 // its element type. 2994 Type *CurTy = PointerType::getUnqual(PointeeType); 2995 for (const SCEV *IndexExpr : IndexExprs) { 2996 // Compute the (potentially symbolic) offset in bytes for this index. 2997 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2998 // For a struct, add the member offset. 2999 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3000 unsigned FieldNo = Index->getZExtValue(); 3001 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3002 3003 // Add the field offset to the running total offset. 3004 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3005 3006 // Update CurTy to the type of the field at Index. 3007 CurTy = STy->getTypeAtIndex(Index); 3008 } else { 3009 // Update CurTy to its element type. 3010 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3011 // For an array, add the element offset, explicitly scaled. 3012 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3013 // Getelementptr indices are signed. 3014 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3015 3016 // Multiply the index by the element size to compute the element offset. 3017 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3018 3019 // Add the element offset to the running total offset. 3020 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3021 } 3022 } 3023 3024 // Add the total offset from all the GEP indices to the base. 3025 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3026 } 3027 3028 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3029 const SCEV *RHS) { 3030 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3031 return getSMaxExpr(Ops); 3032 } 3033 3034 const SCEV * 3035 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3036 assert(!Ops.empty() && "Cannot get empty smax!"); 3037 if (Ops.size() == 1) return Ops[0]; 3038 #ifndef NDEBUG 3039 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3040 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3041 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3042 "SCEVSMaxExpr operand types don't match!"); 3043 #endif 3044 3045 // Sort by complexity, this groups all similar expression types together. 3046 GroupByComplexity(Ops, &LI); 3047 3048 // If there are any constants, fold them together. 3049 unsigned Idx = 0; 3050 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3051 ++Idx; 3052 assert(Idx < Ops.size()); 3053 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3054 // We found two constants, fold them together! 3055 ConstantInt *Fold = ConstantInt::get( 3056 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3057 Ops[0] = getConstant(Fold); 3058 Ops.erase(Ops.begin()+1); // Erase the folded element 3059 if (Ops.size() == 1) return Ops[0]; 3060 LHSC = cast<SCEVConstant>(Ops[0]); 3061 } 3062 3063 // If we are left with a constant minimum-int, strip it off. 3064 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3065 Ops.erase(Ops.begin()); 3066 --Idx; 3067 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3068 // If we have an smax with a constant maximum-int, it will always be 3069 // maximum-int. 3070 return Ops[0]; 3071 } 3072 3073 if (Ops.size() == 1) return Ops[0]; 3074 } 3075 3076 // Find the first SMax 3077 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3078 ++Idx; 3079 3080 // Check to see if one of the operands is an SMax. If so, expand its operands 3081 // onto our operand list, and recurse to simplify. 3082 if (Idx < Ops.size()) { 3083 bool DeletedSMax = false; 3084 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3085 Ops.erase(Ops.begin()+Idx); 3086 Ops.append(SMax->op_begin(), SMax->op_end()); 3087 DeletedSMax = true; 3088 } 3089 3090 if (DeletedSMax) 3091 return getSMaxExpr(Ops); 3092 } 3093 3094 // Okay, check to see if the same value occurs in the operand list twice. If 3095 // so, delete one. Since we sorted the list, these values are required to 3096 // be adjacent. 3097 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3098 // X smax Y smax Y --> X smax Y 3099 // X smax Y --> X, if X is always greater than Y 3100 if (Ops[i] == Ops[i+1] || 3101 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3102 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3103 --i; --e; 3104 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3105 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3106 --i; --e; 3107 } 3108 3109 if (Ops.size() == 1) return Ops[0]; 3110 3111 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3112 3113 // Okay, it looks like we really DO need an smax expr. Check to see if we 3114 // already have one, otherwise create a new one. 3115 FoldingSetNodeID ID; 3116 ID.AddInteger(scSMaxExpr); 3117 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3118 ID.AddPointer(Ops[i]); 3119 void *IP = nullptr; 3120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3121 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3122 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3123 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3124 O, Ops.size()); 3125 UniqueSCEVs.InsertNode(S, IP); 3126 return S; 3127 } 3128 3129 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3130 const SCEV *RHS) { 3131 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3132 return getUMaxExpr(Ops); 3133 } 3134 3135 const SCEV * 3136 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3137 assert(!Ops.empty() && "Cannot get empty umax!"); 3138 if (Ops.size() == 1) return Ops[0]; 3139 #ifndef NDEBUG 3140 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3141 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3142 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3143 "SCEVUMaxExpr operand types don't match!"); 3144 #endif 3145 3146 // Sort by complexity, this groups all similar expression types together. 3147 GroupByComplexity(Ops, &LI); 3148 3149 // If there are any constants, fold them together. 3150 unsigned Idx = 0; 3151 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3152 ++Idx; 3153 assert(Idx < Ops.size()); 3154 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3155 // We found two constants, fold them together! 3156 ConstantInt *Fold = ConstantInt::get( 3157 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3158 Ops[0] = getConstant(Fold); 3159 Ops.erase(Ops.begin()+1); // Erase the folded element 3160 if (Ops.size() == 1) return Ops[0]; 3161 LHSC = cast<SCEVConstant>(Ops[0]); 3162 } 3163 3164 // If we are left with a constant minimum-int, strip it off. 3165 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3166 Ops.erase(Ops.begin()); 3167 --Idx; 3168 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3169 // If we have an umax with a constant maximum-int, it will always be 3170 // maximum-int. 3171 return Ops[0]; 3172 } 3173 3174 if (Ops.size() == 1) return Ops[0]; 3175 } 3176 3177 // Find the first UMax 3178 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3179 ++Idx; 3180 3181 // Check to see if one of the operands is a UMax. If so, expand its operands 3182 // onto our operand list, and recurse to simplify. 3183 if (Idx < Ops.size()) { 3184 bool DeletedUMax = false; 3185 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3186 Ops.erase(Ops.begin()+Idx); 3187 Ops.append(UMax->op_begin(), UMax->op_end()); 3188 DeletedUMax = true; 3189 } 3190 3191 if (DeletedUMax) 3192 return getUMaxExpr(Ops); 3193 } 3194 3195 // Okay, check to see if the same value occurs in the operand list twice. If 3196 // so, delete one. Since we sorted the list, these values are required to 3197 // be adjacent. 3198 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3199 // X umax Y umax Y --> X umax Y 3200 // X umax Y --> X, if X is always greater than Y 3201 if (Ops[i] == Ops[i+1] || 3202 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3203 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3204 --i; --e; 3205 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3206 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3207 --i; --e; 3208 } 3209 3210 if (Ops.size() == 1) return Ops[0]; 3211 3212 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3213 3214 // Okay, it looks like we really DO need a umax expr. Check to see if we 3215 // already have one, otherwise create a new one. 3216 FoldingSetNodeID ID; 3217 ID.AddInteger(scUMaxExpr); 3218 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3219 ID.AddPointer(Ops[i]); 3220 void *IP = nullptr; 3221 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3222 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3223 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3224 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3225 O, Ops.size()); 3226 UniqueSCEVs.InsertNode(S, IP); 3227 return S; 3228 } 3229 3230 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3231 const SCEV *RHS) { 3232 // ~smax(~x, ~y) == smin(x, y). 3233 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3234 } 3235 3236 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3237 const SCEV *RHS) { 3238 // ~umax(~x, ~y) == umin(x, y) 3239 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3240 } 3241 3242 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3243 // We can bypass creating a target-independent 3244 // constant expression and then folding it back into a ConstantInt. 3245 // This is just a compile-time optimization. 3246 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3247 } 3248 3249 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3250 StructType *STy, 3251 unsigned FieldNo) { 3252 // We can bypass creating a target-independent 3253 // constant expression and then folding it back into a ConstantInt. 3254 // This is just a compile-time optimization. 3255 return getConstant( 3256 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3257 } 3258 3259 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3260 // Don't attempt to do anything other than create a SCEVUnknown object 3261 // here. createSCEV only calls getUnknown after checking for all other 3262 // interesting possibilities, and any other code that calls getUnknown 3263 // is doing so in order to hide a value from SCEV canonicalization. 3264 3265 FoldingSetNodeID ID; 3266 ID.AddInteger(scUnknown); 3267 ID.AddPointer(V); 3268 void *IP = nullptr; 3269 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3270 assert(cast<SCEVUnknown>(S)->getValue() == V && 3271 "Stale SCEVUnknown in uniquing map!"); 3272 return S; 3273 } 3274 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3275 FirstUnknown); 3276 FirstUnknown = cast<SCEVUnknown>(S); 3277 UniqueSCEVs.InsertNode(S, IP); 3278 return S; 3279 } 3280 3281 //===----------------------------------------------------------------------===// 3282 // Basic SCEV Analysis and PHI Idiom Recognition Code 3283 // 3284 3285 /// Test if values of the given type are analyzable within the SCEV 3286 /// framework. This primarily includes integer types, and it can optionally 3287 /// include pointer types if the ScalarEvolution class has access to 3288 /// target-specific information. 3289 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3290 // Integers and pointers are always SCEVable. 3291 return Ty->isIntegerTy() || Ty->isPointerTy(); 3292 } 3293 3294 /// Return the size in bits of the specified type, for which isSCEVable must 3295 /// return true. 3296 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3297 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3298 return getDataLayout().getTypeSizeInBits(Ty); 3299 } 3300 3301 /// Return a type with the same bitwidth as the given type and which represents 3302 /// how SCEV will treat the given type, for which isSCEVable must return 3303 /// true. For pointer types, this is the pointer-sized integer type. 3304 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3305 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3306 3307 if (Ty->isIntegerTy()) 3308 return Ty; 3309 3310 // The only other support type is pointer. 3311 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3312 return getDataLayout().getIntPtrType(Ty); 3313 } 3314 3315 const SCEV *ScalarEvolution::getCouldNotCompute() { 3316 return CouldNotCompute.get(); 3317 } 3318 3319 3320 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3321 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3322 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3323 // is set iff if find such SCEVUnknown. 3324 // 3325 struct FindInvalidSCEVUnknown { 3326 bool FindOne; 3327 FindInvalidSCEVUnknown() { FindOne = false; } 3328 bool follow(const SCEV *S) { 3329 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3330 case scConstant: 3331 return false; 3332 case scUnknown: 3333 if (!cast<SCEVUnknown>(S)->getValue()) 3334 FindOne = true; 3335 return false; 3336 default: 3337 return true; 3338 } 3339 } 3340 bool isDone() const { return FindOne; } 3341 }; 3342 3343 FindInvalidSCEVUnknown F; 3344 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3345 ST.visitAll(S); 3346 3347 return !F.FindOne; 3348 } 3349 3350 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3351 // Helper class working with SCEVTraversal to figure out if a SCEV contains a 3352 // sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set iff 3353 // if such sub scAddRecExpr type SCEV is found. 3354 struct FindAddRecurrence { 3355 bool FoundOne; 3356 FindAddRecurrence() : FoundOne(false) {} 3357 3358 bool follow(const SCEV *S) { 3359 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3360 case scAddRecExpr: 3361 FoundOne = true; 3362 case scConstant: 3363 case scUnknown: 3364 case scCouldNotCompute: 3365 return false; 3366 default: 3367 return true; 3368 } 3369 } 3370 bool isDone() const { return FoundOne; } 3371 }; 3372 3373 HasRecMapType::iterator I = HasRecMap.find(S); 3374 if (I != HasRecMap.end()) 3375 return I->second; 3376 3377 FindAddRecurrence F; 3378 SCEVTraversal<FindAddRecurrence> ST(F); 3379 ST.visitAll(S); 3380 HasRecMap.insert({S, F.FoundOne}); 3381 return F.FoundOne; 3382 } 3383 3384 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3385 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3386 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3387 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3388 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3389 if (!Add) 3390 return {S, nullptr}; 3391 3392 if (Add->getNumOperands() != 2) 3393 return {S, nullptr}; 3394 3395 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3396 if (!ConstOp) 3397 return {S, nullptr}; 3398 3399 return {Add->getOperand(1), ConstOp->getValue()}; 3400 } 3401 3402 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3403 /// by the value and offset from any ValueOffsetPair in the set. 3404 SetVector<ScalarEvolution::ValueOffsetPair> * 3405 ScalarEvolution::getSCEVValues(const SCEV *S) { 3406 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3407 if (SI == ExprValueMap.end()) 3408 return nullptr; 3409 #ifndef NDEBUG 3410 if (VerifySCEVMap) { 3411 // Check there is no dangling Value in the set returned. 3412 for (const auto &VE : SI->second) 3413 assert(ValueExprMap.count(VE.first)); 3414 } 3415 #endif 3416 return &SI->second; 3417 } 3418 3419 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3420 /// cannot be used separately. eraseValueFromMap should be used to remove 3421 /// V from ValueExprMap and ExprValueMap at the same time. 3422 void ScalarEvolution::eraseValueFromMap(Value *V) { 3423 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3424 if (I != ValueExprMap.end()) { 3425 const SCEV *S = I->second; 3426 // Remove {V, 0} from the set of ExprValueMap[S] 3427 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3428 SV->remove({V, nullptr}); 3429 3430 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3431 const SCEV *Stripped; 3432 ConstantInt *Offset; 3433 std::tie(Stripped, Offset) = splitAddExpr(S); 3434 if (Offset != nullptr) { 3435 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3436 SV->remove({V, Offset}); 3437 } 3438 ValueExprMap.erase(V); 3439 } 3440 } 3441 3442 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3443 /// create a new one. 3444 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3445 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3446 3447 const SCEV *S = getExistingSCEV(V); 3448 if (S == nullptr) { 3449 S = createSCEV(V); 3450 // During PHI resolution, it is possible to create two SCEVs for the same 3451 // V, so it is needed to double check whether V->S is inserted into 3452 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3453 std::pair<ValueExprMapType::iterator, bool> Pair = 3454 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3455 if (Pair.second) { 3456 ExprValueMap[S].insert({V, nullptr}); 3457 3458 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3459 // ExprValueMap. 3460 const SCEV *Stripped = S; 3461 ConstantInt *Offset = nullptr; 3462 std::tie(Stripped, Offset) = splitAddExpr(S); 3463 // If stripped is SCEVUnknown, don't bother to save 3464 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3465 // increase the complexity of the expansion code. 3466 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3467 // because it may generate add/sub instead of GEP in SCEV expansion. 3468 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3469 !isa<GetElementPtrInst>(V)) 3470 ExprValueMap[Stripped].insert({V, Offset}); 3471 } 3472 } 3473 return S; 3474 } 3475 3476 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3477 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3478 3479 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3480 if (I != ValueExprMap.end()) { 3481 const SCEV *S = I->second; 3482 if (checkValidity(S)) 3483 return S; 3484 eraseValueFromMap(V); 3485 forgetMemoizedResults(S); 3486 } 3487 return nullptr; 3488 } 3489 3490 /// Return a SCEV corresponding to -V = -1*V 3491 /// 3492 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3493 SCEV::NoWrapFlags Flags) { 3494 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3495 return getConstant( 3496 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3497 3498 Type *Ty = V->getType(); 3499 Ty = getEffectiveSCEVType(Ty); 3500 return getMulExpr( 3501 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3502 } 3503 3504 /// Return a SCEV corresponding to ~V = -1-V 3505 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3506 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3507 return getConstant( 3508 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3509 3510 Type *Ty = V->getType(); 3511 Ty = getEffectiveSCEVType(Ty); 3512 const SCEV *AllOnes = 3513 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3514 return getMinusSCEV(AllOnes, V); 3515 } 3516 3517 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3518 SCEV::NoWrapFlags Flags) { 3519 // Fast path: X - X --> 0. 3520 if (LHS == RHS) 3521 return getZero(LHS->getType()); 3522 3523 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3524 // makes it so that we cannot make much use of NUW. 3525 auto AddFlags = SCEV::FlagAnyWrap; 3526 const bool RHSIsNotMinSigned = 3527 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3528 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3529 // Let M be the minimum representable signed value. Then (-1)*RHS 3530 // signed-wraps if and only if RHS is M. That can happen even for 3531 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3532 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3533 // (-1)*RHS, we need to prove that RHS != M. 3534 // 3535 // If LHS is non-negative and we know that LHS - RHS does not 3536 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3537 // either by proving that RHS > M or that LHS >= 0. 3538 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3539 AddFlags = SCEV::FlagNSW; 3540 } 3541 } 3542 3543 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3544 // RHS is NSW and LHS >= 0. 3545 // 3546 // The difficulty here is that the NSW flag may have been proven 3547 // relative to a loop that is to be found in a recurrence in LHS and 3548 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3549 // larger scope than intended. 3550 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3551 3552 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3553 } 3554 3555 const SCEV * 3556 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3557 Type *SrcTy = V->getType(); 3558 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3559 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3560 "Cannot truncate or zero extend with non-integer arguments!"); 3561 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3562 return V; // No conversion 3563 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3564 return getTruncateExpr(V, Ty); 3565 return getZeroExtendExpr(V, Ty); 3566 } 3567 3568 const SCEV * 3569 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3570 Type *Ty) { 3571 Type *SrcTy = V->getType(); 3572 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3573 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3574 "Cannot truncate or zero extend with non-integer arguments!"); 3575 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3576 return V; // No conversion 3577 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3578 return getTruncateExpr(V, Ty); 3579 return getSignExtendExpr(V, Ty); 3580 } 3581 3582 const SCEV * 3583 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3584 Type *SrcTy = V->getType(); 3585 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3586 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3587 "Cannot noop or zero extend with non-integer arguments!"); 3588 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3589 "getNoopOrZeroExtend cannot truncate!"); 3590 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3591 return V; // No conversion 3592 return getZeroExtendExpr(V, Ty); 3593 } 3594 3595 const SCEV * 3596 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3597 Type *SrcTy = V->getType(); 3598 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3599 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3600 "Cannot noop or sign extend with non-integer arguments!"); 3601 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3602 "getNoopOrSignExtend cannot truncate!"); 3603 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3604 return V; // No conversion 3605 return getSignExtendExpr(V, Ty); 3606 } 3607 3608 const SCEV * 3609 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3610 Type *SrcTy = V->getType(); 3611 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3612 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3613 "Cannot noop or any extend with non-integer arguments!"); 3614 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3615 "getNoopOrAnyExtend cannot truncate!"); 3616 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3617 return V; // No conversion 3618 return getAnyExtendExpr(V, Ty); 3619 } 3620 3621 const SCEV * 3622 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3623 Type *SrcTy = V->getType(); 3624 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3625 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3626 "Cannot truncate or noop with non-integer arguments!"); 3627 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3628 "getTruncateOrNoop cannot extend!"); 3629 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3630 return V; // No conversion 3631 return getTruncateExpr(V, Ty); 3632 } 3633 3634 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3635 const SCEV *RHS) { 3636 const SCEV *PromotedLHS = LHS; 3637 const SCEV *PromotedRHS = RHS; 3638 3639 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3640 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3641 else 3642 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3643 3644 return getUMaxExpr(PromotedLHS, PromotedRHS); 3645 } 3646 3647 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3648 const SCEV *RHS) { 3649 const SCEV *PromotedLHS = LHS; 3650 const SCEV *PromotedRHS = RHS; 3651 3652 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3653 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3654 else 3655 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3656 3657 return getUMinExpr(PromotedLHS, PromotedRHS); 3658 } 3659 3660 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3661 // A pointer operand may evaluate to a nonpointer expression, such as null. 3662 if (!V->getType()->isPointerTy()) 3663 return V; 3664 3665 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3666 return getPointerBase(Cast->getOperand()); 3667 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3668 const SCEV *PtrOp = nullptr; 3669 for (const SCEV *NAryOp : NAry->operands()) { 3670 if (NAryOp->getType()->isPointerTy()) { 3671 // Cannot find the base of an expression with multiple pointer operands. 3672 if (PtrOp) 3673 return V; 3674 PtrOp = NAryOp; 3675 } 3676 } 3677 if (!PtrOp) 3678 return V; 3679 return getPointerBase(PtrOp); 3680 } 3681 return V; 3682 } 3683 3684 /// Push users of the given Instruction onto the given Worklist. 3685 static void 3686 PushDefUseChildren(Instruction *I, 3687 SmallVectorImpl<Instruction *> &Worklist) { 3688 // Push the def-use children onto the Worklist stack. 3689 for (User *U : I->users()) 3690 Worklist.push_back(cast<Instruction>(U)); 3691 } 3692 3693 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3694 SmallVector<Instruction *, 16> Worklist; 3695 PushDefUseChildren(PN, Worklist); 3696 3697 SmallPtrSet<Instruction *, 8> Visited; 3698 Visited.insert(PN); 3699 while (!Worklist.empty()) { 3700 Instruction *I = Worklist.pop_back_val(); 3701 if (!Visited.insert(I).second) 3702 continue; 3703 3704 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3705 if (It != ValueExprMap.end()) { 3706 const SCEV *Old = It->second; 3707 3708 // Short-circuit the def-use traversal if the symbolic name 3709 // ceases to appear in expressions. 3710 if (Old != SymName && !hasOperand(Old, SymName)) 3711 continue; 3712 3713 // SCEVUnknown for a PHI either means that it has an unrecognized 3714 // structure, it's a PHI that's in the progress of being computed 3715 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3716 // additional loop trip count information isn't going to change anything. 3717 // In the second case, createNodeForPHI will perform the necessary 3718 // updates on its own when it gets to that point. In the third, we do 3719 // want to forget the SCEVUnknown. 3720 if (!isa<PHINode>(I) || 3721 !isa<SCEVUnknown>(Old) || 3722 (I != PN && Old == SymName)) { 3723 eraseValueFromMap(It->first); 3724 forgetMemoizedResults(Old); 3725 } 3726 } 3727 3728 PushDefUseChildren(I, Worklist); 3729 } 3730 } 3731 3732 namespace { 3733 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3734 public: 3735 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3736 ScalarEvolution &SE) { 3737 SCEVInitRewriter Rewriter(L, SE); 3738 const SCEV *Result = Rewriter.visit(S); 3739 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3740 } 3741 3742 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3743 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3744 3745 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3746 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3747 Valid = false; 3748 return Expr; 3749 } 3750 3751 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3752 // Only allow AddRecExprs for this loop. 3753 if (Expr->getLoop() == L) 3754 return Expr->getStart(); 3755 Valid = false; 3756 return Expr; 3757 } 3758 3759 bool isValid() { return Valid; } 3760 3761 private: 3762 const Loop *L; 3763 bool Valid; 3764 }; 3765 3766 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3767 public: 3768 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3769 ScalarEvolution &SE) { 3770 SCEVShiftRewriter Rewriter(L, SE); 3771 const SCEV *Result = Rewriter.visit(S); 3772 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3773 } 3774 3775 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3776 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3777 3778 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3779 // Only allow AddRecExprs for this loop. 3780 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3781 Valid = false; 3782 return Expr; 3783 } 3784 3785 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3786 if (Expr->getLoop() == L && Expr->isAffine()) 3787 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3788 Valid = false; 3789 return Expr; 3790 } 3791 bool isValid() { return Valid; } 3792 3793 private: 3794 const Loop *L; 3795 bool Valid; 3796 }; 3797 } // end anonymous namespace 3798 3799 SCEV::NoWrapFlags 3800 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3801 if (!AR->isAffine()) 3802 return SCEV::FlagAnyWrap; 3803 3804 typedef OverflowingBinaryOperator OBO; 3805 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3806 3807 if (!AR->hasNoSignedWrap()) { 3808 ConstantRange AddRecRange = getSignedRange(AR); 3809 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3810 3811 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3812 Instruction::Add, IncRange, OBO::NoSignedWrap); 3813 if (NSWRegion.contains(AddRecRange)) 3814 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3815 } 3816 3817 if (!AR->hasNoUnsignedWrap()) { 3818 ConstantRange AddRecRange = getUnsignedRange(AR); 3819 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3820 3821 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3822 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3823 if (NUWRegion.contains(AddRecRange)) 3824 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3825 } 3826 3827 return Result; 3828 } 3829 3830 namespace { 3831 /// Represents an abstract binary operation. This may exist as a 3832 /// normal instruction or constant expression, or may have been 3833 /// derived from an expression tree. 3834 struct BinaryOp { 3835 unsigned Opcode; 3836 Value *LHS; 3837 Value *RHS; 3838 bool IsNSW; 3839 bool IsNUW; 3840 3841 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3842 /// constant expression. 3843 Operator *Op; 3844 3845 explicit BinaryOp(Operator *Op) 3846 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3847 IsNSW(false), IsNUW(false), Op(Op) { 3848 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3849 IsNSW = OBO->hasNoSignedWrap(); 3850 IsNUW = OBO->hasNoUnsignedWrap(); 3851 } 3852 } 3853 3854 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3855 bool IsNUW = false) 3856 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3857 Op(nullptr) {} 3858 }; 3859 } 3860 3861 3862 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3863 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3864 auto *Op = dyn_cast<Operator>(V); 3865 if (!Op) 3866 return None; 3867 3868 // Implementation detail: all the cleverness here should happen without 3869 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3870 // SCEV expressions when possible, and we should not break that. 3871 3872 switch (Op->getOpcode()) { 3873 case Instruction::Add: 3874 case Instruction::Sub: 3875 case Instruction::Mul: 3876 case Instruction::UDiv: 3877 case Instruction::And: 3878 case Instruction::Or: 3879 case Instruction::AShr: 3880 case Instruction::Shl: 3881 return BinaryOp(Op); 3882 3883 case Instruction::Xor: 3884 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3885 // If the RHS of the xor is a signbit, then this is just an add. 3886 // Instcombine turns add of signbit into xor as a strength reduction step. 3887 if (RHSC->getValue().isSignBit()) 3888 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3889 return BinaryOp(Op); 3890 3891 case Instruction::LShr: 3892 // Turn logical shift right of a constant into a unsigned divide. 3893 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3894 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3895 3896 // If the shift count is not less than the bitwidth, the result of 3897 // the shift is undefined. Don't try to analyze it, because the 3898 // resolution chosen here may differ from the resolution chosen in 3899 // other parts of the compiler. 3900 if (SA->getValue().ult(BitWidth)) { 3901 Constant *X = 3902 ConstantInt::get(SA->getContext(), 3903 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3904 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3905 } 3906 } 3907 return BinaryOp(Op); 3908 3909 case Instruction::ExtractValue: { 3910 auto *EVI = cast<ExtractValueInst>(Op); 3911 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3912 break; 3913 3914 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3915 if (!CI) 3916 break; 3917 3918 if (auto *F = CI->getCalledFunction()) 3919 switch (F->getIntrinsicID()) { 3920 case Intrinsic::sadd_with_overflow: 3921 case Intrinsic::uadd_with_overflow: { 3922 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3923 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3924 CI->getArgOperand(1)); 3925 3926 // Now that we know that all uses of the arithmetic-result component of 3927 // CI are guarded by the overflow check, we can go ahead and pretend 3928 // that the arithmetic is non-overflowing. 3929 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3930 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3931 CI->getArgOperand(1), /* IsNSW = */ true, 3932 /* IsNUW = */ false); 3933 else 3934 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3935 CI->getArgOperand(1), /* IsNSW = */ false, 3936 /* IsNUW*/ true); 3937 } 3938 3939 case Intrinsic::ssub_with_overflow: 3940 case Intrinsic::usub_with_overflow: 3941 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3942 CI->getArgOperand(1)); 3943 3944 case Intrinsic::smul_with_overflow: 3945 case Intrinsic::umul_with_overflow: 3946 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3947 CI->getArgOperand(1)); 3948 default: 3949 break; 3950 } 3951 } 3952 3953 default: 3954 break; 3955 } 3956 3957 return None; 3958 } 3959 3960 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3961 const Loop *L = LI.getLoopFor(PN->getParent()); 3962 if (!L || L->getHeader() != PN->getParent()) 3963 return nullptr; 3964 3965 // The loop may have multiple entrances or multiple exits; we can analyze 3966 // this phi as an addrec if it has a unique entry value and a unique 3967 // backedge value. 3968 Value *BEValueV = nullptr, *StartValueV = nullptr; 3969 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3970 Value *V = PN->getIncomingValue(i); 3971 if (L->contains(PN->getIncomingBlock(i))) { 3972 if (!BEValueV) { 3973 BEValueV = V; 3974 } else if (BEValueV != V) { 3975 BEValueV = nullptr; 3976 break; 3977 } 3978 } else if (!StartValueV) { 3979 StartValueV = V; 3980 } else if (StartValueV != V) { 3981 StartValueV = nullptr; 3982 break; 3983 } 3984 } 3985 if (BEValueV && StartValueV) { 3986 // While we are analyzing this PHI node, handle its value symbolically. 3987 const SCEV *SymbolicName = getUnknown(PN); 3988 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3989 "PHI node already processed?"); 3990 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 3991 3992 // Using this symbolic name for the PHI, analyze the value coming around 3993 // the back-edge. 3994 const SCEV *BEValue = getSCEV(BEValueV); 3995 3996 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3997 // has a special value for the first iteration of the loop. 3998 3999 // If the value coming around the backedge is an add with the symbolic 4000 // value we just inserted, then we found a simple induction variable! 4001 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4002 // If there is a single occurrence of the symbolic value, replace it 4003 // with a recurrence. 4004 unsigned FoundIndex = Add->getNumOperands(); 4005 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4006 if (Add->getOperand(i) == SymbolicName) 4007 if (FoundIndex == e) { 4008 FoundIndex = i; 4009 break; 4010 } 4011 4012 if (FoundIndex != Add->getNumOperands()) { 4013 // Create an add with everything but the specified operand. 4014 SmallVector<const SCEV *, 8> Ops; 4015 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4016 if (i != FoundIndex) 4017 Ops.push_back(Add->getOperand(i)); 4018 const SCEV *Accum = getAddExpr(Ops); 4019 4020 // This is not a valid addrec if the step amount is varying each 4021 // loop iteration, but is not itself an addrec in this loop. 4022 if (isLoopInvariant(Accum, L) || 4023 (isa<SCEVAddRecExpr>(Accum) && 4024 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4025 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4026 4027 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4028 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4029 if (BO->IsNUW) 4030 Flags = setFlags(Flags, SCEV::FlagNUW); 4031 if (BO->IsNSW) 4032 Flags = setFlags(Flags, SCEV::FlagNSW); 4033 } 4034 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4035 // If the increment is an inbounds GEP, then we know the address 4036 // space cannot be wrapped around. We cannot make any guarantee 4037 // about signed or unsigned overflow because pointers are 4038 // unsigned but we may have a negative index from the base 4039 // pointer. We can guarantee that no unsigned wrap occurs if the 4040 // indices form a positive value. 4041 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4042 Flags = setFlags(Flags, SCEV::FlagNW); 4043 4044 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4045 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4046 Flags = setFlags(Flags, SCEV::FlagNUW); 4047 } 4048 4049 // We cannot transfer nuw and nsw flags from subtraction 4050 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4051 // for instance. 4052 } 4053 4054 const SCEV *StartVal = getSCEV(StartValueV); 4055 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4056 4057 // Okay, for the entire analysis of this edge we assumed the PHI 4058 // to be symbolic. We now need to go back and purge all of the 4059 // entries for the scalars that use the symbolic expression. 4060 forgetSymbolicName(PN, SymbolicName); 4061 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4062 4063 // We can add Flags to the post-inc expression only if we 4064 // know that it us *undefined behavior* for BEValueV to 4065 // overflow. 4066 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4067 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4068 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4069 4070 return PHISCEV; 4071 } 4072 } 4073 } else { 4074 // Otherwise, this could be a loop like this: 4075 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4076 // In this case, j = {1,+,1} and BEValue is j. 4077 // Because the other in-value of i (0) fits the evolution of BEValue 4078 // i really is an addrec evolution. 4079 // 4080 // We can generalize this saying that i is the shifted value of BEValue 4081 // by one iteration: 4082 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4083 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4084 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4085 if (Shifted != getCouldNotCompute() && 4086 Start != getCouldNotCompute()) { 4087 const SCEV *StartVal = getSCEV(StartValueV); 4088 if (Start == StartVal) { 4089 // Okay, for the entire analysis of this edge we assumed the PHI 4090 // to be symbolic. We now need to go back and purge all of the 4091 // entries for the scalars that use the symbolic expression. 4092 forgetSymbolicName(PN, SymbolicName); 4093 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4094 return Shifted; 4095 } 4096 } 4097 } 4098 4099 // Remove the temporary PHI node SCEV that has been inserted while intending 4100 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4101 // as it will prevent later (possibly simpler) SCEV expressions to be added 4102 // to the ValueExprMap. 4103 eraseValueFromMap(PN); 4104 } 4105 4106 return nullptr; 4107 } 4108 4109 // Checks if the SCEV S is available at BB. S is considered available at BB 4110 // if S can be materialized at BB without introducing a fault. 4111 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4112 BasicBlock *BB) { 4113 struct CheckAvailable { 4114 bool TraversalDone = false; 4115 bool Available = true; 4116 4117 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4118 BasicBlock *BB = nullptr; 4119 DominatorTree &DT; 4120 4121 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4122 : L(L), BB(BB), DT(DT) {} 4123 4124 bool setUnavailable() { 4125 TraversalDone = true; 4126 Available = false; 4127 return false; 4128 } 4129 4130 bool follow(const SCEV *S) { 4131 switch (S->getSCEVType()) { 4132 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4133 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4134 // These expressions are available if their operand(s) is/are. 4135 return true; 4136 4137 case scAddRecExpr: { 4138 // We allow add recurrences that are on the loop BB is in, or some 4139 // outer loop. This guarantees availability because the value of the 4140 // add recurrence at BB is simply the "current" value of the induction 4141 // variable. We can relax this in the future; for instance an add 4142 // recurrence on a sibling dominating loop is also available at BB. 4143 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4144 if (L && (ARLoop == L || ARLoop->contains(L))) 4145 return true; 4146 4147 return setUnavailable(); 4148 } 4149 4150 case scUnknown: { 4151 // For SCEVUnknown, we check for simple dominance. 4152 const auto *SU = cast<SCEVUnknown>(S); 4153 Value *V = SU->getValue(); 4154 4155 if (isa<Argument>(V)) 4156 return false; 4157 4158 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4159 return false; 4160 4161 return setUnavailable(); 4162 } 4163 4164 case scUDivExpr: 4165 case scCouldNotCompute: 4166 // We do not try to smart about these at all. 4167 return setUnavailable(); 4168 } 4169 llvm_unreachable("switch should be fully covered!"); 4170 } 4171 4172 bool isDone() { return TraversalDone; } 4173 }; 4174 4175 CheckAvailable CA(L, BB, DT); 4176 SCEVTraversal<CheckAvailable> ST(CA); 4177 4178 ST.visitAll(S); 4179 return CA.Available; 4180 } 4181 4182 // Try to match a control flow sequence that branches out at BI and merges back 4183 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4184 // match. 4185 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4186 Value *&C, Value *&LHS, Value *&RHS) { 4187 C = BI->getCondition(); 4188 4189 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4190 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4191 4192 if (!LeftEdge.isSingleEdge()) 4193 return false; 4194 4195 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4196 4197 Use &LeftUse = Merge->getOperandUse(0); 4198 Use &RightUse = Merge->getOperandUse(1); 4199 4200 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4201 LHS = LeftUse; 4202 RHS = RightUse; 4203 return true; 4204 } 4205 4206 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4207 LHS = RightUse; 4208 RHS = LeftUse; 4209 return true; 4210 } 4211 4212 return false; 4213 } 4214 4215 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4216 auto IsReachable = 4217 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4218 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4219 const Loop *L = LI.getLoopFor(PN->getParent()); 4220 4221 // We don't want to break LCSSA, even in a SCEV expression tree. 4222 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4223 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4224 return nullptr; 4225 4226 // Try to match 4227 // 4228 // br %cond, label %left, label %right 4229 // left: 4230 // br label %merge 4231 // right: 4232 // br label %merge 4233 // merge: 4234 // V = phi [ %x, %left ], [ %y, %right ] 4235 // 4236 // as "select %cond, %x, %y" 4237 4238 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4239 assert(IDom && "At least the entry block should dominate PN"); 4240 4241 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4242 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4243 4244 if (BI && BI->isConditional() && 4245 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4246 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4247 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4248 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4249 } 4250 4251 return nullptr; 4252 } 4253 4254 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4255 if (const SCEV *S = createAddRecFromPHI(PN)) 4256 return S; 4257 4258 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4259 return S; 4260 4261 // If the PHI has a single incoming value, follow that value, unless the 4262 // PHI's incoming blocks are in a different loop, in which case doing so 4263 // risks breaking LCSSA form. Instcombine would normally zap these, but 4264 // it doesn't have DominatorTree information, so it may miss cases. 4265 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4266 if (LI.replacementPreservesLCSSAForm(PN, V)) 4267 return getSCEV(V); 4268 4269 // If it's not a loop phi, we can't handle it yet. 4270 return getUnknown(PN); 4271 } 4272 4273 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4274 Value *Cond, 4275 Value *TrueVal, 4276 Value *FalseVal) { 4277 // Handle "constant" branch or select. This can occur for instance when a 4278 // loop pass transforms an inner loop and moves on to process the outer loop. 4279 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4280 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4281 4282 // Try to match some simple smax or umax patterns. 4283 auto *ICI = dyn_cast<ICmpInst>(Cond); 4284 if (!ICI) 4285 return getUnknown(I); 4286 4287 Value *LHS = ICI->getOperand(0); 4288 Value *RHS = ICI->getOperand(1); 4289 4290 switch (ICI->getPredicate()) { 4291 case ICmpInst::ICMP_SLT: 4292 case ICmpInst::ICMP_SLE: 4293 std::swap(LHS, RHS); 4294 LLVM_FALLTHROUGH; 4295 case ICmpInst::ICMP_SGT: 4296 case ICmpInst::ICMP_SGE: 4297 // a >s b ? a+x : b+x -> smax(a, b)+x 4298 // a >s b ? b+x : a+x -> smin(a, b)+x 4299 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4300 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4301 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4302 const SCEV *LA = getSCEV(TrueVal); 4303 const SCEV *RA = getSCEV(FalseVal); 4304 const SCEV *LDiff = getMinusSCEV(LA, LS); 4305 const SCEV *RDiff = getMinusSCEV(RA, RS); 4306 if (LDiff == RDiff) 4307 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4308 LDiff = getMinusSCEV(LA, RS); 4309 RDiff = getMinusSCEV(RA, LS); 4310 if (LDiff == RDiff) 4311 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4312 } 4313 break; 4314 case ICmpInst::ICMP_ULT: 4315 case ICmpInst::ICMP_ULE: 4316 std::swap(LHS, RHS); 4317 LLVM_FALLTHROUGH; 4318 case ICmpInst::ICMP_UGT: 4319 case ICmpInst::ICMP_UGE: 4320 // a >u b ? a+x : b+x -> umax(a, b)+x 4321 // a >u b ? b+x : a+x -> umin(a, b)+x 4322 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4323 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4324 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4325 const SCEV *LA = getSCEV(TrueVal); 4326 const SCEV *RA = getSCEV(FalseVal); 4327 const SCEV *LDiff = getMinusSCEV(LA, LS); 4328 const SCEV *RDiff = getMinusSCEV(RA, RS); 4329 if (LDiff == RDiff) 4330 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4331 LDiff = getMinusSCEV(LA, RS); 4332 RDiff = getMinusSCEV(RA, LS); 4333 if (LDiff == RDiff) 4334 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4335 } 4336 break; 4337 case ICmpInst::ICMP_NE: 4338 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4339 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4340 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4341 const SCEV *One = getOne(I->getType()); 4342 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4343 const SCEV *LA = getSCEV(TrueVal); 4344 const SCEV *RA = getSCEV(FalseVal); 4345 const SCEV *LDiff = getMinusSCEV(LA, LS); 4346 const SCEV *RDiff = getMinusSCEV(RA, One); 4347 if (LDiff == RDiff) 4348 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4349 } 4350 break; 4351 case ICmpInst::ICMP_EQ: 4352 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4353 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4354 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4355 const SCEV *One = getOne(I->getType()); 4356 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4357 const SCEV *LA = getSCEV(TrueVal); 4358 const SCEV *RA = getSCEV(FalseVal); 4359 const SCEV *LDiff = getMinusSCEV(LA, One); 4360 const SCEV *RDiff = getMinusSCEV(RA, LS); 4361 if (LDiff == RDiff) 4362 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4363 } 4364 break; 4365 default: 4366 break; 4367 } 4368 4369 return getUnknown(I); 4370 } 4371 4372 /// Expand GEP instructions into add and multiply operations. This allows them 4373 /// to be analyzed by regular SCEV code. 4374 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4375 // Don't attempt to analyze GEPs over unsized objects. 4376 if (!GEP->getSourceElementType()->isSized()) 4377 return getUnknown(GEP); 4378 4379 SmallVector<const SCEV *, 4> IndexExprs; 4380 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4381 IndexExprs.push_back(getSCEV(*Index)); 4382 return getGEPExpr(GEP->getSourceElementType(), 4383 getSCEV(GEP->getPointerOperand()), 4384 IndexExprs, GEP->isInBounds()); 4385 } 4386 4387 uint32_t 4388 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4389 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4390 return C->getAPInt().countTrailingZeros(); 4391 4392 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4393 return std::min(GetMinTrailingZeros(T->getOperand()), 4394 (uint32_t)getTypeSizeInBits(T->getType())); 4395 4396 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4397 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4398 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4399 getTypeSizeInBits(E->getType()) : OpRes; 4400 } 4401 4402 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4403 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4404 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4405 getTypeSizeInBits(E->getType()) : OpRes; 4406 } 4407 4408 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4409 // The result is the min of all operands results. 4410 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4411 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4412 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4413 return MinOpRes; 4414 } 4415 4416 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4417 // The result is the sum of all operands results. 4418 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4419 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4420 for (unsigned i = 1, e = M->getNumOperands(); 4421 SumOpRes != BitWidth && i != e; ++i) 4422 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4423 BitWidth); 4424 return SumOpRes; 4425 } 4426 4427 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4428 // The result is the min of all operands results. 4429 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4430 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4431 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4432 return MinOpRes; 4433 } 4434 4435 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4436 // The result is the min of all operands results. 4437 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4438 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4439 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4440 return MinOpRes; 4441 } 4442 4443 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4444 // The result is the min of all operands results. 4445 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4446 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4447 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4448 return MinOpRes; 4449 } 4450 4451 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4452 // For a SCEVUnknown, ask ValueTracking. 4453 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4454 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4455 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4456 nullptr, &DT); 4457 return Zeros.countTrailingOnes(); 4458 } 4459 4460 // SCEVUDivExpr 4461 return 0; 4462 } 4463 4464 /// Helper method to assign a range to V from metadata present in the IR. 4465 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4466 if (Instruction *I = dyn_cast<Instruction>(V)) 4467 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4468 return getConstantRangeFromMetadata(*MD); 4469 4470 return None; 4471 } 4472 4473 /// Determine the range for a particular SCEV. If SignHint is 4474 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4475 /// with a "cleaner" unsigned (resp. signed) representation. 4476 ConstantRange 4477 ScalarEvolution::getRange(const SCEV *S, 4478 ScalarEvolution::RangeSignHint SignHint) { 4479 DenseMap<const SCEV *, ConstantRange> &Cache = 4480 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4481 : SignedRanges; 4482 4483 // See if we've computed this range already. 4484 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4485 if (I != Cache.end()) 4486 return I->second; 4487 4488 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4489 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4490 4491 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4492 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4493 4494 // If the value has known zeros, the maximum value will have those known zeros 4495 // as well. 4496 uint32_t TZ = GetMinTrailingZeros(S); 4497 if (TZ != 0) { 4498 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4499 ConservativeResult = 4500 ConstantRange(APInt::getMinValue(BitWidth), 4501 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4502 else 4503 ConservativeResult = ConstantRange( 4504 APInt::getSignedMinValue(BitWidth), 4505 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4506 } 4507 4508 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4509 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4510 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4511 X = X.add(getRange(Add->getOperand(i), SignHint)); 4512 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4513 } 4514 4515 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4516 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4517 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4518 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4519 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4520 } 4521 4522 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4523 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4524 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4525 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4526 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4527 } 4528 4529 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4530 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4531 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4532 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4533 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4534 } 4535 4536 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4537 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4538 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4539 return setRange(UDiv, SignHint, 4540 ConservativeResult.intersectWith(X.udiv(Y))); 4541 } 4542 4543 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4544 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4545 return setRange(ZExt, SignHint, 4546 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4547 } 4548 4549 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4550 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4551 return setRange(SExt, SignHint, 4552 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4553 } 4554 4555 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4556 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4557 return setRange(Trunc, SignHint, 4558 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4559 } 4560 4561 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4562 // If there's no unsigned wrap, the value will never be less than its 4563 // initial value. 4564 if (AddRec->hasNoUnsignedWrap()) 4565 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4566 if (!C->getValue()->isZero()) 4567 ConservativeResult = ConservativeResult.intersectWith( 4568 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4569 4570 // If there's no signed wrap, and all the operands have the same sign or 4571 // zero, the value won't ever change sign. 4572 if (AddRec->hasNoSignedWrap()) { 4573 bool AllNonNeg = true; 4574 bool AllNonPos = true; 4575 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4576 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4577 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4578 } 4579 if (AllNonNeg) 4580 ConservativeResult = ConservativeResult.intersectWith( 4581 ConstantRange(APInt(BitWidth, 0), 4582 APInt::getSignedMinValue(BitWidth))); 4583 else if (AllNonPos) 4584 ConservativeResult = ConservativeResult.intersectWith( 4585 ConstantRange(APInt::getSignedMinValue(BitWidth), 4586 APInt(BitWidth, 1))); 4587 } 4588 4589 // TODO: non-affine addrec 4590 if (AddRec->isAffine()) { 4591 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4592 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4593 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4594 auto RangeFromAffine = getRangeForAffineAR( 4595 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4596 BitWidth); 4597 if (!RangeFromAffine.isFullSet()) 4598 ConservativeResult = 4599 ConservativeResult.intersectWith(RangeFromAffine); 4600 4601 auto RangeFromFactoring = getRangeViaFactoring( 4602 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4603 BitWidth); 4604 if (!RangeFromFactoring.isFullSet()) 4605 ConservativeResult = 4606 ConservativeResult.intersectWith(RangeFromFactoring); 4607 } 4608 } 4609 4610 return setRange(AddRec, SignHint, ConservativeResult); 4611 } 4612 4613 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4614 // Check if the IR explicitly contains !range metadata. 4615 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4616 if (MDRange.hasValue()) 4617 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4618 4619 // Split here to avoid paying the compile-time cost of calling both 4620 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4621 // if needed. 4622 const DataLayout &DL = getDataLayout(); 4623 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4624 // For a SCEVUnknown, ask ValueTracking. 4625 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4626 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4627 if (Ones != ~Zeros + 1) 4628 ConservativeResult = 4629 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4630 } else { 4631 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4632 "generalize as needed!"); 4633 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4634 if (NS > 1) 4635 ConservativeResult = ConservativeResult.intersectWith( 4636 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4637 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4638 } 4639 4640 return setRange(U, SignHint, ConservativeResult); 4641 } 4642 4643 return setRange(S, SignHint, ConservativeResult); 4644 } 4645 4646 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4647 const SCEV *Step, 4648 const SCEV *MaxBECount, 4649 unsigned BitWidth) { 4650 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4651 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4652 "Precondition!"); 4653 4654 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4655 4656 // Check for overflow. This must be done with ConstantRange arithmetic 4657 // because we could be called from within the ScalarEvolution overflow 4658 // checking code. 4659 4660 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4661 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4662 ConstantRange ZExtMaxBECountRange = 4663 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4664 4665 ConstantRange StepSRange = getSignedRange(Step); 4666 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4667 4668 ConstantRange StartURange = getUnsignedRange(Start); 4669 ConstantRange EndURange = 4670 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4671 4672 // Check for unsigned overflow. 4673 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4674 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4675 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4676 ZExtEndURange) { 4677 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4678 EndURange.getUnsignedMin()); 4679 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4680 EndURange.getUnsignedMax()); 4681 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4682 if (!IsFullRange) 4683 Result = 4684 Result.intersectWith(ConstantRange(Min, Max + 1)); 4685 } 4686 4687 ConstantRange StartSRange = getSignedRange(Start); 4688 ConstantRange EndSRange = 4689 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4690 4691 // Check for signed overflow. This must be done with ConstantRange 4692 // arithmetic because we could be called from within the ScalarEvolution 4693 // overflow checking code. 4694 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4695 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4696 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4697 SExtEndSRange) { 4698 APInt Min = 4699 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4700 APInt Max = 4701 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4702 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4703 if (!IsFullRange) 4704 Result = 4705 Result.intersectWith(ConstantRange(Min, Max + 1)); 4706 } 4707 4708 return Result; 4709 } 4710 4711 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4712 const SCEV *Step, 4713 const SCEV *MaxBECount, 4714 unsigned BitWidth) { 4715 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4716 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4717 4718 struct SelectPattern { 4719 Value *Condition = nullptr; 4720 APInt TrueValue; 4721 APInt FalseValue; 4722 4723 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4724 const SCEV *S) { 4725 Optional<unsigned> CastOp; 4726 APInt Offset(BitWidth, 0); 4727 4728 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4729 "Should be!"); 4730 4731 // Peel off a constant offset: 4732 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4733 // In the future we could consider being smarter here and handle 4734 // {Start+Step,+,Step} too. 4735 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4736 return; 4737 4738 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4739 S = SA->getOperand(1); 4740 } 4741 4742 // Peel off a cast operation 4743 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4744 CastOp = SCast->getSCEVType(); 4745 S = SCast->getOperand(); 4746 } 4747 4748 using namespace llvm::PatternMatch; 4749 4750 auto *SU = dyn_cast<SCEVUnknown>(S); 4751 const APInt *TrueVal, *FalseVal; 4752 if (!SU || 4753 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4754 m_APInt(FalseVal)))) { 4755 Condition = nullptr; 4756 return; 4757 } 4758 4759 TrueValue = *TrueVal; 4760 FalseValue = *FalseVal; 4761 4762 // Re-apply the cast we peeled off earlier 4763 if (CastOp.hasValue()) 4764 switch (*CastOp) { 4765 default: 4766 llvm_unreachable("Unknown SCEV cast type!"); 4767 4768 case scTruncate: 4769 TrueValue = TrueValue.trunc(BitWidth); 4770 FalseValue = FalseValue.trunc(BitWidth); 4771 break; 4772 case scZeroExtend: 4773 TrueValue = TrueValue.zext(BitWidth); 4774 FalseValue = FalseValue.zext(BitWidth); 4775 break; 4776 case scSignExtend: 4777 TrueValue = TrueValue.sext(BitWidth); 4778 FalseValue = FalseValue.sext(BitWidth); 4779 break; 4780 } 4781 4782 // Re-apply the constant offset we peeled off earlier 4783 TrueValue += Offset; 4784 FalseValue += Offset; 4785 } 4786 4787 bool isRecognized() { return Condition != nullptr; } 4788 }; 4789 4790 SelectPattern StartPattern(*this, BitWidth, Start); 4791 if (!StartPattern.isRecognized()) 4792 return ConstantRange(BitWidth, /* isFullSet = */ true); 4793 4794 SelectPattern StepPattern(*this, BitWidth, Step); 4795 if (!StepPattern.isRecognized()) 4796 return ConstantRange(BitWidth, /* isFullSet = */ true); 4797 4798 if (StartPattern.Condition != StepPattern.Condition) { 4799 // We don't handle this case today; but we could, by considering four 4800 // possibilities below instead of two. I'm not sure if there are cases where 4801 // that will help over what getRange already does, though. 4802 return ConstantRange(BitWidth, /* isFullSet = */ true); 4803 } 4804 4805 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4806 // construct arbitrary general SCEV expressions here. This function is called 4807 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4808 // say) can end up caching a suboptimal value. 4809 4810 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4811 // C2352 and C2512 (otherwise it isn't needed). 4812 4813 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4814 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4815 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4816 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4817 4818 ConstantRange TrueRange = 4819 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4820 ConstantRange FalseRange = 4821 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4822 4823 return TrueRange.unionWith(FalseRange); 4824 } 4825 4826 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4827 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4828 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4829 4830 // Return early if there are no flags to propagate to the SCEV. 4831 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4832 if (BinOp->hasNoUnsignedWrap()) 4833 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4834 if (BinOp->hasNoSignedWrap()) 4835 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4836 if (Flags == SCEV::FlagAnyWrap) 4837 return SCEV::FlagAnyWrap; 4838 4839 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4840 } 4841 4842 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4843 // Here we check that I is in the header of the innermost loop containing I, 4844 // since we only deal with instructions in the loop header. The actual loop we 4845 // need to check later will come from an add recurrence, but getting that 4846 // requires computing the SCEV of the operands, which can be expensive. This 4847 // check we can do cheaply to rule out some cases early. 4848 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4849 if (InnermostContainingLoop == nullptr || 4850 InnermostContainingLoop->getHeader() != I->getParent()) 4851 return false; 4852 4853 // Only proceed if we can prove that I does not yield poison. 4854 if (!isKnownNotFullPoison(I)) return false; 4855 4856 // At this point we know that if I is executed, then it does not wrap 4857 // according to at least one of NSW or NUW. If I is not executed, then we do 4858 // not know if the calculation that I represents would wrap. Multiple 4859 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4860 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4861 // derived from other instructions that map to the same SCEV. We cannot make 4862 // that guarantee for cases where I is not executed. So we need to find the 4863 // loop that I is considered in relation to and prove that I is executed for 4864 // every iteration of that loop. That implies that the value that I 4865 // calculates does not wrap anywhere in the loop, so then we can apply the 4866 // flags to the SCEV. 4867 // 4868 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4869 // from different loops, so that we know which loop to prove that I is 4870 // executed in. 4871 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4872 // I could be an extractvalue from a call to an overflow intrinsic. 4873 // TODO: We can do better here in some cases. 4874 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4875 return false; 4876 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4877 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4878 bool AllOtherOpsLoopInvariant = true; 4879 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4880 ++OtherOpIndex) { 4881 if (OtherOpIndex != OpIndex) { 4882 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4883 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4884 AllOtherOpsLoopInvariant = false; 4885 break; 4886 } 4887 } 4888 } 4889 if (AllOtherOpsLoopInvariant && 4890 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4891 return true; 4892 } 4893 } 4894 return false; 4895 } 4896 4897 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4898 // If we know that \c I can never be poison period, then that's enough. 4899 if (isSCEVExprNeverPoison(I)) 4900 return true; 4901 4902 // For an add recurrence specifically, we assume that infinite loops without 4903 // side effects are undefined behavior, and then reason as follows: 4904 // 4905 // If the add recurrence is poison in any iteration, it is poison on all 4906 // future iterations (since incrementing poison yields poison). If the result 4907 // of the add recurrence is fed into the loop latch condition and the loop 4908 // does not contain any throws or exiting blocks other than the latch, we now 4909 // have the ability to "choose" whether the backedge is taken or not (by 4910 // choosing a sufficiently evil value for the poison feeding into the branch) 4911 // for every iteration including and after the one in which \p I first became 4912 // poison. There are two possibilities (let's call the iteration in which \p 4913 // I first became poison as K): 4914 // 4915 // 1. In the set of iterations including and after K, the loop body executes 4916 // no side effects. In this case executing the backege an infinte number 4917 // of times will yield undefined behavior. 4918 // 4919 // 2. In the set of iterations including and after K, the loop body executes 4920 // at least one side effect. In this case, that specific instance of side 4921 // effect is control dependent on poison, which also yields undefined 4922 // behavior. 4923 4924 auto *ExitingBB = L->getExitingBlock(); 4925 auto *LatchBB = L->getLoopLatch(); 4926 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4927 return false; 4928 4929 SmallPtrSet<const Instruction *, 16> Pushed; 4930 SmallVector<const Instruction *, 8> PoisonStack; 4931 4932 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4933 // things that are known to be fully poison under that assumption go on the 4934 // PoisonStack. 4935 Pushed.insert(I); 4936 PoisonStack.push_back(I); 4937 4938 bool LatchControlDependentOnPoison = false; 4939 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4940 const Instruction *Poison = PoisonStack.pop_back_val(); 4941 4942 for (auto *PoisonUser : Poison->users()) { 4943 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4944 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4945 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4946 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4947 assert(BI->isConditional() && "Only possibility!"); 4948 if (BI->getParent() == LatchBB) { 4949 LatchControlDependentOnPoison = true; 4950 break; 4951 } 4952 } 4953 } 4954 } 4955 4956 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4957 } 4958 4959 ScalarEvolution::LoopProperties 4960 ScalarEvolution::getLoopProperties(const Loop *L) { 4961 typedef ScalarEvolution::LoopProperties LoopProperties; 4962 4963 auto Itr = LoopPropertiesCache.find(L); 4964 if (Itr == LoopPropertiesCache.end()) { 4965 auto HasSideEffects = [](Instruction *I) { 4966 if (auto *SI = dyn_cast<StoreInst>(I)) 4967 return !SI->isSimple(); 4968 4969 return I->mayHaveSideEffects(); 4970 }; 4971 4972 LoopProperties LP = {/* HasNoAbnormalExits */ true, 4973 /*HasNoSideEffects*/ true}; 4974 4975 for (auto *BB : L->getBlocks()) 4976 for (auto &I : *BB) { 4977 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4978 LP.HasNoAbnormalExits = false; 4979 if (HasSideEffects(&I)) 4980 LP.HasNoSideEffects = false; 4981 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 4982 break; // We're already as pessimistic as we can get. 4983 } 4984 4985 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 4986 assert(InsertPair.second && "We just checked!"); 4987 Itr = InsertPair.first; 4988 } 4989 4990 return Itr->second; 4991 } 4992 4993 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4994 if (!isSCEVable(V->getType())) 4995 return getUnknown(V); 4996 4997 if (Instruction *I = dyn_cast<Instruction>(V)) { 4998 // Don't attempt to analyze instructions in blocks that aren't 4999 // reachable. Such instructions don't matter, and they aren't required 5000 // to obey basic rules for definitions dominating uses which this 5001 // analysis depends on. 5002 if (!DT.isReachableFromEntry(I->getParent())) 5003 return getUnknown(V); 5004 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5005 return getConstant(CI); 5006 else if (isa<ConstantPointerNull>(V)) 5007 return getZero(V->getType()); 5008 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5009 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5010 else if (!isa<ConstantExpr>(V)) 5011 return getUnknown(V); 5012 5013 Operator *U = cast<Operator>(V); 5014 if (auto BO = MatchBinaryOp(U, DT)) { 5015 switch (BO->Opcode) { 5016 case Instruction::Add: { 5017 // The simple thing to do would be to just call getSCEV on both operands 5018 // and call getAddExpr with the result. However if we're looking at a 5019 // bunch of things all added together, this can be quite inefficient, 5020 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5021 // Instead, gather up all the operands and make a single getAddExpr call. 5022 // LLVM IR canonical form means we need only traverse the left operands. 5023 SmallVector<const SCEV *, 4> AddOps; 5024 do { 5025 if (BO->Op) { 5026 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5027 AddOps.push_back(OpSCEV); 5028 break; 5029 } 5030 5031 // If a NUW or NSW flag can be applied to the SCEV for this 5032 // addition, then compute the SCEV for this addition by itself 5033 // with a separate call to getAddExpr. We need to do that 5034 // instead of pushing the operands of the addition onto AddOps, 5035 // since the flags are only known to apply to this particular 5036 // addition - they may not apply to other additions that can be 5037 // formed with operands from AddOps. 5038 const SCEV *RHS = getSCEV(BO->RHS); 5039 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5040 if (Flags != SCEV::FlagAnyWrap) { 5041 const SCEV *LHS = getSCEV(BO->LHS); 5042 if (BO->Opcode == Instruction::Sub) 5043 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5044 else 5045 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5046 break; 5047 } 5048 } 5049 5050 if (BO->Opcode == Instruction::Sub) 5051 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5052 else 5053 AddOps.push_back(getSCEV(BO->RHS)); 5054 5055 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5056 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5057 NewBO->Opcode != Instruction::Sub)) { 5058 AddOps.push_back(getSCEV(BO->LHS)); 5059 break; 5060 } 5061 BO = NewBO; 5062 } while (true); 5063 5064 return getAddExpr(AddOps); 5065 } 5066 5067 case Instruction::Mul: { 5068 SmallVector<const SCEV *, 4> MulOps; 5069 do { 5070 if (BO->Op) { 5071 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5072 MulOps.push_back(OpSCEV); 5073 break; 5074 } 5075 5076 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5077 if (Flags != SCEV::FlagAnyWrap) { 5078 MulOps.push_back( 5079 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5080 break; 5081 } 5082 } 5083 5084 MulOps.push_back(getSCEV(BO->RHS)); 5085 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5086 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5087 MulOps.push_back(getSCEV(BO->LHS)); 5088 break; 5089 } 5090 BO = NewBO; 5091 } while (true); 5092 5093 return getMulExpr(MulOps); 5094 } 5095 case Instruction::UDiv: 5096 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5097 case Instruction::Sub: { 5098 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5099 if (BO->Op) 5100 Flags = getNoWrapFlagsFromUB(BO->Op); 5101 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5102 } 5103 case Instruction::And: 5104 // For an expression like x&255 that merely masks off the high bits, 5105 // use zext(trunc(x)) as the SCEV expression. 5106 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5107 if (CI->isNullValue()) 5108 return getSCEV(BO->RHS); 5109 if (CI->isAllOnesValue()) 5110 return getSCEV(BO->LHS); 5111 const APInt &A = CI->getValue(); 5112 5113 // Instcombine's ShrinkDemandedConstant may strip bits out of 5114 // constants, obscuring what would otherwise be a low-bits mask. 5115 // Use computeKnownBits to compute what ShrinkDemandedConstant 5116 // knew about to reconstruct a low-bits mask value. 5117 unsigned LZ = A.countLeadingZeros(); 5118 unsigned TZ = A.countTrailingZeros(); 5119 unsigned BitWidth = A.getBitWidth(); 5120 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5121 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5122 0, &AC, nullptr, &DT); 5123 5124 APInt EffectiveMask = 5125 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5126 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5127 const SCEV *MulCount = getConstant(ConstantInt::get( 5128 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5129 return getMulExpr( 5130 getZeroExtendExpr( 5131 getTruncateExpr( 5132 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5133 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5134 BO->LHS->getType()), 5135 MulCount); 5136 } 5137 } 5138 break; 5139 5140 case Instruction::Or: 5141 // If the RHS of the Or is a constant, we may have something like: 5142 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5143 // optimizations will transparently handle this case. 5144 // 5145 // In order for this transformation to be safe, the LHS must be of the 5146 // form X*(2^n) and the Or constant must be less than 2^n. 5147 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5148 const SCEV *LHS = getSCEV(BO->LHS); 5149 const APInt &CIVal = CI->getValue(); 5150 if (GetMinTrailingZeros(LHS) >= 5151 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5152 // Build a plain add SCEV. 5153 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5154 // If the LHS of the add was an addrec and it has no-wrap flags, 5155 // transfer the no-wrap flags, since an or won't introduce a wrap. 5156 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5157 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5158 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5159 OldAR->getNoWrapFlags()); 5160 } 5161 return S; 5162 } 5163 } 5164 break; 5165 5166 case Instruction::Xor: 5167 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5168 // If the RHS of xor is -1, then this is a not operation. 5169 if (CI->isAllOnesValue()) 5170 return getNotSCEV(getSCEV(BO->LHS)); 5171 5172 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5173 // This is a variant of the check for xor with -1, and it handles 5174 // the case where instcombine has trimmed non-demanded bits out 5175 // of an xor with -1. 5176 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5177 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5178 if (LBO->getOpcode() == Instruction::And && 5179 LCI->getValue() == CI->getValue()) 5180 if (const SCEVZeroExtendExpr *Z = 5181 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5182 Type *UTy = BO->LHS->getType(); 5183 const SCEV *Z0 = Z->getOperand(); 5184 Type *Z0Ty = Z0->getType(); 5185 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5186 5187 // If C is a low-bits mask, the zero extend is serving to 5188 // mask off the high bits. Complement the operand and 5189 // re-apply the zext. 5190 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5191 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5192 5193 // If C is a single bit, it may be in the sign-bit position 5194 // before the zero-extend. In this case, represent the xor 5195 // using an add, which is equivalent, and re-apply the zext. 5196 APInt Trunc = CI->getValue().trunc(Z0TySize); 5197 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5198 Trunc.isSignBit()) 5199 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5200 UTy); 5201 } 5202 } 5203 break; 5204 5205 case Instruction::Shl: 5206 // Turn shift left of a constant amount into a multiply. 5207 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5208 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5209 5210 // If the shift count is not less than the bitwidth, the result of 5211 // the shift is undefined. Don't try to analyze it, because the 5212 // resolution chosen here may differ from the resolution chosen in 5213 // other parts of the compiler. 5214 if (SA->getValue().uge(BitWidth)) 5215 break; 5216 5217 // It is currently not resolved how to interpret NSW for left 5218 // shift by BitWidth - 1, so we avoid applying flags in that 5219 // case. Remove this check (or this comment) once the situation 5220 // is resolved. See 5221 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5222 // and http://reviews.llvm.org/D8890 . 5223 auto Flags = SCEV::FlagAnyWrap; 5224 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5225 Flags = getNoWrapFlagsFromUB(BO->Op); 5226 5227 Constant *X = ConstantInt::get(getContext(), 5228 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5229 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5230 } 5231 break; 5232 5233 case Instruction::AShr: 5234 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5235 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5236 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5237 if (L->getOpcode() == Instruction::Shl && 5238 L->getOperand(1) == BO->RHS) { 5239 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5240 5241 // If the shift count is not less than the bitwidth, the result of 5242 // the shift is undefined. Don't try to analyze it, because the 5243 // resolution chosen here may differ from the resolution chosen in 5244 // other parts of the compiler. 5245 if (CI->getValue().uge(BitWidth)) 5246 break; 5247 5248 uint64_t Amt = BitWidth - CI->getZExtValue(); 5249 if (Amt == BitWidth) 5250 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5251 return getSignExtendExpr( 5252 getTruncateExpr(getSCEV(L->getOperand(0)), 5253 IntegerType::get(getContext(), Amt)), 5254 BO->LHS->getType()); 5255 } 5256 break; 5257 } 5258 } 5259 5260 switch (U->getOpcode()) { 5261 case Instruction::Trunc: 5262 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5263 5264 case Instruction::ZExt: 5265 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5266 5267 case Instruction::SExt: 5268 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5269 5270 case Instruction::BitCast: 5271 // BitCasts are no-op casts so we just eliminate the cast. 5272 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5273 return getSCEV(U->getOperand(0)); 5274 break; 5275 5276 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5277 // lead to pointer expressions which cannot safely be expanded to GEPs, 5278 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5279 // simplifying integer expressions. 5280 5281 case Instruction::GetElementPtr: 5282 return createNodeForGEP(cast<GEPOperator>(U)); 5283 5284 case Instruction::PHI: 5285 return createNodeForPHI(cast<PHINode>(U)); 5286 5287 case Instruction::Select: 5288 // U can also be a select constant expr, which let fall through. Since 5289 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5290 // constant expressions cannot have instructions as operands, we'd have 5291 // returned getUnknown for a select constant expressions anyway. 5292 if (isa<Instruction>(U)) 5293 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5294 U->getOperand(1), U->getOperand(2)); 5295 break; 5296 5297 case Instruction::Call: 5298 case Instruction::Invoke: 5299 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5300 return getSCEV(RV); 5301 break; 5302 } 5303 5304 return getUnknown(V); 5305 } 5306 5307 5308 5309 //===----------------------------------------------------------------------===// 5310 // Iteration Count Computation Code 5311 // 5312 5313 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5314 if (!ExitCount) 5315 return 0; 5316 5317 ConstantInt *ExitConst = ExitCount->getValue(); 5318 5319 // Guard against huge trip counts. 5320 if (ExitConst->getValue().getActiveBits() > 32) 5321 return 0; 5322 5323 // In case of integer overflow, this returns 0, which is correct. 5324 return ((unsigned)ExitConst->getZExtValue()) + 1; 5325 } 5326 5327 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5328 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5329 return getSmallConstantTripCount(L, ExitingBB); 5330 5331 // No trip count information for multiple exits. 5332 return 0; 5333 } 5334 5335 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5336 BasicBlock *ExitingBlock) { 5337 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5338 assert(L->isLoopExiting(ExitingBlock) && 5339 "Exiting block must actually branch out of the loop!"); 5340 const SCEVConstant *ExitCount = 5341 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5342 return getConstantTripCount(ExitCount); 5343 } 5344 5345 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5346 const auto *MaxExitCount = 5347 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5348 return getConstantTripCount(MaxExitCount); 5349 } 5350 5351 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5352 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5353 return getSmallConstantTripMultiple(L, ExitingBB); 5354 5355 // No trip multiple information for multiple exits. 5356 return 0; 5357 } 5358 5359 /// Returns the largest constant divisor of the trip count of this loop as a 5360 /// normal unsigned value, if possible. This means that the actual trip count is 5361 /// always a multiple of the returned value (don't forget the trip count could 5362 /// very well be zero as well!). 5363 /// 5364 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5365 /// multiple of a constant (which is also the case if the trip count is simply 5366 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5367 /// if the trip count is very large (>= 2^32). 5368 /// 5369 /// As explained in the comments for getSmallConstantTripCount, this assumes 5370 /// that control exits the loop via ExitingBlock. 5371 unsigned 5372 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5373 BasicBlock *ExitingBlock) { 5374 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5375 assert(L->isLoopExiting(ExitingBlock) && 5376 "Exiting block must actually branch out of the loop!"); 5377 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5378 if (ExitCount == getCouldNotCompute()) 5379 return 1; 5380 5381 // Get the trip count from the BE count by adding 1. 5382 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5383 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5384 // to factor simple cases. 5385 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5386 TCMul = Mul->getOperand(0); 5387 5388 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5389 if (!MulC) 5390 return 1; 5391 5392 ConstantInt *Result = MulC->getValue(); 5393 5394 // Guard against huge trip counts (this requires checking 5395 // for zero to handle the case where the trip count == -1 and the 5396 // addition wraps). 5397 if (!Result || Result->getValue().getActiveBits() > 32 || 5398 Result->getValue().getActiveBits() == 0) 5399 return 1; 5400 5401 return (unsigned)Result->getZExtValue(); 5402 } 5403 5404 /// Get the expression for the number of loop iterations for which this loop is 5405 /// guaranteed not to exit via ExitingBlock. Otherwise return 5406 /// SCEVCouldNotCompute. 5407 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5408 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5409 } 5410 5411 const SCEV * 5412 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5413 SCEVUnionPredicate &Preds) { 5414 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5415 } 5416 5417 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5418 return getBackedgeTakenInfo(L).getExact(this); 5419 } 5420 5421 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5422 /// known never to be less than the actual backedge taken count. 5423 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5424 return getBackedgeTakenInfo(L).getMax(this); 5425 } 5426 5427 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5428 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5429 } 5430 5431 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5432 static void 5433 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5434 BasicBlock *Header = L->getHeader(); 5435 5436 // Push all Loop-header PHIs onto the Worklist stack. 5437 for (BasicBlock::iterator I = Header->begin(); 5438 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5439 Worklist.push_back(PN); 5440 } 5441 5442 const ScalarEvolution::BackedgeTakenInfo & 5443 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5444 auto &BTI = getBackedgeTakenInfo(L); 5445 if (BTI.hasFullInfo()) 5446 return BTI; 5447 5448 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5449 5450 if (!Pair.second) 5451 return Pair.first->second; 5452 5453 BackedgeTakenInfo Result = 5454 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5455 5456 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5457 } 5458 5459 const ScalarEvolution::BackedgeTakenInfo & 5460 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5461 // Initially insert an invalid entry for this loop. If the insertion 5462 // succeeds, proceed to actually compute a backedge-taken count and 5463 // update the value. The temporary CouldNotCompute value tells SCEV 5464 // code elsewhere that it shouldn't attempt to request a new 5465 // backedge-taken count, which could result in infinite recursion. 5466 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5467 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5468 if (!Pair.second) 5469 return Pair.first->second; 5470 5471 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5472 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5473 // must be cleared in this scope. 5474 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5475 5476 if (Result.getExact(this) != getCouldNotCompute()) { 5477 assert(isLoopInvariant(Result.getExact(this), L) && 5478 isLoopInvariant(Result.getMax(this), L) && 5479 "Computed backedge-taken count isn't loop invariant for loop!"); 5480 ++NumTripCountsComputed; 5481 } 5482 else if (Result.getMax(this) == getCouldNotCompute() && 5483 isa<PHINode>(L->getHeader()->begin())) { 5484 // Only count loops that have phi nodes as not being computable. 5485 ++NumTripCountsNotComputed; 5486 } 5487 5488 // Now that we know more about the trip count for this loop, forget any 5489 // existing SCEV values for PHI nodes in this loop since they are only 5490 // conservative estimates made without the benefit of trip count 5491 // information. This is similar to the code in forgetLoop, except that 5492 // it handles SCEVUnknown PHI nodes specially. 5493 if (Result.hasAnyInfo()) { 5494 SmallVector<Instruction *, 16> Worklist; 5495 PushLoopPHIs(L, Worklist); 5496 5497 SmallPtrSet<Instruction *, 8> Visited; 5498 while (!Worklist.empty()) { 5499 Instruction *I = Worklist.pop_back_val(); 5500 if (!Visited.insert(I).second) 5501 continue; 5502 5503 ValueExprMapType::iterator It = 5504 ValueExprMap.find_as(static_cast<Value *>(I)); 5505 if (It != ValueExprMap.end()) { 5506 const SCEV *Old = It->second; 5507 5508 // SCEVUnknown for a PHI either means that it has an unrecognized 5509 // structure, or it's a PHI that's in the progress of being computed 5510 // by createNodeForPHI. In the former case, additional loop trip 5511 // count information isn't going to change anything. In the later 5512 // case, createNodeForPHI will perform the necessary updates on its 5513 // own when it gets to that point. 5514 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5515 eraseValueFromMap(It->first); 5516 forgetMemoizedResults(Old); 5517 } 5518 if (PHINode *PN = dyn_cast<PHINode>(I)) 5519 ConstantEvolutionLoopExitValue.erase(PN); 5520 } 5521 5522 PushDefUseChildren(I, Worklist); 5523 } 5524 } 5525 5526 // Re-lookup the insert position, since the call to 5527 // computeBackedgeTakenCount above could result in a 5528 // recusive call to getBackedgeTakenInfo (on a different 5529 // loop), which would invalidate the iterator computed 5530 // earlier. 5531 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5532 } 5533 5534 void ScalarEvolution::forgetLoop(const Loop *L) { 5535 // Drop any stored trip count value. 5536 auto RemoveLoopFromBackedgeMap = 5537 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5538 auto BTCPos = Map.find(L); 5539 if (BTCPos != Map.end()) { 5540 BTCPos->second.clear(); 5541 Map.erase(BTCPos); 5542 } 5543 }; 5544 5545 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5546 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5547 5548 // Drop information about expressions based on loop-header PHIs. 5549 SmallVector<Instruction *, 16> Worklist; 5550 PushLoopPHIs(L, Worklist); 5551 5552 SmallPtrSet<Instruction *, 8> Visited; 5553 while (!Worklist.empty()) { 5554 Instruction *I = Worklist.pop_back_val(); 5555 if (!Visited.insert(I).second) 5556 continue; 5557 5558 ValueExprMapType::iterator It = 5559 ValueExprMap.find_as(static_cast<Value *>(I)); 5560 if (It != ValueExprMap.end()) { 5561 eraseValueFromMap(It->first); 5562 forgetMemoizedResults(It->second); 5563 if (PHINode *PN = dyn_cast<PHINode>(I)) 5564 ConstantEvolutionLoopExitValue.erase(PN); 5565 } 5566 5567 PushDefUseChildren(I, Worklist); 5568 } 5569 5570 // Forget all contained loops too, to avoid dangling entries in the 5571 // ValuesAtScopes map. 5572 for (Loop *I : *L) 5573 forgetLoop(I); 5574 5575 LoopPropertiesCache.erase(L); 5576 } 5577 5578 void ScalarEvolution::forgetValue(Value *V) { 5579 Instruction *I = dyn_cast<Instruction>(V); 5580 if (!I) return; 5581 5582 // Drop information about expressions based on loop-header PHIs. 5583 SmallVector<Instruction *, 16> Worklist; 5584 Worklist.push_back(I); 5585 5586 SmallPtrSet<Instruction *, 8> Visited; 5587 while (!Worklist.empty()) { 5588 I = Worklist.pop_back_val(); 5589 if (!Visited.insert(I).second) 5590 continue; 5591 5592 ValueExprMapType::iterator It = 5593 ValueExprMap.find_as(static_cast<Value *>(I)); 5594 if (It != ValueExprMap.end()) { 5595 eraseValueFromMap(It->first); 5596 forgetMemoizedResults(It->second); 5597 if (PHINode *PN = dyn_cast<PHINode>(I)) 5598 ConstantEvolutionLoopExitValue.erase(PN); 5599 } 5600 5601 PushDefUseChildren(I, Worklist); 5602 } 5603 } 5604 5605 /// Get the exact loop backedge taken count considering all loop exits. A 5606 /// computable result can only be returned for loops with a single exit. 5607 /// Returning the minimum taken count among all exits is incorrect because one 5608 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5609 /// the limit of each loop test is never skipped. This is a valid assumption as 5610 /// long as the loop exits via that test. For precise results, it is the 5611 /// caller's responsibility to specify the relevant loop exit using 5612 /// getExact(ExitingBlock, SE). 5613 const SCEV * 5614 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5615 SCEVUnionPredicate *Preds) const { 5616 // If any exits were not computable, the loop is not computable. 5617 if (!isComplete() || ExitNotTaken.empty()) 5618 return SE->getCouldNotCompute(); 5619 5620 const SCEV *BECount = nullptr; 5621 for (auto &ENT : ExitNotTaken) { 5622 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5623 5624 if (!BECount) 5625 BECount = ENT.ExactNotTaken; 5626 else if (BECount != ENT.ExactNotTaken) 5627 return SE->getCouldNotCompute(); 5628 if (Preds && !ENT.hasAlwaysTruePredicate()) 5629 Preds->add(ENT.Predicate.get()); 5630 5631 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5632 "Predicate should be always true!"); 5633 } 5634 5635 assert(BECount && "Invalid not taken count for loop exit"); 5636 return BECount; 5637 } 5638 5639 /// Get the exact not taken count for this loop exit. 5640 const SCEV * 5641 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5642 ScalarEvolution *SE) const { 5643 for (auto &ENT : ExitNotTaken) 5644 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5645 return ENT.ExactNotTaken; 5646 5647 return SE->getCouldNotCompute(); 5648 } 5649 5650 /// getMax - Get the max backedge taken count for the loop. 5651 const SCEV * 5652 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5653 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5654 return !ENT.hasAlwaysTruePredicate(); 5655 }; 5656 5657 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5658 return SE->getCouldNotCompute(); 5659 5660 return getMax(); 5661 } 5662 5663 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5664 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5665 return !ENT.hasAlwaysTruePredicate(); 5666 }; 5667 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5668 } 5669 5670 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5671 ScalarEvolution *SE) const { 5672 if (getMax() && getMax() != SE->getCouldNotCompute() && 5673 SE->hasOperand(getMax(), S)) 5674 return true; 5675 5676 for (auto &ENT : ExitNotTaken) 5677 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5678 SE->hasOperand(ENT.ExactNotTaken, S)) 5679 return true; 5680 5681 return false; 5682 } 5683 5684 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5685 /// computable exit into a persistent ExitNotTakenInfo array. 5686 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5687 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5688 &&ExitCounts, 5689 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5690 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5691 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5692 ExitNotTaken.reserve(ExitCounts.size()); 5693 std::transform( 5694 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5695 [&](const EdgeExitInfo &EEI) { 5696 BasicBlock *ExitBB = EEI.first; 5697 const ExitLimit &EL = EEI.second; 5698 if (EL.Predicates.empty()) 5699 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5700 5701 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5702 for (auto *Pred : EL.Predicates) 5703 Predicate->add(Pred); 5704 5705 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5706 }); 5707 } 5708 5709 /// Invalidate this result and free the ExitNotTakenInfo array. 5710 void ScalarEvolution::BackedgeTakenInfo::clear() { 5711 ExitNotTaken.clear(); 5712 } 5713 5714 /// Compute the number of times the backedge of the specified loop will execute. 5715 ScalarEvolution::BackedgeTakenInfo 5716 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5717 bool AllowPredicates) { 5718 SmallVector<BasicBlock *, 8> ExitingBlocks; 5719 L->getExitingBlocks(ExitingBlocks); 5720 5721 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5722 5723 SmallVector<EdgeExitInfo, 4> ExitCounts; 5724 bool CouldComputeBECount = true; 5725 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5726 const SCEV *MustExitMaxBECount = nullptr; 5727 const SCEV *MayExitMaxBECount = nullptr; 5728 bool MustExitMaxOrZero = false; 5729 5730 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5731 // and compute maxBECount. 5732 // Do a union of all the predicates here. 5733 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5734 BasicBlock *ExitBB = ExitingBlocks[i]; 5735 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5736 5737 assert((AllowPredicates || EL.Predicates.empty()) && 5738 "Predicated exit limit when predicates are not allowed!"); 5739 5740 // 1. For each exit that can be computed, add an entry to ExitCounts. 5741 // CouldComputeBECount is true only if all exits can be computed. 5742 if (EL.ExactNotTaken == getCouldNotCompute()) 5743 // We couldn't compute an exact value for this exit, so 5744 // we won't be able to compute an exact value for the loop. 5745 CouldComputeBECount = false; 5746 else 5747 ExitCounts.emplace_back(ExitBB, EL); 5748 5749 // 2. Derive the loop's MaxBECount from each exit's max number of 5750 // non-exiting iterations. Partition the loop exits into two kinds: 5751 // LoopMustExits and LoopMayExits. 5752 // 5753 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5754 // is a LoopMayExit. If any computable LoopMustExit is found, then 5755 // MaxBECount is the minimum EL.MaxNotTaken of computable 5756 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5757 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5758 // computable EL.MaxNotTaken. 5759 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5760 DT.dominates(ExitBB, Latch)) { 5761 if (!MustExitMaxBECount) { 5762 MustExitMaxBECount = EL.MaxNotTaken; 5763 MustExitMaxOrZero = EL.MaxOrZero; 5764 } else { 5765 MustExitMaxBECount = 5766 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5767 } 5768 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5769 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5770 MayExitMaxBECount = EL.MaxNotTaken; 5771 else { 5772 MayExitMaxBECount = 5773 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5774 } 5775 } 5776 } 5777 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5778 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5779 // The loop backedge will be taken the maximum or zero times if there's 5780 // a single exit that must be taken the maximum or zero times. 5781 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5782 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5783 MaxBECount, MaxOrZero); 5784 } 5785 5786 ScalarEvolution::ExitLimit 5787 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5788 bool AllowPredicates) { 5789 5790 // Okay, we've chosen an exiting block. See what condition causes us to exit 5791 // at this block and remember the exit block and whether all other targets 5792 // lead to the loop header. 5793 bool MustExecuteLoopHeader = true; 5794 BasicBlock *Exit = nullptr; 5795 for (auto *SBB : successors(ExitingBlock)) 5796 if (!L->contains(SBB)) { 5797 if (Exit) // Multiple exit successors. 5798 return getCouldNotCompute(); 5799 Exit = SBB; 5800 } else if (SBB != L->getHeader()) { 5801 MustExecuteLoopHeader = false; 5802 } 5803 5804 // At this point, we know we have a conditional branch that determines whether 5805 // the loop is exited. However, we don't know if the branch is executed each 5806 // time through the loop. If not, then the execution count of the branch will 5807 // not be equal to the trip count of the loop. 5808 // 5809 // Currently we check for this by checking to see if the Exit branch goes to 5810 // the loop header. If so, we know it will always execute the same number of 5811 // times as the loop. We also handle the case where the exit block *is* the 5812 // loop header. This is common for un-rotated loops. 5813 // 5814 // If both of those tests fail, walk up the unique predecessor chain to the 5815 // header, stopping if there is an edge that doesn't exit the loop. If the 5816 // header is reached, the execution count of the branch will be equal to the 5817 // trip count of the loop. 5818 // 5819 // More extensive analysis could be done to handle more cases here. 5820 // 5821 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5822 // The simple checks failed, try climbing the unique predecessor chain 5823 // up to the header. 5824 bool Ok = false; 5825 for (BasicBlock *BB = ExitingBlock; BB; ) { 5826 BasicBlock *Pred = BB->getUniquePredecessor(); 5827 if (!Pred) 5828 return getCouldNotCompute(); 5829 TerminatorInst *PredTerm = Pred->getTerminator(); 5830 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5831 if (PredSucc == BB) 5832 continue; 5833 // If the predecessor has a successor that isn't BB and isn't 5834 // outside the loop, assume the worst. 5835 if (L->contains(PredSucc)) 5836 return getCouldNotCompute(); 5837 } 5838 if (Pred == L->getHeader()) { 5839 Ok = true; 5840 break; 5841 } 5842 BB = Pred; 5843 } 5844 if (!Ok) 5845 return getCouldNotCompute(); 5846 } 5847 5848 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5849 TerminatorInst *Term = ExitingBlock->getTerminator(); 5850 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5851 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5852 // Proceed to the next level to examine the exit condition expression. 5853 return computeExitLimitFromCond( 5854 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5855 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5856 } 5857 5858 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5859 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5860 /*ControlsExit=*/IsOnlyExit); 5861 5862 return getCouldNotCompute(); 5863 } 5864 5865 ScalarEvolution::ExitLimit 5866 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5867 Value *ExitCond, 5868 BasicBlock *TBB, 5869 BasicBlock *FBB, 5870 bool ControlsExit, 5871 bool AllowPredicates) { 5872 // Check if the controlling expression for this loop is an And or Or. 5873 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5874 if (BO->getOpcode() == Instruction::And) { 5875 // Recurse on the operands of the and. 5876 bool EitherMayExit = L->contains(TBB); 5877 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5878 ControlsExit && !EitherMayExit, 5879 AllowPredicates); 5880 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5881 ControlsExit && !EitherMayExit, 5882 AllowPredicates); 5883 const SCEV *BECount = getCouldNotCompute(); 5884 const SCEV *MaxBECount = getCouldNotCompute(); 5885 if (EitherMayExit) { 5886 // Both conditions must be true for the loop to continue executing. 5887 // Choose the less conservative count. 5888 if (EL0.ExactNotTaken == getCouldNotCompute() || 5889 EL1.ExactNotTaken == getCouldNotCompute()) 5890 BECount = getCouldNotCompute(); 5891 else 5892 BECount = 5893 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5894 if (EL0.MaxNotTaken == getCouldNotCompute()) 5895 MaxBECount = EL1.MaxNotTaken; 5896 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5897 MaxBECount = EL0.MaxNotTaken; 5898 else 5899 MaxBECount = 5900 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5901 } else { 5902 // Both conditions must be true at the same time for the loop to exit. 5903 // For now, be conservative. 5904 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5905 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5906 MaxBECount = EL0.MaxNotTaken; 5907 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5908 BECount = EL0.ExactNotTaken; 5909 } 5910 5911 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5912 // to be more aggressive when computing BECount than when computing 5913 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5914 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5915 // to not. 5916 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5917 !isa<SCEVCouldNotCompute>(BECount)) 5918 MaxBECount = BECount; 5919 5920 return ExitLimit(BECount, MaxBECount, false, 5921 {&EL0.Predicates, &EL1.Predicates}); 5922 } 5923 if (BO->getOpcode() == Instruction::Or) { 5924 // Recurse on the operands of the or. 5925 bool EitherMayExit = L->contains(FBB); 5926 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5927 ControlsExit && !EitherMayExit, 5928 AllowPredicates); 5929 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5930 ControlsExit && !EitherMayExit, 5931 AllowPredicates); 5932 const SCEV *BECount = getCouldNotCompute(); 5933 const SCEV *MaxBECount = getCouldNotCompute(); 5934 if (EitherMayExit) { 5935 // Both conditions must be false for the loop to continue executing. 5936 // Choose the less conservative count. 5937 if (EL0.ExactNotTaken == getCouldNotCompute() || 5938 EL1.ExactNotTaken == getCouldNotCompute()) 5939 BECount = getCouldNotCompute(); 5940 else 5941 BECount = 5942 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5943 if (EL0.MaxNotTaken == getCouldNotCompute()) 5944 MaxBECount = EL1.MaxNotTaken; 5945 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5946 MaxBECount = EL0.MaxNotTaken; 5947 else 5948 MaxBECount = 5949 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5950 } else { 5951 // Both conditions must be false at the same time for the loop to exit. 5952 // For now, be conservative. 5953 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5954 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5955 MaxBECount = EL0.MaxNotTaken; 5956 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5957 BECount = EL0.ExactNotTaken; 5958 } 5959 5960 return ExitLimit(BECount, MaxBECount, false, 5961 {&EL0.Predicates, &EL1.Predicates}); 5962 } 5963 } 5964 5965 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5966 // Proceed to the next level to examine the icmp. 5967 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5968 ExitLimit EL = 5969 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5970 if (EL.hasFullInfo() || !AllowPredicates) 5971 return EL; 5972 5973 // Try again, but use SCEV predicates this time. 5974 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5975 /*AllowPredicates=*/true); 5976 } 5977 5978 // Check for a constant condition. These are normally stripped out by 5979 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5980 // preserve the CFG and is temporarily leaving constant conditions 5981 // in place. 5982 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5983 if (L->contains(FBB) == !CI->getZExtValue()) 5984 // The backedge is always taken. 5985 return getCouldNotCompute(); 5986 else 5987 // The backedge is never taken. 5988 return getZero(CI->getType()); 5989 } 5990 5991 // If it's not an integer or pointer comparison then compute it the hard way. 5992 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5993 } 5994 5995 ScalarEvolution::ExitLimit 5996 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 5997 ICmpInst *ExitCond, 5998 BasicBlock *TBB, 5999 BasicBlock *FBB, 6000 bool ControlsExit, 6001 bool AllowPredicates) { 6002 6003 // If the condition was exit on true, convert the condition to exit on false 6004 ICmpInst::Predicate Cond; 6005 if (!L->contains(FBB)) 6006 Cond = ExitCond->getPredicate(); 6007 else 6008 Cond = ExitCond->getInversePredicate(); 6009 6010 // Handle common loops like: for (X = "string"; *X; ++X) 6011 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6012 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6013 ExitLimit ItCnt = 6014 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6015 if (ItCnt.hasAnyInfo()) 6016 return ItCnt; 6017 } 6018 6019 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6020 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6021 6022 // Try to evaluate any dependencies out of the loop. 6023 LHS = getSCEVAtScope(LHS, L); 6024 RHS = getSCEVAtScope(RHS, L); 6025 6026 // At this point, we would like to compute how many iterations of the 6027 // loop the predicate will return true for these inputs. 6028 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6029 // If there is a loop-invariant, force it into the RHS. 6030 std::swap(LHS, RHS); 6031 Cond = ICmpInst::getSwappedPredicate(Cond); 6032 } 6033 6034 // Simplify the operands before analyzing them. 6035 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6036 6037 // If we have a comparison of a chrec against a constant, try to use value 6038 // ranges to answer this query. 6039 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6040 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6041 if (AddRec->getLoop() == L) { 6042 // Form the constant range. 6043 ConstantRange CompRange = 6044 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6045 6046 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6047 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6048 } 6049 6050 switch (Cond) { 6051 case ICmpInst::ICMP_NE: { // while (X != Y) 6052 // Convert to: while (X-Y != 0) 6053 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6054 AllowPredicates); 6055 if (EL.hasAnyInfo()) return EL; 6056 break; 6057 } 6058 case ICmpInst::ICMP_EQ: { // while (X == Y) 6059 // Convert to: while (X-Y == 0) 6060 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6061 if (EL.hasAnyInfo()) return EL; 6062 break; 6063 } 6064 case ICmpInst::ICMP_SLT: 6065 case ICmpInst::ICMP_ULT: { // while (X < Y) 6066 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6067 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6068 AllowPredicates); 6069 if (EL.hasAnyInfo()) return EL; 6070 break; 6071 } 6072 case ICmpInst::ICMP_SGT: 6073 case ICmpInst::ICMP_UGT: { // while (X > Y) 6074 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6075 ExitLimit EL = 6076 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6077 AllowPredicates); 6078 if (EL.hasAnyInfo()) return EL; 6079 break; 6080 } 6081 default: 6082 break; 6083 } 6084 6085 auto *ExhaustiveCount = 6086 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6087 6088 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6089 return ExhaustiveCount; 6090 6091 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6092 ExitCond->getOperand(1), L, Cond); 6093 } 6094 6095 ScalarEvolution::ExitLimit 6096 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6097 SwitchInst *Switch, 6098 BasicBlock *ExitingBlock, 6099 bool ControlsExit) { 6100 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6101 6102 // Give up if the exit is the default dest of a switch. 6103 if (Switch->getDefaultDest() == ExitingBlock) 6104 return getCouldNotCompute(); 6105 6106 assert(L->contains(Switch->getDefaultDest()) && 6107 "Default case must not exit the loop!"); 6108 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6109 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6110 6111 // while (X != Y) --> while (X-Y != 0) 6112 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6113 if (EL.hasAnyInfo()) 6114 return EL; 6115 6116 return getCouldNotCompute(); 6117 } 6118 6119 static ConstantInt * 6120 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6121 ScalarEvolution &SE) { 6122 const SCEV *InVal = SE.getConstant(C); 6123 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6124 assert(isa<SCEVConstant>(Val) && 6125 "Evaluation of SCEV at constant didn't fold correctly?"); 6126 return cast<SCEVConstant>(Val)->getValue(); 6127 } 6128 6129 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6130 /// compute the backedge execution count. 6131 ScalarEvolution::ExitLimit 6132 ScalarEvolution::computeLoadConstantCompareExitLimit( 6133 LoadInst *LI, 6134 Constant *RHS, 6135 const Loop *L, 6136 ICmpInst::Predicate predicate) { 6137 6138 if (LI->isVolatile()) return getCouldNotCompute(); 6139 6140 // Check to see if the loaded pointer is a getelementptr of a global. 6141 // TODO: Use SCEV instead of manually grubbing with GEPs. 6142 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6143 if (!GEP) return getCouldNotCompute(); 6144 6145 // Make sure that it is really a constant global we are gepping, with an 6146 // initializer, and make sure the first IDX is really 0. 6147 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6148 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6149 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6150 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6151 return getCouldNotCompute(); 6152 6153 // Okay, we allow one non-constant index into the GEP instruction. 6154 Value *VarIdx = nullptr; 6155 std::vector<Constant*> Indexes; 6156 unsigned VarIdxNum = 0; 6157 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6158 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6159 Indexes.push_back(CI); 6160 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6161 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6162 VarIdx = GEP->getOperand(i); 6163 VarIdxNum = i-2; 6164 Indexes.push_back(nullptr); 6165 } 6166 6167 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6168 if (!VarIdx) 6169 return getCouldNotCompute(); 6170 6171 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6172 // Check to see if X is a loop variant variable value now. 6173 const SCEV *Idx = getSCEV(VarIdx); 6174 Idx = getSCEVAtScope(Idx, L); 6175 6176 // We can only recognize very limited forms of loop index expressions, in 6177 // particular, only affine AddRec's like {C1,+,C2}. 6178 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6179 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6180 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6181 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6182 return getCouldNotCompute(); 6183 6184 unsigned MaxSteps = MaxBruteForceIterations; 6185 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6186 ConstantInt *ItCst = ConstantInt::get( 6187 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6188 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6189 6190 // Form the GEP offset. 6191 Indexes[VarIdxNum] = Val; 6192 6193 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6194 Indexes); 6195 if (!Result) break; // Cannot compute! 6196 6197 // Evaluate the condition for this iteration. 6198 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6199 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6200 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6201 ++NumArrayLenItCounts; 6202 return getConstant(ItCst); // Found terminating iteration! 6203 } 6204 } 6205 return getCouldNotCompute(); 6206 } 6207 6208 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6209 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6210 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6211 if (!RHS) 6212 return getCouldNotCompute(); 6213 6214 const BasicBlock *Latch = L->getLoopLatch(); 6215 if (!Latch) 6216 return getCouldNotCompute(); 6217 6218 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6219 if (!Predecessor) 6220 return getCouldNotCompute(); 6221 6222 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6223 // Return LHS in OutLHS and shift_opt in OutOpCode. 6224 auto MatchPositiveShift = 6225 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6226 6227 using namespace PatternMatch; 6228 6229 ConstantInt *ShiftAmt; 6230 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6231 OutOpCode = Instruction::LShr; 6232 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6233 OutOpCode = Instruction::AShr; 6234 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6235 OutOpCode = Instruction::Shl; 6236 else 6237 return false; 6238 6239 return ShiftAmt->getValue().isStrictlyPositive(); 6240 }; 6241 6242 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6243 // 6244 // loop: 6245 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6246 // %iv.shifted = lshr i32 %iv, <positive constant> 6247 // 6248 // Return true on a succesful match. Return the corresponding PHI node (%iv 6249 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6250 auto MatchShiftRecurrence = 6251 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6252 Optional<Instruction::BinaryOps> PostShiftOpCode; 6253 6254 { 6255 Instruction::BinaryOps OpC; 6256 Value *V; 6257 6258 // If we encounter a shift instruction, "peel off" the shift operation, 6259 // and remember that we did so. Later when we inspect %iv's backedge 6260 // value, we will make sure that the backedge value uses the same 6261 // operation. 6262 // 6263 // Note: the peeled shift operation does not have to be the same 6264 // instruction as the one feeding into the PHI's backedge value. We only 6265 // really care about it being the same *kind* of shift instruction -- 6266 // that's all that is required for our later inferences to hold. 6267 if (MatchPositiveShift(LHS, V, OpC)) { 6268 PostShiftOpCode = OpC; 6269 LHS = V; 6270 } 6271 } 6272 6273 PNOut = dyn_cast<PHINode>(LHS); 6274 if (!PNOut || PNOut->getParent() != L->getHeader()) 6275 return false; 6276 6277 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6278 Value *OpLHS; 6279 6280 return 6281 // The backedge value for the PHI node must be a shift by a positive 6282 // amount 6283 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6284 6285 // of the PHI node itself 6286 OpLHS == PNOut && 6287 6288 // and the kind of shift should be match the kind of shift we peeled 6289 // off, if any. 6290 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6291 }; 6292 6293 PHINode *PN; 6294 Instruction::BinaryOps OpCode; 6295 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6296 return getCouldNotCompute(); 6297 6298 const DataLayout &DL = getDataLayout(); 6299 6300 // The key rationale for this optimization is that for some kinds of shift 6301 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6302 // within a finite number of iterations. If the condition guarding the 6303 // backedge (in the sense that the backedge is taken if the condition is true) 6304 // is false for the value the shift recurrence stabilizes to, then we know 6305 // that the backedge is taken only a finite number of times. 6306 6307 ConstantInt *StableValue = nullptr; 6308 switch (OpCode) { 6309 default: 6310 llvm_unreachable("Impossible case!"); 6311 6312 case Instruction::AShr: { 6313 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6314 // bitwidth(K) iterations. 6315 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6316 bool KnownZero, KnownOne; 6317 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6318 Predecessor->getTerminator(), &DT); 6319 auto *Ty = cast<IntegerType>(RHS->getType()); 6320 if (KnownZero) 6321 StableValue = ConstantInt::get(Ty, 0); 6322 else if (KnownOne) 6323 StableValue = ConstantInt::get(Ty, -1, true); 6324 else 6325 return getCouldNotCompute(); 6326 6327 break; 6328 } 6329 case Instruction::LShr: 6330 case Instruction::Shl: 6331 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6332 // stabilize to 0 in at most bitwidth(K) iterations. 6333 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6334 break; 6335 } 6336 6337 auto *Result = 6338 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6339 assert(Result->getType()->isIntegerTy(1) && 6340 "Otherwise cannot be an operand to a branch instruction"); 6341 6342 if (Result->isZeroValue()) { 6343 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6344 const SCEV *UpperBound = 6345 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6346 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6347 } 6348 6349 return getCouldNotCompute(); 6350 } 6351 6352 /// Return true if we can constant fold an instruction of the specified type, 6353 /// assuming that all operands were constants. 6354 static bool CanConstantFold(const Instruction *I) { 6355 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6356 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6357 isa<LoadInst>(I)) 6358 return true; 6359 6360 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6361 if (const Function *F = CI->getCalledFunction()) 6362 return canConstantFoldCallTo(F); 6363 return false; 6364 } 6365 6366 /// Determine whether this instruction can constant evolve within this loop 6367 /// assuming its operands can all constant evolve. 6368 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6369 // An instruction outside of the loop can't be derived from a loop PHI. 6370 if (!L->contains(I)) return false; 6371 6372 if (isa<PHINode>(I)) { 6373 // We don't currently keep track of the control flow needed to evaluate 6374 // PHIs, so we cannot handle PHIs inside of loops. 6375 return L->getHeader() == I->getParent(); 6376 } 6377 6378 // If we won't be able to constant fold this expression even if the operands 6379 // are constants, bail early. 6380 return CanConstantFold(I); 6381 } 6382 6383 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6384 /// recursing through each instruction operand until reaching a loop header phi. 6385 static PHINode * 6386 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6387 DenseMap<Instruction *, PHINode *> &PHIMap) { 6388 6389 // Otherwise, we can evaluate this instruction if all of its operands are 6390 // constant or derived from a PHI node themselves. 6391 PHINode *PHI = nullptr; 6392 for (Value *Op : UseInst->operands()) { 6393 if (isa<Constant>(Op)) continue; 6394 6395 Instruction *OpInst = dyn_cast<Instruction>(Op); 6396 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6397 6398 PHINode *P = dyn_cast<PHINode>(OpInst); 6399 if (!P) 6400 // If this operand is already visited, reuse the prior result. 6401 // We may have P != PHI if this is the deepest point at which the 6402 // inconsistent paths meet. 6403 P = PHIMap.lookup(OpInst); 6404 if (!P) { 6405 // Recurse and memoize the results, whether a phi is found or not. 6406 // This recursive call invalidates pointers into PHIMap. 6407 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6408 PHIMap[OpInst] = P; 6409 } 6410 if (!P) 6411 return nullptr; // Not evolving from PHI 6412 if (PHI && PHI != P) 6413 return nullptr; // Evolving from multiple different PHIs. 6414 PHI = P; 6415 } 6416 // This is a expression evolving from a constant PHI! 6417 return PHI; 6418 } 6419 6420 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6421 /// in the loop that V is derived from. We allow arbitrary operations along the 6422 /// way, but the operands of an operation must either be constants or a value 6423 /// derived from a constant PHI. If this expression does not fit with these 6424 /// constraints, return null. 6425 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6426 Instruction *I = dyn_cast<Instruction>(V); 6427 if (!I || !canConstantEvolve(I, L)) return nullptr; 6428 6429 if (PHINode *PN = dyn_cast<PHINode>(I)) 6430 return PN; 6431 6432 // Record non-constant instructions contained by the loop. 6433 DenseMap<Instruction *, PHINode *> PHIMap; 6434 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6435 } 6436 6437 /// EvaluateExpression - Given an expression that passes the 6438 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6439 /// in the loop has the value PHIVal. If we can't fold this expression for some 6440 /// reason, return null. 6441 static Constant *EvaluateExpression(Value *V, const Loop *L, 6442 DenseMap<Instruction *, Constant *> &Vals, 6443 const DataLayout &DL, 6444 const TargetLibraryInfo *TLI) { 6445 // Convenient constant check, but redundant for recursive calls. 6446 if (Constant *C = dyn_cast<Constant>(V)) return C; 6447 Instruction *I = dyn_cast<Instruction>(V); 6448 if (!I) return nullptr; 6449 6450 if (Constant *C = Vals.lookup(I)) return C; 6451 6452 // An instruction inside the loop depends on a value outside the loop that we 6453 // weren't given a mapping for, or a value such as a call inside the loop. 6454 if (!canConstantEvolve(I, L)) return nullptr; 6455 6456 // An unmapped PHI can be due to a branch or another loop inside this loop, 6457 // or due to this not being the initial iteration through a loop where we 6458 // couldn't compute the evolution of this particular PHI last time. 6459 if (isa<PHINode>(I)) return nullptr; 6460 6461 std::vector<Constant*> Operands(I->getNumOperands()); 6462 6463 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6464 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6465 if (!Operand) { 6466 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6467 if (!Operands[i]) return nullptr; 6468 continue; 6469 } 6470 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6471 Vals[Operand] = C; 6472 if (!C) return nullptr; 6473 Operands[i] = C; 6474 } 6475 6476 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6477 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6478 Operands[1], DL, TLI); 6479 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6480 if (!LI->isVolatile()) 6481 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6482 } 6483 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6484 } 6485 6486 6487 // If every incoming value to PN except the one for BB is a specific Constant, 6488 // return that, else return nullptr. 6489 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6490 Constant *IncomingVal = nullptr; 6491 6492 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6493 if (PN->getIncomingBlock(i) == BB) 6494 continue; 6495 6496 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6497 if (!CurrentVal) 6498 return nullptr; 6499 6500 if (IncomingVal != CurrentVal) { 6501 if (IncomingVal) 6502 return nullptr; 6503 IncomingVal = CurrentVal; 6504 } 6505 } 6506 6507 return IncomingVal; 6508 } 6509 6510 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6511 /// in the header of its containing loop, we know the loop executes a 6512 /// constant number of times, and the PHI node is just a recurrence 6513 /// involving constants, fold it. 6514 Constant * 6515 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6516 const APInt &BEs, 6517 const Loop *L) { 6518 auto I = ConstantEvolutionLoopExitValue.find(PN); 6519 if (I != ConstantEvolutionLoopExitValue.end()) 6520 return I->second; 6521 6522 if (BEs.ugt(MaxBruteForceIterations)) 6523 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6524 6525 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6526 6527 DenseMap<Instruction *, Constant *> CurrentIterVals; 6528 BasicBlock *Header = L->getHeader(); 6529 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6530 6531 BasicBlock *Latch = L->getLoopLatch(); 6532 if (!Latch) 6533 return nullptr; 6534 6535 for (auto &I : *Header) { 6536 PHINode *PHI = dyn_cast<PHINode>(&I); 6537 if (!PHI) break; 6538 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6539 if (!StartCST) continue; 6540 CurrentIterVals[PHI] = StartCST; 6541 } 6542 if (!CurrentIterVals.count(PN)) 6543 return RetVal = nullptr; 6544 6545 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6546 6547 // Execute the loop symbolically to determine the exit value. 6548 if (BEs.getActiveBits() >= 32) 6549 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6550 6551 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6552 unsigned IterationNum = 0; 6553 const DataLayout &DL = getDataLayout(); 6554 for (; ; ++IterationNum) { 6555 if (IterationNum == NumIterations) 6556 return RetVal = CurrentIterVals[PN]; // Got exit value! 6557 6558 // Compute the value of the PHIs for the next iteration. 6559 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6560 DenseMap<Instruction *, Constant *> NextIterVals; 6561 Constant *NextPHI = 6562 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6563 if (!NextPHI) 6564 return nullptr; // Couldn't evaluate! 6565 NextIterVals[PN] = NextPHI; 6566 6567 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6568 6569 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6570 // cease to be able to evaluate one of them or if they stop evolving, 6571 // because that doesn't necessarily prevent us from computing PN. 6572 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6573 for (const auto &I : CurrentIterVals) { 6574 PHINode *PHI = dyn_cast<PHINode>(I.first); 6575 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6576 PHIsToCompute.emplace_back(PHI, I.second); 6577 } 6578 // We use two distinct loops because EvaluateExpression may invalidate any 6579 // iterators into CurrentIterVals. 6580 for (const auto &I : PHIsToCompute) { 6581 PHINode *PHI = I.first; 6582 Constant *&NextPHI = NextIterVals[PHI]; 6583 if (!NextPHI) { // Not already computed. 6584 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6585 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6586 } 6587 if (NextPHI != I.second) 6588 StoppedEvolving = false; 6589 } 6590 6591 // If all entries in CurrentIterVals == NextIterVals then we can stop 6592 // iterating, the loop can't continue to change. 6593 if (StoppedEvolving) 6594 return RetVal = CurrentIterVals[PN]; 6595 6596 CurrentIterVals.swap(NextIterVals); 6597 } 6598 } 6599 6600 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6601 Value *Cond, 6602 bool ExitWhen) { 6603 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6604 if (!PN) return getCouldNotCompute(); 6605 6606 // If the loop is canonicalized, the PHI will have exactly two entries. 6607 // That's the only form we support here. 6608 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6609 6610 DenseMap<Instruction *, Constant *> CurrentIterVals; 6611 BasicBlock *Header = L->getHeader(); 6612 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6613 6614 BasicBlock *Latch = L->getLoopLatch(); 6615 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6616 6617 for (auto &I : *Header) { 6618 PHINode *PHI = dyn_cast<PHINode>(&I); 6619 if (!PHI) 6620 break; 6621 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6622 if (!StartCST) continue; 6623 CurrentIterVals[PHI] = StartCST; 6624 } 6625 if (!CurrentIterVals.count(PN)) 6626 return getCouldNotCompute(); 6627 6628 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6629 // the loop symbolically to determine when the condition gets a value of 6630 // "ExitWhen". 6631 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6632 const DataLayout &DL = getDataLayout(); 6633 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6634 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6635 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6636 6637 // Couldn't symbolically evaluate. 6638 if (!CondVal) return getCouldNotCompute(); 6639 6640 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6641 ++NumBruteForceTripCountsComputed; 6642 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6643 } 6644 6645 // Update all the PHI nodes for the next iteration. 6646 DenseMap<Instruction *, Constant *> NextIterVals; 6647 6648 // Create a list of which PHIs we need to compute. We want to do this before 6649 // calling EvaluateExpression on them because that may invalidate iterators 6650 // into CurrentIterVals. 6651 SmallVector<PHINode *, 8> PHIsToCompute; 6652 for (const auto &I : CurrentIterVals) { 6653 PHINode *PHI = dyn_cast<PHINode>(I.first); 6654 if (!PHI || PHI->getParent() != Header) continue; 6655 PHIsToCompute.push_back(PHI); 6656 } 6657 for (PHINode *PHI : PHIsToCompute) { 6658 Constant *&NextPHI = NextIterVals[PHI]; 6659 if (NextPHI) continue; // Already computed! 6660 6661 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6662 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6663 } 6664 CurrentIterVals.swap(NextIterVals); 6665 } 6666 6667 // Too many iterations were needed to evaluate. 6668 return getCouldNotCompute(); 6669 } 6670 6671 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6672 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6673 ValuesAtScopes[V]; 6674 // Check to see if we've folded this expression at this loop before. 6675 for (auto &LS : Values) 6676 if (LS.first == L) 6677 return LS.second ? LS.second : V; 6678 6679 Values.emplace_back(L, nullptr); 6680 6681 // Otherwise compute it. 6682 const SCEV *C = computeSCEVAtScope(V, L); 6683 for (auto &LS : reverse(ValuesAtScopes[V])) 6684 if (LS.first == L) { 6685 LS.second = C; 6686 break; 6687 } 6688 return C; 6689 } 6690 6691 /// This builds up a Constant using the ConstantExpr interface. That way, we 6692 /// will return Constants for objects which aren't represented by a 6693 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6694 /// Returns NULL if the SCEV isn't representable as a Constant. 6695 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6696 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6697 case scCouldNotCompute: 6698 case scAddRecExpr: 6699 break; 6700 case scConstant: 6701 return cast<SCEVConstant>(V)->getValue(); 6702 case scUnknown: 6703 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6704 case scSignExtend: { 6705 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6706 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6707 return ConstantExpr::getSExt(CastOp, SS->getType()); 6708 break; 6709 } 6710 case scZeroExtend: { 6711 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6712 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6713 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6714 break; 6715 } 6716 case scTruncate: { 6717 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6718 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6719 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6720 break; 6721 } 6722 case scAddExpr: { 6723 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6724 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6725 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6726 unsigned AS = PTy->getAddressSpace(); 6727 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6728 C = ConstantExpr::getBitCast(C, DestPtrTy); 6729 } 6730 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6731 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6732 if (!C2) return nullptr; 6733 6734 // First pointer! 6735 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6736 unsigned AS = C2->getType()->getPointerAddressSpace(); 6737 std::swap(C, C2); 6738 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6739 // The offsets have been converted to bytes. We can add bytes to an 6740 // i8* by GEP with the byte count in the first index. 6741 C = ConstantExpr::getBitCast(C, DestPtrTy); 6742 } 6743 6744 // Don't bother trying to sum two pointers. We probably can't 6745 // statically compute a load that results from it anyway. 6746 if (C2->getType()->isPointerTy()) 6747 return nullptr; 6748 6749 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6750 if (PTy->getElementType()->isStructTy()) 6751 C2 = ConstantExpr::getIntegerCast( 6752 C2, Type::getInt32Ty(C->getContext()), true); 6753 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6754 } else 6755 C = ConstantExpr::getAdd(C, C2); 6756 } 6757 return C; 6758 } 6759 break; 6760 } 6761 case scMulExpr: { 6762 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6763 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6764 // Don't bother with pointers at all. 6765 if (C->getType()->isPointerTy()) return nullptr; 6766 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6767 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6768 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6769 C = ConstantExpr::getMul(C, C2); 6770 } 6771 return C; 6772 } 6773 break; 6774 } 6775 case scUDivExpr: { 6776 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6777 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6778 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6779 if (LHS->getType() == RHS->getType()) 6780 return ConstantExpr::getUDiv(LHS, RHS); 6781 break; 6782 } 6783 case scSMaxExpr: 6784 case scUMaxExpr: 6785 break; // TODO: smax, umax. 6786 } 6787 return nullptr; 6788 } 6789 6790 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6791 if (isa<SCEVConstant>(V)) return V; 6792 6793 // If this instruction is evolved from a constant-evolving PHI, compute the 6794 // exit value from the loop without using SCEVs. 6795 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6796 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6797 const Loop *LI = this->LI[I->getParent()]; 6798 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6799 if (PHINode *PN = dyn_cast<PHINode>(I)) 6800 if (PN->getParent() == LI->getHeader()) { 6801 // Okay, there is no closed form solution for the PHI node. Check 6802 // to see if the loop that contains it has a known backedge-taken 6803 // count. If so, we may be able to force computation of the exit 6804 // value. 6805 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6806 if (const SCEVConstant *BTCC = 6807 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6808 // Okay, we know how many times the containing loop executes. If 6809 // this is a constant evolving PHI node, get the final value at 6810 // the specified iteration number. 6811 Constant *RV = 6812 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6813 if (RV) return getSCEV(RV); 6814 } 6815 } 6816 6817 // Okay, this is an expression that we cannot symbolically evaluate 6818 // into a SCEV. Check to see if it's possible to symbolically evaluate 6819 // the arguments into constants, and if so, try to constant propagate the 6820 // result. This is particularly useful for computing loop exit values. 6821 if (CanConstantFold(I)) { 6822 SmallVector<Constant *, 4> Operands; 6823 bool MadeImprovement = false; 6824 for (Value *Op : I->operands()) { 6825 if (Constant *C = dyn_cast<Constant>(Op)) { 6826 Operands.push_back(C); 6827 continue; 6828 } 6829 6830 // If any of the operands is non-constant and if they are 6831 // non-integer and non-pointer, don't even try to analyze them 6832 // with scev techniques. 6833 if (!isSCEVable(Op->getType())) 6834 return V; 6835 6836 const SCEV *OrigV = getSCEV(Op); 6837 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6838 MadeImprovement |= OrigV != OpV; 6839 6840 Constant *C = BuildConstantFromSCEV(OpV); 6841 if (!C) return V; 6842 if (C->getType() != Op->getType()) 6843 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6844 Op->getType(), 6845 false), 6846 C, Op->getType()); 6847 Operands.push_back(C); 6848 } 6849 6850 // Check to see if getSCEVAtScope actually made an improvement. 6851 if (MadeImprovement) { 6852 Constant *C = nullptr; 6853 const DataLayout &DL = getDataLayout(); 6854 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6855 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6856 Operands[1], DL, &TLI); 6857 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6858 if (!LI->isVolatile()) 6859 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6860 } else 6861 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6862 if (!C) return V; 6863 return getSCEV(C); 6864 } 6865 } 6866 } 6867 6868 // This is some other type of SCEVUnknown, just return it. 6869 return V; 6870 } 6871 6872 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6873 // Avoid performing the look-up in the common case where the specified 6874 // expression has no loop-variant portions. 6875 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6876 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6877 if (OpAtScope != Comm->getOperand(i)) { 6878 // Okay, at least one of these operands is loop variant but might be 6879 // foldable. Build a new instance of the folded commutative expression. 6880 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6881 Comm->op_begin()+i); 6882 NewOps.push_back(OpAtScope); 6883 6884 for (++i; i != e; ++i) { 6885 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6886 NewOps.push_back(OpAtScope); 6887 } 6888 if (isa<SCEVAddExpr>(Comm)) 6889 return getAddExpr(NewOps); 6890 if (isa<SCEVMulExpr>(Comm)) 6891 return getMulExpr(NewOps); 6892 if (isa<SCEVSMaxExpr>(Comm)) 6893 return getSMaxExpr(NewOps); 6894 if (isa<SCEVUMaxExpr>(Comm)) 6895 return getUMaxExpr(NewOps); 6896 llvm_unreachable("Unknown commutative SCEV type!"); 6897 } 6898 } 6899 // If we got here, all operands are loop invariant. 6900 return Comm; 6901 } 6902 6903 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6904 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6905 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6906 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6907 return Div; // must be loop invariant 6908 return getUDivExpr(LHS, RHS); 6909 } 6910 6911 // If this is a loop recurrence for a loop that does not contain L, then we 6912 // are dealing with the final value computed by the loop. 6913 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6914 // First, attempt to evaluate each operand. 6915 // Avoid performing the look-up in the common case where the specified 6916 // expression has no loop-variant portions. 6917 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6918 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6919 if (OpAtScope == AddRec->getOperand(i)) 6920 continue; 6921 6922 // Okay, at least one of these operands is loop variant but might be 6923 // foldable. Build a new instance of the folded commutative expression. 6924 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6925 AddRec->op_begin()+i); 6926 NewOps.push_back(OpAtScope); 6927 for (++i; i != e; ++i) 6928 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6929 6930 const SCEV *FoldedRec = 6931 getAddRecExpr(NewOps, AddRec->getLoop(), 6932 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6933 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6934 // The addrec may be folded to a nonrecurrence, for example, if the 6935 // induction variable is multiplied by zero after constant folding. Go 6936 // ahead and return the folded value. 6937 if (!AddRec) 6938 return FoldedRec; 6939 break; 6940 } 6941 6942 // If the scope is outside the addrec's loop, evaluate it by using the 6943 // loop exit value of the addrec. 6944 if (!AddRec->getLoop()->contains(L)) { 6945 // To evaluate this recurrence, we need to know how many times the AddRec 6946 // loop iterates. Compute this now. 6947 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6948 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6949 6950 // Then, evaluate the AddRec. 6951 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6952 } 6953 6954 return AddRec; 6955 } 6956 6957 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6958 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6959 if (Op == Cast->getOperand()) 6960 return Cast; // must be loop invariant 6961 return getZeroExtendExpr(Op, Cast->getType()); 6962 } 6963 6964 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6965 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6966 if (Op == Cast->getOperand()) 6967 return Cast; // must be loop invariant 6968 return getSignExtendExpr(Op, Cast->getType()); 6969 } 6970 6971 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6972 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6973 if (Op == Cast->getOperand()) 6974 return Cast; // must be loop invariant 6975 return getTruncateExpr(Op, Cast->getType()); 6976 } 6977 6978 llvm_unreachable("Unknown SCEV type!"); 6979 } 6980 6981 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6982 return getSCEVAtScope(getSCEV(V), L); 6983 } 6984 6985 /// Finds the minimum unsigned root of the following equation: 6986 /// 6987 /// A * X = B (mod N) 6988 /// 6989 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6990 /// A and B isn't important. 6991 /// 6992 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6993 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6994 ScalarEvolution &SE) { 6995 uint32_t BW = A.getBitWidth(); 6996 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6997 assert(A != 0 && "A must be non-zero."); 6998 6999 // 1. D = gcd(A, N) 7000 // 7001 // The gcd of A and N may have only one prime factor: 2. The number of 7002 // trailing zeros in A is its multiplicity 7003 uint32_t Mult2 = A.countTrailingZeros(); 7004 // D = 2^Mult2 7005 7006 // 2. Check if B is divisible by D. 7007 // 7008 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7009 // is not less than multiplicity of this prime factor for D. 7010 if (B.countTrailingZeros() < Mult2) 7011 return SE.getCouldNotCompute(); 7012 7013 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7014 // modulo (N / D). 7015 // 7016 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7017 // bit width during computations. 7018 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7019 APInt Mod(BW + 1, 0); 7020 Mod.setBit(BW - Mult2); // Mod = N / D 7021 APInt I = AD.multiplicativeInverse(Mod); 7022 7023 // 4. Compute the minimum unsigned root of the equation: 7024 // I * (B / D) mod (N / D) 7025 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7026 7027 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7028 // bits. 7029 return SE.getConstant(Result.trunc(BW)); 7030 } 7031 7032 /// Find the roots of the quadratic equation for the given quadratic chrec 7033 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7034 /// two SCEVCouldNotCompute objects. 7035 /// 7036 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7037 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7038 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7039 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7040 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7041 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7042 7043 // We currently can only solve this if the coefficients are constants. 7044 if (!LC || !MC || !NC) 7045 return None; 7046 7047 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7048 const APInt &L = LC->getAPInt(); 7049 const APInt &M = MC->getAPInt(); 7050 const APInt &N = NC->getAPInt(); 7051 APInt Two(BitWidth, 2); 7052 APInt Four(BitWidth, 4); 7053 7054 { 7055 using namespace APIntOps; 7056 const APInt& C = L; 7057 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7058 // The B coefficient is M-N/2 7059 APInt B(M); 7060 B -= sdiv(N,Two); 7061 7062 // The A coefficient is N/2 7063 APInt A(N.sdiv(Two)); 7064 7065 // Compute the B^2-4ac term. 7066 APInt SqrtTerm(B); 7067 SqrtTerm *= B; 7068 SqrtTerm -= Four * (A * C); 7069 7070 if (SqrtTerm.isNegative()) { 7071 // The loop is provably infinite. 7072 return None; 7073 } 7074 7075 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7076 // integer value or else APInt::sqrt() will assert. 7077 APInt SqrtVal(SqrtTerm.sqrt()); 7078 7079 // Compute the two solutions for the quadratic formula. 7080 // The divisions must be performed as signed divisions. 7081 APInt NegB(-B); 7082 APInt TwoA(A << 1); 7083 if (TwoA.isMinValue()) 7084 return None; 7085 7086 LLVMContext &Context = SE.getContext(); 7087 7088 ConstantInt *Solution1 = 7089 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7090 ConstantInt *Solution2 = 7091 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7092 7093 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7094 cast<SCEVConstant>(SE.getConstant(Solution2))); 7095 } // end APIntOps namespace 7096 } 7097 7098 ScalarEvolution::ExitLimit 7099 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7100 bool AllowPredicates) { 7101 7102 // This is only used for loops with a "x != y" exit test. The exit condition 7103 // is now expressed as a single expression, V = x-y. So the exit test is 7104 // effectively V != 0. We know and take advantage of the fact that this 7105 // expression only being used in a comparison by zero context. 7106 7107 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7108 // If the value is a constant 7109 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7110 // If the value is already zero, the branch will execute zero times. 7111 if (C->getValue()->isZero()) return C; 7112 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7113 } 7114 7115 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7116 if (!AddRec && AllowPredicates) 7117 // Try to make this an AddRec using runtime tests, in the first X 7118 // iterations of this loop, where X is the SCEV expression found by the 7119 // algorithm below. 7120 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7121 7122 if (!AddRec || AddRec->getLoop() != L) 7123 return getCouldNotCompute(); 7124 7125 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7126 // the quadratic equation to solve it. 7127 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7128 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7129 const SCEVConstant *R1 = Roots->first; 7130 const SCEVConstant *R2 = Roots->second; 7131 // Pick the smallest positive root value. 7132 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7133 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7134 if (!CB->getZExtValue()) 7135 std::swap(R1, R2); // R1 is the minimum root now. 7136 7137 // We can only use this value if the chrec ends up with an exact zero 7138 // value at this index. When solving for "X*X != 5", for example, we 7139 // should not accept a root of 2. 7140 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7141 if (Val->isZero()) 7142 // We found a quadratic root! 7143 return ExitLimit(R1, R1, false, Predicates); 7144 } 7145 } 7146 return getCouldNotCompute(); 7147 } 7148 7149 // Otherwise we can only handle this if it is affine. 7150 if (!AddRec->isAffine()) 7151 return getCouldNotCompute(); 7152 7153 // If this is an affine expression, the execution count of this branch is 7154 // the minimum unsigned root of the following equation: 7155 // 7156 // Start + Step*N = 0 (mod 2^BW) 7157 // 7158 // equivalent to: 7159 // 7160 // Step*N = -Start (mod 2^BW) 7161 // 7162 // where BW is the common bit width of Start and Step. 7163 7164 // Get the initial value for the loop. 7165 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7166 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7167 7168 // For now we handle only constant steps. 7169 // 7170 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7171 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7172 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7173 // We have not yet seen any such cases. 7174 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7175 if (!StepC || StepC->getValue()->equalsInt(0)) 7176 return getCouldNotCompute(); 7177 7178 // For positive steps (counting up until unsigned overflow): 7179 // N = -Start/Step (as unsigned) 7180 // For negative steps (counting down to zero): 7181 // N = Start/-Step 7182 // First compute the unsigned distance from zero in the direction of Step. 7183 bool CountDown = StepC->getAPInt().isNegative(); 7184 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7185 7186 // Handle unitary steps, which cannot wraparound. 7187 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7188 // N = Distance (as unsigned) 7189 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7190 ConstantRange CR = getUnsignedRange(Start); 7191 const SCEV *MaxBECount; 7192 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7193 // When counting up, the worst starting value is 1, not 0. 7194 MaxBECount = CR.getUnsignedMax().isMinValue() 7195 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7196 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7197 else 7198 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7199 : -CR.getUnsignedMin()); 7200 return ExitLimit(Distance, MaxBECount, false, Predicates); 7201 } 7202 7203 // As a special case, handle the instance where Step is a positive power of 7204 // two. In this case, determining whether Step divides Distance evenly can be 7205 // done by counting and comparing the number of trailing zeros of Step and 7206 // Distance. 7207 if (!CountDown) { 7208 const APInt &StepV = StepC->getAPInt(); 7209 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7210 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7211 // case is not handled as this code is guarded by !CountDown. 7212 if (StepV.isPowerOf2() && 7213 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7214 // Here we've constrained the equation to be of the form 7215 // 7216 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7217 // 7218 // where we're operating on a W bit wide integer domain and k is 7219 // non-negative. The smallest unsigned solution for X is the trip count. 7220 // 7221 // (0) is equivalent to: 7222 // 7223 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7224 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7225 // <=> 2^k * Distance' - X = L * 2^(W - N) 7226 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7227 // 7228 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7229 // by 2^(W - N). 7230 // 7231 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7232 // 7233 // E.g. say we're solving 7234 // 7235 // 2 * Val = 2 * X (in i8) ... (3) 7236 // 7237 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7238 // 7239 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7240 // necessarily the smallest unsigned value of X that satisfies (3). 7241 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7242 // is i8 1, not i8 -127 7243 7244 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7245 7246 // Since SCEV does not have a URem node, we construct one using a truncate 7247 // and a zero extend. 7248 7249 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7250 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7251 auto *WideTy = Distance->getType(); 7252 7253 const SCEV *Limit = 7254 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7255 return ExitLimit(Limit, Limit, false, Predicates); 7256 } 7257 } 7258 7259 // If the condition controls loop exit (the loop exits only if the expression 7260 // is true) and the addition is no-wrap we can use unsigned divide to 7261 // compute the backedge count. In this case, the step may not divide the 7262 // distance, but we don't care because if the condition is "missed" the loop 7263 // will have undefined behavior due to wrapping. 7264 if (ControlsExit && AddRec->hasNoSelfWrap() && 7265 loopHasNoAbnormalExits(AddRec->getLoop())) { 7266 const SCEV *Exact = 7267 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7268 return ExitLimit(Exact, Exact, false, Predicates); 7269 } 7270 7271 // Then, try to solve the above equation provided that Start is constant. 7272 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7273 const SCEV *E = SolveLinEquationWithOverflow( 7274 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7275 return ExitLimit(E, E, false, Predicates); 7276 } 7277 return getCouldNotCompute(); 7278 } 7279 7280 ScalarEvolution::ExitLimit 7281 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7282 // Loops that look like: while (X == 0) are very strange indeed. We don't 7283 // handle them yet except for the trivial case. This could be expanded in the 7284 // future as needed. 7285 7286 // If the value is a constant, check to see if it is known to be non-zero 7287 // already. If so, the backedge will execute zero times. 7288 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7289 if (!C->getValue()->isNullValue()) 7290 return getZero(C->getType()); 7291 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7292 } 7293 7294 // We could implement others, but I really doubt anyone writes loops like 7295 // this, and if they did, they would already be constant folded. 7296 return getCouldNotCompute(); 7297 } 7298 7299 std::pair<BasicBlock *, BasicBlock *> 7300 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7301 // If the block has a unique predecessor, then there is no path from the 7302 // predecessor to the block that does not go through the direct edge 7303 // from the predecessor to the block. 7304 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7305 return {Pred, BB}; 7306 7307 // A loop's header is defined to be a block that dominates the loop. 7308 // If the header has a unique predecessor outside the loop, it must be 7309 // a block that has exactly one successor that can reach the loop. 7310 if (Loop *L = LI.getLoopFor(BB)) 7311 return {L->getLoopPredecessor(), L->getHeader()}; 7312 7313 return {nullptr, nullptr}; 7314 } 7315 7316 /// SCEV structural equivalence is usually sufficient for testing whether two 7317 /// expressions are equal, however for the purposes of looking for a condition 7318 /// guarding a loop, it can be useful to be a little more general, since a 7319 /// front-end may have replicated the controlling expression. 7320 /// 7321 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7322 // Quick check to see if they are the same SCEV. 7323 if (A == B) return true; 7324 7325 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7326 // Not all instructions that are "identical" compute the same value. For 7327 // instance, two distinct alloca instructions allocating the same type are 7328 // identical and do not read memory; but compute distinct values. 7329 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7330 }; 7331 7332 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7333 // two different instructions with the same value. Check for this case. 7334 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7335 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7336 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7337 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7338 if (ComputesEqualValues(AI, BI)) 7339 return true; 7340 7341 // Otherwise assume they may have a different value. 7342 return false; 7343 } 7344 7345 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7346 const SCEV *&LHS, const SCEV *&RHS, 7347 unsigned Depth) { 7348 bool Changed = false; 7349 7350 // If we hit the max recursion limit bail out. 7351 if (Depth >= 3) 7352 return false; 7353 7354 // Canonicalize a constant to the right side. 7355 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7356 // Check for both operands constant. 7357 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7358 if (ConstantExpr::getICmp(Pred, 7359 LHSC->getValue(), 7360 RHSC->getValue())->isNullValue()) 7361 goto trivially_false; 7362 else 7363 goto trivially_true; 7364 } 7365 // Otherwise swap the operands to put the constant on the right. 7366 std::swap(LHS, RHS); 7367 Pred = ICmpInst::getSwappedPredicate(Pred); 7368 Changed = true; 7369 } 7370 7371 // If we're comparing an addrec with a value which is loop-invariant in the 7372 // addrec's loop, put the addrec on the left. Also make a dominance check, 7373 // as both operands could be addrecs loop-invariant in each other's loop. 7374 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7375 const Loop *L = AR->getLoop(); 7376 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7377 std::swap(LHS, RHS); 7378 Pred = ICmpInst::getSwappedPredicate(Pred); 7379 Changed = true; 7380 } 7381 } 7382 7383 // If there's a constant operand, canonicalize comparisons with boundary 7384 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7385 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7386 const APInt &RA = RC->getAPInt(); 7387 7388 bool SimplifiedByConstantRange = false; 7389 7390 if (!ICmpInst::isEquality(Pred)) { 7391 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7392 if (ExactCR.isFullSet()) 7393 goto trivially_true; 7394 else if (ExactCR.isEmptySet()) 7395 goto trivially_false; 7396 7397 APInt NewRHS; 7398 CmpInst::Predicate NewPred; 7399 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7400 ICmpInst::isEquality(NewPred)) { 7401 // We were able to convert an inequality to an equality. 7402 Pred = NewPred; 7403 RHS = getConstant(NewRHS); 7404 Changed = SimplifiedByConstantRange = true; 7405 } 7406 } 7407 7408 if (!SimplifiedByConstantRange) { 7409 switch (Pred) { 7410 default: 7411 break; 7412 case ICmpInst::ICMP_EQ: 7413 case ICmpInst::ICMP_NE: 7414 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7415 if (!RA) 7416 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7417 if (const SCEVMulExpr *ME = 7418 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7419 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7420 ME->getOperand(0)->isAllOnesValue()) { 7421 RHS = AE->getOperand(1); 7422 LHS = ME->getOperand(1); 7423 Changed = true; 7424 } 7425 break; 7426 7427 7428 // The "Should have been caught earlier!" messages refer to the fact 7429 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7430 // should have fired on the corresponding cases, and canonicalized the 7431 // check to trivially_true or trivially_false. 7432 7433 case ICmpInst::ICMP_UGE: 7434 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7435 Pred = ICmpInst::ICMP_UGT; 7436 RHS = getConstant(RA - 1); 7437 Changed = true; 7438 break; 7439 case ICmpInst::ICMP_ULE: 7440 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7441 Pred = ICmpInst::ICMP_ULT; 7442 RHS = getConstant(RA + 1); 7443 Changed = true; 7444 break; 7445 case ICmpInst::ICMP_SGE: 7446 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7447 Pred = ICmpInst::ICMP_SGT; 7448 RHS = getConstant(RA - 1); 7449 Changed = true; 7450 break; 7451 case ICmpInst::ICMP_SLE: 7452 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7453 Pred = ICmpInst::ICMP_SLT; 7454 RHS = getConstant(RA + 1); 7455 Changed = true; 7456 break; 7457 } 7458 } 7459 } 7460 7461 // Check for obvious equality. 7462 if (HasSameValue(LHS, RHS)) { 7463 if (ICmpInst::isTrueWhenEqual(Pred)) 7464 goto trivially_true; 7465 if (ICmpInst::isFalseWhenEqual(Pred)) 7466 goto trivially_false; 7467 } 7468 7469 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7470 // adding or subtracting 1 from one of the operands. 7471 switch (Pred) { 7472 case ICmpInst::ICMP_SLE: 7473 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7474 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7475 SCEV::FlagNSW); 7476 Pred = ICmpInst::ICMP_SLT; 7477 Changed = true; 7478 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7479 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7480 SCEV::FlagNSW); 7481 Pred = ICmpInst::ICMP_SLT; 7482 Changed = true; 7483 } 7484 break; 7485 case ICmpInst::ICMP_SGE: 7486 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7487 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7488 SCEV::FlagNSW); 7489 Pred = ICmpInst::ICMP_SGT; 7490 Changed = true; 7491 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7492 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7493 SCEV::FlagNSW); 7494 Pred = ICmpInst::ICMP_SGT; 7495 Changed = true; 7496 } 7497 break; 7498 case ICmpInst::ICMP_ULE: 7499 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7500 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7501 SCEV::FlagNUW); 7502 Pred = ICmpInst::ICMP_ULT; 7503 Changed = true; 7504 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7505 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7506 Pred = ICmpInst::ICMP_ULT; 7507 Changed = true; 7508 } 7509 break; 7510 case ICmpInst::ICMP_UGE: 7511 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7512 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7513 Pred = ICmpInst::ICMP_UGT; 7514 Changed = true; 7515 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7516 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7517 SCEV::FlagNUW); 7518 Pred = ICmpInst::ICMP_UGT; 7519 Changed = true; 7520 } 7521 break; 7522 default: 7523 break; 7524 } 7525 7526 // TODO: More simplifications are possible here. 7527 7528 // Recursively simplify until we either hit a recursion limit or nothing 7529 // changes. 7530 if (Changed) 7531 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7532 7533 return Changed; 7534 7535 trivially_true: 7536 // Return 0 == 0. 7537 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7538 Pred = ICmpInst::ICMP_EQ; 7539 return true; 7540 7541 trivially_false: 7542 // Return 0 != 0. 7543 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7544 Pred = ICmpInst::ICMP_NE; 7545 return true; 7546 } 7547 7548 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7549 return getSignedRange(S).getSignedMax().isNegative(); 7550 } 7551 7552 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7553 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7554 } 7555 7556 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7557 return !getSignedRange(S).getSignedMin().isNegative(); 7558 } 7559 7560 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7561 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7562 } 7563 7564 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7565 return isKnownNegative(S) || isKnownPositive(S); 7566 } 7567 7568 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7569 const SCEV *LHS, const SCEV *RHS) { 7570 // Canonicalize the inputs first. 7571 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7572 7573 // If LHS or RHS is an addrec, check to see if the condition is true in 7574 // every iteration of the loop. 7575 // If LHS and RHS are both addrec, both conditions must be true in 7576 // every iteration of the loop. 7577 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7578 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7579 bool LeftGuarded = false; 7580 bool RightGuarded = false; 7581 if (LAR) { 7582 const Loop *L = LAR->getLoop(); 7583 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7584 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7585 if (!RAR) return true; 7586 LeftGuarded = true; 7587 } 7588 } 7589 if (RAR) { 7590 const Loop *L = RAR->getLoop(); 7591 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7592 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7593 if (!LAR) return true; 7594 RightGuarded = true; 7595 } 7596 } 7597 if (LeftGuarded && RightGuarded) 7598 return true; 7599 7600 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7601 return true; 7602 7603 // Otherwise see what can be done with known constant ranges. 7604 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7605 } 7606 7607 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7608 ICmpInst::Predicate Pred, 7609 bool &Increasing) { 7610 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7611 7612 #ifndef NDEBUG 7613 // Verify an invariant: inverting the predicate should turn a monotonically 7614 // increasing change to a monotonically decreasing one, and vice versa. 7615 bool IncreasingSwapped; 7616 bool ResultSwapped = isMonotonicPredicateImpl( 7617 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7618 7619 assert(Result == ResultSwapped && "should be able to analyze both!"); 7620 if (ResultSwapped) 7621 assert(Increasing == !IncreasingSwapped && 7622 "monotonicity should flip as we flip the predicate"); 7623 #endif 7624 7625 return Result; 7626 } 7627 7628 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7629 ICmpInst::Predicate Pred, 7630 bool &Increasing) { 7631 7632 // A zero step value for LHS means the induction variable is essentially a 7633 // loop invariant value. We don't really depend on the predicate actually 7634 // flipping from false to true (for increasing predicates, and the other way 7635 // around for decreasing predicates), all we care about is that *if* the 7636 // predicate changes then it only changes from false to true. 7637 // 7638 // A zero step value in itself is not very useful, but there may be places 7639 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7640 // as general as possible. 7641 7642 switch (Pred) { 7643 default: 7644 return false; // Conservative answer 7645 7646 case ICmpInst::ICMP_UGT: 7647 case ICmpInst::ICMP_UGE: 7648 case ICmpInst::ICMP_ULT: 7649 case ICmpInst::ICMP_ULE: 7650 if (!LHS->hasNoUnsignedWrap()) 7651 return false; 7652 7653 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7654 return true; 7655 7656 case ICmpInst::ICMP_SGT: 7657 case ICmpInst::ICMP_SGE: 7658 case ICmpInst::ICMP_SLT: 7659 case ICmpInst::ICMP_SLE: { 7660 if (!LHS->hasNoSignedWrap()) 7661 return false; 7662 7663 const SCEV *Step = LHS->getStepRecurrence(*this); 7664 7665 if (isKnownNonNegative(Step)) { 7666 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7667 return true; 7668 } 7669 7670 if (isKnownNonPositive(Step)) { 7671 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7672 return true; 7673 } 7674 7675 return false; 7676 } 7677 7678 } 7679 7680 llvm_unreachable("switch has default clause!"); 7681 } 7682 7683 bool ScalarEvolution::isLoopInvariantPredicate( 7684 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7685 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7686 const SCEV *&InvariantRHS) { 7687 7688 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7689 if (!isLoopInvariant(RHS, L)) { 7690 if (!isLoopInvariant(LHS, L)) 7691 return false; 7692 7693 std::swap(LHS, RHS); 7694 Pred = ICmpInst::getSwappedPredicate(Pred); 7695 } 7696 7697 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7698 if (!ArLHS || ArLHS->getLoop() != L) 7699 return false; 7700 7701 bool Increasing; 7702 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7703 return false; 7704 7705 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7706 // true as the loop iterates, and the backedge is control dependent on 7707 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7708 // 7709 // * if the predicate was false in the first iteration then the predicate 7710 // is never evaluated again, since the loop exits without taking the 7711 // backedge. 7712 // * if the predicate was true in the first iteration then it will 7713 // continue to be true for all future iterations since it is 7714 // monotonically increasing. 7715 // 7716 // For both the above possibilities, we can replace the loop varying 7717 // predicate with its value on the first iteration of the loop (which is 7718 // loop invariant). 7719 // 7720 // A similar reasoning applies for a monotonically decreasing predicate, by 7721 // replacing true with false and false with true in the above two bullets. 7722 7723 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7724 7725 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7726 return false; 7727 7728 InvariantPred = Pred; 7729 InvariantLHS = ArLHS->getStart(); 7730 InvariantRHS = RHS; 7731 return true; 7732 } 7733 7734 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7735 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7736 if (HasSameValue(LHS, RHS)) 7737 return ICmpInst::isTrueWhenEqual(Pred); 7738 7739 // This code is split out from isKnownPredicate because it is called from 7740 // within isLoopEntryGuardedByCond. 7741 7742 auto CheckRanges = 7743 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7744 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7745 .contains(RangeLHS); 7746 }; 7747 7748 // The check at the top of the function catches the case where the values are 7749 // known to be equal. 7750 if (Pred == CmpInst::ICMP_EQ) 7751 return false; 7752 7753 if (Pred == CmpInst::ICMP_NE) 7754 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7755 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7756 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7757 7758 if (CmpInst::isSigned(Pred)) 7759 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7760 7761 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7762 } 7763 7764 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7765 const SCEV *LHS, 7766 const SCEV *RHS) { 7767 7768 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7769 // Return Y via OutY. 7770 auto MatchBinaryAddToConst = 7771 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7772 SCEV::NoWrapFlags ExpectedFlags) { 7773 const SCEV *NonConstOp, *ConstOp; 7774 SCEV::NoWrapFlags FlagsPresent; 7775 7776 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7777 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7778 return false; 7779 7780 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7781 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7782 }; 7783 7784 APInt C; 7785 7786 switch (Pred) { 7787 default: 7788 break; 7789 7790 case ICmpInst::ICMP_SGE: 7791 std::swap(LHS, RHS); 7792 case ICmpInst::ICMP_SLE: 7793 // X s<= (X + C)<nsw> if C >= 0 7794 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7795 return true; 7796 7797 // (X + C)<nsw> s<= X if C <= 0 7798 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7799 !C.isStrictlyPositive()) 7800 return true; 7801 break; 7802 7803 case ICmpInst::ICMP_SGT: 7804 std::swap(LHS, RHS); 7805 case ICmpInst::ICMP_SLT: 7806 // X s< (X + C)<nsw> if C > 0 7807 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7808 C.isStrictlyPositive()) 7809 return true; 7810 7811 // (X + C)<nsw> s< X if C < 0 7812 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7813 return true; 7814 break; 7815 } 7816 7817 return false; 7818 } 7819 7820 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7821 const SCEV *LHS, 7822 const SCEV *RHS) { 7823 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7824 return false; 7825 7826 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7827 // the stack can result in exponential time complexity. 7828 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7829 7830 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7831 // 7832 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7833 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7834 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7835 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7836 // use isKnownPredicate later if needed. 7837 return isKnownNonNegative(RHS) && 7838 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7839 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7840 } 7841 7842 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7843 ICmpInst::Predicate Pred, 7844 const SCEV *LHS, const SCEV *RHS) { 7845 // No need to even try if we know the module has no guards. 7846 if (!HasGuards) 7847 return false; 7848 7849 return any_of(*BB, [&](Instruction &I) { 7850 using namespace llvm::PatternMatch; 7851 7852 Value *Condition; 7853 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7854 m_Value(Condition))) && 7855 isImpliedCond(Pred, LHS, RHS, Condition, false); 7856 }); 7857 } 7858 7859 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7860 /// protected by a conditional between LHS and RHS. This is used to 7861 /// to eliminate casts. 7862 bool 7863 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7864 ICmpInst::Predicate Pred, 7865 const SCEV *LHS, const SCEV *RHS) { 7866 // Interpret a null as meaning no loop, where there is obviously no guard 7867 // (interprocedural conditions notwithstanding). 7868 if (!L) return true; 7869 7870 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7871 return true; 7872 7873 BasicBlock *Latch = L->getLoopLatch(); 7874 if (!Latch) 7875 return false; 7876 7877 BranchInst *LoopContinuePredicate = 7878 dyn_cast<BranchInst>(Latch->getTerminator()); 7879 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7880 isImpliedCond(Pred, LHS, RHS, 7881 LoopContinuePredicate->getCondition(), 7882 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7883 return true; 7884 7885 // We don't want more than one activation of the following loops on the stack 7886 // -- that can lead to O(n!) time complexity. 7887 if (WalkingBEDominatingConds) 7888 return false; 7889 7890 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7891 7892 // See if we can exploit a trip count to prove the predicate. 7893 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7894 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7895 if (LatchBECount != getCouldNotCompute()) { 7896 // We know that Latch branches back to the loop header exactly 7897 // LatchBECount times. This means the backdege condition at Latch is 7898 // equivalent to "{0,+,1} u< LatchBECount". 7899 Type *Ty = LatchBECount->getType(); 7900 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7901 const SCEV *LoopCounter = 7902 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7903 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7904 LatchBECount)) 7905 return true; 7906 } 7907 7908 // Check conditions due to any @llvm.assume intrinsics. 7909 for (auto &AssumeVH : AC.assumptions()) { 7910 if (!AssumeVH) 7911 continue; 7912 auto *CI = cast<CallInst>(AssumeVH); 7913 if (!DT.dominates(CI, Latch->getTerminator())) 7914 continue; 7915 7916 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7917 return true; 7918 } 7919 7920 // If the loop is not reachable from the entry block, we risk running into an 7921 // infinite loop as we walk up into the dom tree. These loops do not matter 7922 // anyway, so we just return a conservative answer when we see them. 7923 if (!DT.isReachableFromEntry(L->getHeader())) 7924 return false; 7925 7926 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7927 return true; 7928 7929 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7930 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7931 7932 assert(DTN && "should reach the loop header before reaching the root!"); 7933 7934 BasicBlock *BB = DTN->getBlock(); 7935 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7936 return true; 7937 7938 BasicBlock *PBB = BB->getSinglePredecessor(); 7939 if (!PBB) 7940 continue; 7941 7942 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7943 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7944 continue; 7945 7946 Value *Condition = ContinuePredicate->getCondition(); 7947 7948 // If we have an edge `E` within the loop body that dominates the only 7949 // latch, the condition guarding `E` also guards the backedge. This 7950 // reasoning works only for loops with a single latch. 7951 7952 BasicBlockEdge DominatingEdge(PBB, BB); 7953 if (DominatingEdge.isSingleEdge()) { 7954 // We're constructively (and conservatively) enumerating edges within the 7955 // loop body that dominate the latch. The dominator tree better agree 7956 // with us on this: 7957 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7958 7959 if (isImpliedCond(Pred, LHS, RHS, Condition, 7960 BB != ContinuePredicate->getSuccessor(0))) 7961 return true; 7962 } 7963 } 7964 7965 return false; 7966 } 7967 7968 bool 7969 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7970 ICmpInst::Predicate Pred, 7971 const SCEV *LHS, const SCEV *RHS) { 7972 // Interpret a null as meaning no loop, where there is obviously no guard 7973 // (interprocedural conditions notwithstanding). 7974 if (!L) return false; 7975 7976 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7977 return true; 7978 7979 // Starting at the loop predecessor, climb up the predecessor chain, as long 7980 // as there are predecessors that can be found that have unique successors 7981 // leading to the original header. 7982 for (std::pair<BasicBlock *, BasicBlock *> 7983 Pair(L->getLoopPredecessor(), L->getHeader()); 7984 Pair.first; 7985 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7986 7987 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 7988 return true; 7989 7990 BranchInst *LoopEntryPredicate = 7991 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7992 if (!LoopEntryPredicate || 7993 LoopEntryPredicate->isUnconditional()) 7994 continue; 7995 7996 if (isImpliedCond(Pred, LHS, RHS, 7997 LoopEntryPredicate->getCondition(), 7998 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7999 return true; 8000 } 8001 8002 // Check conditions due to any @llvm.assume intrinsics. 8003 for (auto &AssumeVH : AC.assumptions()) { 8004 if (!AssumeVH) 8005 continue; 8006 auto *CI = cast<CallInst>(AssumeVH); 8007 if (!DT.dominates(CI, L->getHeader())) 8008 continue; 8009 8010 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8011 return true; 8012 } 8013 8014 return false; 8015 } 8016 8017 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8018 const SCEV *LHS, const SCEV *RHS, 8019 Value *FoundCondValue, 8020 bool Inverse) { 8021 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8022 return false; 8023 8024 auto ClearOnExit = 8025 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8026 8027 // Recursively handle And and Or conditions. 8028 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8029 if (BO->getOpcode() == Instruction::And) { 8030 if (!Inverse) 8031 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8032 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8033 } else if (BO->getOpcode() == Instruction::Or) { 8034 if (Inverse) 8035 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8036 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8037 } 8038 } 8039 8040 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8041 if (!ICI) return false; 8042 8043 // Now that we found a conditional branch that dominates the loop or controls 8044 // the loop latch. Check to see if it is the comparison we are looking for. 8045 ICmpInst::Predicate FoundPred; 8046 if (Inverse) 8047 FoundPred = ICI->getInversePredicate(); 8048 else 8049 FoundPred = ICI->getPredicate(); 8050 8051 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8052 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8053 8054 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8055 } 8056 8057 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8058 const SCEV *RHS, 8059 ICmpInst::Predicate FoundPred, 8060 const SCEV *FoundLHS, 8061 const SCEV *FoundRHS) { 8062 // Balance the types. 8063 if (getTypeSizeInBits(LHS->getType()) < 8064 getTypeSizeInBits(FoundLHS->getType())) { 8065 if (CmpInst::isSigned(Pred)) { 8066 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8067 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8068 } else { 8069 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8070 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8071 } 8072 } else if (getTypeSizeInBits(LHS->getType()) > 8073 getTypeSizeInBits(FoundLHS->getType())) { 8074 if (CmpInst::isSigned(FoundPred)) { 8075 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8076 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8077 } else { 8078 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8079 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8080 } 8081 } 8082 8083 // Canonicalize the query to match the way instcombine will have 8084 // canonicalized the comparison. 8085 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8086 if (LHS == RHS) 8087 return CmpInst::isTrueWhenEqual(Pred); 8088 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8089 if (FoundLHS == FoundRHS) 8090 return CmpInst::isFalseWhenEqual(FoundPred); 8091 8092 // Check to see if we can make the LHS or RHS match. 8093 if (LHS == FoundRHS || RHS == FoundLHS) { 8094 if (isa<SCEVConstant>(RHS)) { 8095 std::swap(FoundLHS, FoundRHS); 8096 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8097 } else { 8098 std::swap(LHS, RHS); 8099 Pred = ICmpInst::getSwappedPredicate(Pred); 8100 } 8101 } 8102 8103 // Check whether the found predicate is the same as the desired predicate. 8104 if (FoundPred == Pred) 8105 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8106 8107 // Check whether swapping the found predicate makes it the same as the 8108 // desired predicate. 8109 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8110 if (isa<SCEVConstant>(RHS)) 8111 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8112 else 8113 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8114 RHS, LHS, FoundLHS, FoundRHS); 8115 } 8116 8117 // Unsigned comparison is the same as signed comparison when both the operands 8118 // are non-negative. 8119 if (CmpInst::isUnsigned(FoundPred) && 8120 CmpInst::getSignedPredicate(FoundPred) == Pred && 8121 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8122 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8123 8124 // Check if we can make progress by sharpening ranges. 8125 if (FoundPred == ICmpInst::ICMP_NE && 8126 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8127 8128 const SCEVConstant *C = nullptr; 8129 const SCEV *V = nullptr; 8130 8131 if (isa<SCEVConstant>(FoundLHS)) { 8132 C = cast<SCEVConstant>(FoundLHS); 8133 V = FoundRHS; 8134 } else { 8135 C = cast<SCEVConstant>(FoundRHS); 8136 V = FoundLHS; 8137 } 8138 8139 // The guarding predicate tells us that C != V. If the known range 8140 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8141 // range we consider has to correspond to same signedness as the 8142 // predicate we're interested in folding. 8143 8144 APInt Min = ICmpInst::isSigned(Pred) ? 8145 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8146 8147 if (Min == C->getAPInt()) { 8148 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8149 // This is true even if (Min + 1) wraps around -- in case of 8150 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8151 8152 APInt SharperMin = Min + 1; 8153 8154 switch (Pred) { 8155 case ICmpInst::ICMP_SGE: 8156 case ICmpInst::ICMP_UGE: 8157 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8158 // RHS, we're done. 8159 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8160 getConstant(SharperMin))) 8161 return true; 8162 8163 case ICmpInst::ICMP_SGT: 8164 case ICmpInst::ICMP_UGT: 8165 // We know from the range information that (V `Pred` Min || 8166 // V == Min). We know from the guarding condition that !(V 8167 // == Min). This gives us 8168 // 8169 // V `Pred` Min || V == Min && !(V == Min) 8170 // => V `Pred` Min 8171 // 8172 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8173 8174 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8175 return true; 8176 8177 default: 8178 // No change 8179 break; 8180 } 8181 } 8182 } 8183 8184 // Check whether the actual condition is beyond sufficient. 8185 if (FoundPred == ICmpInst::ICMP_EQ) 8186 if (ICmpInst::isTrueWhenEqual(Pred)) 8187 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8188 return true; 8189 if (Pred == ICmpInst::ICMP_NE) 8190 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8191 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8192 return true; 8193 8194 // Otherwise assume the worst. 8195 return false; 8196 } 8197 8198 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8199 const SCEV *&L, const SCEV *&R, 8200 SCEV::NoWrapFlags &Flags) { 8201 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8202 if (!AE || AE->getNumOperands() != 2) 8203 return false; 8204 8205 L = AE->getOperand(0); 8206 R = AE->getOperand(1); 8207 Flags = AE->getNoWrapFlags(); 8208 return true; 8209 } 8210 8211 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8212 const SCEV *Less) { 8213 // We avoid subtracting expressions here because this function is usually 8214 // fairly deep in the call stack (i.e. is called many times). 8215 8216 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8217 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8218 const auto *MAR = cast<SCEVAddRecExpr>(More); 8219 8220 if (LAR->getLoop() != MAR->getLoop()) 8221 return None; 8222 8223 // We look at affine expressions only; not for correctness but to keep 8224 // getStepRecurrence cheap. 8225 if (!LAR->isAffine() || !MAR->isAffine()) 8226 return None; 8227 8228 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8229 return None; 8230 8231 Less = LAR->getStart(); 8232 More = MAR->getStart(); 8233 8234 // fall through 8235 } 8236 8237 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8238 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8239 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8240 return M - L; 8241 } 8242 8243 const SCEV *L, *R; 8244 SCEV::NoWrapFlags Flags; 8245 if (splitBinaryAdd(Less, L, R, Flags)) 8246 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8247 if (R == More) 8248 return -(LC->getAPInt()); 8249 8250 if (splitBinaryAdd(More, L, R, Flags)) 8251 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8252 if (R == Less) 8253 return LC->getAPInt(); 8254 8255 return None; 8256 } 8257 8258 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8259 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8260 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8261 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8262 return false; 8263 8264 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8265 if (!AddRecLHS) 8266 return false; 8267 8268 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8269 if (!AddRecFoundLHS) 8270 return false; 8271 8272 // We'd like to let SCEV reason about control dependencies, so we constrain 8273 // both the inequalities to be about add recurrences on the same loop. This 8274 // way we can use isLoopEntryGuardedByCond later. 8275 8276 const Loop *L = AddRecFoundLHS->getLoop(); 8277 if (L != AddRecLHS->getLoop()) 8278 return false; 8279 8280 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8281 // 8282 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8283 // ... (2) 8284 // 8285 // Informal proof for (2), assuming (1) [*]: 8286 // 8287 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8288 // 8289 // Then 8290 // 8291 // FoundLHS s< FoundRHS s< INT_MIN - C 8292 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8293 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8294 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8295 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8296 // <=> FoundLHS + C s< FoundRHS + C 8297 // 8298 // [*]: (1) can be proved by ruling out overflow. 8299 // 8300 // [**]: This can be proved by analyzing all the four possibilities: 8301 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8302 // (A s>= 0, B s>= 0). 8303 // 8304 // Note: 8305 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8306 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8307 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8308 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8309 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8310 // C)". 8311 8312 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8313 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8314 if (!LDiff || !RDiff || *LDiff != *RDiff) 8315 return false; 8316 8317 if (LDiff->isMinValue()) 8318 return true; 8319 8320 APInt FoundRHSLimit; 8321 8322 if (Pred == CmpInst::ICMP_ULT) { 8323 FoundRHSLimit = -(*RDiff); 8324 } else { 8325 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8326 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8327 } 8328 8329 // Try to prove (1) or (2), as needed. 8330 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8331 getConstant(FoundRHSLimit)); 8332 } 8333 8334 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8335 const SCEV *LHS, const SCEV *RHS, 8336 const SCEV *FoundLHS, 8337 const SCEV *FoundRHS) { 8338 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8339 return true; 8340 8341 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8342 return true; 8343 8344 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8345 FoundLHS, FoundRHS) || 8346 // ~x < ~y --> x > y 8347 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8348 getNotSCEV(FoundRHS), 8349 getNotSCEV(FoundLHS)); 8350 } 8351 8352 8353 /// If Expr computes ~A, return A else return nullptr 8354 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8355 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8356 if (!Add || Add->getNumOperands() != 2 || 8357 !Add->getOperand(0)->isAllOnesValue()) 8358 return nullptr; 8359 8360 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8361 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8362 !AddRHS->getOperand(0)->isAllOnesValue()) 8363 return nullptr; 8364 8365 return AddRHS->getOperand(1); 8366 } 8367 8368 8369 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8370 template<typename MaxExprType> 8371 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8372 const SCEV *Candidate) { 8373 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8374 if (!MaxExpr) return false; 8375 8376 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8377 } 8378 8379 8380 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8381 template<typename MaxExprType> 8382 static bool IsMinConsistingOf(ScalarEvolution &SE, 8383 const SCEV *MaybeMinExpr, 8384 const SCEV *Candidate) { 8385 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8386 if (!MaybeMaxExpr) 8387 return false; 8388 8389 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8390 } 8391 8392 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8393 ICmpInst::Predicate Pred, 8394 const SCEV *LHS, const SCEV *RHS) { 8395 8396 // If both sides are affine addrecs for the same loop, with equal 8397 // steps, and we know the recurrences don't wrap, then we only 8398 // need to check the predicate on the starting values. 8399 8400 if (!ICmpInst::isRelational(Pred)) 8401 return false; 8402 8403 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8404 if (!LAR) 8405 return false; 8406 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8407 if (!RAR) 8408 return false; 8409 if (LAR->getLoop() != RAR->getLoop()) 8410 return false; 8411 if (!LAR->isAffine() || !RAR->isAffine()) 8412 return false; 8413 8414 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8415 return false; 8416 8417 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8418 SCEV::FlagNSW : SCEV::FlagNUW; 8419 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8420 return false; 8421 8422 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8423 } 8424 8425 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8426 /// expression? 8427 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8428 ICmpInst::Predicate Pred, 8429 const SCEV *LHS, const SCEV *RHS) { 8430 switch (Pred) { 8431 default: 8432 return false; 8433 8434 case ICmpInst::ICMP_SGE: 8435 std::swap(LHS, RHS); 8436 LLVM_FALLTHROUGH; 8437 case ICmpInst::ICMP_SLE: 8438 return 8439 // min(A, ...) <= A 8440 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8441 // A <= max(A, ...) 8442 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8443 8444 case ICmpInst::ICMP_UGE: 8445 std::swap(LHS, RHS); 8446 LLVM_FALLTHROUGH; 8447 case ICmpInst::ICMP_ULE: 8448 return 8449 // min(A, ...) <= A 8450 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8451 // A <= max(A, ...) 8452 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8453 } 8454 8455 llvm_unreachable("covered switch fell through?!"); 8456 } 8457 8458 bool 8459 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8460 const SCEV *LHS, const SCEV *RHS, 8461 const SCEV *FoundLHS, 8462 const SCEV *FoundRHS) { 8463 auto IsKnownPredicateFull = 8464 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8465 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8466 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8467 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8468 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8469 }; 8470 8471 switch (Pred) { 8472 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8473 case ICmpInst::ICMP_EQ: 8474 case ICmpInst::ICMP_NE: 8475 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8476 return true; 8477 break; 8478 case ICmpInst::ICMP_SLT: 8479 case ICmpInst::ICMP_SLE: 8480 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8481 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8482 return true; 8483 break; 8484 case ICmpInst::ICMP_SGT: 8485 case ICmpInst::ICMP_SGE: 8486 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8487 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8488 return true; 8489 break; 8490 case ICmpInst::ICMP_ULT: 8491 case ICmpInst::ICMP_ULE: 8492 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8493 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8494 return true; 8495 break; 8496 case ICmpInst::ICMP_UGT: 8497 case ICmpInst::ICMP_UGE: 8498 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8499 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8500 return true; 8501 break; 8502 } 8503 8504 return false; 8505 } 8506 8507 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8508 const SCEV *LHS, 8509 const SCEV *RHS, 8510 const SCEV *FoundLHS, 8511 const SCEV *FoundRHS) { 8512 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8513 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8514 // reduce the compile time impact of this optimization. 8515 return false; 8516 8517 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8518 if (!Addend) 8519 return false; 8520 8521 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8522 8523 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8524 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8525 ConstantRange FoundLHSRange = 8526 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8527 8528 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8529 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8530 8531 // We can also compute the range of values for `LHS` that satisfy the 8532 // consequent, "`LHS` `Pred` `RHS`": 8533 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8534 ConstantRange SatisfyingLHSRange = 8535 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8536 8537 // The antecedent implies the consequent if every value of `LHS` that 8538 // satisfies the antecedent also satisfies the consequent. 8539 return SatisfyingLHSRange.contains(LHSRange); 8540 } 8541 8542 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8543 bool IsSigned, bool NoWrap) { 8544 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8545 8546 if (NoWrap) return false; 8547 8548 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8549 const SCEV *One = getOne(Stride->getType()); 8550 8551 if (IsSigned) { 8552 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8553 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8554 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8555 .getSignedMax(); 8556 8557 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8558 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8559 } 8560 8561 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8562 APInt MaxValue = APInt::getMaxValue(BitWidth); 8563 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8564 .getUnsignedMax(); 8565 8566 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8567 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8568 } 8569 8570 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8571 bool IsSigned, bool NoWrap) { 8572 if (NoWrap) return false; 8573 8574 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8575 const SCEV *One = getOne(Stride->getType()); 8576 8577 if (IsSigned) { 8578 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8579 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8580 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8581 .getSignedMax(); 8582 8583 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8584 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8585 } 8586 8587 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8588 APInt MinValue = APInt::getMinValue(BitWidth); 8589 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8590 .getUnsignedMax(); 8591 8592 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8593 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8594 } 8595 8596 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8597 bool Equality) { 8598 const SCEV *One = getOne(Step->getType()); 8599 Delta = Equality ? getAddExpr(Delta, Step) 8600 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8601 return getUDivExpr(Delta, Step); 8602 } 8603 8604 ScalarEvolution::ExitLimit 8605 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8606 const Loop *L, bool IsSigned, 8607 bool ControlsExit, bool AllowPredicates) { 8608 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8609 // We handle only IV < Invariant 8610 if (!isLoopInvariant(RHS, L)) 8611 return getCouldNotCompute(); 8612 8613 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8614 bool PredicatedIV = false; 8615 8616 if (!IV && AllowPredicates) { 8617 // Try to make this an AddRec using runtime tests, in the first X 8618 // iterations of this loop, where X is the SCEV expression found by the 8619 // algorithm below. 8620 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8621 PredicatedIV = true; 8622 } 8623 8624 // Avoid weird loops 8625 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8626 return getCouldNotCompute(); 8627 8628 bool NoWrap = ControlsExit && 8629 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8630 8631 const SCEV *Stride = IV->getStepRecurrence(*this); 8632 8633 bool PositiveStride = isKnownPositive(Stride); 8634 8635 // Avoid negative or zero stride values. 8636 if (!PositiveStride) { 8637 // We can compute the correct backedge taken count for loops with unknown 8638 // strides if we can prove that the loop is not an infinite loop with side 8639 // effects. Here's the loop structure we are trying to handle - 8640 // 8641 // i = start 8642 // do { 8643 // A[i] = i; 8644 // i += s; 8645 // } while (i < end); 8646 // 8647 // The backedge taken count for such loops is evaluated as - 8648 // (max(end, start + stride) - start - 1) /u stride 8649 // 8650 // The additional preconditions that we need to check to prove correctness 8651 // of the above formula is as follows - 8652 // 8653 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8654 // NoWrap flag). 8655 // b) loop is single exit with no side effects. 8656 // 8657 // 8658 // Precondition a) implies that if the stride is negative, this is a single 8659 // trip loop. The backedge taken count formula reduces to zero in this case. 8660 // 8661 // Precondition b) implies that the unknown stride cannot be zero otherwise 8662 // we have UB. 8663 // 8664 // The positive stride case is the same as isKnownPositive(Stride) returning 8665 // true (original behavior of the function). 8666 // 8667 // We want to make sure that the stride is truly unknown as there are edge 8668 // cases where ScalarEvolution propagates no wrap flags to the 8669 // post-increment/decrement IV even though the increment/decrement operation 8670 // itself is wrapping. The computed backedge taken count may be wrong in 8671 // such cases. This is prevented by checking that the stride is not known to 8672 // be either positive or non-positive. For example, no wrap flags are 8673 // propagated to the post-increment IV of this loop with a trip count of 2 - 8674 // 8675 // unsigned char i; 8676 // for(i=127; i<128; i+=129) 8677 // A[i] = i; 8678 // 8679 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8680 !loopHasNoSideEffects(L)) 8681 return getCouldNotCompute(); 8682 8683 } else if (!Stride->isOne() && 8684 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8685 // Avoid proven overflow cases: this will ensure that the backedge taken 8686 // count will not generate any unsigned overflow. Relaxed no-overflow 8687 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8688 // undefined behaviors like the case of C language. 8689 return getCouldNotCompute(); 8690 8691 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8692 : ICmpInst::ICMP_ULT; 8693 const SCEV *Start = IV->getStart(); 8694 const SCEV *End = RHS; 8695 // If the backedge is taken at least once, then it will be taken 8696 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8697 // is the LHS value of the less-than comparison the first time it is evaluated 8698 // and End is the RHS. 8699 const SCEV *BECountIfBackedgeTaken = 8700 computeBECount(getMinusSCEV(End, Start), Stride, false); 8701 // If the loop entry is guarded by the result of the backedge test of the 8702 // first loop iteration, then we know the backedge will be taken at least 8703 // once and so the backedge taken count is as above. If not then we use the 8704 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8705 // as if the backedge is taken at least once max(End,Start) is End and so the 8706 // result is as above, and if not max(End,Start) is Start so we get a backedge 8707 // count of zero. 8708 const SCEV *BECount; 8709 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8710 BECount = BECountIfBackedgeTaken; 8711 else { 8712 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8713 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8714 } 8715 8716 const SCEV *MaxBECount; 8717 bool MaxOrZero = false; 8718 if (isa<SCEVConstant>(BECount)) 8719 MaxBECount = BECount; 8720 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8721 // If we know exactly how many times the backedge will be taken if it's 8722 // taken at least once, then the backedge count will either be that or 8723 // zero. 8724 MaxBECount = BECountIfBackedgeTaken; 8725 MaxOrZero = true; 8726 } else { 8727 // Calculate the maximum backedge count based on the range of values 8728 // permitted by Start, End, and Stride. 8729 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8730 : getUnsignedRange(Start).getUnsignedMin(); 8731 8732 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8733 8734 APInt StrideForMaxBECount; 8735 8736 if (PositiveStride) 8737 StrideForMaxBECount = 8738 IsSigned ? getSignedRange(Stride).getSignedMin() 8739 : getUnsignedRange(Stride).getUnsignedMin(); 8740 else 8741 // Using a stride of 1 is safe when computing max backedge taken count for 8742 // a loop with unknown stride. 8743 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8744 8745 APInt Limit = 8746 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8747 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8748 8749 // Although End can be a MAX expression we estimate MaxEnd considering only 8750 // the case End = RHS. This is safe because in the other case (End - Start) 8751 // is zero, leading to a zero maximum backedge taken count. 8752 APInt MaxEnd = 8753 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8754 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8755 8756 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8757 getConstant(StrideForMaxBECount), false); 8758 } 8759 8760 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8761 MaxBECount = BECount; 8762 8763 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 8764 } 8765 8766 ScalarEvolution::ExitLimit 8767 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8768 const Loop *L, bool IsSigned, 8769 bool ControlsExit, bool AllowPredicates) { 8770 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8771 // We handle only IV > Invariant 8772 if (!isLoopInvariant(RHS, L)) 8773 return getCouldNotCompute(); 8774 8775 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8776 if (!IV && AllowPredicates) 8777 // Try to make this an AddRec using runtime tests, in the first X 8778 // iterations of this loop, where X is the SCEV expression found by the 8779 // algorithm below. 8780 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8781 8782 // Avoid weird loops 8783 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8784 return getCouldNotCompute(); 8785 8786 bool NoWrap = ControlsExit && 8787 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8788 8789 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8790 8791 // Avoid negative or zero stride values 8792 if (!isKnownPositive(Stride)) 8793 return getCouldNotCompute(); 8794 8795 // Avoid proven overflow cases: this will ensure that the backedge taken count 8796 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8797 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8798 // behaviors like the case of C language. 8799 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8800 return getCouldNotCompute(); 8801 8802 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8803 : ICmpInst::ICMP_UGT; 8804 8805 const SCEV *Start = IV->getStart(); 8806 const SCEV *End = RHS; 8807 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8808 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8809 8810 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8811 8812 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8813 : getUnsignedRange(Start).getUnsignedMax(); 8814 8815 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8816 : getUnsignedRange(Stride).getUnsignedMin(); 8817 8818 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8819 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8820 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8821 8822 // Although End can be a MIN expression we estimate MinEnd considering only 8823 // the case End = RHS. This is safe because in the other case (Start - End) 8824 // is zero, leading to a zero maximum backedge taken count. 8825 APInt MinEnd = 8826 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8827 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8828 8829 8830 const SCEV *MaxBECount = getCouldNotCompute(); 8831 if (isa<SCEVConstant>(BECount)) 8832 MaxBECount = BECount; 8833 else 8834 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8835 getConstant(MinStride), false); 8836 8837 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8838 MaxBECount = BECount; 8839 8840 return ExitLimit(BECount, MaxBECount, false, Predicates); 8841 } 8842 8843 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8844 ScalarEvolution &SE) const { 8845 if (Range.isFullSet()) // Infinite loop. 8846 return SE.getCouldNotCompute(); 8847 8848 // If the start is a non-zero constant, shift the range to simplify things. 8849 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8850 if (!SC->getValue()->isZero()) { 8851 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8852 Operands[0] = SE.getZero(SC->getType()); 8853 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8854 getNoWrapFlags(FlagNW)); 8855 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8856 return ShiftedAddRec->getNumIterationsInRange( 8857 Range.subtract(SC->getAPInt()), SE); 8858 // This is strange and shouldn't happen. 8859 return SE.getCouldNotCompute(); 8860 } 8861 8862 // The only time we can solve this is when we have all constant indices. 8863 // Otherwise, we cannot determine the overflow conditions. 8864 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8865 return SE.getCouldNotCompute(); 8866 8867 // Okay at this point we know that all elements of the chrec are constants and 8868 // that the start element is zero. 8869 8870 // First check to see if the range contains zero. If not, the first 8871 // iteration exits. 8872 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8873 if (!Range.contains(APInt(BitWidth, 0))) 8874 return SE.getZero(getType()); 8875 8876 if (isAffine()) { 8877 // If this is an affine expression then we have this situation: 8878 // Solve {0,+,A} in Range === Ax in Range 8879 8880 // We know that zero is in the range. If A is positive then we know that 8881 // the upper value of the range must be the first possible exit value. 8882 // If A is negative then the lower of the range is the last possible loop 8883 // value. Also note that we already checked for a full range. 8884 APInt One(BitWidth,1); 8885 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8886 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8887 8888 // The exit value should be (End+A)/A. 8889 APInt ExitVal = (End + A).udiv(A); 8890 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8891 8892 // Evaluate at the exit value. If we really did fall out of the valid 8893 // range, then we computed our trip count, otherwise wrap around or other 8894 // things must have happened. 8895 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8896 if (Range.contains(Val->getValue())) 8897 return SE.getCouldNotCompute(); // Something strange happened 8898 8899 // Ensure that the previous value is in the range. This is a sanity check. 8900 assert(Range.contains( 8901 EvaluateConstantChrecAtConstant(this, 8902 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8903 "Linear scev computation is off in a bad way!"); 8904 return SE.getConstant(ExitValue); 8905 } else if (isQuadratic()) { 8906 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8907 // quadratic equation to solve it. To do this, we must frame our problem in 8908 // terms of figuring out when zero is crossed, instead of when 8909 // Range.getUpper() is crossed. 8910 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8911 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8912 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8913 8914 // Next, solve the constructed addrec 8915 if (auto Roots = 8916 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8917 const SCEVConstant *R1 = Roots->first; 8918 const SCEVConstant *R2 = Roots->second; 8919 // Pick the smallest positive root value. 8920 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8921 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8922 if (!CB->getZExtValue()) 8923 std::swap(R1, R2); // R1 is the minimum root now. 8924 8925 // Make sure the root is not off by one. The returned iteration should 8926 // not be in the range, but the previous one should be. When solving 8927 // for "X*X < 5", for example, we should not return a root of 2. 8928 ConstantInt *R1Val = 8929 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8930 if (Range.contains(R1Val->getValue())) { 8931 // The next iteration must be out of the range... 8932 ConstantInt *NextVal = 8933 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8934 8935 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8936 if (!Range.contains(R1Val->getValue())) 8937 return SE.getConstant(NextVal); 8938 return SE.getCouldNotCompute(); // Something strange happened 8939 } 8940 8941 // If R1 was not in the range, then it is a good return value. Make 8942 // sure that R1-1 WAS in the range though, just in case. 8943 ConstantInt *NextVal = 8944 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8945 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8946 if (Range.contains(R1Val->getValue())) 8947 return R1; 8948 return SE.getCouldNotCompute(); // Something strange happened 8949 } 8950 } 8951 } 8952 8953 return SE.getCouldNotCompute(); 8954 } 8955 8956 namespace { 8957 struct FindUndefs { 8958 bool Found; 8959 FindUndefs() : Found(false) {} 8960 8961 bool follow(const SCEV *S) { 8962 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 8963 if (isa<UndefValue>(C->getValue())) 8964 Found = true; 8965 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 8966 if (isa<UndefValue>(C->getValue())) 8967 Found = true; 8968 } 8969 8970 // Keep looking if we haven't found it yet. 8971 return !Found; 8972 } 8973 bool isDone() const { 8974 // Stop recursion if we have found an undef. 8975 return Found; 8976 } 8977 }; 8978 } 8979 8980 // Return true when S contains at least an undef value. 8981 static inline bool 8982 containsUndefs(const SCEV *S) { 8983 FindUndefs F; 8984 SCEVTraversal<FindUndefs> ST(F); 8985 ST.visitAll(S); 8986 8987 return F.Found; 8988 } 8989 8990 namespace { 8991 // Collect all steps of SCEV expressions. 8992 struct SCEVCollectStrides { 8993 ScalarEvolution &SE; 8994 SmallVectorImpl<const SCEV *> &Strides; 8995 8996 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 8997 : SE(SE), Strides(S) {} 8998 8999 bool follow(const SCEV *S) { 9000 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9001 Strides.push_back(AR->getStepRecurrence(SE)); 9002 return true; 9003 } 9004 bool isDone() const { return false; } 9005 }; 9006 9007 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9008 struct SCEVCollectTerms { 9009 SmallVectorImpl<const SCEV *> &Terms; 9010 9011 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9012 : Terms(T) {} 9013 9014 bool follow(const SCEV *S) { 9015 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9016 isa<SCEVSignExtendExpr>(S)) { 9017 if (!containsUndefs(S)) 9018 Terms.push_back(S); 9019 9020 // Stop recursion: once we collected a term, do not walk its operands. 9021 return false; 9022 } 9023 9024 // Keep looking. 9025 return true; 9026 } 9027 bool isDone() const { return false; } 9028 }; 9029 9030 // Check if a SCEV contains an AddRecExpr. 9031 struct SCEVHasAddRec { 9032 bool &ContainsAddRec; 9033 9034 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9035 ContainsAddRec = false; 9036 } 9037 9038 bool follow(const SCEV *S) { 9039 if (isa<SCEVAddRecExpr>(S)) { 9040 ContainsAddRec = true; 9041 9042 // Stop recursion: once we collected a term, do not walk its operands. 9043 return false; 9044 } 9045 9046 // Keep looking. 9047 return true; 9048 } 9049 bool isDone() const { return false; } 9050 }; 9051 9052 // Find factors that are multiplied with an expression that (possibly as a 9053 // subexpression) contains an AddRecExpr. In the expression: 9054 // 9055 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9056 // 9057 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9058 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9059 // parameters as they form a product with an induction variable. 9060 // 9061 // This collector expects all array size parameters to be in the same MulExpr. 9062 // It might be necessary to later add support for collecting parameters that are 9063 // spread over different nested MulExpr. 9064 struct SCEVCollectAddRecMultiplies { 9065 SmallVectorImpl<const SCEV *> &Terms; 9066 ScalarEvolution &SE; 9067 9068 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9069 : Terms(T), SE(SE) {} 9070 9071 bool follow(const SCEV *S) { 9072 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9073 bool HasAddRec = false; 9074 SmallVector<const SCEV *, 0> Operands; 9075 for (auto Op : Mul->operands()) { 9076 if (isa<SCEVUnknown>(Op)) { 9077 Operands.push_back(Op); 9078 } else { 9079 bool ContainsAddRec; 9080 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9081 visitAll(Op, ContiansAddRec); 9082 HasAddRec |= ContainsAddRec; 9083 } 9084 } 9085 if (Operands.size() == 0) 9086 return true; 9087 9088 if (!HasAddRec) 9089 return false; 9090 9091 Terms.push_back(SE.getMulExpr(Operands)); 9092 // Stop recursion: once we collected a term, do not walk its operands. 9093 return false; 9094 } 9095 9096 // Keep looking. 9097 return true; 9098 } 9099 bool isDone() const { return false; } 9100 }; 9101 } 9102 9103 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9104 /// two places: 9105 /// 1) The strides of AddRec expressions. 9106 /// 2) Unknowns that are multiplied with AddRec expressions. 9107 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9108 SmallVectorImpl<const SCEV *> &Terms) { 9109 SmallVector<const SCEV *, 4> Strides; 9110 SCEVCollectStrides StrideCollector(*this, Strides); 9111 visitAll(Expr, StrideCollector); 9112 9113 DEBUG({ 9114 dbgs() << "Strides:\n"; 9115 for (const SCEV *S : Strides) 9116 dbgs() << *S << "\n"; 9117 }); 9118 9119 for (const SCEV *S : Strides) { 9120 SCEVCollectTerms TermCollector(Terms); 9121 visitAll(S, TermCollector); 9122 } 9123 9124 DEBUG({ 9125 dbgs() << "Terms:\n"; 9126 for (const SCEV *T : Terms) 9127 dbgs() << *T << "\n"; 9128 }); 9129 9130 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9131 visitAll(Expr, MulCollector); 9132 } 9133 9134 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9135 SmallVectorImpl<const SCEV *> &Terms, 9136 SmallVectorImpl<const SCEV *> &Sizes) { 9137 int Last = Terms.size() - 1; 9138 const SCEV *Step = Terms[Last]; 9139 9140 // End of recursion. 9141 if (Last == 0) { 9142 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9143 SmallVector<const SCEV *, 2> Qs; 9144 for (const SCEV *Op : M->operands()) 9145 if (!isa<SCEVConstant>(Op)) 9146 Qs.push_back(Op); 9147 9148 Step = SE.getMulExpr(Qs); 9149 } 9150 9151 Sizes.push_back(Step); 9152 return true; 9153 } 9154 9155 for (const SCEV *&Term : Terms) { 9156 // Normalize the terms before the next call to findArrayDimensionsRec. 9157 const SCEV *Q, *R; 9158 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9159 9160 // Bail out when GCD does not evenly divide one of the terms. 9161 if (!R->isZero()) 9162 return false; 9163 9164 Term = Q; 9165 } 9166 9167 // Remove all SCEVConstants. 9168 Terms.erase( 9169 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9170 Terms.end()); 9171 9172 if (Terms.size() > 0) 9173 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9174 return false; 9175 9176 Sizes.push_back(Step); 9177 return true; 9178 } 9179 9180 // Returns true when S contains at least a SCEVUnknown parameter. 9181 static inline bool 9182 containsParameters(const SCEV *S) { 9183 struct FindParameter { 9184 bool FoundParameter; 9185 FindParameter() : FoundParameter(false) {} 9186 9187 bool follow(const SCEV *S) { 9188 if (isa<SCEVUnknown>(S)) { 9189 FoundParameter = true; 9190 // Stop recursion: we found a parameter. 9191 return false; 9192 } 9193 // Keep looking. 9194 return true; 9195 } 9196 bool isDone() const { 9197 // Stop recursion if we have found a parameter. 9198 return FoundParameter; 9199 } 9200 }; 9201 9202 FindParameter F; 9203 SCEVTraversal<FindParameter> ST(F); 9204 ST.visitAll(S); 9205 9206 return F.FoundParameter; 9207 } 9208 9209 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9210 static inline bool 9211 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9212 for (const SCEV *T : Terms) 9213 if (containsParameters(T)) 9214 return true; 9215 return false; 9216 } 9217 9218 // Return the number of product terms in S. 9219 static inline int numberOfTerms(const SCEV *S) { 9220 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9221 return Expr->getNumOperands(); 9222 return 1; 9223 } 9224 9225 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9226 if (isa<SCEVConstant>(T)) 9227 return nullptr; 9228 9229 if (isa<SCEVUnknown>(T)) 9230 return T; 9231 9232 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9233 SmallVector<const SCEV *, 2> Factors; 9234 for (const SCEV *Op : M->operands()) 9235 if (!isa<SCEVConstant>(Op)) 9236 Factors.push_back(Op); 9237 9238 return SE.getMulExpr(Factors); 9239 } 9240 9241 return T; 9242 } 9243 9244 /// Return the size of an element read or written by Inst. 9245 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9246 Type *Ty; 9247 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9248 Ty = Store->getValueOperand()->getType(); 9249 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9250 Ty = Load->getType(); 9251 else 9252 return nullptr; 9253 9254 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9255 return getSizeOfExpr(ETy, Ty); 9256 } 9257 9258 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9259 SmallVectorImpl<const SCEV *> &Sizes, 9260 const SCEV *ElementSize) const { 9261 if (Terms.size() < 1 || !ElementSize) 9262 return; 9263 9264 // Early return when Terms do not contain parameters: we do not delinearize 9265 // non parametric SCEVs. 9266 if (!containsParameters(Terms)) 9267 return; 9268 9269 DEBUG({ 9270 dbgs() << "Terms:\n"; 9271 for (const SCEV *T : Terms) 9272 dbgs() << *T << "\n"; 9273 }); 9274 9275 // Remove duplicates. 9276 std::sort(Terms.begin(), Terms.end()); 9277 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9278 9279 // Put larger terms first. 9280 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9281 return numberOfTerms(LHS) > numberOfTerms(RHS); 9282 }); 9283 9284 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9285 9286 // Try to divide all terms by the element size. If term is not divisible by 9287 // element size, proceed with the original term. 9288 for (const SCEV *&Term : Terms) { 9289 const SCEV *Q, *R; 9290 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9291 if (!Q->isZero()) 9292 Term = Q; 9293 } 9294 9295 SmallVector<const SCEV *, 4> NewTerms; 9296 9297 // Remove constant factors. 9298 for (const SCEV *T : Terms) 9299 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9300 NewTerms.push_back(NewT); 9301 9302 DEBUG({ 9303 dbgs() << "Terms after sorting:\n"; 9304 for (const SCEV *T : NewTerms) 9305 dbgs() << *T << "\n"; 9306 }); 9307 9308 if (NewTerms.empty() || 9309 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9310 Sizes.clear(); 9311 return; 9312 } 9313 9314 // The last element to be pushed into Sizes is the size of an element. 9315 Sizes.push_back(ElementSize); 9316 9317 DEBUG({ 9318 dbgs() << "Sizes:\n"; 9319 for (const SCEV *S : Sizes) 9320 dbgs() << *S << "\n"; 9321 }); 9322 } 9323 9324 void ScalarEvolution::computeAccessFunctions( 9325 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9326 SmallVectorImpl<const SCEV *> &Sizes) { 9327 9328 // Early exit in case this SCEV is not an affine multivariate function. 9329 if (Sizes.empty()) 9330 return; 9331 9332 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9333 if (!AR->isAffine()) 9334 return; 9335 9336 const SCEV *Res = Expr; 9337 int Last = Sizes.size() - 1; 9338 for (int i = Last; i >= 0; i--) { 9339 const SCEV *Q, *R; 9340 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9341 9342 DEBUG({ 9343 dbgs() << "Res: " << *Res << "\n"; 9344 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9345 dbgs() << "Res divided by Sizes[i]:\n"; 9346 dbgs() << "Quotient: " << *Q << "\n"; 9347 dbgs() << "Remainder: " << *R << "\n"; 9348 }); 9349 9350 Res = Q; 9351 9352 // Do not record the last subscript corresponding to the size of elements in 9353 // the array. 9354 if (i == Last) { 9355 9356 // Bail out if the remainder is too complex. 9357 if (isa<SCEVAddRecExpr>(R)) { 9358 Subscripts.clear(); 9359 Sizes.clear(); 9360 return; 9361 } 9362 9363 continue; 9364 } 9365 9366 // Record the access function for the current subscript. 9367 Subscripts.push_back(R); 9368 } 9369 9370 // Also push in last position the remainder of the last division: it will be 9371 // the access function of the innermost dimension. 9372 Subscripts.push_back(Res); 9373 9374 std::reverse(Subscripts.begin(), Subscripts.end()); 9375 9376 DEBUG({ 9377 dbgs() << "Subscripts:\n"; 9378 for (const SCEV *S : Subscripts) 9379 dbgs() << *S << "\n"; 9380 }); 9381 } 9382 9383 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9384 /// sizes of an array access. Returns the remainder of the delinearization that 9385 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9386 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9387 /// expressions in the stride and base of a SCEV corresponding to the 9388 /// computation of a GCD (greatest common divisor) of base and stride. When 9389 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9390 /// 9391 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9392 /// 9393 /// void foo(long n, long m, long o, double A[n][m][o]) { 9394 /// 9395 /// for (long i = 0; i < n; i++) 9396 /// for (long j = 0; j < m; j++) 9397 /// for (long k = 0; k < o; k++) 9398 /// A[i][j][k] = 1.0; 9399 /// } 9400 /// 9401 /// the delinearization input is the following AddRec SCEV: 9402 /// 9403 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9404 /// 9405 /// From this SCEV, we are able to say that the base offset of the access is %A 9406 /// because it appears as an offset that does not divide any of the strides in 9407 /// the loops: 9408 /// 9409 /// CHECK: Base offset: %A 9410 /// 9411 /// and then SCEV->delinearize determines the size of some of the dimensions of 9412 /// the array as these are the multiples by which the strides are happening: 9413 /// 9414 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9415 /// 9416 /// Note that the outermost dimension remains of UnknownSize because there are 9417 /// no strides that would help identifying the size of the last dimension: when 9418 /// the array has been statically allocated, one could compute the size of that 9419 /// dimension by dividing the overall size of the array by the size of the known 9420 /// dimensions: %m * %o * 8. 9421 /// 9422 /// Finally delinearize provides the access functions for the array reference 9423 /// that does correspond to A[i][j][k] of the above C testcase: 9424 /// 9425 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9426 /// 9427 /// The testcases are checking the output of a function pass: 9428 /// DelinearizationPass that walks through all loads and stores of a function 9429 /// asking for the SCEV of the memory access with respect to all enclosing 9430 /// loops, calling SCEV->delinearize on that and printing the results. 9431 9432 void ScalarEvolution::delinearize(const SCEV *Expr, 9433 SmallVectorImpl<const SCEV *> &Subscripts, 9434 SmallVectorImpl<const SCEV *> &Sizes, 9435 const SCEV *ElementSize) { 9436 // First step: collect parametric terms. 9437 SmallVector<const SCEV *, 4> Terms; 9438 collectParametricTerms(Expr, Terms); 9439 9440 if (Terms.empty()) 9441 return; 9442 9443 // Second step: find subscript sizes. 9444 findArrayDimensions(Terms, Sizes, ElementSize); 9445 9446 if (Sizes.empty()) 9447 return; 9448 9449 // Third step: compute the access functions for each subscript. 9450 computeAccessFunctions(Expr, Subscripts, Sizes); 9451 9452 if (Subscripts.empty()) 9453 return; 9454 9455 DEBUG({ 9456 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9457 dbgs() << "ArrayDecl[UnknownSize]"; 9458 for (const SCEV *S : Sizes) 9459 dbgs() << "[" << *S << "]"; 9460 9461 dbgs() << "\nArrayRef"; 9462 for (const SCEV *S : Subscripts) 9463 dbgs() << "[" << *S << "]"; 9464 dbgs() << "\n"; 9465 }); 9466 } 9467 9468 //===----------------------------------------------------------------------===// 9469 // SCEVCallbackVH Class Implementation 9470 //===----------------------------------------------------------------------===// 9471 9472 void ScalarEvolution::SCEVCallbackVH::deleted() { 9473 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9474 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9475 SE->ConstantEvolutionLoopExitValue.erase(PN); 9476 SE->eraseValueFromMap(getValPtr()); 9477 // this now dangles! 9478 } 9479 9480 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9481 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9482 9483 // Forget all the expressions associated with users of the old value, 9484 // so that future queries will recompute the expressions using the new 9485 // value. 9486 Value *Old = getValPtr(); 9487 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9488 SmallPtrSet<User *, 8> Visited; 9489 while (!Worklist.empty()) { 9490 User *U = Worklist.pop_back_val(); 9491 // Deleting the Old value will cause this to dangle. Postpone 9492 // that until everything else is done. 9493 if (U == Old) 9494 continue; 9495 if (!Visited.insert(U).second) 9496 continue; 9497 if (PHINode *PN = dyn_cast<PHINode>(U)) 9498 SE->ConstantEvolutionLoopExitValue.erase(PN); 9499 SE->eraseValueFromMap(U); 9500 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9501 } 9502 // Delete the Old value. 9503 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9504 SE->ConstantEvolutionLoopExitValue.erase(PN); 9505 SE->eraseValueFromMap(Old); 9506 // this now dangles! 9507 } 9508 9509 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9510 : CallbackVH(V), SE(se) {} 9511 9512 //===----------------------------------------------------------------------===// 9513 // ScalarEvolution Class Implementation 9514 //===----------------------------------------------------------------------===// 9515 9516 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9517 AssumptionCache &AC, DominatorTree &DT, 9518 LoopInfo &LI) 9519 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9520 CouldNotCompute(new SCEVCouldNotCompute()), 9521 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9522 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9523 FirstUnknown(nullptr) { 9524 9525 // To use guards for proving predicates, we need to scan every instruction in 9526 // relevant basic blocks, and not just terminators. Doing this is a waste of 9527 // time if the IR does not actually contain any calls to 9528 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9529 // 9530 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9531 // to _add_ guards to the module when there weren't any before, and wants 9532 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9533 // efficient in lieu of being smart in that rather obscure case. 9534 9535 auto *GuardDecl = F.getParent()->getFunction( 9536 Intrinsic::getName(Intrinsic::experimental_guard)); 9537 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9538 } 9539 9540 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9541 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9542 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9543 ValueExprMap(std::move(Arg.ValueExprMap)), 9544 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9545 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9546 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9547 PredicatedBackedgeTakenCounts( 9548 std::move(Arg.PredicatedBackedgeTakenCounts)), 9549 ConstantEvolutionLoopExitValue( 9550 std::move(Arg.ConstantEvolutionLoopExitValue)), 9551 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9552 LoopDispositions(std::move(Arg.LoopDispositions)), 9553 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9554 BlockDispositions(std::move(Arg.BlockDispositions)), 9555 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9556 SignedRanges(std::move(Arg.SignedRanges)), 9557 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9558 UniquePreds(std::move(Arg.UniquePreds)), 9559 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9560 FirstUnknown(Arg.FirstUnknown) { 9561 Arg.FirstUnknown = nullptr; 9562 } 9563 9564 ScalarEvolution::~ScalarEvolution() { 9565 // Iterate through all the SCEVUnknown instances and call their 9566 // destructors, so that they release their references to their values. 9567 for (SCEVUnknown *U = FirstUnknown; U;) { 9568 SCEVUnknown *Tmp = U; 9569 U = U->Next; 9570 Tmp->~SCEVUnknown(); 9571 } 9572 FirstUnknown = nullptr; 9573 9574 ExprValueMap.clear(); 9575 ValueExprMap.clear(); 9576 HasRecMap.clear(); 9577 9578 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9579 // that a loop had multiple computable exits. 9580 for (auto &BTCI : BackedgeTakenCounts) 9581 BTCI.second.clear(); 9582 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9583 BTCI.second.clear(); 9584 9585 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9586 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9587 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9588 } 9589 9590 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9591 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9592 } 9593 9594 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9595 const Loop *L) { 9596 // Print all inner loops first 9597 for (Loop *I : *L) 9598 PrintLoopInfo(OS, SE, I); 9599 9600 OS << "Loop "; 9601 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9602 OS << ": "; 9603 9604 SmallVector<BasicBlock *, 8> ExitBlocks; 9605 L->getExitBlocks(ExitBlocks); 9606 if (ExitBlocks.size() != 1) 9607 OS << "<multiple exits> "; 9608 9609 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9610 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9611 } else { 9612 OS << "Unpredictable backedge-taken count. "; 9613 } 9614 9615 OS << "\n" 9616 "Loop "; 9617 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9618 OS << ": "; 9619 9620 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9621 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9622 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9623 OS << ", actual taken count either this or zero."; 9624 } else { 9625 OS << "Unpredictable max backedge-taken count. "; 9626 } 9627 9628 OS << "\n" 9629 "Loop "; 9630 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9631 OS << ": "; 9632 9633 SCEVUnionPredicate Pred; 9634 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9635 if (!isa<SCEVCouldNotCompute>(PBT)) { 9636 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9637 OS << " Predicates:\n"; 9638 Pred.print(OS, 4); 9639 } else { 9640 OS << "Unpredictable predicated backedge-taken count. "; 9641 } 9642 OS << "\n"; 9643 } 9644 9645 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9646 switch (LD) { 9647 case ScalarEvolution::LoopVariant: 9648 return "Variant"; 9649 case ScalarEvolution::LoopInvariant: 9650 return "Invariant"; 9651 case ScalarEvolution::LoopComputable: 9652 return "Computable"; 9653 } 9654 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9655 } 9656 9657 void ScalarEvolution::print(raw_ostream &OS) const { 9658 // ScalarEvolution's implementation of the print method is to print 9659 // out SCEV values of all instructions that are interesting. Doing 9660 // this potentially causes it to create new SCEV objects though, 9661 // which technically conflicts with the const qualifier. This isn't 9662 // observable from outside the class though, so casting away the 9663 // const isn't dangerous. 9664 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9665 9666 OS << "Classifying expressions for: "; 9667 F.printAsOperand(OS, /*PrintType=*/false); 9668 OS << "\n"; 9669 for (Instruction &I : instructions(F)) 9670 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9671 OS << I << '\n'; 9672 OS << " --> "; 9673 const SCEV *SV = SE.getSCEV(&I); 9674 SV->print(OS); 9675 if (!isa<SCEVCouldNotCompute>(SV)) { 9676 OS << " U: "; 9677 SE.getUnsignedRange(SV).print(OS); 9678 OS << " S: "; 9679 SE.getSignedRange(SV).print(OS); 9680 } 9681 9682 const Loop *L = LI.getLoopFor(I.getParent()); 9683 9684 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9685 if (AtUse != SV) { 9686 OS << " --> "; 9687 AtUse->print(OS); 9688 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9689 OS << " U: "; 9690 SE.getUnsignedRange(AtUse).print(OS); 9691 OS << " S: "; 9692 SE.getSignedRange(AtUse).print(OS); 9693 } 9694 } 9695 9696 if (L) { 9697 OS << "\t\t" "Exits: "; 9698 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9699 if (!SE.isLoopInvariant(ExitValue, L)) { 9700 OS << "<<Unknown>>"; 9701 } else { 9702 OS << *ExitValue; 9703 } 9704 9705 bool First = true; 9706 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9707 if (First) { 9708 OS << "\t\t" "LoopDispositions: { "; 9709 First = false; 9710 } else { 9711 OS << ", "; 9712 } 9713 9714 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9715 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9716 } 9717 9718 for (auto *InnerL : depth_first(L)) { 9719 if (InnerL == L) 9720 continue; 9721 if (First) { 9722 OS << "\t\t" "LoopDispositions: { "; 9723 First = false; 9724 } else { 9725 OS << ", "; 9726 } 9727 9728 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9729 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9730 } 9731 9732 OS << " }"; 9733 } 9734 9735 OS << "\n"; 9736 } 9737 9738 OS << "Determining loop execution counts for: "; 9739 F.printAsOperand(OS, /*PrintType=*/false); 9740 OS << "\n"; 9741 for (Loop *I : LI) 9742 PrintLoopInfo(OS, &SE, I); 9743 } 9744 9745 ScalarEvolution::LoopDisposition 9746 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9747 auto &Values = LoopDispositions[S]; 9748 for (auto &V : Values) { 9749 if (V.getPointer() == L) 9750 return V.getInt(); 9751 } 9752 Values.emplace_back(L, LoopVariant); 9753 LoopDisposition D = computeLoopDisposition(S, L); 9754 auto &Values2 = LoopDispositions[S]; 9755 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9756 if (V.getPointer() == L) { 9757 V.setInt(D); 9758 break; 9759 } 9760 } 9761 return D; 9762 } 9763 9764 ScalarEvolution::LoopDisposition 9765 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9766 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9767 case scConstant: 9768 return LoopInvariant; 9769 case scTruncate: 9770 case scZeroExtend: 9771 case scSignExtend: 9772 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9773 case scAddRecExpr: { 9774 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9775 9776 // If L is the addrec's loop, it's computable. 9777 if (AR->getLoop() == L) 9778 return LoopComputable; 9779 9780 // Add recurrences are never invariant in the function-body (null loop). 9781 if (!L) 9782 return LoopVariant; 9783 9784 // This recurrence is variant w.r.t. L if L contains AR's loop. 9785 if (L->contains(AR->getLoop())) 9786 return LoopVariant; 9787 9788 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9789 if (AR->getLoop()->contains(L)) 9790 return LoopInvariant; 9791 9792 // This recurrence is variant w.r.t. L if any of its operands 9793 // are variant. 9794 for (auto *Op : AR->operands()) 9795 if (!isLoopInvariant(Op, L)) 9796 return LoopVariant; 9797 9798 // Otherwise it's loop-invariant. 9799 return LoopInvariant; 9800 } 9801 case scAddExpr: 9802 case scMulExpr: 9803 case scUMaxExpr: 9804 case scSMaxExpr: { 9805 bool HasVarying = false; 9806 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9807 LoopDisposition D = getLoopDisposition(Op, L); 9808 if (D == LoopVariant) 9809 return LoopVariant; 9810 if (D == LoopComputable) 9811 HasVarying = true; 9812 } 9813 return HasVarying ? LoopComputable : LoopInvariant; 9814 } 9815 case scUDivExpr: { 9816 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9817 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9818 if (LD == LoopVariant) 9819 return LoopVariant; 9820 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9821 if (RD == LoopVariant) 9822 return LoopVariant; 9823 return (LD == LoopInvariant && RD == LoopInvariant) ? 9824 LoopInvariant : LoopComputable; 9825 } 9826 case scUnknown: 9827 // All non-instruction values are loop invariant. All instructions are loop 9828 // invariant if they are not contained in the specified loop. 9829 // Instructions are never considered invariant in the function body 9830 // (null loop) because they are defined within the "loop". 9831 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9832 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9833 return LoopInvariant; 9834 case scCouldNotCompute: 9835 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9836 } 9837 llvm_unreachable("Unknown SCEV kind!"); 9838 } 9839 9840 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9841 return getLoopDisposition(S, L) == LoopInvariant; 9842 } 9843 9844 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9845 return getLoopDisposition(S, L) == LoopComputable; 9846 } 9847 9848 ScalarEvolution::BlockDisposition 9849 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9850 auto &Values = BlockDispositions[S]; 9851 for (auto &V : Values) { 9852 if (V.getPointer() == BB) 9853 return V.getInt(); 9854 } 9855 Values.emplace_back(BB, DoesNotDominateBlock); 9856 BlockDisposition D = computeBlockDisposition(S, BB); 9857 auto &Values2 = BlockDispositions[S]; 9858 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9859 if (V.getPointer() == BB) { 9860 V.setInt(D); 9861 break; 9862 } 9863 } 9864 return D; 9865 } 9866 9867 ScalarEvolution::BlockDisposition 9868 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9869 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9870 case scConstant: 9871 return ProperlyDominatesBlock; 9872 case scTruncate: 9873 case scZeroExtend: 9874 case scSignExtend: 9875 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9876 case scAddRecExpr: { 9877 // This uses a "dominates" query instead of "properly dominates" query 9878 // to test for proper dominance too, because the instruction which 9879 // produces the addrec's value is a PHI, and a PHI effectively properly 9880 // dominates its entire containing block. 9881 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9882 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9883 return DoesNotDominateBlock; 9884 9885 // Fall through into SCEVNAryExpr handling. 9886 LLVM_FALLTHROUGH; 9887 } 9888 case scAddExpr: 9889 case scMulExpr: 9890 case scUMaxExpr: 9891 case scSMaxExpr: { 9892 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9893 bool Proper = true; 9894 for (const SCEV *NAryOp : NAry->operands()) { 9895 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9896 if (D == DoesNotDominateBlock) 9897 return DoesNotDominateBlock; 9898 if (D == DominatesBlock) 9899 Proper = false; 9900 } 9901 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9902 } 9903 case scUDivExpr: { 9904 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9905 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9906 BlockDisposition LD = getBlockDisposition(LHS, BB); 9907 if (LD == DoesNotDominateBlock) 9908 return DoesNotDominateBlock; 9909 BlockDisposition RD = getBlockDisposition(RHS, BB); 9910 if (RD == DoesNotDominateBlock) 9911 return DoesNotDominateBlock; 9912 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9913 ProperlyDominatesBlock : DominatesBlock; 9914 } 9915 case scUnknown: 9916 if (Instruction *I = 9917 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9918 if (I->getParent() == BB) 9919 return DominatesBlock; 9920 if (DT.properlyDominates(I->getParent(), BB)) 9921 return ProperlyDominatesBlock; 9922 return DoesNotDominateBlock; 9923 } 9924 return ProperlyDominatesBlock; 9925 case scCouldNotCompute: 9926 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9927 } 9928 llvm_unreachable("Unknown SCEV kind!"); 9929 } 9930 9931 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9932 return getBlockDisposition(S, BB) >= DominatesBlock; 9933 } 9934 9935 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9936 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9937 } 9938 9939 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9940 // Search for a SCEV expression node within an expression tree. 9941 // Implements SCEVTraversal::Visitor. 9942 struct SCEVSearch { 9943 const SCEV *Node; 9944 bool IsFound; 9945 9946 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 9947 9948 bool follow(const SCEV *S) { 9949 IsFound |= (S == Node); 9950 return !IsFound; 9951 } 9952 bool isDone() const { return IsFound; } 9953 }; 9954 9955 SCEVSearch Search(Op); 9956 visitAll(S, Search); 9957 return Search.IsFound; 9958 } 9959 9960 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9961 ValuesAtScopes.erase(S); 9962 LoopDispositions.erase(S); 9963 BlockDispositions.erase(S); 9964 UnsignedRanges.erase(S); 9965 SignedRanges.erase(S); 9966 ExprValueMap.erase(S); 9967 HasRecMap.erase(S); 9968 9969 auto RemoveSCEVFromBackedgeMap = 9970 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 9971 for (auto I = Map.begin(), E = Map.end(); I != E;) { 9972 BackedgeTakenInfo &BEInfo = I->second; 9973 if (BEInfo.hasOperand(S, this)) { 9974 BEInfo.clear(); 9975 Map.erase(I++); 9976 } else 9977 ++I; 9978 } 9979 }; 9980 9981 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 9982 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 9983 } 9984 9985 typedef DenseMap<const Loop *, std::string> VerifyMap; 9986 9987 /// replaceSubString - Replaces all occurrences of From in Str with To. 9988 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9989 size_t Pos = 0; 9990 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9991 Str.replace(Pos, From.size(), To.data(), To.size()); 9992 Pos += To.size(); 9993 } 9994 } 9995 9996 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9997 static void 9998 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9999 std::string &S = Map[L]; 10000 if (S.empty()) { 10001 raw_string_ostream OS(S); 10002 SE.getBackedgeTakenCount(L)->print(OS); 10003 10004 // false and 0 are semantically equivalent. This can happen in dead loops. 10005 replaceSubString(OS.str(), "false", "0"); 10006 // Remove wrap flags, their use in SCEV is highly fragile. 10007 // FIXME: Remove this when SCEV gets smarter about them. 10008 replaceSubString(OS.str(), "<nw>", ""); 10009 replaceSubString(OS.str(), "<nsw>", ""); 10010 replaceSubString(OS.str(), "<nuw>", ""); 10011 } 10012 10013 for (auto *R : reverse(*L)) 10014 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 10015 } 10016 10017 void ScalarEvolution::verify() const { 10018 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10019 10020 // Gather stringified backedge taken counts for all loops using SCEV's caches. 10021 // FIXME: It would be much better to store actual values instead of strings, 10022 // but SCEV pointers will change if we drop the caches. 10023 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 10024 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10025 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 10026 10027 // Gather stringified backedge taken counts for all loops using a fresh 10028 // ScalarEvolution object. 10029 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10030 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10031 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 10032 10033 // Now compare whether they're the same with and without caches. This allows 10034 // verifying that no pass changed the cache. 10035 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 10036 "New loops suddenly appeared!"); 10037 10038 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 10039 OldE = BackedgeDumpsOld.end(), 10040 NewI = BackedgeDumpsNew.begin(); 10041 OldI != OldE; ++OldI, ++NewI) { 10042 assert(OldI->first == NewI->first && "Loop order changed!"); 10043 10044 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10045 // changes. 10046 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10047 // means that a pass is buggy or SCEV has to learn a new pattern but is 10048 // usually not harmful. 10049 if (OldI->second != NewI->second && 10050 OldI->second.find("undef") == std::string::npos && 10051 NewI->second.find("undef") == std::string::npos && 10052 OldI->second != "***COULDNOTCOMPUTE***" && 10053 NewI->second != "***COULDNOTCOMPUTE***") { 10054 dbgs() << "SCEVValidator: SCEV for loop '" 10055 << OldI->first->getHeader()->getName() 10056 << "' changed from '" << OldI->second 10057 << "' to '" << NewI->second << "'!\n"; 10058 std::abort(); 10059 } 10060 } 10061 10062 // TODO: Verify more things. 10063 } 10064 10065 char ScalarEvolutionAnalysis::PassID; 10066 10067 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10068 FunctionAnalysisManager &AM) { 10069 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10070 AM.getResult<AssumptionAnalysis>(F), 10071 AM.getResult<DominatorTreeAnalysis>(F), 10072 AM.getResult<LoopAnalysis>(F)); 10073 } 10074 10075 PreservedAnalyses 10076 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10077 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10078 return PreservedAnalyses::all(); 10079 } 10080 10081 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10082 "Scalar Evolution Analysis", false, true) 10083 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10084 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10085 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10086 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10087 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10088 "Scalar Evolution Analysis", false, true) 10089 char ScalarEvolutionWrapperPass::ID = 0; 10090 10091 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10092 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10093 } 10094 10095 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10096 SE.reset(new ScalarEvolution( 10097 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10098 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10099 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10100 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10101 return false; 10102 } 10103 10104 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10105 10106 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10107 SE->print(OS); 10108 } 10109 10110 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10111 if (!VerifySCEV) 10112 return; 10113 10114 SE->verify(); 10115 } 10116 10117 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10118 AU.setPreservesAll(); 10119 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10120 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10121 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10122 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10123 } 10124 10125 const SCEVPredicate * 10126 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10127 const SCEVConstant *RHS) { 10128 FoldingSetNodeID ID; 10129 // Unique this node based on the arguments 10130 ID.AddInteger(SCEVPredicate::P_Equal); 10131 ID.AddPointer(LHS); 10132 ID.AddPointer(RHS); 10133 void *IP = nullptr; 10134 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10135 return S; 10136 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10137 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10138 UniquePreds.InsertNode(Eq, IP); 10139 return Eq; 10140 } 10141 10142 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10143 const SCEVAddRecExpr *AR, 10144 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10145 FoldingSetNodeID ID; 10146 // Unique this node based on the arguments 10147 ID.AddInteger(SCEVPredicate::P_Wrap); 10148 ID.AddPointer(AR); 10149 ID.AddInteger(AddedFlags); 10150 void *IP = nullptr; 10151 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10152 return S; 10153 auto *OF = new (SCEVAllocator) 10154 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10155 UniquePreds.InsertNode(OF, IP); 10156 return OF; 10157 } 10158 10159 namespace { 10160 10161 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10162 public: 10163 /// Rewrites \p S in the context of a loop L and the SCEV predication 10164 /// infrastructure. 10165 /// 10166 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10167 /// equivalences present in \p Pred. 10168 /// 10169 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10170 /// \p NewPreds such that the result will be an AddRecExpr. 10171 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10172 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10173 SCEVUnionPredicate *Pred) { 10174 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10175 return Rewriter.visit(S); 10176 } 10177 10178 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10179 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10180 SCEVUnionPredicate *Pred) 10181 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10182 10183 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10184 if (Pred) { 10185 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10186 for (auto *Pred : ExprPreds) 10187 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10188 if (IPred->getLHS() == Expr) 10189 return IPred->getRHS(); 10190 } 10191 10192 return Expr; 10193 } 10194 10195 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10196 const SCEV *Operand = visit(Expr->getOperand()); 10197 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10198 if (AR && AR->getLoop() == L && AR->isAffine()) { 10199 // This couldn't be folded because the operand didn't have the nuw 10200 // flag. Add the nusw flag as an assumption that we could make. 10201 const SCEV *Step = AR->getStepRecurrence(SE); 10202 Type *Ty = Expr->getType(); 10203 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10204 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10205 SE.getSignExtendExpr(Step, Ty), L, 10206 AR->getNoWrapFlags()); 10207 } 10208 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10209 } 10210 10211 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10212 const SCEV *Operand = visit(Expr->getOperand()); 10213 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10214 if (AR && AR->getLoop() == L && AR->isAffine()) { 10215 // This couldn't be folded because the operand didn't have the nsw 10216 // flag. Add the nssw flag as an assumption that we could make. 10217 const SCEV *Step = AR->getStepRecurrence(SE); 10218 Type *Ty = Expr->getType(); 10219 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10220 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10221 SE.getSignExtendExpr(Step, Ty), L, 10222 AR->getNoWrapFlags()); 10223 } 10224 return SE.getSignExtendExpr(Operand, Expr->getType()); 10225 } 10226 10227 private: 10228 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10229 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10230 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10231 if (!NewPreds) { 10232 // Check if we've already made this assumption. 10233 return Pred && Pred->implies(A); 10234 } 10235 NewPreds->insert(A); 10236 return true; 10237 } 10238 10239 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10240 SCEVUnionPredicate *Pred; 10241 const Loop *L; 10242 }; 10243 } // end anonymous namespace 10244 10245 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10246 SCEVUnionPredicate &Preds) { 10247 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10248 } 10249 10250 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10251 const SCEV *S, const Loop *L, 10252 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10253 10254 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10255 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10256 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10257 10258 if (!AddRec) 10259 return nullptr; 10260 10261 // Since the transformation was successful, we can now transfer the SCEV 10262 // predicates. 10263 for (auto *P : TransformPreds) 10264 Preds.insert(P); 10265 10266 return AddRec; 10267 } 10268 10269 /// SCEV predicates 10270 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10271 SCEVPredicateKind Kind) 10272 : FastID(ID), Kind(Kind) {} 10273 10274 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10275 const SCEVUnknown *LHS, 10276 const SCEVConstant *RHS) 10277 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10278 10279 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10280 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10281 10282 if (!Op) 10283 return false; 10284 10285 return Op->LHS == LHS && Op->RHS == RHS; 10286 } 10287 10288 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10289 10290 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10291 10292 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10293 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10294 } 10295 10296 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10297 const SCEVAddRecExpr *AR, 10298 IncrementWrapFlags Flags) 10299 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10300 10301 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10302 10303 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10304 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10305 10306 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10307 } 10308 10309 bool SCEVWrapPredicate::isAlwaysTrue() const { 10310 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10311 IncrementWrapFlags IFlags = Flags; 10312 10313 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10314 IFlags = clearFlags(IFlags, IncrementNSSW); 10315 10316 return IFlags == IncrementAnyWrap; 10317 } 10318 10319 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10320 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10321 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10322 OS << "<nusw>"; 10323 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10324 OS << "<nssw>"; 10325 OS << "\n"; 10326 } 10327 10328 SCEVWrapPredicate::IncrementWrapFlags 10329 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10330 ScalarEvolution &SE) { 10331 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10332 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10333 10334 // We can safely transfer the NSW flag as NSSW. 10335 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10336 ImpliedFlags = IncrementNSSW; 10337 10338 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10339 // If the increment is positive, the SCEV NUW flag will also imply the 10340 // WrapPredicate NUSW flag. 10341 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10342 if (Step->getValue()->getValue().isNonNegative()) 10343 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10344 } 10345 10346 return ImpliedFlags; 10347 } 10348 10349 /// Union predicates don't get cached so create a dummy set ID for it. 10350 SCEVUnionPredicate::SCEVUnionPredicate() 10351 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10352 10353 bool SCEVUnionPredicate::isAlwaysTrue() const { 10354 return all_of(Preds, 10355 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10356 } 10357 10358 ArrayRef<const SCEVPredicate *> 10359 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10360 auto I = SCEVToPreds.find(Expr); 10361 if (I == SCEVToPreds.end()) 10362 return ArrayRef<const SCEVPredicate *>(); 10363 return I->second; 10364 } 10365 10366 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10367 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10368 return all_of(Set->Preds, 10369 [this](const SCEVPredicate *I) { return this->implies(I); }); 10370 10371 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10372 if (ScevPredsIt == SCEVToPreds.end()) 10373 return false; 10374 auto &SCEVPreds = ScevPredsIt->second; 10375 10376 return any_of(SCEVPreds, 10377 [N](const SCEVPredicate *I) { return I->implies(N); }); 10378 } 10379 10380 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10381 10382 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10383 for (auto Pred : Preds) 10384 Pred->print(OS, Depth); 10385 } 10386 10387 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10388 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10389 for (auto Pred : Set->Preds) 10390 add(Pred); 10391 return; 10392 } 10393 10394 if (implies(N)) 10395 return; 10396 10397 const SCEV *Key = N->getExpr(); 10398 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10399 " associated expression!"); 10400 10401 SCEVToPreds[Key].push_back(N); 10402 Preds.push_back(N); 10403 } 10404 10405 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10406 Loop &L) 10407 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10408 10409 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10410 const SCEV *Expr = SE.getSCEV(V); 10411 RewriteEntry &Entry = RewriteMap[Expr]; 10412 10413 // If we already have an entry and the version matches, return it. 10414 if (Entry.second && Generation == Entry.first) 10415 return Entry.second; 10416 10417 // We found an entry but it's stale. Rewrite the stale entry 10418 // acording to the current predicate. 10419 if (Entry.second) 10420 Expr = Entry.second; 10421 10422 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10423 Entry = {Generation, NewSCEV}; 10424 10425 return NewSCEV; 10426 } 10427 10428 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10429 if (!BackedgeCount) { 10430 SCEVUnionPredicate BackedgePred; 10431 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10432 addPredicate(BackedgePred); 10433 } 10434 return BackedgeCount; 10435 } 10436 10437 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10438 if (Preds.implies(&Pred)) 10439 return; 10440 Preds.add(&Pred); 10441 updateGeneration(); 10442 } 10443 10444 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10445 return Preds; 10446 } 10447 10448 void PredicatedScalarEvolution::updateGeneration() { 10449 // If the generation number wrapped recompute everything. 10450 if (++Generation == 0) { 10451 for (auto &II : RewriteMap) { 10452 const SCEV *Rewritten = II.second.second; 10453 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10454 } 10455 } 10456 } 10457 10458 void PredicatedScalarEvolution::setNoOverflow( 10459 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10460 const SCEV *Expr = getSCEV(V); 10461 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10462 10463 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10464 10465 // Clear the statically implied flags. 10466 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10467 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10468 10469 auto II = FlagsMap.insert({V, Flags}); 10470 if (!II.second) 10471 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10472 } 10473 10474 bool PredicatedScalarEvolution::hasNoOverflow( 10475 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10476 const SCEV *Expr = getSCEV(V); 10477 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10478 10479 Flags = SCEVWrapPredicate::clearFlags( 10480 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10481 10482 auto II = FlagsMap.find(V); 10483 10484 if (II != FlagsMap.end()) 10485 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10486 10487 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10488 } 10489 10490 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10491 const SCEV *Expr = this->getSCEV(V); 10492 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10493 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10494 10495 if (!New) 10496 return nullptr; 10497 10498 for (auto *P : NewPreds) 10499 Preds.add(P); 10500 10501 updateGeneration(); 10502 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10503 return New; 10504 } 10505 10506 PredicatedScalarEvolution::PredicatedScalarEvolution( 10507 const PredicatedScalarEvolution &Init) 10508 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10509 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10510 for (const auto &I : Init.FlagsMap) 10511 FlagsMap.insert(I); 10512 } 10513 10514 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10515 // For each block. 10516 for (auto *BB : L.getBlocks()) 10517 for (auto &I : *BB) { 10518 if (!SE.isSCEVable(I.getType())) 10519 continue; 10520 10521 auto *Expr = SE.getSCEV(&I); 10522 auto II = RewriteMap.find(Expr); 10523 10524 if (II == RewriteMap.end()) 10525 continue; 10526 10527 // Don't print things that are not interesting. 10528 if (II->second.second == Expr) 10529 continue; 10530 10531 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10532 OS.indent(Depth + 2) << *Expr << "\n"; 10533 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10534 } 10535 } 10536