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/SmallPtrSet.h" 65 #include "llvm/ADT/Statistic.h" 66 #include "llvm/Analysis/AssumptionCache.h" 67 #include "llvm/Analysis/ConstantFolding.h" 68 #include "llvm/Analysis/InstructionSimplify.h" 69 #include "llvm/Analysis/LoopInfo.h" 70 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 71 #include "llvm/Analysis/TargetLibraryInfo.h" 72 #include "llvm/Analysis/ValueTracking.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DerivedTypes.h" 77 #include "llvm/IR/Dominators.h" 78 #include "llvm/IR/GetElementPtrTypeIterator.h" 79 #include "llvm/IR/GlobalAlias.h" 80 #include "llvm/IR/GlobalVariable.h" 81 #include "llvm/IR/InstIterator.h" 82 #include "llvm/IR/Instructions.h" 83 #include "llvm/IR/LLVMContext.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/Support/CommandLine.h" 88 #include "llvm/Support/Debug.h" 89 #include "llvm/Support/ErrorHandling.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Support/SaveAndRestore.h" 93 #include <algorithm> 94 using namespace llvm; 95 96 #define DEBUG_TYPE "scalar-evolution" 97 98 STATISTIC(NumArrayLenItCounts, 99 "Number of trip counts computed with array length"); 100 STATISTIC(NumTripCountsComputed, 101 "Number of loops with predictable loop counts"); 102 STATISTIC(NumTripCountsNotComputed, 103 "Number of loops without predictable loop counts"); 104 STATISTIC(NumBruteForceTripCountsComputed, 105 "Number of loops with trip counts computed by force"); 106 107 static cl::opt<unsigned> 108 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 109 cl::desc("Maximum number of iterations SCEV will " 110 "symbolically execute a constant " 111 "derived loop"), 112 cl::init(100)); 113 114 // FIXME: Enable this with XDEBUG when the test suite is clean. 115 static cl::opt<bool> 116 VerifySCEV("verify-scev", 117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 118 static cl::opt<bool> 119 VerifySCEVMap("verify-scev-maps", 120 cl::desc("Verify no dangling value in ScalarEvolution's" 121 "ExprValueMap (slow)")); 122 123 //===----------------------------------------------------------------------===// 124 // SCEV class definitions 125 //===----------------------------------------------------------------------===// 126 127 //===----------------------------------------------------------------------===// 128 // Implementation of the SCEV class. 129 // 130 131 LLVM_DUMP_METHOD 132 void SCEV::dump() const { 133 print(dbgs()); 134 dbgs() << '\n'; 135 } 136 137 void SCEV::print(raw_ostream &OS) const { 138 switch (static_cast<SCEVTypes>(getSCEVType())) { 139 case scConstant: 140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 141 return; 142 case scTruncate: { 143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 144 const SCEV *Op = Trunc->getOperand(); 145 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 146 << *Trunc->getType() << ")"; 147 return; 148 } 149 case scZeroExtend: { 150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 151 const SCEV *Op = ZExt->getOperand(); 152 OS << "(zext " << *Op->getType() << " " << *Op << " to " 153 << *ZExt->getType() << ")"; 154 return; 155 } 156 case scSignExtend: { 157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 158 const SCEV *Op = SExt->getOperand(); 159 OS << "(sext " << *Op->getType() << " " << *Op << " to " 160 << *SExt->getType() << ")"; 161 return; 162 } 163 case scAddRecExpr: { 164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 165 OS << "{" << *AR->getOperand(0); 166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 167 OS << ",+," << *AR->getOperand(i); 168 OS << "}<"; 169 if (AR->hasNoUnsignedWrap()) 170 OS << "nuw><"; 171 if (AR->hasNoSignedWrap()) 172 OS << "nsw><"; 173 if (AR->hasNoSelfWrap() && 174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 175 OS << "nw><"; 176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 177 OS << ">"; 178 return; 179 } 180 case scAddExpr: 181 case scMulExpr: 182 case scUMaxExpr: 183 case scSMaxExpr: { 184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 185 const char *OpStr = nullptr; 186 switch (NAry->getSCEVType()) { 187 case scAddExpr: OpStr = " + "; break; 188 case scMulExpr: OpStr = " * "; break; 189 case scUMaxExpr: OpStr = " umax "; break; 190 case scSMaxExpr: OpStr = " smax "; break; 191 } 192 OS << "("; 193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 194 I != E; ++I) { 195 OS << **I; 196 if (std::next(I) != E) 197 OS << OpStr; 198 } 199 OS << ")"; 200 switch (NAry->getSCEVType()) { 201 case scAddExpr: 202 case scMulExpr: 203 if (NAry->hasNoUnsignedWrap()) 204 OS << "<nuw>"; 205 if (NAry->hasNoSignedWrap()) 206 OS << "<nsw>"; 207 } 208 return; 209 } 210 case scUDivExpr: { 211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 213 return; 214 } 215 case scUnknown: { 216 const SCEVUnknown *U = cast<SCEVUnknown>(this); 217 Type *AllocTy; 218 if (U->isSizeOf(AllocTy)) { 219 OS << "sizeof(" << *AllocTy << ")"; 220 return; 221 } 222 if (U->isAlignOf(AllocTy)) { 223 OS << "alignof(" << *AllocTy << ")"; 224 return; 225 } 226 227 Type *CTy; 228 Constant *FieldNo; 229 if (U->isOffsetOf(CTy, FieldNo)) { 230 OS << "offsetof(" << *CTy << ", "; 231 FieldNo->printAsOperand(OS, false); 232 OS << ")"; 233 return; 234 } 235 236 // Otherwise just print it normally. 237 U->getValue()->printAsOperand(OS, false); 238 return; 239 } 240 case scCouldNotCompute: 241 OS << "***COULDNOTCOMPUTE***"; 242 return; 243 } 244 llvm_unreachable("Unknown SCEV kind!"); 245 } 246 247 Type *SCEV::getType() const { 248 switch (static_cast<SCEVTypes>(getSCEVType())) { 249 case scConstant: 250 return cast<SCEVConstant>(this)->getType(); 251 case scTruncate: 252 case scZeroExtend: 253 case scSignExtend: 254 return cast<SCEVCastExpr>(this)->getType(); 255 case scAddRecExpr: 256 case scMulExpr: 257 case scUMaxExpr: 258 case scSMaxExpr: 259 return cast<SCEVNAryExpr>(this)->getType(); 260 case scAddExpr: 261 return cast<SCEVAddExpr>(this)->getType(); 262 case scUDivExpr: 263 return cast<SCEVUDivExpr>(this)->getType(); 264 case scUnknown: 265 return cast<SCEVUnknown>(this)->getType(); 266 case scCouldNotCompute: 267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 268 } 269 llvm_unreachable("Unknown SCEV kind!"); 270 } 271 272 bool SCEV::isZero() const { 273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 274 return SC->getValue()->isZero(); 275 return false; 276 } 277 278 bool SCEV::isOne() const { 279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 280 return SC->getValue()->isOne(); 281 return false; 282 } 283 284 bool SCEV::isAllOnesValue() const { 285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 286 return SC->getValue()->isAllOnesValue(); 287 return false; 288 } 289 290 /// isNonConstantNegative - Return true if the specified scev is negated, but 291 /// not a constant. 292 bool SCEV::isNonConstantNegative() const { 293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 294 if (!Mul) return false; 295 296 // If there is a constant factor, it will be first. 297 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 298 if (!SC) return false; 299 300 // Return true if the value is negative, this matches things like (-42 * V). 301 return SC->getAPInt().isNegative(); 302 } 303 304 SCEVCouldNotCompute::SCEVCouldNotCompute() : 305 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 306 307 bool SCEVCouldNotCompute::classof(const SCEV *S) { 308 return S->getSCEVType() == scCouldNotCompute; 309 } 310 311 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 312 FoldingSetNodeID ID; 313 ID.AddInteger(scConstant); 314 ID.AddPointer(V); 315 void *IP = nullptr; 316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 317 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 318 UniqueSCEVs.InsertNode(S, IP); 319 return S; 320 } 321 322 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 323 return getConstant(ConstantInt::get(getContext(), Val)); 324 } 325 326 const SCEV * 327 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 328 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 329 return getConstant(ConstantInt::get(ITy, V, isSigned)); 330 } 331 332 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 333 unsigned SCEVTy, const SCEV *op, Type *ty) 334 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 335 336 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 337 const SCEV *op, Type *ty) 338 : SCEVCastExpr(ID, scTruncate, op, ty) { 339 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 340 (Ty->isIntegerTy() || Ty->isPointerTy()) && 341 "Cannot truncate non-integer value!"); 342 } 343 344 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 345 const SCEV *op, Type *ty) 346 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 347 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 348 (Ty->isIntegerTy() || Ty->isPointerTy()) && 349 "Cannot zero extend non-integer value!"); 350 } 351 352 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 353 const SCEV *op, Type *ty) 354 : SCEVCastExpr(ID, scSignExtend, op, ty) { 355 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 356 (Ty->isIntegerTy() || Ty->isPointerTy()) && 357 "Cannot sign extend non-integer value!"); 358 } 359 360 void SCEVUnknown::deleted() { 361 // Clear this SCEVUnknown from various maps. 362 SE->forgetMemoizedResults(this); 363 364 // Remove this SCEVUnknown from the uniquing map. 365 SE->UniqueSCEVs.RemoveNode(this); 366 367 // Release the value. 368 setValPtr(nullptr); 369 } 370 371 void SCEVUnknown::allUsesReplacedWith(Value *New) { 372 // Clear this SCEVUnknown from various maps. 373 SE->forgetMemoizedResults(this); 374 375 // Remove this SCEVUnknown from the uniquing map. 376 SE->UniqueSCEVs.RemoveNode(this); 377 378 // Update this SCEVUnknown to point to the new value. This is needed 379 // because there may still be outstanding SCEVs which still point to 380 // this SCEVUnknown. 381 setValPtr(New); 382 } 383 384 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 386 if (VCE->getOpcode() == Instruction::PtrToInt) 387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 388 if (CE->getOpcode() == Instruction::GetElementPtr && 389 CE->getOperand(0)->isNullValue() && 390 CE->getNumOperands() == 2) 391 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 392 if (CI->isOne()) { 393 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 394 ->getElementType(); 395 return true; 396 } 397 398 return false; 399 } 400 401 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 402 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 403 if (VCE->getOpcode() == Instruction::PtrToInt) 404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 405 if (CE->getOpcode() == Instruction::GetElementPtr && 406 CE->getOperand(0)->isNullValue()) { 407 Type *Ty = 408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 409 if (StructType *STy = dyn_cast<StructType>(Ty)) 410 if (!STy->isPacked() && 411 CE->getNumOperands() == 3 && 412 CE->getOperand(1)->isNullValue()) { 413 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 414 if (CI->isOne() && 415 STy->getNumElements() == 2 && 416 STy->getElementType(0)->isIntegerTy(1)) { 417 AllocTy = STy->getElementType(1); 418 return true; 419 } 420 } 421 } 422 423 return false; 424 } 425 426 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 428 if (VCE->getOpcode() == Instruction::PtrToInt) 429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 430 if (CE->getOpcode() == Instruction::GetElementPtr && 431 CE->getNumOperands() == 3 && 432 CE->getOperand(0)->isNullValue() && 433 CE->getOperand(1)->isNullValue()) { 434 Type *Ty = 435 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 436 // Ignore vector types here so that ScalarEvolutionExpander doesn't 437 // emit getelementptrs that index into vectors. 438 if (Ty->isStructTy() || Ty->isArrayTy()) { 439 CTy = Ty; 440 FieldNo = CE->getOperand(2); 441 return true; 442 } 443 } 444 445 return false; 446 } 447 448 //===----------------------------------------------------------------------===// 449 // SCEV Utilities 450 //===----------------------------------------------------------------------===// 451 452 namespace { 453 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 454 /// than the complexity of the RHS. This comparator is used to canonicalize 455 /// expressions. 456 class SCEVComplexityCompare { 457 const LoopInfo *const LI; 458 public: 459 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} 460 461 // Return true or false if LHS is less than, or at least RHS, respectively. 462 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 463 return compare(LHS, RHS) < 0; 464 } 465 466 // Return negative, zero, or positive, if LHS is less than, equal to, or 467 // greater than RHS, respectively. A three-way result allows recursive 468 // comparisons to be more efficient. 469 int compare(const SCEV *LHS, const SCEV *RHS) const { 470 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 471 if (LHS == RHS) 472 return 0; 473 474 // Primarily, sort the SCEVs by their getSCEVType(). 475 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 476 if (LType != RType) 477 return (int)LType - (int)RType; 478 479 // Aside from the getSCEVType() ordering, the particular ordering 480 // isn't very important except that it's beneficial to be consistent, 481 // so that (a + b) and (b + a) don't end up as different expressions. 482 switch (static_cast<SCEVTypes>(LType)) { 483 case scUnknown: { 484 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 485 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 486 487 // Sort SCEVUnknown values with some loose heuristics. TODO: This is 488 // not as complete as it could be. 489 const Value *LV = LU->getValue(), *RV = RU->getValue(); 490 491 // Order pointer values after integer values. This helps SCEVExpander 492 // form GEPs. 493 bool LIsPointer = LV->getType()->isPointerTy(), 494 RIsPointer = RV->getType()->isPointerTy(); 495 if (LIsPointer != RIsPointer) 496 return (int)LIsPointer - (int)RIsPointer; 497 498 // Compare getValueID values. 499 unsigned LID = LV->getValueID(), 500 RID = RV->getValueID(); 501 if (LID != RID) 502 return (int)LID - (int)RID; 503 504 // Sort arguments by their position. 505 if (const Argument *LA = dyn_cast<Argument>(LV)) { 506 const Argument *RA = cast<Argument>(RV); 507 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 508 return (int)LArgNo - (int)RArgNo; 509 } 510 511 // For instructions, compare their loop depth, and their operand 512 // count. This is pretty loose. 513 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { 514 const Instruction *RInst = cast<Instruction>(RV); 515 516 // Compare loop depths. 517 const BasicBlock *LParent = LInst->getParent(), 518 *RParent = RInst->getParent(); 519 if (LParent != RParent) { 520 unsigned LDepth = LI->getLoopDepth(LParent), 521 RDepth = LI->getLoopDepth(RParent); 522 if (LDepth != RDepth) 523 return (int)LDepth - (int)RDepth; 524 } 525 526 // Compare the number of operands. 527 unsigned LNumOps = LInst->getNumOperands(), 528 RNumOps = RInst->getNumOperands(); 529 return (int)LNumOps - (int)RNumOps; 530 } 531 532 return 0; 533 } 534 535 case scConstant: { 536 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 537 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 538 539 // Compare constant values. 540 const APInt &LA = LC->getAPInt(); 541 const APInt &RA = RC->getAPInt(); 542 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 543 if (LBitWidth != RBitWidth) 544 return (int)LBitWidth - (int)RBitWidth; 545 return LA.ult(RA) ? -1 : 1; 546 } 547 548 case scAddRecExpr: { 549 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 550 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 551 552 // Compare addrec loop depths. 553 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 554 if (LLoop != RLoop) { 555 unsigned LDepth = LLoop->getLoopDepth(), 556 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 = compare(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 = compare(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 = compare(LC->getLHS(), RC->getLHS()); 604 if (X != 0) 605 return X; 606 return compare(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 compare(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 } // end anonymous namespace 626 627 /// GroupByComplexity - Given a list of SCEV objects, order them by their 628 /// complexity, and group objects of the same complexity together by value. 629 /// When this routine is finished, we know that any duplicates in the vector are 630 /// consecutive and that complexity is monotonically increasing. 631 /// 632 /// Note that we go take special precautions to ensure that we get deterministic 633 /// results from this routine. In other words, we don't want the results of 634 /// this to depend on where the addresses of various SCEV objects happened to 635 /// land in memory. 636 /// 637 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 638 LoopInfo *LI) { 639 if (Ops.size() < 2) return; // Noop 640 if (Ops.size() == 2) { 641 // This is the common case, which also happens to be trivially simple. 642 // Special case it. 643 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 644 if (SCEVComplexityCompare(LI)(RHS, LHS)) 645 std::swap(LHS, RHS); 646 return; 647 } 648 649 // Do the rough sort by complexity. 650 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); 651 652 // Now that we are sorted by complexity, group elements of the same 653 // complexity. Note that this is, at worst, N^2, but the vector is likely to 654 // be extremely short in practice. Note that we take this approach because we 655 // do not want to depend on the addresses of the objects we are grouping. 656 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 657 const SCEV *S = Ops[i]; 658 unsigned Complexity = S->getSCEVType(); 659 660 // If there are any objects of the same complexity and same value as this 661 // one, group them. 662 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 663 if (Ops[j] == S) { // Found a duplicate. 664 // Move it to immediately after i'th element. 665 std::swap(Ops[i+1], Ops[j]); 666 ++i; // no need to rescan it. 667 if (i == e-2) return; // Done! 668 } 669 } 670 } 671 } 672 673 // Returns the size of the SCEV S. 674 static inline int sizeOfSCEV(const SCEV *S) { 675 struct FindSCEVSize { 676 int Size; 677 FindSCEVSize() : Size(0) {} 678 679 bool follow(const SCEV *S) { 680 ++Size; 681 // Keep looking at all operands of S. 682 return true; 683 } 684 bool isDone() const { 685 return false; 686 } 687 }; 688 689 FindSCEVSize F; 690 SCEVTraversal<FindSCEVSize> ST(F); 691 ST.visitAll(S); 692 return F.Size; 693 } 694 695 namespace { 696 697 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 698 public: 699 // Computes the Quotient and Remainder of the division of Numerator by 700 // Denominator. 701 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 702 const SCEV *Denominator, const SCEV **Quotient, 703 const SCEV **Remainder) { 704 assert(Numerator && Denominator && "Uninitialized SCEV"); 705 706 SCEVDivision D(SE, Numerator, Denominator); 707 708 // Check for the trivial case here to avoid having to check for it in the 709 // rest of the code. 710 if (Numerator == Denominator) { 711 *Quotient = D.One; 712 *Remainder = D.Zero; 713 return; 714 } 715 716 if (Numerator->isZero()) { 717 *Quotient = D.Zero; 718 *Remainder = D.Zero; 719 return; 720 } 721 722 // A simple case when N/1. The quotient is N. 723 if (Denominator->isOne()) { 724 *Quotient = Numerator; 725 *Remainder = D.Zero; 726 return; 727 } 728 729 // Split the Denominator when it is a product. 730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) { 731 const SCEV *Q, *R; 732 *Quotient = Numerator; 733 for (const SCEV *Op : T->operands()) { 734 divide(SE, *Quotient, Op, &Q, &R); 735 *Quotient = Q; 736 737 // Bail out when the Numerator is not divisible by one of the terms of 738 // the Denominator. 739 if (!R->isZero()) { 740 *Quotient = D.Zero; 741 *Remainder = Numerator; 742 return; 743 } 744 } 745 *Remainder = D.Zero; 746 return; 747 } 748 749 D.visit(Numerator); 750 *Quotient = D.Quotient; 751 *Remainder = D.Remainder; 752 } 753 754 // Except in the trivial case described above, we do not know how to divide 755 // Expr by Denominator for the following functions with empty implementation. 756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 762 void visitUnknown(const SCEVUnknown *Numerator) {} 763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 764 765 void visitConstant(const SCEVConstant *Numerator) { 766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 767 APInt NumeratorVal = Numerator->getAPInt(); 768 APInt DenominatorVal = D->getAPInt(); 769 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 770 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 771 772 if (NumeratorBW > DenominatorBW) 773 DenominatorVal = DenominatorVal.sext(NumeratorBW); 774 else if (NumeratorBW < DenominatorBW) 775 NumeratorVal = NumeratorVal.sext(DenominatorBW); 776 777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 780 Quotient = SE.getConstant(QuotientVal); 781 Remainder = SE.getConstant(RemainderVal); 782 return; 783 } 784 } 785 786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 787 const SCEV *StartQ, *StartR, *StepQ, *StepR; 788 if (!Numerator->isAffine()) 789 return cannotDivide(Numerator); 790 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 791 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 792 // Bail out if the types do not match. 793 Type *Ty = Denominator->getType(); 794 if (Ty != StartQ->getType() || Ty != StartR->getType() || 795 Ty != StepQ->getType() || Ty != StepR->getType()) 796 return cannotDivide(Numerator); 797 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 798 Numerator->getNoWrapFlags()); 799 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 800 Numerator->getNoWrapFlags()); 801 } 802 803 void visitAddExpr(const SCEVAddExpr *Numerator) { 804 SmallVector<const SCEV *, 2> Qs, Rs; 805 Type *Ty = Denominator->getType(); 806 807 for (const SCEV *Op : Numerator->operands()) { 808 const SCEV *Q, *R; 809 divide(SE, Op, Denominator, &Q, &R); 810 811 // Bail out if types do not match. 812 if (Ty != Q->getType() || Ty != R->getType()) 813 return cannotDivide(Numerator); 814 815 Qs.push_back(Q); 816 Rs.push_back(R); 817 } 818 819 if (Qs.size() == 1) { 820 Quotient = Qs[0]; 821 Remainder = Rs[0]; 822 return; 823 } 824 825 Quotient = SE.getAddExpr(Qs); 826 Remainder = SE.getAddExpr(Rs); 827 } 828 829 void visitMulExpr(const SCEVMulExpr *Numerator) { 830 SmallVector<const SCEV *, 2> Qs; 831 Type *Ty = Denominator->getType(); 832 833 bool FoundDenominatorTerm = false; 834 for (const SCEV *Op : Numerator->operands()) { 835 // Bail out if types do not match. 836 if (Ty != Op->getType()) 837 return cannotDivide(Numerator); 838 839 if (FoundDenominatorTerm) { 840 Qs.push_back(Op); 841 continue; 842 } 843 844 // Check whether Denominator divides one of the product operands. 845 const SCEV *Q, *R; 846 divide(SE, Op, Denominator, &Q, &R); 847 if (!R->isZero()) { 848 Qs.push_back(Op); 849 continue; 850 } 851 852 // Bail out if types do not match. 853 if (Ty != Q->getType()) 854 return cannotDivide(Numerator); 855 856 FoundDenominatorTerm = true; 857 Qs.push_back(Q); 858 } 859 860 if (FoundDenominatorTerm) { 861 Remainder = Zero; 862 if (Qs.size() == 1) 863 Quotient = Qs[0]; 864 else 865 Quotient = SE.getMulExpr(Qs); 866 return; 867 } 868 869 if (!isa<SCEVUnknown>(Denominator)) 870 return cannotDivide(Numerator); 871 872 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 873 ValueToValueMap RewriteMap; 874 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 875 cast<SCEVConstant>(Zero)->getValue(); 876 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 877 878 if (Remainder->isZero()) { 879 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 881 cast<SCEVConstant>(One)->getValue(); 882 Quotient = 883 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 884 return; 885 } 886 887 // Quotient is (Numerator - Remainder) divided by Denominator. 888 const SCEV *Q, *R; 889 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 890 // This SCEV does not seem to simplify: fail the division here. 891 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 892 return cannotDivide(Numerator); 893 divide(SE, Diff, Denominator, &Q, &R); 894 if (R != Zero) 895 return cannotDivide(Numerator); 896 Quotient = Q; 897 } 898 899 private: 900 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 901 const SCEV *Denominator) 902 : SE(S), Denominator(Denominator) { 903 Zero = SE.getZero(Denominator->getType()); 904 One = SE.getOne(Denominator->getType()); 905 906 // We generally do not know how to divide Expr by Denominator. We 907 // initialize the division to a "cannot divide" state to simplify the rest 908 // of the code. 909 cannotDivide(Numerator); 910 } 911 912 // Convenience function for giving up on the division. We set the quotient to 913 // be equal to zero and the remainder to be equal to the numerator. 914 void cannotDivide(const SCEV *Numerator) { 915 Quotient = Zero; 916 Remainder = Numerator; 917 } 918 919 ScalarEvolution &SE; 920 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 921 }; 922 923 } 924 925 //===----------------------------------------------------------------------===// 926 // Simple SCEV method implementations 927 //===----------------------------------------------------------------------===// 928 929 /// BinomialCoefficient - Compute BC(It, K). The result has width W. 930 /// 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 /// evaluateAtIteration - Return the value of this chain of recurrences at 1042 /// the specified iteration number. We can evaluate this recurrence by 1043 /// multiplying each element in the chain by the binomial coefficient 1044 /// corresponding to it. In other words, we 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 we have special knowledge that this addrec won't overflow, 1458 // we don't need to do any further analysis. 1459 if (AR->hasNoUnsignedWrap()) 1460 return getAddRecExpr( 1461 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1462 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1463 1464 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1465 // Note that this serves two purposes: It filters out loops that are 1466 // simply not analyzable, and it covers the case where this code is 1467 // being called from within backedge-taken count analysis, such that 1468 // attempting to ask for the backedge-taken count would likely result 1469 // in infinite recursion. In the later case, the analysis code will 1470 // cope with a conservative value, and it will take care to purge 1471 // that value once it has finished. 1472 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1473 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1474 // Manually compute the final value for AR, checking for 1475 // overflow. 1476 1477 // Check whether the backedge-taken count can be losslessly casted to 1478 // the addrec's type. The count is always unsigned. 1479 const SCEV *CastedMaxBECount = 1480 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1481 const SCEV *RecastedMaxBECount = 1482 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1483 if (MaxBECount == RecastedMaxBECount) { 1484 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1485 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1486 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1487 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1488 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1489 const SCEV *WideMaxBECount = 1490 getZeroExtendExpr(CastedMaxBECount, WideTy); 1491 const SCEV *OperandExtendedAdd = 1492 getAddExpr(WideStart, 1493 getMulExpr(WideMaxBECount, 1494 getZeroExtendExpr(Step, WideTy))); 1495 if (ZAdd == OperandExtendedAdd) { 1496 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1497 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1498 // Return the expression with the addrec on the outside. 1499 return getAddRecExpr( 1500 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1501 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1502 } 1503 // Similar to above, only this time treat the step value as signed. 1504 // This covers loops that count down. 1505 OperandExtendedAdd = 1506 getAddExpr(WideStart, 1507 getMulExpr(WideMaxBECount, 1508 getSignExtendExpr(Step, WideTy))); 1509 if (ZAdd == OperandExtendedAdd) { 1510 // Cache knowledge of AR NW, which is propagated to this AddRec. 1511 // Negative step causes unsigned wrap, but it still can't self-wrap. 1512 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1513 // Return the expression with the addrec on the outside. 1514 return getAddRecExpr( 1515 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1516 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1517 } 1518 } 1519 1520 // If the backedge is guarded by a comparison with the pre-inc value 1521 // the addrec is safe. Also, if the entry is guarded by a comparison 1522 // with the start value and the backedge is guarded by a comparison 1523 // with the post-inc value, the addrec is safe. 1524 if (isKnownPositive(Step)) { 1525 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1526 getUnsignedRange(Step).getUnsignedMax()); 1527 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1528 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1529 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1530 AR->getPostIncExpr(*this), N))) { 1531 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1532 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1533 // Return the expression with the addrec on the outside. 1534 return getAddRecExpr( 1535 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1536 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1537 } 1538 } else if (isKnownNegative(Step)) { 1539 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1540 getSignedRange(Step).getSignedMin()); 1541 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1542 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1543 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1544 AR->getPostIncExpr(*this), N))) { 1545 // Cache knowledge of AR NW, which is propagated to this AddRec. 1546 // Negative step causes unsigned wrap, but it still can't self-wrap. 1547 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1548 // Return the expression with the addrec on the outside. 1549 return getAddRecExpr( 1550 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1551 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1552 } 1553 } 1554 } 1555 1556 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1557 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1558 return getAddRecExpr( 1559 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1560 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1561 } 1562 } 1563 1564 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1565 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1566 if (SA->hasNoUnsignedWrap()) { 1567 // If the addition does not unsign overflow then we can, by definition, 1568 // commute the zero extension with the addition operation. 1569 SmallVector<const SCEV *, 4> Ops; 1570 for (const auto *Op : SA->operands()) 1571 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1572 return getAddExpr(Ops, SCEV::FlagNUW); 1573 } 1574 } 1575 1576 // The cast wasn't folded; create an explicit cast node. 1577 // Recompute the insert position, as it may have been invalidated. 1578 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1579 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1580 Op, Ty); 1581 UniqueSCEVs.InsertNode(S, IP); 1582 return S; 1583 } 1584 1585 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1586 Type *Ty) { 1587 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1588 "This is not an extending conversion!"); 1589 assert(isSCEVable(Ty) && 1590 "This is not a conversion to a SCEVable type!"); 1591 Ty = getEffectiveSCEVType(Ty); 1592 1593 // Fold if the operand is constant. 1594 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1595 return getConstant( 1596 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1597 1598 // sext(sext(x)) --> sext(x) 1599 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1600 return getSignExtendExpr(SS->getOperand(), Ty); 1601 1602 // sext(zext(x)) --> zext(x) 1603 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1604 return getZeroExtendExpr(SZ->getOperand(), Ty); 1605 1606 // Before doing any expensive analysis, check to see if we've already 1607 // computed a SCEV for this Op and Ty. 1608 FoldingSetNodeID ID; 1609 ID.AddInteger(scSignExtend); 1610 ID.AddPointer(Op); 1611 ID.AddPointer(Ty); 1612 void *IP = nullptr; 1613 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1614 1615 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1616 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1617 // It's possible the bits taken off by the truncate were all sign bits. If 1618 // so, we should be able to simplify this further. 1619 const SCEV *X = ST->getOperand(); 1620 ConstantRange CR = getSignedRange(X); 1621 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1622 unsigned NewBits = getTypeSizeInBits(Ty); 1623 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1624 CR.sextOrTrunc(NewBits))) 1625 return getTruncateOrSignExtend(X, Ty); 1626 } 1627 1628 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1629 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1630 if (SA->getNumOperands() == 2) { 1631 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1632 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1633 if (SMul && SC1) { 1634 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1635 const APInt &C1 = SC1->getAPInt(); 1636 const APInt &C2 = SC2->getAPInt(); 1637 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1638 C2.ugt(C1) && C2.isPowerOf2()) 1639 return getAddExpr(getSignExtendExpr(SC1, Ty), 1640 getSignExtendExpr(SMul, Ty)); 1641 } 1642 } 1643 } 1644 1645 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1646 if (SA->hasNoSignedWrap()) { 1647 // If the addition does not sign overflow then we can, by definition, 1648 // commute the sign extension with the addition operation. 1649 SmallVector<const SCEV *, 4> Ops; 1650 for (const auto *Op : SA->operands()) 1651 Ops.push_back(getSignExtendExpr(Op, Ty)); 1652 return getAddExpr(Ops, SCEV::FlagNSW); 1653 } 1654 } 1655 // If the input value is a chrec scev, and we can prove that the value 1656 // did not overflow the old, smaller, value, we can sign extend all of the 1657 // operands (often constants). This allows analysis of something like 1658 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1659 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1660 if (AR->isAffine()) { 1661 const SCEV *Start = AR->getStart(); 1662 const SCEV *Step = AR->getStepRecurrence(*this); 1663 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1664 const Loop *L = AR->getLoop(); 1665 1666 // If we have special knowledge that this addrec won't overflow, 1667 // we don't need to do any further analysis. 1668 if (AR->hasNoSignedWrap()) 1669 return getAddRecExpr( 1670 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1671 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1672 1673 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1674 // Note that this serves two purposes: It filters out loops that are 1675 // simply not analyzable, and it covers the case where this code is 1676 // being called from within backedge-taken count analysis, such that 1677 // attempting to ask for the backedge-taken count would likely result 1678 // in infinite recursion. In the later case, the analysis code will 1679 // cope with a conservative value, and it will take care to purge 1680 // that value once it has finished. 1681 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1682 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1683 // Manually compute the final value for AR, checking for 1684 // overflow. 1685 1686 // Check whether the backedge-taken count can be losslessly casted to 1687 // the addrec's type. The count is always unsigned. 1688 const SCEV *CastedMaxBECount = 1689 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1690 const SCEV *RecastedMaxBECount = 1691 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1692 if (MaxBECount == RecastedMaxBECount) { 1693 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1694 // Check whether Start+Step*MaxBECount has no signed overflow. 1695 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1696 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1697 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1698 const SCEV *WideMaxBECount = 1699 getZeroExtendExpr(CastedMaxBECount, WideTy); 1700 const SCEV *OperandExtendedAdd = 1701 getAddExpr(WideStart, 1702 getMulExpr(WideMaxBECount, 1703 getSignExtendExpr(Step, WideTy))); 1704 if (SAdd == OperandExtendedAdd) { 1705 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1706 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1707 // Return the expression with the addrec on the outside. 1708 return getAddRecExpr( 1709 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1710 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1711 } 1712 // Similar to above, only this time treat the step value as unsigned. 1713 // This covers loops that count up with an unsigned step. 1714 OperandExtendedAdd = 1715 getAddExpr(WideStart, 1716 getMulExpr(WideMaxBECount, 1717 getZeroExtendExpr(Step, WideTy))); 1718 if (SAdd == OperandExtendedAdd) { 1719 // If AR wraps around then 1720 // 1721 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1722 // => SAdd != OperandExtendedAdd 1723 // 1724 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1725 // (SAdd == OperandExtendedAdd => AR is NW) 1726 1727 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1728 1729 // Return the expression with the addrec on the outside. 1730 return getAddRecExpr( 1731 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1732 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1733 } 1734 } 1735 1736 // If the backedge is guarded by a comparison with the pre-inc value 1737 // the addrec is safe. Also, if the entry is guarded by a comparison 1738 // with the start value and the backedge is guarded by a comparison 1739 // with the post-inc value, the addrec is safe. 1740 ICmpInst::Predicate Pred; 1741 const SCEV *OverflowLimit = 1742 getSignedOverflowLimitForStep(Step, &Pred, this); 1743 if (OverflowLimit && 1744 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1745 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1746 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1747 OverflowLimit)))) { 1748 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1752 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1753 } 1754 } 1755 // If Start and Step are constants, check if we can apply this 1756 // transformation: 1757 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1758 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1759 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1760 if (SC1 && SC2) { 1761 const APInt &C1 = SC1->getAPInt(); 1762 const APInt &C2 = SC2->getAPInt(); 1763 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1764 C2.isPowerOf2()) { 1765 Start = getSignExtendExpr(Start, Ty); 1766 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1767 AR->getNoWrapFlags()); 1768 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1769 } 1770 } 1771 1772 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1773 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1774 return getAddRecExpr( 1775 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1776 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1777 } 1778 } 1779 1780 // If the input value is provably positive and we could not simplify 1781 // away the sext build a zext instead. 1782 if (isKnownNonNegative(Op)) 1783 return getZeroExtendExpr(Op, Ty); 1784 1785 // The cast wasn't folded; create an explicit cast node. 1786 // Recompute the insert position, as it may have been invalidated. 1787 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1788 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1789 Op, Ty); 1790 UniqueSCEVs.InsertNode(S, IP); 1791 return S; 1792 } 1793 1794 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1795 /// unspecified bits out to the given type. 1796 /// 1797 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1798 Type *Ty) { 1799 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1800 "This is not an extending conversion!"); 1801 assert(isSCEVable(Ty) && 1802 "This is not a conversion to a SCEVable type!"); 1803 Ty = getEffectiveSCEVType(Ty); 1804 1805 // Sign-extend negative constants. 1806 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1807 if (SC->getAPInt().isNegative()) 1808 return getSignExtendExpr(Op, Ty); 1809 1810 // Peel off a truncate cast. 1811 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1812 const SCEV *NewOp = T->getOperand(); 1813 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1814 return getAnyExtendExpr(NewOp, Ty); 1815 return getTruncateOrNoop(NewOp, Ty); 1816 } 1817 1818 // Next try a zext cast. If the cast is folded, use it. 1819 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1820 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1821 return ZExt; 1822 1823 // Next try a sext cast. If the cast is folded, use it. 1824 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1825 if (!isa<SCEVSignExtendExpr>(SExt)) 1826 return SExt; 1827 1828 // Force the cast to be folded into the operands of an addrec. 1829 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1830 SmallVector<const SCEV *, 4> Ops; 1831 for (const SCEV *Op : AR->operands()) 1832 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1833 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1834 } 1835 1836 // If the expression is obviously signed, use the sext cast value. 1837 if (isa<SCEVSMaxExpr>(Op)) 1838 return SExt; 1839 1840 // Absent any other information, use the zext cast value. 1841 return ZExt; 1842 } 1843 1844 /// CollectAddOperandsWithScales - Process the given Ops list, which is 1845 /// a list of operands to be added under the given scale, update the given 1846 /// map. This is a helper function for getAddRecExpr. As an example of 1847 /// what it does, given a sequence of operands that would form an add 1848 /// expression like this: 1849 /// 1850 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1851 /// 1852 /// where A and B are constants, update the map with these values: 1853 /// 1854 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1855 /// 1856 /// and add 13 + A*B*29 to AccumulatedConstant. 1857 /// This will allow getAddRecExpr to produce this: 1858 /// 1859 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1860 /// 1861 /// This form often exposes folding opportunities that are hidden in 1862 /// the original operand list. 1863 /// 1864 /// Return true iff it appears that any interesting folding opportunities 1865 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1866 /// the common case where no interesting opportunities are present, and 1867 /// is also used as a check to avoid infinite recursion. 1868 /// 1869 static bool 1870 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1871 SmallVectorImpl<const SCEV *> &NewOps, 1872 APInt &AccumulatedConstant, 1873 const SCEV *const *Ops, size_t NumOperands, 1874 const APInt &Scale, 1875 ScalarEvolution &SE) { 1876 bool Interesting = false; 1877 1878 // Iterate over the add operands. They are sorted, with constants first. 1879 unsigned i = 0; 1880 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1881 ++i; 1882 // Pull a buried constant out to the outside. 1883 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1884 Interesting = true; 1885 AccumulatedConstant += Scale * C->getAPInt(); 1886 } 1887 1888 // Next comes everything else. We're especially interested in multiplies 1889 // here, but they're in the middle, so just visit the rest with one loop. 1890 for (; i != NumOperands; ++i) { 1891 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1892 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1893 APInt NewScale = 1894 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1895 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1896 // A multiplication of a constant with another add; recurse. 1897 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1898 Interesting |= 1899 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1900 Add->op_begin(), Add->getNumOperands(), 1901 NewScale, SE); 1902 } else { 1903 // A multiplication of a constant with some other value. Update 1904 // the map. 1905 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1906 const SCEV *Key = SE.getMulExpr(MulOps); 1907 auto Pair = M.insert({Key, NewScale}); 1908 if (Pair.second) { 1909 NewOps.push_back(Pair.first->first); 1910 } else { 1911 Pair.first->second += NewScale; 1912 // The map already had an entry for this value, which may indicate 1913 // a folding opportunity. 1914 Interesting = true; 1915 } 1916 } 1917 } else { 1918 // An ordinary operand. Update the map. 1919 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1920 M.insert({Ops[i], Scale}); 1921 if (Pair.second) { 1922 NewOps.push_back(Pair.first->first); 1923 } else { 1924 Pair.first->second += Scale; 1925 // The map already had an entry for this value, which may indicate 1926 // a folding opportunity. 1927 Interesting = true; 1928 } 1929 } 1930 } 1931 1932 return Interesting; 1933 } 1934 1935 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 1936 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 1937 // can't-overflow flags for the operation if possible. 1938 static SCEV::NoWrapFlags 1939 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 1940 const SmallVectorImpl<const SCEV *> &Ops, 1941 SCEV::NoWrapFlags Flags) { 1942 using namespace std::placeholders; 1943 typedef OverflowingBinaryOperator OBO; 1944 1945 bool CanAnalyze = 1946 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 1947 (void)CanAnalyze; 1948 assert(CanAnalyze && "don't call from other places!"); 1949 1950 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1951 SCEV::NoWrapFlags SignOrUnsignWrap = 1952 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1953 1954 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1955 auto IsKnownNonNegative = [&](const SCEV *S) { 1956 return SE->isKnownNonNegative(S); 1957 }; 1958 1959 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 1960 Flags = 1961 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1962 1963 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1964 1965 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 1966 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 1967 1968 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 1969 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 1970 1971 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 1972 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 1973 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 1974 Instruction::Add, C, OBO::NoSignedWrap); 1975 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 1976 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 1977 } 1978 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 1979 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 1980 Instruction::Add, C, OBO::NoUnsignedWrap); 1981 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 1982 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 1983 } 1984 } 1985 1986 return Flags; 1987 } 1988 1989 /// getAddExpr - Get a canonical add expression, or something simpler if 1990 /// possible. 1991 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 1992 SCEV::NoWrapFlags Flags) { 1993 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 1994 "only nuw or nsw allowed"); 1995 assert(!Ops.empty() && "Cannot get empty add!"); 1996 if (Ops.size() == 1) return Ops[0]; 1997 #ifndef NDEBUG 1998 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 1999 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2000 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2001 "SCEVAddExpr operand types don't match!"); 2002 #endif 2003 2004 // Sort by complexity, this groups all similar expression types together. 2005 GroupByComplexity(Ops, &LI); 2006 2007 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2008 2009 // If there are any constants, fold them together. 2010 unsigned Idx = 0; 2011 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2012 ++Idx; 2013 assert(Idx < Ops.size()); 2014 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2015 // We found two constants, fold them together! 2016 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2017 if (Ops.size() == 2) return Ops[0]; 2018 Ops.erase(Ops.begin()+1); // Erase the folded element 2019 LHSC = cast<SCEVConstant>(Ops[0]); 2020 } 2021 2022 // If we are left with a constant zero being added, strip it off. 2023 if (LHSC->getValue()->isZero()) { 2024 Ops.erase(Ops.begin()); 2025 --Idx; 2026 } 2027 2028 if (Ops.size() == 1) return Ops[0]; 2029 } 2030 2031 // Okay, check to see if the same value occurs in the operand list more than 2032 // once. If so, merge them together into an multiply expression. Since we 2033 // sorted the list, these values are required to be adjacent. 2034 Type *Ty = Ops[0]->getType(); 2035 bool FoundMatch = false; 2036 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2037 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2038 // Scan ahead to count how many equal operands there are. 2039 unsigned Count = 2; 2040 while (i+Count != e && Ops[i+Count] == Ops[i]) 2041 ++Count; 2042 // Merge the values into a multiply. 2043 const SCEV *Scale = getConstant(Ty, Count); 2044 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2045 if (Ops.size() == Count) 2046 return Mul; 2047 Ops[i] = Mul; 2048 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2049 --i; e -= Count - 1; 2050 FoundMatch = true; 2051 } 2052 if (FoundMatch) 2053 return getAddExpr(Ops, Flags); 2054 2055 // Check for truncates. If all the operands are truncated from the same 2056 // type, see if factoring out the truncate would permit the result to be 2057 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2058 // if the contents of the resulting outer trunc fold to something simple. 2059 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2060 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2061 Type *DstType = Trunc->getType(); 2062 Type *SrcType = Trunc->getOperand()->getType(); 2063 SmallVector<const SCEV *, 8> LargeOps; 2064 bool Ok = true; 2065 // Check all the operands to see if they can be represented in the 2066 // source type of the truncate. 2067 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2068 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2069 if (T->getOperand()->getType() != SrcType) { 2070 Ok = false; 2071 break; 2072 } 2073 LargeOps.push_back(T->getOperand()); 2074 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2075 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2076 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2077 SmallVector<const SCEV *, 8> LargeMulOps; 2078 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2079 if (const SCEVTruncateExpr *T = 2080 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2081 if (T->getOperand()->getType() != SrcType) { 2082 Ok = false; 2083 break; 2084 } 2085 LargeMulOps.push_back(T->getOperand()); 2086 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2087 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2088 } else { 2089 Ok = false; 2090 break; 2091 } 2092 } 2093 if (Ok) 2094 LargeOps.push_back(getMulExpr(LargeMulOps)); 2095 } else { 2096 Ok = false; 2097 break; 2098 } 2099 } 2100 if (Ok) { 2101 // Evaluate the expression in the larger type. 2102 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2103 // If it folds to something simple, use it. Otherwise, don't. 2104 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2105 return getTruncateExpr(Fold, DstType); 2106 } 2107 } 2108 2109 // Skip past any other cast SCEVs. 2110 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2111 ++Idx; 2112 2113 // If there are add operands they would be next. 2114 if (Idx < Ops.size()) { 2115 bool DeletedAdd = false; 2116 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2117 // If we have an add, expand the add operands onto the end of the operands 2118 // list. 2119 Ops.erase(Ops.begin()+Idx); 2120 Ops.append(Add->op_begin(), Add->op_end()); 2121 DeletedAdd = true; 2122 } 2123 2124 // If we deleted at least one add, we added operands to the end of the list, 2125 // and they are not necessarily sorted. Recurse to resort and resimplify 2126 // any operands we just acquired. 2127 if (DeletedAdd) 2128 return getAddExpr(Ops); 2129 } 2130 2131 // Skip over the add expression until we get to a multiply. 2132 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2133 ++Idx; 2134 2135 // Check to see if there are any folding opportunities present with 2136 // operands multiplied by constant values. 2137 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2138 uint64_t BitWidth = getTypeSizeInBits(Ty); 2139 DenseMap<const SCEV *, APInt> M; 2140 SmallVector<const SCEV *, 8> NewOps; 2141 APInt AccumulatedConstant(BitWidth, 0); 2142 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2143 Ops.data(), Ops.size(), 2144 APInt(BitWidth, 1), *this)) { 2145 struct APIntCompare { 2146 bool operator()(const APInt &LHS, const APInt &RHS) const { 2147 return LHS.ult(RHS); 2148 } 2149 }; 2150 2151 // Some interesting folding opportunity is present, so its worthwhile to 2152 // re-generate the operands list. Group the operands by constant scale, 2153 // to avoid multiplying by the same constant scale multiple times. 2154 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2155 for (const SCEV *NewOp : NewOps) 2156 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2157 // Re-generate the operands list. 2158 Ops.clear(); 2159 if (AccumulatedConstant != 0) 2160 Ops.push_back(getConstant(AccumulatedConstant)); 2161 for (auto &MulOp : MulOpLists) 2162 if (MulOp.first != 0) 2163 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2164 getAddExpr(MulOp.second))); 2165 if (Ops.empty()) 2166 return getZero(Ty); 2167 if (Ops.size() == 1) 2168 return Ops[0]; 2169 return getAddExpr(Ops); 2170 } 2171 } 2172 2173 // If we are adding something to a multiply expression, make sure the 2174 // something is not already an operand of the multiply. If so, merge it into 2175 // the multiply. 2176 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2177 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2178 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2179 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2180 if (isa<SCEVConstant>(MulOpSCEV)) 2181 continue; 2182 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2183 if (MulOpSCEV == Ops[AddOp]) { 2184 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2185 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2186 if (Mul->getNumOperands() != 2) { 2187 // If the multiply has more than two operands, we must get the 2188 // Y*Z term. 2189 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2190 Mul->op_begin()+MulOp); 2191 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2192 InnerMul = getMulExpr(MulOps); 2193 } 2194 const SCEV *One = getOne(Ty); 2195 const SCEV *AddOne = getAddExpr(One, InnerMul); 2196 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2197 if (Ops.size() == 2) return OuterMul; 2198 if (AddOp < Idx) { 2199 Ops.erase(Ops.begin()+AddOp); 2200 Ops.erase(Ops.begin()+Idx-1); 2201 } else { 2202 Ops.erase(Ops.begin()+Idx); 2203 Ops.erase(Ops.begin()+AddOp-1); 2204 } 2205 Ops.push_back(OuterMul); 2206 return getAddExpr(Ops); 2207 } 2208 2209 // Check this multiply against other multiplies being added together. 2210 for (unsigned OtherMulIdx = Idx+1; 2211 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2212 ++OtherMulIdx) { 2213 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2214 // If MulOp occurs in OtherMul, we can fold the two multiplies 2215 // together. 2216 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2217 OMulOp != e; ++OMulOp) 2218 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2219 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2220 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2221 if (Mul->getNumOperands() != 2) { 2222 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2223 Mul->op_begin()+MulOp); 2224 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2225 InnerMul1 = getMulExpr(MulOps); 2226 } 2227 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2228 if (OtherMul->getNumOperands() != 2) { 2229 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2230 OtherMul->op_begin()+OMulOp); 2231 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2232 InnerMul2 = getMulExpr(MulOps); 2233 } 2234 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2235 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2236 if (Ops.size() == 2) return OuterMul; 2237 Ops.erase(Ops.begin()+Idx); 2238 Ops.erase(Ops.begin()+OtherMulIdx-1); 2239 Ops.push_back(OuterMul); 2240 return getAddExpr(Ops); 2241 } 2242 } 2243 } 2244 } 2245 2246 // If there are any add recurrences in the operands list, see if any other 2247 // added values are loop invariant. If so, we can fold them into the 2248 // recurrence. 2249 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2250 ++Idx; 2251 2252 // Scan over all recurrences, trying to fold loop invariants into them. 2253 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2254 // Scan all of the other operands to this add and add them to the vector if 2255 // they are loop invariant w.r.t. the recurrence. 2256 SmallVector<const SCEV *, 8> LIOps; 2257 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2258 const Loop *AddRecLoop = AddRec->getLoop(); 2259 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2260 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2261 LIOps.push_back(Ops[i]); 2262 Ops.erase(Ops.begin()+i); 2263 --i; --e; 2264 } 2265 2266 // If we found some loop invariants, fold them into the recurrence. 2267 if (!LIOps.empty()) { 2268 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2269 LIOps.push_back(AddRec->getStart()); 2270 2271 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2272 AddRec->op_end()); 2273 AddRecOps[0] = getAddExpr(LIOps); 2274 2275 // Build the new addrec. Propagate the NUW and NSW flags if both the 2276 // outer add and the inner addrec are guaranteed to have no overflow. 2277 // Always propagate NW. 2278 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2279 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2280 2281 // If all of the other operands were loop invariant, we are done. 2282 if (Ops.size() == 1) return NewRec; 2283 2284 // Otherwise, add the folded AddRec by the non-invariant parts. 2285 for (unsigned i = 0;; ++i) 2286 if (Ops[i] == AddRec) { 2287 Ops[i] = NewRec; 2288 break; 2289 } 2290 return getAddExpr(Ops); 2291 } 2292 2293 // Okay, if there weren't any loop invariants to be folded, check to see if 2294 // there are multiple AddRec's with the same loop induction variable being 2295 // added together. If so, we can fold them. 2296 for (unsigned OtherIdx = Idx+1; 2297 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2298 ++OtherIdx) 2299 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2300 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2301 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2302 AddRec->op_end()); 2303 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2304 ++OtherIdx) 2305 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2306 if (OtherAddRec->getLoop() == AddRecLoop) { 2307 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2308 i != e; ++i) { 2309 if (i >= AddRecOps.size()) { 2310 AddRecOps.append(OtherAddRec->op_begin()+i, 2311 OtherAddRec->op_end()); 2312 break; 2313 } 2314 AddRecOps[i] = getAddExpr(AddRecOps[i], 2315 OtherAddRec->getOperand(i)); 2316 } 2317 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2318 } 2319 // Step size has changed, so we cannot guarantee no self-wraparound. 2320 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2321 return getAddExpr(Ops); 2322 } 2323 2324 // Otherwise couldn't fold anything into this recurrence. Move onto the 2325 // next one. 2326 } 2327 2328 // Okay, it looks like we really DO need an add expr. Check to see if we 2329 // already have one, otherwise create a new one. 2330 FoldingSetNodeID ID; 2331 ID.AddInteger(scAddExpr); 2332 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2333 ID.AddPointer(Ops[i]); 2334 void *IP = nullptr; 2335 SCEVAddExpr *S = 2336 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2337 if (!S) { 2338 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2339 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2340 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2341 O, Ops.size()); 2342 UniqueSCEVs.InsertNode(S, IP); 2343 } 2344 S->setNoWrapFlags(Flags); 2345 return S; 2346 } 2347 2348 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2349 uint64_t k = i*j; 2350 if (j > 1 && k / j != i) Overflow = true; 2351 return k; 2352 } 2353 2354 /// Compute the result of "n choose k", the binomial coefficient. If an 2355 /// intermediate computation overflows, Overflow will be set and the return will 2356 /// be garbage. Overflow is not cleared on absence of overflow. 2357 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2358 // We use the multiplicative formula: 2359 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2360 // At each iteration, we take the n-th term of the numeral and divide by the 2361 // (k-n)th term of the denominator. This division will always produce an 2362 // integral result, and helps reduce the chance of overflow in the 2363 // intermediate computations. However, we can still overflow even when the 2364 // final result would fit. 2365 2366 if (n == 0 || n == k) return 1; 2367 if (k > n) return 0; 2368 2369 if (k > n/2) 2370 k = n-k; 2371 2372 uint64_t r = 1; 2373 for (uint64_t i = 1; i <= k; ++i) { 2374 r = umul_ov(r, n-(i-1), Overflow); 2375 r /= i; 2376 } 2377 return r; 2378 } 2379 2380 /// Determine if any of the operands in this SCEV are a constant or if 2381 /// any of the add or multiply expressions in this SCEV contain a constant. 2382 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2383 SmallVector<const SCEV *, 4> Ops; 2384 Ops.push_back(StartExpr); 2385 while (!Ops.empty()) { 2386 const SCEV *CurrentExpr = Ops.pop_back_val(); 2387 if (isa<SCEVConstant>(*CurrentExpr)) 2388 return true; 2389 2390 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2391 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2392 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2393 } 2394 } 2395 return false; 2396 } 2397 2398 /// getMulExpr - Get a canonical multiply expression, or something simpler if 2399 /// possible. 2400 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2401 SCEV::NoWrapFlags Flags) { 2402 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2403 "only nuw or nsw allowed"); 2404 assert(!Ops.empty() && "Cannot get empty mul!"); 2405 if (Ops.size() == 1) return Ops[0]; 2406 #ifndef NDEBUG 2407 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2408 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2409 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2410 "SCEVMulExpr operand types don't match!"); 2411 #endif 2412 2413 // Sort by complexity, this groups all similar expression types together. 2414 GroupByComplexity(Ops, &LI); 2415 2416 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2417 2418 // If there are any constants, fold them together. 2419 unsigned Idx = 0; 2420 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2421 2422 // C1*(C2+V) -> C1*C2 + C1*V 2423 if (Ops.size() == 2) 2424 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2425 // If any of Add's ops are Adds or Muls with a constant, 2426 // apply this transformation as well. 2427 if (Add->getNumOperands() == 2) 2428 if (containsConstantSomewhere(Add)) 2429 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2430 getMulExpr(LHSC, Add->getOperand(1))); 2431 2432 ++Idx; 2433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2434 // We found two constants, fold them together! 2435 ConstantInt *Fold = 2436 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2437 Ops[0] = getConstant(Fold); 2438 Ops.erase(Ops.begin()+1); // Erase the folded element 2439 if (Ops.size() == 1) return Ops[0]; 2440 LHSC = cast<SCEVConstant>(Ops[0]); 2441 } 2442 2443 // If we are left with a constant one being multiplied, strip it off. 2444 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2445 Ops.erase(Ops.begin()); 2446 --Idx; 2447 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2448 // If we have a multiply of zero, it will always be zero. 2449 return Ops[0]; 2450 } else if (Ops[0]->isAllOnesValue()) { 2451 // If we have a mul by -1 of an add, try distributing the -1 among the 2452 // add operands. 2453 if (Ops.size() == 2) { 2454 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2455 SmallVector<const SCEV *, 4> NewOps; 2456 bool AnyFolded = false; 2457 for (const SCEV *AddOp : Add->operands()) { 2458 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2459 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2460 NewOps.push_back(Mul); 2461 } 2462 if (AnyFolded) 2463 return getAddExpr(NewOps); 2464 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2465 // Negation preserves a recurrence's no self-wrap property. 2466 SmallVector<const SCEV *, 4> Operands; 2467 for (const SCEV *AddRecOp : AddRec->operands()) 2468 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2469 2470 return getAddRecExpr(Operands, AddRec->getLoop(), 2471 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2472 } 2473 } 2474 } 2475 2476 if (Ops.size() == 1) 2477 return Ops[0]; 2478 } 2479 2480 // Skip over the add expression until we get to a multiply. 2481 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2482 ++Idx; 2483 2484 // If there are mul operands inline them all into this expression. 2485 if (Idx < Ops.size()) { 2486 bool DeletedMul = false; 2487 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2488 // If we have an mul, expand the mul operands onto the end of the operands 2489 // list. 2490 Ops.erase(Ops.begin()+Idx); 2491 Ops.append(Mul->op_begin(), Mul->op_end()); 2492 DeletedMul = true; 2493 } 2494 2495 // If we deleted at least one mul, we added operands to the end of the list, 2496 // and they are not necessarily sorted. Recurse to resort and resimplify 2497 // any operands we just acquired. 2498 if (DeletedMul) 2499 return getMulExpr(Ops); 2500 } 2501 2502 // If there are any add recurrences in the operands list, see if any other 2503 // added values are loop invariant. If so, we can fold them into the 2504 // recurrence. 2505 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2506 ++Idx; 2507 2508 // Scan over all recurrences, trying to fold loop invariants into them. 2509 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2510 // Scan all of the other operands to this mul and add them to the vector if 2511 // they are loop invariant w.r.t. the recurrence. 2512 SmallVector<const SCEV *, 8> LIOps; 2513 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2514 const Loop *AddRecLoop = AddRec->getLoop(); 2515 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2516 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2517 LIOps.push_back(Ops[i]); 2518 Ops.erase(Ops.begin()+i); 2519 --i; --e; 2520 } 2521 2522 // If we found some loop invariants, fold them into the recurrence. 2523 if (!LIOps.empty()) { 2524 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2525 SmallVector<const SCEV *, 4> NewOps; 2526 NewOps.reserve(AddRec->getNumOperands()); 2527 const SCEV *Scale = getMulExpr(LIOps); 2528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2529 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2530 2531 // Build the new addrec. Propagate the NUW and NSW flags if both the 2532 // outer mul and the inner addrec are guaranteed to have no overflow. 2533 // 2534 // No self-wrap cannot be guaranteed after changing the step size, but 2535 // will be inferred if either NUW or NSW is true. 2536 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2537 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2538 2539 // If all of the other operands were loop invariant, we are done. 2540 if (Ops.size() == 1) return NewRec; 2541 2542 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2543 for (unsigned i = 0;; ++i) 2544 if (Ops[i] == AddRec) { 2545 Ops[i] = NewRec; 2546 break; 2547 } 2548 return getMulExpr(Ops); 2549 } 2550 2551 // Okay, if there weren't any loop invariants to be folded, check to see if 2552 // there are multiple AddRec's with the same loop induction variable being 2553 // multiplied together. If so, we can fold them. 2554 2555 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2556 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2557 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2558 // ]]],+,...up to x=2n}. 2559 // Note that the arguments to choose() are always integers with values 2560 // known at compile time, never SCEV objects. 2561 // 2562 // The implementation avoids pointless extra computations when the two 2563 // addrec's are of different length (mathematically, it's equivalent to 2564 // an infinite stream of zeros on the right). 2565 bool OpsModified = false; 2566 for (unsigned OtherIdx = Idx+1; 2567 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2568 ++OtherIdx) { 2569 const SCEVAddRecExpr *OtherAddRec = 2570 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2571 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2572 continue; 2573 2574 bool Overflow = false; 2575 Type *Ty = AddRec->getType(); 2576 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2577 SmallVector<const SCEV*, 7> AddRecOps; 2578 for (int x = 0, xe = AddRec->getNumOperands() + 2579 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2580 const SCEV *Term = getZero(Ty); 2581 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2582 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2583 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2584 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2585 z < ze && !Overflow; ++z) { 2586 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2587 uint64_t Coeff; 2588 if (LargerThan64Bits) 2589 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2590 else 2591 Coeff = Coeff1*Coeff2; 2592 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2593 const SCEV *Term1 = AddRec->getOperand(y-z); 2594 const SCEV *Term2 = OtherAddRec->getOperand(z); 2595 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2596 } 2597 } 2598 AddRecOps.push_back(Term); 2599 } 2600 if (!Overflow) { 2601 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2602 SCEV::FlagAnyWrap); 2603 if (Ops.size() == 2) return NewAddRec; 2604 Ops[Idx] = NewAddRec; 2605 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2606 OpsModified = true; 2607 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2608 if (!AddRec) 2609 break; 2610 } 2611 } 2612 if (OpsModified) 2613 return getMulExpr(Ops); 2614 2615 // Otherwise couldn't fold anything into this recurrence. Move onto the 2616 // next one. 2617 } 2618 2619 // Okay, it looks like we really DO need an mul expr. Check to see if we 2620 // already have one, otherwise create a new one. 2621 FoldingSetNodeID ID; 2622 ID.AddInteger(scMulExpr); 2623 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2624 ID.AddPointer(Ops[i]); 2625 void *IP = nullptr; 2626 SCEVMulExpr *S = 2627 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2628 if (!S) { 2629 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2630 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2631 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2632 O, Ops.size()); 2633 UniqueSCEVs.InsertNode(S, IP); 2634 } 2635 S->setNoWrapFlags(Flags); 2636 return S; 2637 } 2638 2639 /// getUDivExpr - Get a canonical unsigned division expression, or something 2640 /// simpler if possible. 2641 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2642 const SCEV *RHS) { 2643 assert(getEffectiveSCEVType(LHS->getType()) == 2644 getEffectiveSCEVType(RHS->getType()) && 2645 "SCEVUDivExpr operand types don't match!"); 2646 2647 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2648 if (RHSC->getValue()->equalsInt(1)) 2649 return LHS; // X udiv 1 --> x 2650 // If the denominator is zero, the result of the udiv is undefined. Don't 2651 // try to analyze it, because the resolution chosen here may differ from 2652 // the resolution chosen in other parts of the compiler. 2653 if (!RHSC->getValue()->isZero()) { 2654 // Determine if the division can be folded into the operands of 2655 // its operands. 2656 // TODO: Generalize this to non-constants by using known-bits information. 2657 Type *Ty = LHS->getType(); 2658 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2659 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2660 // For non-power-of-two values, effectively round the value up to the 2661 // nearest power of two. 2662 if (!RHSC->getAPInt().isPowerOf2()) 2663 ++MaxShiftAmt; 2664 IntegerType *ExtTy = 2665 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2666 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2667 if (const SCEVConstant *Step = 2668 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2669 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2670 const APInt &StepInt = Step->getAPInt(); 2671 const APInt &DivInt = RHSC->getAPInt(); 2672 if (!StepInt.urem(DivInt) && 2673 getZeroExtendExpr(AR, ExtTy) == 2674 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2675 getZeroExtendExpr(Step, ExtTy), 2676 AR->getLoop(), SCEV::FlagAnyWrap)) { 2677 SmallVector<const SCEV *, 4> Operands; 2678 for (const SCEV *Op : AR->operands()) 2679 Operands.push_back(getUDivExpr(Op, RHS)); 2680 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2681 } 2682 /// Get a canonical UDivExpr for a recurrence. 2683 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2684 // We can currently only fold X%N if X is constant. 2685 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2686 if (StartC && !DivInt.urem(StepInt) && 2687 getZeroExtendExpr(AR, ExtTy) == 2688 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2689 getZeroExtendExpr(Step, ExtTy), 2690 AR->getLoop(), SCEV::FlagAnyWrap)) { 2691 const APInt &StartInt = StartC->getAPInt(); 2692 const APInt &StartRem = StartInt.urem(StepInt); 2693 if (StartRem != 0) 2694 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2695 AR->getLoop(), SCEV::FlagNW); 2696 } 2697 } 2698 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2699 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2700 SmallVector<const SCEV *, 4> Operands; 2701 for (const SCEV *Op : M->operands()) 2702 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2703 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2704 // Find an operand that's safely divisible. 2705 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2706 const SCEV *Op = M->getOperand(i); 2707 const SCEV *Div = getUDivExpr(Op, RHSC); 2708 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2709 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2710 M->op_end()); 2711 Operands[i] = Div; 2712 return getMulExpr(Operands); 2713 } 2714 } 2715 } 2716 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2717 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2718 SmallVector<const SCEV *, 4> Operands; 2719 for (const SCEV *Op : A->operands()) 2720 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2721 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2722 Operands.clear(); 2723 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2724 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2725 if (isa<SCEVUDivExpr>(Op) || 2726 getMulExpr(Op, RHS) != A->getOperand(i)) 2727 break; 2728 Operands.push_back(Op); 2729 } 2730 if (Operands.size() == A->getNumOperands()) 2731 return getAddExpr(Operands); 2732 } 2733 } 2734 2735 // Fold if both operands are constant. 2736 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2737 Constant *LHSCV = LHSC->getValue(); 2738 Constant *RHSCV = RHSC->getValue(); 2739 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2740 RHSCV))); 2741 } 2742 } 2743 } 2744 2745 FoldingSetNodeID ID; 2746 ID.AddInteger(scUDivExpr); 2747 ID.AddPointer(LHS); 2748 ID.AddPointer(RHS); 2749 void *IP = nullptr; 2750 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2751 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2752 LHS, RHS); 2753 UniqueSCEVs.InsertNode(S, IP); 2754 return S; 2755 } 2756 2757 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2758 APInt A = C1->getAPInt().abs(); 2759 APInt B = C2->getAPInt().abs(); 2760 uint32_t ABW = A.getBitWidth(); 2761 uint32_t BBW = B.getBitWidth(); 2762 2763 if (ABW > BBW) 2764 B = B.zext(ABW); 2765 else if (ABW < BBW) 2766 A = A.zext(BBW); 2767 2768 return APIntOps::GreatestCommonDivisor(A, B); 2769 } 2770 2771 /// getUDivExactExpr - Get a canonical unsigned division expression, or 2772 /// something simpler if possible. There is no representation for an exact udiv 2773 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. 2774 /// We can't do this when it's not exact because the udiv may be clearing bits. 2775 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2776 const SCEV *RHS) { 2777 // TODO: we could try to find factors in all sorts of things, but for now we 2778 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2779 // end of this file for inspiration. 2780 2781 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2782 if (!Mul) 2783 return getUDivExpr(LHS, RHS); 2784 2785 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2786 // If the mulexpr multiplies by a constant, then that constant must be the 2787 // first element of the mulexpr. 2788 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2789 if (LHSCst == RHSCst) { 2790 SmallVector<const SCEV *, 2> Operands; 2791 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2792 return getMulExpr(Operands); 2793 } 2794 2795 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2796 // that there's a factor provided by one of the other terms. We need to 2797 // check. 2798 APInt Factor = gcd(LHSCst, RHSCst); 2799 if (!Factor.isIntN(1)) { 2800 LHSCst = 2801 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2802 RHSCst = 2803 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2804 SmallVector<const SCEV *, 2> Operands; 2805 Operands.push_back(LHSCst); 2806 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2807 LHS = getMulExpr(Operands); 2808 RHS = RHSCst; 2809 Mul = dyn_cast<SCEVMulExpr>(LHS); 2810 if (!Mul) 2811 return getUDivExactExpr(LHS, RHS); 2812 } 2813 } 2814 } 2815 2816 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2817 if (Mul->getOperand(i) == RHS) { 2818 SmallVector<const SCEV *, 2> Operands; 2819 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2820 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2821 return getMulExpr(Operands); 2822 } 2823 } 2824 2825 return getUDivExpr(LHS, RHS); 2826 } 2827 2828 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2829 /// Simplify the expression as much as possible. 2830 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2831 const Loop *L, 2832 SCEV::NoWrapFlags Flags) { 2833 SmallVector<const SCEV *, 4> Operands; 2834 Operands.push_back(Start); 2835 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2836 if (StepChrec->getLoop() == L) { 2837 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2838 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2839 } 2840 2841 Operands.push_back(Step); 2842 return getAddRecExpr(Operands, L, Flags); 2843 } 2844 2845 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2846 /// Simplify the expression as much as possible. 2847 const SCEV * 2848 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2849 const Loop *L, SCEV::NoWrapFlags Flags) { 2850 if (Operands.size() == 1) return Operands[0]; 2851 #ifndef NDEBUG 2852 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2853 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2854 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2855 "SCEVAddRecExpr operand types don't match!"); 2856 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2857 assert(isLoopInvariant(Operands[i], L) && 2858 "SCEVAddRecExpr operand is not loop-invariant!"); 2859 #endif 2860 2861 if (Operands.back()->isZero()) { 2862 Operands.pop_back(); 2863 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2864 } 2865 2866 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2867 // use that information to infer NUW and NSW flags. However, computing a 2868 // BE count requires calling getAddRecExpr, so we may not yet have a 2869 // meaningful BE count at this point (and if we don't, we'd be stuck 2870 // with a SCEVCouldNotCompute as the cached BE count). 2871 2872 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2873 2874 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2875 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2876 const Loop *NestedLoop = NestedAR->getLoop(); 2877 if (L->contains(NestedLoop) 2878 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2879 : (!NestedLoop->contains(L) && 2880 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2881 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2882 NestedAR->op_end()); 2883 Operands[0] = NestedAR->getStart(); 2884 // AddRecs require their operands be loop-invariant with respect to their 2885 // loops. Don't perform this transformation if it would break this 2886 // requirement. 2887 bool AllInvariant = all_of( 2888 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2889 2890 if (AllInvariant) { 2891 // Create a recurrence for the outer loop with the same step size. 2892 // 2893 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2894 // inner recurrence has the same property. 2895 SCEV::NoWrapFlags OuterFlags = 2896 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2897 2898 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2899 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2900 return isLoopInvariant(Op, NestedLoop); 2901 }); 2902 2903 if (AllInvariant) { 2904 // Ok, both add recurrences are valid after the transformation. 2905 // 2906 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2907 // the outer recurrence has the same property. 2908 SCEV::NoWrapFlags InnerFlags = 2909 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2910 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2911 } 2912 } 2913 // Reset Operands to its original state. 2914 Operands[0] = NestedAR; 2915 } 2916 } 2917 2918 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2919 // already have one, otherwise create a new one. 2920 FoldingSetNodeID ID; 2921 ID.AddInteger(scAddRecExpr); 2922 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2923 ID.AddPointer(Operands[i]); 2924 ID.AddPointer(L); 2925 void *IP = nullptr; 2926 SCEVAddRecExpr *S = 2927 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2928 if (!S) { 2929 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2930 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2931 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2932 O, Operands.size(), L); 2933 UniqueSCEVs.InsertNode(S, IP); 2934 } 2935 S->setNoWrapFlags(Flags); 2936 return S; 2937 } 2938 2939 const SCEV * 2940 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 2941 const SmallVectorImpl<const SCEV *> &IndexExprs, 2942 bool InBounds) { 2943 // getSCEV(Base)->getType() has the same address space as Base->getType() 2944 // because SCEV::getType() preserves the address space. 2945 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 2946 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 2947 // instruction to its SCEV, because the Instruction may be guarded by control 2948 // flow and the no-overflow bits may not be valid for the expression in any 2949 // context. This can be fixed similarly to how these flags are handled for 2950 // adds. 2951 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 2952 2953 const SCEV *TotalOffset = getZero(IntPtrTy); 2954 // The address space is unimportant. The first thing we do on CurTy is getting 2955 // its element type. 2956 Type *CurTy = PointerType::getUnqual(PointeeType); 2957 for (const SCEV *IndexExpr : IndexExprs) { 2958 // Compute the (potentially symbolic) offset in bytes for this index. 2959 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2960 // For a struct, add the member offset. 2961 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 2962 unsigned FieldNo = Index->getZExtValue(); 2963 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 2964 2965 // Add the field offset to the running total offset. 2966 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 2967 2968 // Update CurTy to the type of the field at Index. 2969 CurTy = STy->getTypeAtIndex(Index); 2970 } else { 2971 // Update CurTy to its element type. 2972 CurTy = cast<SequentialType>(CurTy)->getElementType(); 2973 // For an array, add the element offset, explicitly scaled. 2974 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 2975 // Getelementptr indices are signed. 2976 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 2977 2978 // Multiply the index by the element size to compute the element offset. 2979 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 2980 2981 // Add the element offset to the running total offset. 2982 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 2983 } 2984 } 2985 2986 // Add the total offset from all the GEP indices to the base. 2987 return getAddExpr(BaseExpr, TotalOffset, Wrap); 2988 } 2989 2990 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 2991 const SCEV *RHS) { 2992 SmallVector<const SCEV *, 2> Ops; 2993 Ops.push_back(LHS); 2994 Ops.push_back(RHS); 2995 return getSMaxExpr(Ops); 2996 } 2997 2998 const SCEV * 2999 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3000 assert(!Ops.empty() && "Cannot get empty smax!"); 3001 if (Ops.size() == 1) return Ops[0]; 3002 #ifndef NDEBUG 3003 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3004 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3005 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3006 "SCEVSMaxExpr operand types don't match!"); 3007 #endif 3008 3009 // Sort by complexity, this groups all similar expression types together. 3010 GroupByComplexity(Ops, &LI); 3011 3012 // If there are any constants, fold them together. 3013 unsigned Idx = 0; 3014 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3015 ++Idx; 3016 assert(Idx < Ops.size()); 3017 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3018 // We found two constants, fold them together! 3019 ConstantInt *Fold = ConstantInt::get( 3020 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3021 Ops[0] = getConstant(Fold); 3022 Ops.erase(Ops.begin()+1); // Erase the folded element 3023 if (Ops.size() == 1) return Ops[0]; 3024 LHSC = cast<SCEVConstant>(Ops[0]); 3025 } 3026 3027 // If we are left with a constant minimum-int, strip it off. 3028 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3029 Ops.erase(Ops.begin()); 3030 --Idx; 3031 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3032 // If we have an smax with a constant maximum-int, it will always be 3033 // maximum-int. 3034 return Ops[0]; 3035 } 3036 3037 if (Ops.size() == 1) return Ops[0]; 3038 } 3039 3040 // Find the first SMax 3041 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3042 ++Idx; 3043 3044 // Check to see if one of the operands is an SMax. If so, expand its operands 3045 // onto our operand list, and recurse to simplify. 3046 if (Idx < Ops.size()) { 3047 bool DeletedSMax = false; 3048 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3049 Ops.erase(Ops.begin()+Idx); 3050 Ops.append(SMax->op_begin(), SMax->op_end()); 3051 DeletedSMax = true; 3052 } 3053 3054 if (DeletedSMax) 3055 return getSMaxExpr(Ops); 3056 } 3057 3058 // Okay, check to see if the same value occurs in the operand list twice. If 3059 // so, delete one. Since we sorted the list, these values are required to 3060 // be adjacent. 3061 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3062 // X smax Y smax Y --> X smax Y 3063 // X smax Y --> X, if X is always greater than Y 3064 if (Ops[i] == Ops[i+1] || 3065 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3066 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3067 --i; --e; 3068 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3069 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3070 --i; --e; 3071 } 3072 3073 if (Ops.size() == 1) return Ops[0]; 3074 3075 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3076 3077 // Okay, it looks like we really DO need an smax expr. Check to see if we 3078 // already have one, otherwise create a new one. 3079 FoldingSetNodeID ID; 3080 ID.AddInteger(scSMaxExpr); 3081 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3082 ID.AddPointer(Ops[i]); 3083 void *IP = nullptr; 3084 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3085 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3086 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3087 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3088 O, Ops.size()); 3089 UniqueSCEVs.InsertNode(S, IP); 3090 return S; 3091 } 3092 3093 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3094 const SCEV *RHS) { 3095 SmallVector<const SCEV *, 2> Ops; 3096 Ops.push_back(LHS); 3097 Ops.push_back(RHS); 3098 return getUMaxExpr(Ops); 3099 } 3100 3101 const SCEV * 3102 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3103 assert(!Ops.empty() && "Cannot get empty umax!"); 3104 if (Ops.size() == 1) return Ops[0]; 3105 #ifndef NDEBUG 3106 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3107 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3108 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3109 "SCEVUMaxExpr operand types don't match!"); 3110 #endif 3111 3112 // Sort by complexity, this groups all similar expression types together. 3113 GroupByComplexity(Ops, &LI); 3114 3115 // If there are any constants, fold them together. 3116 unsigned Idx = 0; 3117 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3118 ++Idx; 3119 assert(Idx < Ops.size()); 3120 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3121 // We found two constants, fold them together! 3122 ConstantInt *Fold = ConstantInt::get( 3123 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3124 Ops[0] = getConstant(Fold); 3125 Ops.erase(Ops.begin()+1); // Erase the folded element 3126 if (Ops.size() == 1) return Ops[0]; 3127 LHSC = cast<SCEVConstant>(Ops[0]); 3128 } 3129 3130 // If we are left with a constant minimum-int, strip it off. 3131 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3132 Ops.erase(Ops.begin()); 3133 --Idx; 3134 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3135 // If we have an umax with a constant maximum-int, it will always be 3136 // maximum-int. 3137 return Ops[0]; 3138 } 3139 3140 if (Ops.size() == 1) return Ops[0]; 3141 } 3142 3143 // Find the first UMax 3144 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3145 ++Idx; 3146 3147 // Check to see if one of the operands is a UMax. If so, expand its operands 3148 // onto our operand list, and recurse to simplify. 3149 if (Idx < Ops.size()) { 3150 bool DeletedUMax = false; 3151 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3152 Ops.erase(Ops.begin()+Idx); 3153 Ops.append(UMax->op_begin(), UMax->op_end()); 3154 DeletedUMax = true; 3155 } 3156 3157 if (DeletedUMax) 3158 return getUMaxExpr(Ops); 3159 } 3160 3161 // Okay, check to see if the same value occurs in the operand list twice. If 3162 // so, delete one. Since we sorted the list, these values are required to 3163 // be adjacent. 3164 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3165 // X umax Y umax Y --> X umax Y 3166 // X umax Y --> X, if X is always greater than Y 3167 if (Ops[i] == Ops[i+1] || 3168 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3169 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3170 --i; --e; 3171 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3172 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3173 --i; --e; 3174 } 3175 3176 if (Ops.size() == 1) return Ops[0]; 3177 3178 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3179 3180 // Okay, it looks like we really DO need a umax expr. Check to see if we 3181 // already have one, otherwise create a new one. 3182 FoldingSetNodeID ID; 3183 ID.AddInteger(scUMaxExpr); 3184 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3185 ID.AddPointer(Ops[i]); 3186 void *IP = nullptr; 3187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3188 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3189 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3190 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3191 O, Ops.size()); 3192 UniqueSCEVs.InsertNode(S, IP); 3193 return S; 3194 } 3195 3196 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3197 const SCEV *RHS) { 3198 // ~smax(~x, ~y) == smin(x, y). 3199 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3200 } 3201 3202 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3203 const SCEV *RHS) { 3204 // ~umax(~x, ~y) == umin(x, y) 3205 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3206 } 3207 3208 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3209 // We can bypass creating a target-independent 3210 // constant expression and then folding it back into a ConstantInt. 3211 // This is just a compile-time optimization. 3212 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3213 } 3214 3215 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3216 StructType *STy, 3217 unsigned FieldNo) { 3218 // We can bypass creating a target-independent 3219 // constant expression and then folding it back into a ConstantInt. 3220 // This is just a compile-time optimization. 3221 return getConstant( 3222 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3223 } 3224 3225 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3226 // Don't attempt to do anything other than create a SCEVUnknown object 3227 // here. createSCEV only calls getUnknown after checking for all other 3228 // interesting possibilities, and any other code that calls getUnknown 3229 // is doing so in order to hide a value from SCEV canonicalization. 3230 3231 FoldingSetNodeID ID; 3232 ID.AddInteger(scUnknown); 3233 ID.AddPointer(V); 3234 void *IP = nullptr; 3235 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3236 assert(cast<SCEVUnknown>(S)->getValue() == V && 3237 "Stale SCEVUnknown in uniquing map!"); 3238 return S; 3239 } 3240 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3241 FirstUnknown); 3242 FirstUnknown = cast<SCEVUnknown>(S); 3243 UniqueSCEVs.InsertNode(S, IP); 3244 return S; 3245 } 3246 3247 //===----------------------------------------------------------------------===// 3248 // Basic SCEV Analysis and PHI Idiom Recognition Code 3249 // 3250 3251 /// isSCEVable - Test if values of the given type are analyzable within 3252 /// the SCEV framework. This primarily includes integer types, and it 3253 /// can optionally include pointer types if the ScalarEvolution class 3254 /// has access to target-specific information. 3255 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3256 // Integers and pointers are always SCEVable. 3257 return Ty->isIntegerTy() || Ty->isPointerTy(); 3258 } 3259 3260 /// getTypeSizeInBits - Return the size in bits of the specified type, 3261 /// for which isSCEVable must return true. 3262 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3263 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3264 return getDataLayout().getTypeSizeInBits(Ty); 3265 } 3266 3267 /// getEffectiveSCEVType - Return a type with the same bitwidth as 3268 /// the given type and which represents how SCEV will treat the given 3269 /// type, for which isSCEVable must return true. For pointer types, 3270 /// this is the pointer-sized integer type. 3271 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3272 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3273 3274 if (Ty->isIntegerTy()) 3275 return Ty; 3276 3277 // The only other support type is pointer. 3278 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3279 return getDataLayout().getIntPtrType(Ty); 3280 } 3281 3282 const SCEV *ScalarEvolution::getCouldNotCompute() { 3283 return CouldNotCompute.get(); 3284 } 3285 3286 3287 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3288 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3289 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3290 // is set iff if find such SCEVUnknown. 3291 // 3292 struct FindInvalidSCEVUnknown { 3293 bool FindOne; 3294 FindInvalidSCEVUnknown() { FindOne = false; } 3295 bool follow(const SCEV *S) { 3296 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3297 case scConstant: 3298 return false; 3299 case scUnknown: 3300 if (!cast<SCEVUnknown>(S)->getValue()) 3301 FindOne = true; 3302 return false; 3303 default: 3304 return true; 3305 } 3306 } 3307 bool isDone() const { return FindOne; } 3308 }; 3309 3310 FindInvalidSCEVUnknown F; 3311 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3312 ST.visitAll(S); 3313 3314 return !F.FindOne; 3315 } 3316 3317 namespace { 3318 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3319 // a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set 3320 // iff if such sub scAddRecExpr type SCEV is found. 3321 struct FindAddRecurrence { 3322 bool FoundOne; 3323 FindAddRecurrence() : FoundOne(false) {} 3324 3325 bool follow(const SCEV *S) { 3326 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3327 case scAddRecExpr: 3328 FoundOne = true; 3329 case scConstant: 3330 case scUnknown: 3331 case scCouldNotCompute: 3332 return false; 3333 default: 3334 return true; 3335 } 3336 } 3337 bool isDone() const { return FoundOne; } 3338 }; 3339 } 3340 3341 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3342 HasRecMapType::iterator I = HasRecMap.find_as(S); 3343 if (I != HasRecMap.end()) 3344 return I->second; 3345 3346 FindAddRecurrence F; 3347 SCEVTraversal<FindAddRecurrence> ST(F); 3348 ST.visitAll(S); 3349 HasRecMap.insert({S, F.FoundOne}); 3350 return F.FoundOne; 3351 } 3352 3353 /// getSCEVValues - Return the Value set from S. 3354 SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) { 3355 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3356 if (SI == ExprValueMap.end()) 3357 return nullptr; 3358 #ifndef NDEBUG 3359 if (VerifySCEVMap) { 3360 // Check there is no dangling Value in the set returned. 3361 for (const auto &VE : SI->second) 3362 assert(ValueExprMap.count(VE)); 3363 } 3364 #endif 3365 return &SI->second; 3366 } 3367 3368 /// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap. 3369 /// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S), 3370 /// eraseValueFromMap should be used instead to ensure whenever V->S is removed 3371 /// from ValueExprMap, V is also removed from the set of ExprValueMap[S]. 3372 void ScalarEvolution::eraseValueFromMap(Value *V) { 3373 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3374 if (I != ValueExprMap.end()) { 3375 const SCEV *S = I->second; 3376 SetVector<Value *> *SV = getSCEVValues(S); 3377 // Remove V from the set of ExprValueMap[S] 3378 if (SV) 3379 SV->remove(V); 3380 ValueExprMap.erase(V); 3381 } 3382 } 3383 3384 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 3385 /// expression and create a new one. 3386 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3387 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3388 3389 const SCEV *S = getExistingSCEV(V); 3390 if (S == nullptr) { 3391 S = createSCEV(V); 3392 // During PHI resolution, it is possible to create two SCEVs for the same 3393 // V, so it is needed to double check whether V->S is inserted into 3394 // ValueExprMap before insert S->V into ExprValueMap. 3395 std::pair<ValueExprMapType::iterator, bool> Pair = 3396 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3397 if (Pair.second) 3398 ExprValueMap[S].insert(V); 3399 } 3400 return S; 3401 } 3402 3403 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3404 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3405 3406 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3407 if (I != ValueExprMap.end()) { 3408 const SCEV *S = I->second; 3409 if (checkValidity(S)) 3410 return S; 3411 forgetMemoizedResults(S); 3412 ValueExprMap.erase(I); 3413 } 3414 return nullptr; 3415 } 3416 3417 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 3418 /// 3419 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3420 SCEV::NoWrapFlags Flags) { 3421 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3422 return getConstant( 3423 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3424 3425 Type *Ty = V->getType(); 3426 Ty = getEffectiveSCEVType(Ty); 3427 return getMulExpr( 3428 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3429 } 3430 3431 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 3432 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3433 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3434 return getConstant( 3435 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3436 3437 Type *Ty = V->getType(); 3438 Ty = getEffectiveSCEVType(Ty); 3439 const SCEV *AllOnes = 3440 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3441 return getMinusSCEV(AllOnes, V); 3442 } 3443 3444 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 3445 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3446 SCEV::NoWrapFlags Flags) { 3447 // Fast path: X - X --> 0. 3448 if (LHS == RHS) 3449 return getZero(LHS->getType()); 3450 3451 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3452 // makes it so that we cannot make much use of NUW. 3453 auto AddFlags = SCEV::FlagAnyWrap; 3454 const bool RHSIsNotMinSigned = 3455 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3456 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3457 // Let M be the minimum representable signed value. Then (-1)*RHS 3458 // signed-wraps if and only if RHS is M. That can happen even for 3459 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3460 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3461 // (-1)*RHS, we need to prove that RHS != M. 3462 // 3463 // If LHS is non-negative and we know that LHS - RHS does not 3464 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3465 // either by proving that RHS > M or that LHS >= 0. 3466 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3467 AddFlags = SCEV::FlagNSW; 3468 } 3469 } 3470 3471 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3472 // RHS is NSW and LHS >= 0. 3473 // 3474 // The difficulty here is that the NSW flag may have been proven 3475 // relative to a loop that is to be found in a recurrence in LHS and 3476 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3477 // larger scope than intended. 3478 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3479 3480 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3481 } 3482 3483 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 3484 /// input value to the specified type. If the type must be extended, it is zero 3485 /// extended. 3486 const SCEV * 3487 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3488 Type *SrcTy = V->getType(); 3489 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3490 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3491 "Cannot truncate or zero extend with non-integer arguments!"); 3492 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3493 return V; // No conversion 3494 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3495 return getTruncateExpr(V, Ty); 3496 return getZeroExtendExpr(V, Ty); 3497 } 3498 3499 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 3500 /// input value to the specified type. If the type must be extended, it is sign 3501 /// extended. 3502 const SCEV * 3503 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3504 Type *Ty) { 3505 Type *SrcTy = V->getType(); 3506 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3507 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3508 "Cannot truncate or zero extend with non-integer arguments!"); 3509 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3510 return V; // No conversion 3511 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3512 return getTruncateExpr(V, Ty); 3513 return getSignExtendExpr(V, Ty); 3514 } 3515 3516 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the 3517 /// input value to the specified type. If the type must be extended, it is zero 3518 /// extended. The conversion must not be narrowing. 3519 const SCEV * 3520 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3521 Type *SrcTy = V->getType(); 3522 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3523 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3524 "Cannot noop or zero extend with non-integer arguments!"); 3525 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3526 "getNoopOrZeroExtend cannot truncate!"); 3527 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3528 return V; // No conversion 3529 return getZeroExtendExpr(V, Ty); 3530 } 3531 3532 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the 3533 /// input value to the specified type. If the type must be extended, it is sign 3534 /// extended. The conversion must not be narrowing. 3535 const SCEV * 3536 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3537 Type *SrcTy = V->getType(); 3538 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3539 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3540 "Cannot noop or sign extend with non-integer arguments!"); 3541 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3542 "getNoopOrSignExtend cannot truncate!"); 3543 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3544 return V; // No conversion 3545 return getSignExtendExpr(V, Ty); 3546 } 3547 3548 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 3549 /// the input value to the specified type. If the type must be extended, 3550 /// it is extended with unspecified bits. The conversion must not be 3551 /// narrowing. 3552 const SCEV * 3553 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3554 Type *SrcTy = V->getType(); 3555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3556 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3557 "Cannot noop or any extend with non-integer arguments!"); 3558 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3559 "getNoopOrAnyExtend cannot truncate!"); 3560 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3561 return V; // No conversion 3562 return getAnyExtendExpr(V, Ty); 3563 } 3564 3565 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 3566 /// input value to the specified type. The conversion must not be widening. 3567 const SCEV * 3568 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3569 Type *SrcTy = V->getType(); 3570 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3571 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3572 "Cannot truncate or noop with non-integer arguments!"); 3573 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3574 "getTruncateOrNoop cannot extend!"); 3575 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3576 return V; // No conversion 3577 return getTruncateExpr(V, Ty); 3578 } 3579 3580 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 3581 /// the types using zero-extension, and then perform a umax operation 3582 /// with them. 3583 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3584 const SCEV *RHS) { 3585 const SCEV *PromotedLHS = LHS; 3586 const SCEV *PromotedRHS = RHS; 3587 3588 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3589 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3590 else 3591 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3592 3593 return getUMaxExpr(PromotedLHS, PromotedRHS); 3594 } 3595 3596 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 3597 /// the types using zero-extension, and then perform a umin operation 3598 /// with them. 3599 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3600 const SCEV *RHS) { 3601 const SCEV *PromotedLHS = LHS; 3602 const SCEV *PromotedRHS = RHS; 3603 3604 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3605 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3606 else 3607 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3608 3609 return getUMinExpr(PromotedLHS, PromotedRHS); 3610 } 3611 3612 /// getPointerBase - Transitively follow the chain of pointer-type operands 3613 /// until reaching a SCEV that does not have a single pointer operand. This 3614 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 3615 /// but corner cases do exist. 3616 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3617 // A pointer operand may evaluate to a nonpointer expression, such as null. 3618 if (!V->getType()->isPointerTy()) 3619 return V; 3620 3621 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3622 return getPointerBase(Cast->getOperand()); 3623 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3624 const SCEV *PtrOp = nullptr; 3625 for (const SCEV *NAryOp : NAry->operands()) { 3626 if (NAryOp->getType()->isPointerTy()) { 3627 // Cannot find the base of an expression with multiple pointer operands. 3628 if (PtrOp) 3629 return V; 3630 PtrOp = NAryOp; 3631 } 3632 } 3633 if (!PtrOp) 3634 return V; 3635 return getPointerBase(PtrOp); 3636 } 3637 return V; 3638 } 3639 3640 /// PushDefUseChildren - Push users of the given Instruction 3641 /// onto the given Worklist. 3642 static void 3643 PushDefUseChildren(Instruction *I, 3644 SmallVectorImpl<Instruction *> &Worklist) { 3645 // Push the def-use children onto the Worklist stack. 3646 for (User *U : I->users()) 3647 Worklist.push_back(cast<Instruction>(U)); 3648 } 3649 3650 /// ForgetSymbolicValue - This looks up computed SCEV values for all 3651 /// instructions that depend on the given instruction and removes them from 3652 /// the ValueExprMapType map if they reference SymName. This is used during PHI 3653 /// resolution. 3654 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3655 SmallVector<Instruction *, 16> Worklist; 3656 PushDefUseChildren(PN, Worklist); 3657 3658 SmallPtrSet<Instruction *, 8> Visited; 3659 Visited.insert(PN); 3660 while (!Worklist.empty()) { 3661 Instruction *I = Worklist.pop_back_val(); 3662 if (!Visited.insert(I).second) 3663 continue; 3664 3665 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3666 if (It != ValueExprMap.end()) { 3667 const SCEV *Old = It->second; 3668 3669 // Short-circuit the def-use traversal if the symbolic name 3670 // ceases to appear in expressions. 3671 if (Old != SymName && !hasOperand(Old, SymName)) 3672 continue; 3673 3674 // SCEVUnknown for a PHI either means that it has an unrecognized 3675 // structure, it's a PHI that's in the progress of being computed 3676 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3677 // additional loop trip count information isn't going to change anything. 3678 // In the second case, createNodeForPHI will perform the necessary 3679 // updates on its own when it gets to that point. In the third, we do 3680 // want to forget the SCEVUnknown. 3681 if (!isa<PHINode>(I) || 3682 !isa<SCEVUnknown>(Old) || 3683 (I != PN && Old == SymName)) { 3684 forgetMemoizedResults(Old); 3685 ValueExprMap.erase(It); 3686 } 3687 } 3688 3689 PushDefUseChildren(I, Worklist); 3690 } 3691 } 3692 3693 namespace { 3694 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3695 public: 3696 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3697 ScalarEvolution &SE) { 3698 SCEVInitRewriter Rewriter(L, SE); 3699 const SCEV *Result = Rewriter.visit(S); 3700 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3701 } 3702 3703 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3704 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3705 3706 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3707 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3708 Valid = false; 3709 return Expr; 3710 } 3711 3712 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3713 // Only allow AddRecExprs for this loop. 3714 if (Expr->getLoop() == L) 3715 return Expr->getStart(); 3716 Valid = false; 3717 return Expr; 3718 } 3719 3720 bool isValid() { return Valid; } 3721 3722 private: 3723 const Loop *L; 3724 bool Valid; 3725 }; 3726 3727 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3728 public: 3729 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3730 ScalarEvolution &SE) { 3731 SCEVShiftRewriter Rewriter(L, SE); 3732 const SCEV *Result = Rewriter.visit(S); 3733 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3734 } 3735 3736 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3737 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3738 3739 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3740 // Only allow AddRecExprs for this loop. 3741 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3742 Valid = false; 3743 return Expr; 3744 } 3745 3746 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3747 if (Expr->getLoop() == L && Expr->isAffine()) 3748 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3749 Valid = false; 3750 return Expr; 3751 } 3752 bool isValid() { return Valid; } 3753 3754 private: 3755 const Loop *L; 3756 bool Valid; 3757 }; 3758 } // end anonymous namespace 3759 3760 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3761 const Loop *L = LI.getLoopFor(PN->getParent()); 3762 if (!L || L->getHeader() != PN->getParent()) 3763 return nullptr; 3764 3765 // The loop may have multiple entrances or multiple exits; we can analyze 3766 // this phi as an addrec if it has a unique entry value and a unique 3767 // backedge value. 3768 Value *BEValueV = nullptr, *StartValueV = nullptr; 3769 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3770 Value *V = PN->getIncomingValue(i); 3771 if (L->contains(PN->getIncomingBlock(i))) { 3772 if (!BEValueV) { 3773 BEValueV = V; 3774 } else if (BEValueV != V) { 3775 BEValueV = nullptr; 3776 break; 3777 } 3778 } else if (!StartValueV) { 3779 StartValueV = V; 3780 } else if (StartValueV != V) { 3781 StartValueV = nullptr; 3782 break; 3783 } 3784 } 3785 if (BEValueV && StartValueV) { 3786 // While we are analyzing this PHI node, handle its value symbolically. 3787 const SCEV *SymbolicName = getUnknown(PN); 3788 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3789 "PHI node already processed?"); 3790 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 3791 3792 // Using this symbolic name for the PHI, analyze the value coming around 3793 // the back-edge. 3794 const SCEV *BEValue = getSCEV(BEValueV); 3795 3796 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3797 // has a special value for the first iteration of the loop. 3798 3799 // If the value coming around the backedge is an add with the symbolic 3800 // value we just inserted, then we found a simple induction variable! 3801 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3802 // If there is a single occurrence of the symbolic value, replace it 3803 // with a recurrence. 3804 unsigned FoundIndex = Add->getNumOperands(); 3805 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3806 if (Add->getOperand(i) == SymbolicName) 3807 if (FoundIndex == e) { 3808 FoundIndex = i; 3809 break; 3810 } 3811 3812 if (FoundIndex != Add->getNumOperands()) { 3813 // Create an add with everything but the specified operand. 3814 SmallVector<const SCEV *, 8> Ops; 3815 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3816 if (i != FoundIndex) 3817 Ops.push_back(Add->getOperand(i)); 3818 const SCEV *Accum = getAddExpr(Ops); 3819 3820 // This is not a valid addrec if the step amount is varying each 3821 // loop iteration, but is not itself an addrec in this loop. 3822 if (isLoopInvariant(Accum, L) || 3823 (isa<SCEVAddRecExpr>(Accum) && 3824 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 3825 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 3826 3827 // If the increment doesn't overflow, then neither the addrec nor 3828 // the post-increment will overflow. 3829 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { 3830 if (OBO->getOperand(0) == PN) { 3831 if (OBO->hasNoUnsignedWrap()) 3832 Flags = setFlags(Flags, SCEV::FlagNUW); 3833 if (OBO->hasNoSignedWrap()) 3834 Flags = setFlags(Flags, SCEV::FlagNSW); 3835 } 3836 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 3837 // If the increment is an inbounds GEP, then we know the address 3838 // space cannot be wrapped around. We cannot make any guarantee 3839 // about signed or unsigned overflow because pointers are 3840 // unsigned but we may have a negative index from the base 3841 // pointer. We can guarantee that no unsigned wrap occurs if the 3842 // indices form a positive value. 3843 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 3844 Flags = setFlags(Flags, SCEV::FlagNW); 3845 3846 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 3847 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 3848 Flags = setFlags(Flags, SCEV::FlagNUW); 3849 } 3850 3851 // We cannot transfer nuw and nsw flags from subtraction 3852 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 3853 // for instance. 3854 } 3855 3856 const SCEV *StartVal = getSCEV(StartValueV); 3857 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 3858 3859 // Since the no-wrap flags are on the increment, they apply to the 3860 // post-incremented value as well. 3861 if (isLoopInvariant(Accum, L)) 3862 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 3863 3864 // Okay, for the entire analysis of this edge we assumed the PHI 3865 // to be symbolic. We now need to go back and purge all of the 3866 // entries for the scalars that use the symbolic expression. 3867 forgetSymbolicName(PN, SymbolicName); 3868 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 3869 return PHISCEV; 3870 } 3871 } 3872 } else { 3873 // Otherwise, this could be a loop like this: 3874 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 3875 // In this case, j = {1,+,1} and BEValue is j. 3876 // Because the other in-value of i (0) fits the evolution of BEValue 3877 // i really is an addrec evolution. 3878 // 3879 // We can generalize this saying that i is the shifted value of BEValue 3880 // by one iteration: 3881 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 3882 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 3883 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 3884 if (Shifted != getCouldNotCompute() && 3885 Start != getCouldNotCompute()) { 3886 const SCEV *StartVal = getSCEV(StartValueV); 3887 if (Start == StartVal) { 3888 // Okay, for the entire analysis of this edge we assumed the PHI 3889 // to be symbolic. We now need to go back and purge all of the 3890 // entries for the scalars that use the symbolic expression. 3891 forgetSymbolicName(PN, SymbolicName); 3892 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 3893 return Shifted; 3894 } 3895 } 3896 } 3897 3898 // Remove the temporary PHI node SCEV that has been inserted while intending 3899 // to create an AddRecExpr for this PHI node. We can not keep this temporary 3900 // as it will prevent later (possibly simpler) SCEV expressions to be added 3901 // to the ValueExprMap. 3902 ValueExprMap.erase(PN); 3903 } 3904 3905 return nullptr; 3906 } 3907 3908 // Checks if the SCEV S is available at BB. S is considered available at BB 3909 // if S can be materialized at BB without introducing a fault. 3910 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 3911 BasicBlock *BB) { 3912 struct CheckAvailable { 3913 bool TraversalDone = false; 3914 bool Available = true; 3915 3916 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 3917 BasicBlock *BB = nullptr; 3918 DominatorTree &DT; 3919 3920 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 3921 : L(L), BB(BB), DT(DT) {} 3922 3923 bool setUnavailable() { 3924 TraversalDone = true; 3925 Available = false; 3926 return false; 3927 } 3928 3929 bool follow(const SCEV *S) { 3930 switch (S->getSCEVType()) { 3931 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 3932 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 3933 // These expressions are available if their operand(s) is/are. 3934 return true; 3935 3936 case scAddRecExpr: { 3937 // We allow add recurrences that are on the loop BB is in, or some 3938 // outer loop. This guarantees availability because the value of the 3939 // add recurrence at BB is simply the "current" value of the induction 3940 // variable. We can relax this in the future; for instance an add 3941 // recurrence on a sibling dominating loop is also available at BB. 3942 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 3943 if (L && (ARLoop == L || ARLoop->contains(L))) 3944 return true; 3945 3946 return setUnavailable(); 3947 } 3948 3949 case scUnknown: { 3950 // For SCEVUnknown, we check for simple dominance. 3951 const auto *SU = cast<SCEVUnknown>(S); 3952 Value *V = SU->getValue(); 3953 3954 if (isa<Argument>(V)) 3955 return false; 3956 3957 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 3958 return false; 3959 3960 return setUnavailable(); 3961 } 3962 3963 case scUDivExpr: 3964 case scCouldNotCompute: 3965 // We do not try to smart about these at all. 3966 return setUnavailable(); 3967 } 3968 llvm_unreachable("switch should be fully covered!"); 3969 } 3970 3971 bool isDone() { return TraversalDone; } 3972 }; 3973 3974 CheckAvailable CA(L, BB, DT); 3975 SCEVTraversal<CheckAvailable> ST(CA); 3976 3977 ST.visitAll(S); 3978 return CA.Available; 3979 } 3980 3981 // Try to match a control flow sequence that branches out at BI and merges back 3982 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 3983 // match. 3984 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 3985 Value *&C, Value *&LHS, Value *&RHS) { 3986 C = BI->getCondition(); 3987 3988 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 3989 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 3990 3991 if (!LeftEdge.isSingleEdge()) 3992 return false; 3993 3994 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 3995 3996 Use &LeftUse = Merge->getOperandUse(0); 3997 Use &RightUse = Merge->getOperandUse(1); 3998 3999 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4000 LHS = LeftUse; 4001 RHS = RightUse; 4002 return true; 4003 } 4004 4005 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4006 LHS = RightUse; 4007 RHS = LeftUse; 4008 return true; 4009 } 4010 4011 return false; 4012 } 4013 4014 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4015 if (PN->getNumIncomingValues() == 2) { 4016 const Loop *L = LI.getLoopFor(PN->getParent()); 4017 4018 // We don't want to break LCSSA, even in a SCEV expression tree. 4019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4020 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4021 return nullptr; 4022 4023 // Try to match 4024 // 4025 // br %cond, label %left, label %right 4026 // left: 4027 // br label %merge 4028 // right: 4029 // br label %merge 4030 // merge: 4031 // V = phi [ %x, %left ], [ %y, %right ] 4032 // 4033 // as "select %cond, %x, %y" 4034 4035 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4036 assert(IDom && "At least the entry block should dominate PN"); 4037 4038 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4039 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4040 4041 if (BI && BI->isConditional() && 4042 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4043 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4044 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4045 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4046 } 4047 4048 return nullptr; 4049 } 4050 4051 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4052 if (const SCEV *S = createAddRecFromPHI(PN)) 4053 return S; 4054 4055 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4056 return S; 4057 4058 // If the PHI has a single incoming value, follow that value, unless the 4059 // PHI's incoming blocks are in a different loop, in which case doing so 4060 // risks breaking LCSSA form. Instcombine would normally zap these, but 4061 // it doesn't have DominatorTree information, so it may miss cases. 4062 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4063 if (LI.replacementPreservesLCSSAForm(PN, V)) 4064 return getSCEV(V); 4065 4066 // If it's not a loop phi, we can't handle it yet. 4067 return getUnknown(PN); 4068 } 4069 4070 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4071 Value *Cond, 4072 Value *TrueVal, 4073 Value *FalseVal) { 4074 // Handle "constant" branch or select. This can occur for instance when a 4075 // loop pass transforms an inner loop and moves on to process the outer loop. 4076 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4077 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4078 4079 // Try to match some simple smax or umax patterns. 4080 auto *ICI = dyn_cast<ICmpInst>(Cond); 4081 if (!ICI) 4082 return getUnknown(I); 4083 4084 Value *LHS = ICI->getOperand(0); 4085 Value *RHS = ICI->getOperand(1); 4086 4087 switch (ICI->getPredicate()) { 4088 case ICmpInst::ICMP_SLT: 4089 case ICmpInst::ICMP_SLE: 4090 std::swap(LHS, RHS); 4091 // fall through 4092 case ICmpInst::ICMP_SGT: 4093 case ICmpInst::ICMP_SGE: 4094 // a >s b ? a+x : b+x -> smax(a, b)+x 4095 // a >s b ? b+x : a+x -> smin(a, b)+x 4096 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4097 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4098 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4099 const SCEV *LA = getSCEV(TrueVal); 4100 const SCEV *RA = getSCEV(FalseVal); 4101 const SCEV *LDiff = getMinusSCEV(LA, LS); 4102 const SCEV *RDiff = getMinusSCEV(RA, RS); 4103 if (LDiff == RDiff) 4104 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4105 LDiff = getMinusSCEV(LA, RS); 4106 RDiff = getMinusSCEV(RA, LS); 4107 if (LDiff == RDiff) 4108 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4109 } 4110 break; 4111 case ICmpInst::ICMP_ULT: 4112 case ICmpInst::ICMP_ULE: 4113 std::swap(LHS, RHS); 4114 // fall through 4115 case ICmpInst::ICMP_UGT: 4116 case ICmpInst::ICMP_UGE: 4117 // a >u b ? a+x : b+x -> umax(a, b)+x 4118 // a >u b ? b+x : a+x -> umin(a, b)+x 4119 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4120 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4121 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4122 const SCEV *LA = getSCEV(TrueVal); 4123 const SCEV *RA = getSCEV(FalseVal); 4124 const SCEV *LDiff = getMinusSCEV(LA, LS); 4125 const SCEV *RDiff = getMinusSCEV(RA, RS); 4126 if (LDiff == RDiff) 4127 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4128 LDiff = getMinusSCEV(LA, RS); 4129 RDiff = getMinusSCEV(RA, LS); 4130 if (LDiff == RDiff) 4131 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4132 } 4133 break; 4134 case ICmpInst::ICMP_NE: 4135 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4136 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4137 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4138 const SCEV *One = getOne(I->getType()); 4139 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4140 const SCEV *LA = getSCEV(TrueVal); 4141 const SCEV *RA = getSCEV(FalseVal); 4142 const SCEV *LDiff = getMinusSCEV(LA, LS); 4143 const SCEV *RDiff = getMinusSCEV(RA, One); 4144 if (LDiff == RDiff) 4145 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4146 } 4147 break; 4148 case ICmpInst::ICMP_EQ: 4149 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4150 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4151 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4152 const SCEV *One = getOne(I->getType()); 4153 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4154 const SCEV *LA = getSCEV(TrueVal); 4155 const SCEV *RA = getSCEV(FalseVal); 4156 const SCEV *LDiff = getMinusSCEV(LA, One); 4157 const SCEV *RDiff = getMinusSCEV(RA, LS); 4158 if (LDiff == RDiff) 4159 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4160 } 4161 break; 4162 default: 4163 break; 4164 } 4165 4166 return getUnknown(I); 4167 } 4168 4169 /// createNodeForGEP - Expand GEP instructions into add and multiply 4170 /// operations. This allows them to be analyzed by regular SCEV code. 4171 /// 4172 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4173 // Don't attempt to analyze GEPs over unsized objects. 4174 if (!GEP->getSourceElementType()->isSized()) 4175 return getUnknown(GEP); 4176 4177 SmallVector<const SCEV *, 4> IndexExprs; 4178 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4179 IndexExprs.push_back(getSCEV(*Index)); 4180 return getGEPExpr(GEP->getSourceElementType(), 4181 getSCEV(GEP->getPointerOperand()), 4182 IndexExprs, GEP->isInBounds()); 4183 } 4184 4185 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 4186 /// guaranteed to end in (at every loop iteration). It is, at the same time, 4187 /// the minimum number of times S is divisible by 2. For example, given {4,+,8} 4188 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 4189 uint32_t 4190 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4191 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4192 return C->getAPInt().countTrailingZeros(); 4193 4194 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4195 return std::min(GetMinTrailingZeros(T->getOperand()), 4196 (uint32_t)getTypeSizeInBits(T->getType())); 4197 4198 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4199 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4200 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4201 getTypeSizeInBits(E->getType()) : OpRes; 4202 } 4203 4204 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4205 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4206 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4207 getTypeSizeInBits(E->getType()) : OpRes; 4208 } 4209 4210 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4211 // The result is the min of all operands results. 4212 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4213 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4214 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4215 return MinOpRes; 4216 } 4217 4218 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4219 // The result is the sum of all operands results. 4220 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4221 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4222 for (unsigned i = 1, e = M->getNumOperands(); 4223 SumOpRes != BitWidth && i != e; ++i) 4224 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4225 BitWidth); 4226 return SumOpRes; 4227 } 4228 4229 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4230 // The result is the min of all operands results. 4231 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4232 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4233 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4234 return MinOpRes; 4235 } 4236 4237 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4238 // The result is the min of all operands results. 4239 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4240 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4241 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4242 return MinOpRes; 4243 } 4244 4245 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4246 // The result is the min of all operands results. 4247 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4248 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4249 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4250 return MinOpRes; 4251 } 4252 4253 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4254 // For a SCEVUnknown, ask ValueTracking. 4255 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4256 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4257 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4258 nullptr, &DT); 4259 return Zeros.countTrailingOnes(); 4260 } 4261 4262 // SCEVUDivExpr 4263 return 0; 4264 } 4265 4266 /// GetRangeFromMetadata - Helper method to assign a range to V from 4267 /// metadata present in the IR. 4268 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4269 if (Instruction *I = dyn_cast<Instruction>(V)) 4270 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4271 return getConstantRangeFromMetadata(*MD); 4272 4273 return None; 4274 } 4275 4276 /// getRange - Determine the range for a particular SCEV. If SignHint is 4277 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4278 /// with a "cleaner" unsigned (resp. signed) representation. 4279 /// 4280 ConstantRange 4281 ScalarEvolution::getRange(const SCEV *S, 4282 ScalarEvolution::RangeSignHint SignHint) { 4283 DenseMap<const SCEV *, ConstantRange> &Cache = 4284 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4285 : SignedRanges; 4286 4287 // See if we've computed this range already. 4288 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4289 if (I != Cache.end()) 4290 return I->second; 4291 4292 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4293 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4294 4295 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4296 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4297 4298 // If the value has known zeros, the maximum value will have those known zeros 4299 // as well. 4300 uint32_t TZ = GetMinTrailingZeros(S); 4301 if (TZ != 0) { 4302 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4303 ConservativeResult = 4304 ConstantRange(APInt::getMinValue(BitWidth), 4305 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4306 else 4307 ConservativeResult = ConstantRange( 4308 APInt::getSignedMinValue(BitWidth), 4309 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4310 } 4311 4312 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4313 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4314 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4315 X = X.add(getRange(Add->getOperand(i), SignHint)); 4316 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4317 } 4318 4319 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4320 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4321 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4322 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4323 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4324 } 4325 4326 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4327 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4328 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4329 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4330 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4331 } 4332 4333 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4334 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4335 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4336 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4337 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4338 } 4339 4340 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4341 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4342 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4343 return setRange(UDiv, SignHint, 4344 ConservativeResult.intersectWith(X.udiv(Y))); 4345 } 4346 4347 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4348 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4349 return setRange(ZExt, SignHint, 4350 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4351 } 4352 4353 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4354 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4355 return setRange(SExt, SignHint, 4356 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4357 } 4358 4359 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4360 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4361 return setRange(Trunc, SignHint, 4362 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4363 } 4364 4365 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4366 // If there's no unsigned wrap, the value will never be less than its 4367 // initial value. 4368 if (AddRec->hasNoUnsignedWrap()) 4369 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4370 if (!C->getValue()->isZero()) 4371 ConservativeResult = ConservativeResult.intersectWith( 4372 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4373 4374 // If there's no signed wrap, and all the operands have the same sign or 4375 // zero, the value won't ever change sign. 4376 if (AddRec->hasNoSignedWrap()) { 4377 bool AllNonNeg = true; 4378 bool AllNonPos = true; 4379 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4380 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4381 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4382 } 4383 if (AllNonNeg) 4384 ConservativeResult = ConservativeResult.intersectWith( 4385 ConstantRange(APInt(BitWidth, 0), 4386 APInt::getSignedMinValue(BitWidth))); 4387 else if (AllNonPos) 4388 ConservativeResult = ConservativeResult.intersectWith( 4389 ConstantRange(APInt::getSignedMinValue(BitWidth), 4390 APInt(BitWidth, 1))); 4391 } 4392 4393 // TODO: non-affine addrec 4394 if (AddRec->isAffine()) { 4395 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4396 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4397 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4398 auto RangeFromAffine = getRangeForAffineAR( 4399 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4400 BitWidth); 4401 if (!RangeFromAffine.isFullSet()) 4402 ConservativeResult = 4403 ConservativeResult.intersectWith(RangeFromAffine); 4404 4405 auto RangeFromFactoring = getRangeViaFactoring( 4406 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4407 BitWidth); 4408 if (!RangeFromFactoring.isFullSet()) 4409 ConservativeResult = 4410 ConservativeResult.intersectWith(RangeFromFactoring); 4411 } 4412 } 4413 4414 return setRange(AddRec, SignHint, ConservativeResult); 4415 } 4416 4417 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4418 // Check if the IR explicitly contains !range metadata. 4419 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4420 if (MDRange.hasValue()) 4421 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4422 4423 // Split here to avoid paying the compile-time cost of calling both 4424 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4425 // if needed. 4426 const DataLayout &DL = getDataLayout(); 4427 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4428 // For a SCEVUnknown, ask ValueTracking. 4429 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4430 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4431 if (Ones != ~Zeros + 1) 4432 ConservativeResult = 4433 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4434 } else { 4435 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4436 "generalize as needed!"); 4437 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4438 if (NS > 1) 4439 ConservativeResult = ConservativeResult.intersectWith( 4440 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4441 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4442 } 4443 4444 return setRange(U, SignHint, ConservativeResult); 4445 } 4446 4447 return setRange(S, SignHint, ConservativeResult); 4448 } 4449 4450 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4451 const SCEV *Step, 4452 const SCEV *MaxBECount, 4453 unsigned BitWidth) { 4454 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4455 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4456 "Precondition!"); 4457 4458 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4459 4460 // Check for overflow. This must be done with ConstantRange arithmetic 4461 // because we could be called from within the ScalarEvolution overflow 4462 // checking code. 4463 4464 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4465 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4466 ConstantRange ZExtMaxBECountRange = 4467 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4468 4469 ConstantRange StepSRange = getSignedRange(Step); 4470 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4471 4472 ConstantRange StartURange = getUnsignedRange(Start); 4473 ConstantRange EndURange = 4474 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4475 4476 // Check for unsigned overflow. 4477 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4478 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4479 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4480 ZExtEndURange) { 4481 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4482 EndURange.getUnsignedMin()); 4483 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4484 EndURange.getUnsignedMax()); 4485 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4486 if (!IsFullRange) 4487 Result = 4488 Result.intersectWith(ConstantRange(Min, Max + 1)); 4489 } 4490 4491 ConstantRange StartSRange = getSignedRange(Start); 4492 ConstantRange EndSRange = 4493 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4494 4495 // Check for signed overflow. This must be done with ConstantRange 4496 // arithmetic because we could be called from within the ScalarEvolution 4497 // overflow checking code. 4498 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4499 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4500 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4501 SExtEndSRange) { 4502 APInt Min = 4503 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4504 APInt Max = 4505 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4506 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4507 if (!IsFullRange) 4508 Result = 4509 Result.intersectWith(ConstantRange(Min, Max + 1)); 4510 } 4511 4512 return Result; 4513 } 4514 4515 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4516 const SCEV *Step, 4517 const SCEV *MaxBECount, 4518 unsigned BitWidth) { 4519 APInt Offset(BitWidth, 0); 4520 4521 if (auto *SA = dyn_cast<SCEVAddExpr>(Start)) { 4522 // Peel off a constant offset, if possible. In the future we could consider 4523 // being smarter here and handle {Start+Step,+,Step} too. 4524 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4525 return ConstantRange(BitWidth, /* isFullSet = */ true); 4526 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4527 Start = SA->getOperand(1); 4528 } 4529 4530 if (!isa<SCEVUnknown>(Start) || !isa<SCEVUnknown>(Step)) 4531 // We don't have anything new to contribute in this case. 4532 return ConstantRange(BitWidth, /* isFullSet = */ true); 4533 4534 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4535 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4536 4537 struct SelectPattern { 4538 Value *Condition = nullptr; 4539 const APInt *TrueValue = nullptr; 4540 const APInt *FalseValue = nullptr; 4541 4542 explicit SelectPattern(const SCEVUnknown *SU) { 4543 using namespace llvm::PatternMatch; 4544 4545 if (!match(SU->getValue(), 4546 m_Select(m_Value(Condition), m_APInt(TrueValue), 4547 m_APInt(FalseValue)))) { 4548 Condition = nullptr; 4549 TrueValue = FalseValue = nullptr; 4550 } 4551 } 4552 4553 bool isRecognized() { 4554 assert(((Condition && TrueValue && FalseValue) || 4555 (!Condition && !TrueValue && !FalseValue)) && 4556 "Invariant: either all three are non-null or all three are null"); 4557 return TrueValue != nullptr; 4558 } 4559 }; 4560 4561 SelectPattern StartPattern(cast<SCEVUnknown>(Start)); 4562 if (!StartPattern.isRecognized()) 4563 return ConstantRange(BitWidth, /* isFullSet = */ true); 4564 4565 SelectPattern StepPattern(cast<SCEVUnknown>(Step)); 4566 if (!StepPattern.isRecognized()) 4567 return ConstantRange(BitWidth, /* isFullSet = */ true); 4568 4569 if (StartPattern.Condition != StepPattern.Condition) { 4570 // We don't handle this case today; but we could, by considering four 4571 // possibilities below instead of two. I'm not sure if there are cases where 4572 // that will help over what getRange already does, though. 4573 return ConstantRange(BitWidth, /* isFullSet = */ true); 4574 } 4575 4576 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4577 // construct arbitrary general SCEV expressions here. This function is called 4578 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4579 // say) can end up caching a suboptimal value. 4580 4581 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4582 // C2352 and C2512 (otherwise it isn't needed). 4583 4584 const SCEV *TrueStart = this->getConstant(*StartPattern.TrueValue + Offset); 4585 const SCEV *TrueStep = this->getConstant(*StepPattern.TrueValue); 4586 const SCEV *FalseStart = this->getConstant(*StartPattern.FalseValue + Offset); 4587 const SCEV *FalseStep = this->getConstant(*StepPattern.FalseValue); 4588 4589 ConstantRange TrueRange = 4590 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4591 ConstantRange FalseRange = 4592 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4593 4594 return TrueRange.unionWith(FalseRange); 4595 } 4596 4597 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4598 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4599 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4600 4601 // Return early if there are no flags to propagate to the SCEV. 4602 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4603 if (BinOp->hasNoUnsignedWrap()) 4604 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4605 if (BinOp->hasNoSignedWrap()) 4606 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4607 if (Flags == SCEV::FlagAnyWrap) 4608 return SCEV::FlagAnyWrap; 4609 4610 // Here we check that BinOp is in the header of the innermost loop 4611 // containing BinOp, since we only deal with instructions in the loop 4612 // header. The actual loop we need to check later will come from an add 4613 // recurrence, but getting that requires computing the SCEV of the operands, 4614 // which can be expensive. This check we can do cheaply to rule out some 4615 // cases early. 4616 Loop *InnermostContainingLoop = LI.getLoopFor(BinOp->getParent()); 4617 if (InnermostContainingLoop == nullptr || 4618 InnermostContainingLoop->getHeader() != BinOp->getParent()) 4619 return SCEV::FlagAnyWrap; 4620 4621 // Only proceed if we can prove that BinOp does not yield poison. 4622 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap; 4623 4624 // At this point we know that if V is executed, then it does not wrap 4625 // according to at least one of NSW or NUW. If V is not executed, then we do 4626 // not know if the calculation that V represents would wrap. Multiple 4627 // instructions can map to the same SCEV. If we apply NSW or NUW from V to 4628 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4629 // derived from other instructions that map to the same SCEV. We cannot make 4630 // that guarantee for cases where V is not executed. So we need to find the 4631 // loop that V is considered in relation to and prove that V is executed for 4632 // every iteration of that loop. That implies that the value that V 4633 // calculates does not wrap anywhere in the loop, so then we can apply the 4634 // flags to the SCEV. 4635 // 4636 // We check isLoopInvariant to disambiguate in case we are adding two 4637 // recurrences from different loops, so that we know which loop to prove 4638 // that V is executed in. 4639 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) { 4640 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex)); 4641 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4642 const int OtherOpIndex = 1 - OpIndex; 4643 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex)); 4644 if (isLoopInvariant(OtherOp, AddRec->getLoop()) && 4645 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop())) 4646 return Flags; 4647 } 4648 } 4649 return SCEV::FlagAnyWrap; 4650 } 4651 4652 /// createSCEV - We know that there is no SCEV for the specified value. Analyze 4653 /// the expression. 4654 /// 4655 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4656 if (!isSCEVable(V->getType())) 4657 return getUnknown(V); 4658 4659 unsigned Opcode = Instruction::UserOp1; 4660 if (Instruction *I = dyn_cast<Instruction>(V)) { 4661 Opcode = I->getOpcode(); 4662 4663 // Don't attempt to analyze instructions in blocks that aren't 4664 // reachable. Such instructions don't matter, and they aren't required 4665 // to obey basic rules for definitions dominating uses which this 4666 // analysis depends on. 4667 if (!DT.isReachableFromEntry(I->getParent())) 4668 return getUnknown(V); 4669 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 4670 Opcode = CE->getOpcode(); 4671 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 4672 return getConstant(CI); 4673 else if (isa<ConstantPointerNull>(V)) 4674 return getZero(V->getType()); 4675 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 4676 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); 4677 else 4678 return getUnknown(V); 4679 4680 Operator *U = cast<Operator>(V); 4681 switch (Opcode) { 4682 case Instruction::Add: { 4683 // The simple thing to do would be to just call getSCEV on both operands 4684 // and call getAddExpr with the result. However if we're looking at a 4685 // bunch of things all added together, this can be quite inefficient, 4686 // because it leads to N-1 getAddExpr calls for N ultimate operands. 4687 // Instead, gather up all the operands and make a single getAddExpr call. 4688 // LLVM IR canonical form means we need only traverse the left operands. 4689 SmallVector<const SCEV *, 4> AddOps; 4690 for (Value *Op = U;; Op = U->getOperand(0)) { 4691 U = dyn_cast<Operator>(Op); 4692 unsigned Opcode = U ? U->getOpcode() : 0; 4693 if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) { 4694 assert(Op != V && "V should be an add"); 4695 AddOps.push_back(getSCEV(Op)); 4696 break; 4697 } 4698 4699 if (auto *OpSCEV = getExistingSCEV(U)) { 4700 AddOps.push_back(OpSCEV); 4701 break; 4702 } 4703 4704 // If a NUW or NSW flag can be applied to the SCEV for this 4705 // addition, then compute the SCEV for this addition by itself 4706 // with a separate call to getAddExpr. We need to do that 4707 // instead of pushing the operands of the addition onto AddOps, 4708 // since the flags are only known to apply to this particular 4709 // addition - they may not apply to other additions that can be 4710 // formed with operands from AddOps. 4711 const SCEV *RHS = getSCEV(U->getOperand(1)); 4712 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); 4713 if (Flags != SCEV::FlagAnyWrap) { 4714 const SCEV *LHS = getSCEV(U->getOperand(0)); 4715 if (Opcode == Instruction::Sub) 4716 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 4717 else 4718 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 4719 break; 4720 } 4721 4722 if (Opcode == Instruction::Sub) 4723 AddOps.push_back(getNegativeSCEV(RHS)); 4724 else 4725 AddOps.push_back(RHS); 4726 } 4727 return getAddExpr(AddOps); 4728 } 4729 4730 case Instruction::Mul: { 4731 SmallVector<const SCEV *, 4> MulOps; 4732 for (Value *Op = U;; Op = U->getOperand(0)) { 4733 U = dyn_cast<Operator>(Op); 4734 if (!U || U->getOpcode() != Instruction::Mul) { 4735 assert(Op != V && "V should be a mul"); 4736 MulOps.push_back(getSCEV(Op)); 4737 break; 4738 } 4739 4740 if (auto *OpSCEV = getExistingSCEV(U)) { 4741 MulOps.push_back(OpSCEV); 4742 break; 4743 } 4744 4745 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); 4746 if (Flags != SCEV::FlagAnyWrap) { 4747 MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)), 4748 getSCEV(U->getOperand(1)), Flags)); 4749 break; 4750 } 4751 4752 MulOps.push_back(getSCEV(U->getOperand(1))); 4753 } 4754 return getMulExpr(MulOps); 4755 } 4756 case Instruction::UDiv: 4757 return getUDivExpr(getSCEV(U->getOperand(0)), 4758 getSCEV(U->getOperand(1))); 4759 case Instruction::Sub: 4760 return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)), 4761 getNoWrapFlagsFromUB(U)); 4762 case Instruction::And: 4763 // For an expression like x&255 that merely masks off the high bits, 4764 // use zext(trunc(x)) as the SCEV expression. 4765 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4766 if (CI->isNullValue()) 4767 return getSCEV(U->getOperand(1)); 4768 if (CI->isAllOnesValue()) 4769 return getSCEV(U->getOperand(0)); 4770 const APInt &A = CI->getValue(); 4771 4772 // Instcombine's ShrinkDemandedConstant may strip bits out of 4773 // constants, obscuring what would otherwise be a low-bits mask. 4774 // Use computeKnownBits to compute what ShrinkDemandedConstant 4775 // knew about to reconstruct a low-bits mask value. 4776 unsigned LZ = A.countLeadingZeros(); 4777 unsigned TZ = A.countTrailingZeros(); 4778 unsigned BitWidth = A.getBitWidth(); 4779 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 4780 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, getDataLayout(), 4781 0, &AC, nullptr, &DT); 4782 4783 APInt EffectiveMask = 4784 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 4785 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 4786 const SCEV *MulCount = getConstant( 4787 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ))); 4788 return getMulExpr( 4789 getZeroExtendExpr( 4790 getTruncateExpr( 4791 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount), 4792 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 4793 U->getType()), 4794 MulCount); 4795 } 4796 } 4797 break; 4798 4799 case Instruction::Or: 4800 // If the RHS of the Or is a constant, we may have something like: 4801 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 4802 // optimizations will transparently handle this case. 4803 // 4804 // In order for this transformation to be safe, the LHS must be of the 4805 // form X*(2^n) and the Or constant must be less than 2^n. 4806 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4807 const SCEV *LHS = getSCEV(U->getOperand(0)); 4808 const APInt &CIVal = CI->getValue(); 4809 if (GetMinTrailingZeros(LHS) >= 4810 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 4811 // Build a plain add SCEV. 4812 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 4813 // If the LHS of the add was an addrec and it has no-wrap flags, 4814 // transfer the no-wrap flags, since an or won't introduce a wrap. 4815 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 4816 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 4817 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 4818 OldAR->getNoWrapFlags()); 4819 } 4820 return S; 4821 } 4822 } 4823 break; 4824 case Instruction::Xor: 4825 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4826 // If the RHS of the xor is a signbit, then this is just an add. 4827 // Instcombine turns add of signbit into xor as a strength reduction step. 4828 if (CI->getValue().isSignBit()) 4829 return getAddExpr(getSCEV(U->getOperand(0)), 4830 getSCEV(U->getOperand(1))); 4831 4832 // If the RHS of xor is -1, then this is a not operation. 4833 if (CI->isAllOnesValue()) 4834 return getNotSCEV(getSCEV(U->getOperand(0))); 4835 4836 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 4837 // This is a variant of the check for xor with -1, and it handles 4838 // the case where instcombine has trimmed non-demanded bits out 4839 // of an xor with -1. 4840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) 4841 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) 4842 if (BO->getOpcode() == Instruction::And && 4843 LCI->getValue() == CI->getValue()) 4844 if (const SCEVZeroExtendExpr *Z = 4845 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { 4846 Type *UTy = U->getType(); 4847 const SCEV *Z0 = Z->getOperand(); 4848 Type *Z0Ty = Z0->getType(); 4849 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 4850 4851 // If C is a low-bits mask, the zero extend is serving to 4852 // mask off the high bits. Complement the operand and 4853 // re-apply the zext. 4854 if (APIntOps::isMask(Z0TySize, CI->getValue())) 4855 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 4856 4857 // If C is a single bit, it may be in the sign-bit position 4858 // before the zero-extend. In this case, represent the xor 4859 // using an add, which is equivalent, and re-apply the zext. 4860 APInt Trunc = CI->getValue().trunc(Z0TySize); 4861 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 4862 Trunc.isSignBit()) 4863 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 4864 UTy); 4865 } 4866 } 4867 break; 4868 4869 case Instruction::Shl: 4870 // Turn shift left of a constant amount into a multiply. 4871 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 4872 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 4873 4874 // If the shift count is not less than the bitwidth, the result of 4875 // the shift is undefined. Don't try to analyze it, because the 4876 // resolution chosen here may differ from the resolution chosen in 4877 // other parts of the compiler. 4878 if (SA->getValue().uge(BitWidth)) 4879 break; 4880 4881 // It is currently not resolved how to interpret NSW for left 4882 // shift by BitWidth - 1, so we avoid applying flags in that 4883 // case. Remove this check (or this comment) once the situation 4884 // is resolved. See 4885 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 4886 // and http://reviews.llvm.org/D8890 . 4887 auto Flags = SCEV::FlagAnyWrap; 4888 if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U); 4889 4890 Constant *X = ConstantInt::get(getContext(), 4891 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4892 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags); 4893 } 4894 break; 4895 4896 case Instruction::LShr: 4897 // Turn logical shift right of a constant into a unsigned divide. 4898 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 4899 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 4900 4901 // If the shift count is not less than the bitwidth, the result of 4902 // the shift is undefined. Don't try to analyze it, because the 4903 // resolution chosen here may differ from the resolution chosen in 4904 // other parts of the compiler. 4905 if (SA->getValue().uge(BitWidth)) 4906 break; 4907 4908 Constant *X = ConstantInt::get(getContext(), 4909 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4910 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 4911 } 4912 break; 4913 4914 case Instruction::AShr: 4915 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 4916 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 4917 if (Operator *L = dyn_cast<Operator>(U->getOperand(0))) 4918 if (L->getOpcode() == Instruction::Shl && 4919 L->getOperand(1) == U->getOperand(1)) { 4920 uint64_t BitWidth = getTypeSizeInBits(U->getType()); 4921 4922 // If the shift count is not less than the bitwidth, the result of 4923 // the shift is undefined. Don't try to analyze it, because the 4924 // resolution chosen here may differ from the resolution chosen in 4925 // other parts of the compiler. 4926 if (CI->getValue().uge(BitWidth)) 4927 break; 4928 4929 uint64_t Amt = BitWidth - CI->getZExtValue(); 4930 if (Amt == BitWidth) 4931 return getSCEV(L->getOperand(0)); // shift by zero --> noop 4932 return 4933 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 4934 IntegerType::get(getContext(), 4935 Amt)), 4936 U->getType()); 4937 } 4938 break; 4939 4940 case Instruction::Trunc: 4941 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 4942 4943 case Instruction::ZExt: 4944 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 4945 4946 case Instruction::SExt: 4947 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 4948 4949 case Instruction::BitCast: 4950 // BitCasts are no-op casts so we just eliminate the cast. 4951 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 4952 return getSCEV(U->getOperand(0)); 4953 break; 4954 4955 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 4956 // lead to pointer expressions which cannot safely be expanded to GEPs, 4957 // because ScalarEvolution doesn't respect the GEP aliasing rules when 4958 // simplifying integer expressions. 4959 4960 case Instruction::GetElementPtr: 4961 return createNodeForGEP(cast<GEPOperator>(U)); 4962 4963 case Instruction::PHI: 4964 return createNodeForPHI(cast<PHINode>(U)); 4965 4966 case Instruction::Select: 4967 // U can also be a select constant expr, which let fall through. Since 4968 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 4969 // constant expressions cannot have instructions as operands, we'd have 4970 // returned getUnknown for a select constant expressions anyway. 4971 if (isa<Instruction>(U)) 4972 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 4973 U->getOperand(1), U->getOperand(2)); 4974 4975 default: // We cannot analyze this expression. 4976 break; 4977 } 4978 4979 return getUnknown(V); 4980 } 4981 4982 4983 4984 //===----------------------------------------------------------------------===// 4985 // Iteration Count Computation Code 4986 // 4987 4988 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 4989 if (BasicBlock *ExitingBB = L->getExitingBlock()) 4990 return getSmallConstantTripCount(L, ExitingBB); 4991 4992 // No trip count information for multiple exits. 4993 return 0; 4994 } 4995 4996 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a 4997 /// normal unsigned value. Returns 0 if the trip count is unknown or not 4998 /// constant. Will also return 0 if the maximum trip count is very large (>= 4999 /// 2^32). 5000 /// 5001 /// This "trip count" assumes that control exits via ExitingBlock. More 5002 /// precisely, it is the number of times that control may reach ExitingBlock 5003 /// before taking the branch. For loops with multiple exits, it may not be the 5004 /// number times that the loop header executes because the loop may exit 5005 /// prematurely via another branch. 5006 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5007 BasicBlock *ExitingBlock) { 5008 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5009 assert(L->isLoopExiting(ExitingBlock) && 5010 "Exiting block must actually branch out of the loop!"); 5011 const SCEVConstant *ExitCount = 5012 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5013 if (!ExitCount) 5014 return 0; 5015 5016 ConstantInt *ExitConst = ExitCount->getValue(); 5017 5018 // Guard against huge trip counts. 5019 if (ExitConst->getValue().getActiveBits() > 32) 5020 return 0; 5021 5022 // In case of integer overflow, this returns 0, which is correct. 5023 return ((unsigned)ExitConst->getZExtValue()) + 1; 5024 } 5025 5026 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5027 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5028 return getSmallConstantTripMultiple(L, ExitingBB); 5029 5030 // No trip multiple information for multiple exits. 5031 return 0; 5032 } 5033 5034 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the 5035 /// trip count of this loop as a normal unsigned value, if possible. This 5036 /// means that the actual trip count is always a multiple of the returned 5037 /// value (don't forget the trip count could very well be zero as well!). 5038 /// 5039 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5040 /// multiple of a constant (which is also the case if the trip count is simply 5041 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5042 /// if the trip count is very large (>= 2^32). 5043 /// 5044 /// As explained in the comments for getSmallConstantTripCount, this assumes 5045 /// that control exits the loop via ExitingBlock. 5046 unsigned 5047 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5048 BasicBlock *ExitingBlock) { 5049 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5050 assert(L->isLoopExiting(ExitingBlock) && 5051 "Exiting block must actually branch out of the loop!"); 5052 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5053 if (ExitCount == getCouldNotCompute()) 5054 return 1; 5055 5056 // Get the trip count from the BE count by adding 1. 5057 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5058 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5059 // to factor simple cases. 5060 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5061 TCMul = Mul->getOperand(0); 5062 5063 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5064 if (!MulC) 5065 return 1; 5066 5067 ConstantInt *Result = MulC->getValue(); 5068 5069 // Guard against huge trip counts (this requires checking 5070 // for zero to handle the case where the trip count == -1 and the 5071 // addition wraps). 5072 if (!Result || Result->getValue().getActiveBits() > 32 || 5073 Result->getValue().getActiveBits() == 0) 5074 return 1; 5075 5076 return (unsigned)Result->getZExtValue(); 5077 } 5078 5079 // getExitCount - Get the expression for the number of loop iterations for which 5080 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return 5081 // SCEVCouldNotCompute. 5082 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5083 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5084 } 5085 5086 /// getBackedgeTakenCount - If the specified loop has a predictable 5087 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 5088 /// object. The backedge-taken count is the number of times the loop header 5089 /// will be branched to from within the loop. This is one less than the 5090 /// trip count of the loop, since it doesn't count the first iteration, 5091 /// when the header is branched to from outside the loop. 5092 /// 5093 /// Note that it is not valid to call this method on a loop without a 5094 /// loop-invariant backedge-taken count (see 5095 /// hasLoopInvariantBackedgeTakenCount). 5096 /// 5097 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5098 return getBackedgeTakenInfo(L).getExact(this); 5099 } 5100 5101 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 5102 /// return the least SCEV value that is known never to be less than the 5103 /// actual backedge taken count. 5104 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5105 return getBackedgeTakenInfo(L).getMax(this); 5106 } 5107 5108 /// PushLoopPHIs - Push PHI nodes in the header of the given loop 5109 /// onto the given Worklist. 5110 static void 5111 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5112 BasicBlock *Header = L->getHeader(); 5113 5114 // Push all Loop-header PHIs onto the Worklist stack. 5115 for (BasicBlock::iterator I = Header->begin(); 5116 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5117 Worklist.push_back(PN); 5118 } 5119 5120 const ScalarEvolution::BackedgeTakenInfo & 5121 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5122 // Initially insert an invalid entry for this loop. If the insertion 5123 // succeeds, proceed to actually compute a backedge-taken count and 5124 // update the value. The temporary CouldNotCompute value tells SCEV 5125 // code elsewhere that it shouldn't attempt to request a new 5126 // backedge-taken count, which could result in infinite recursion. 5127 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5128 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5129 if (!Pair.second) 5130 return Pair.first->second; 5131 5132 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5133 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5134 // must be cleared in this scope. 5135 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5136 5137 if (Result.getExact(this) != getCouldNotCompute()) { 5138 assert(isLoopInvariant(Result.getExact(this), L) && 5139 isLoopInvariant(Result.getMax(this), L) && 5140 "Computed backedge-taken count isn't loop invariant for loop!"); 5141 ++NumTripCountsComputed; 5142 } 5143 else if (Result.getMax(this) == getCouldNotCompute() && 5144 isa<PHINode>(L->getHeader()->begin())) { 5145 // Only count loops that have phi nodes as not being computable. 5146 ++NumTripCountsNotComputed; 5147 } 5148 5149 // Now that we know more about the trip count for this loop, forget any 5150 // existing SCEV values for PHI nodes in this loop since they are only 5151 // conservative estimates made without the benefit of trip count 5152 // information. This is similar to the code in forgetLoop, except that 5153 // it handles SCEVUnknown PHI nodes specially. 5154 if (Result.hasAnyInfo()) { 5155 SmallVector<Instruction *, 16> Worklist; 5156 PushLoopPHIs(L, Worklist); 5157 5158 SmallPtrSet<Instruction *, 8> Visited; 5159 while (!Worklist.empty()) { 5160 Instruction *I = Worklist.pop_back_val(); 5161 if (!Visited.insert(I).second) 5162 continue; 5163 5164 ValueExprMapType::iterator It = 5165 ValueExprMap.find_as(static_cast<Value *>(I)); 5166 if (It != ValueExprMap.end()) { 5167 const SCEV *Old = It->second; 5168 5169 // SCEVUnknown for a PHI either means that it has an unrecognized 5170 // structure, or it's a PHI that's in the progress of being computed 5171 // by createNodeForPHI. In the former case, additional loop trip 5172 // count information isn't going to change anything. In the later 5173 // case, createNodeForPHI will perform the necessary updates on its 5174 // own when it gets to that point. 5175 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5176 forgetMemoizedResults(Old); 5177 ValueExprMap.erase(It); 5178 } 5179 if (PHINode *PN = dyn_cast<PHINode>(I)) 5180 ConstantEvolutionLoopExitValue.erase(PN); 5181 } 5182 5183 PushDefUseChildren(I, Worklist); 5184 } 5185 } 5186 5187 // Re-lookup the insert position, since the call to 5188 // computeBackedgeTakenCount above could result in a 5189 // recusive call to getBackedgeTakenInfo (on a different 5190 // loop), which would invalidate the iterator computed 5191 // earlier. 5192 return BackedgeTakenCounts.find(L)->second = Result; 5193 } 5194 5195 /// forgetLoop - This method should be called by the client when it has 5196 /// changed a loop in a way that may effect ScalarEvolution's ability to 5197 /// compute a trip count, or if the loop is deleted. 5198 void ScalarEvolution::forgetLoop(const Loop *L) { 5199 // Drop any stored trip count value. 5200 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = 5201 BackedgeTakenCounts.find(L); 5202 if (BTCPos != BackedgeTakenCounts.end()) { 5203 BTCPos->second.clear(); 5204 BackedgeTakenCounts.erase(BTCPos); 5205 } 5206 5207 // Drop information about expressions based on loop-header PHIs. 5208 SmallVector<Instruction *, 16> Worklist; 5209 PushLoopPHIs(L, Worklist); 5210 5211 SmallPtrSet<Instruction *, 8> Visited; 5212 while (!Worklist.empty()) { 5213 Instruction *I = Worklist.pop_back_val(); 5214 if (!Visited.insert(I).second) 5215 continue; 5216 5217 ValueExprMapType::iterator It = 5218 ValueExprMap.find_as(static_cast<Value *>(I)); 5219 if (It != ValueExprMap.end()) { 5220 forgetMemoizedResults(It->second); 5221 ValueExprMap.erase(It); 5222 if (PHINode *PN = dyn_cast<PHINode>(I)) 5223 ConstantEvolutionLoopExitValue.erase(PN); 5224 } 5225 5226 PushDefUseChildren(I, Worklist); 5227 } 5228 5229 // Forget all contained loops too, to avoid dangling entries in the 5230 // ValuesAtScopes map. 5231 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 5232 forgetLoop(*I); 5233 } 5234 5235 /// forgetValue - This method should be called by the client when it has 5236 /// changed a value in a way that may effect its value, or which may 5237 /// disconnect it from a def-use chain linking it to a loop. 5238 void ScalarEvolution::forgetValue(Value *V) { 5239 Instruction *I = dyn_cast<Instruction>(V); 5240 if (!I) return; 5241 5242 // Drop information about expressions based on loop-header PHIs. 5243 SmallVector<Instruction *, 16> Worklist; 5244 Worklist.push_back(I); 5245 5246 SmallPtrSet<Instruction *, 8> Visited; 5247 while (!Worklist.empty()) { 5248 I = Worklist.pop_back_val(); 5249 if (!Visited.insert(I).second) 5250 continue; 5251 5252 ValueExprMapType::iterator It = 5253 ValueExprMap.find_as(static_cast<Value *>(I)); 5254 if (It != ValueExprMap.end()) { 5255 forgetMemoizedResults(It->second); 5256 ValueExprMap.erase(It); 5257 if (PHINode *PN = dyn_cast<PHINode>(I)) 5258 ConstantEvolutionLoopExitValue.erase(PN); 5259 } 5260 5261 PushDefUseChildren(I, Worklist); 5262 } 5263 } 5264 5265 /// getExact - Get the exact loop backedge taken count considering all loop 5266 /// exits. A computable result can only be returned for loops with a single 5267 /// exit. Returning the minimum taken count among all exits is incorrect 5268 /// because one of the loop's exit limit's may have been skipped. HowFarToZero 5269 /// assumes that the limit of each loop test is never skipped. This is a valid 5270 /// assumption as long as the loop exits via that test. For precise results, it 5271 /// is the caller's responsibility to specify the relevant loop exit using 5272 /// getExact(ExitingBlock, SE). 5273 const SCEV * 5274 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { 5275 // If any exits were not computable, the loop is not computable. 5276 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); 5277 5278 // We need exactly one computable exit. 5279 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); 5280 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); 5281 5282 const SCEV *BECount = nullptr; 5283 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 5284 ENT != nullptr; ENT = ENT->getNextExit()) { 5285 5286 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5287 5288 if (!BECount) 5289 BECount = ENT->ExactNotTaken; 5290 else if (BECount != ENT->ExactNotTaken) 5291 return SE->getCouldNotCompute(); 5292 } 5293 assert(BECount && "Invalid not taken count for loop exit"); 5294 return BECount; 5295 } 5296 5297 /// getExact - Get the exact not taken count for this loop exit. 5298 const SCEV * 5299 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5300 ScalarEvolution *SE) const { 5301 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 5302 ENT != nullptr; ENT = ENT->getNextExit()) { 5303 5304 if (ENT->ExitingBlock == ExitingBlock) 5305 return ENT->ExactNotTaken; 5306 } 5307 return SE->getCouldNotCompute(); 5308 } 5309 5310 /// getMax - Get the max backedge taken count for the loop. 5311 const SCEV * 5312 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5313 return Max ? Max : SE->getCouldNotCompute(); 5314 } 5315 5316 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5317 ScalarEvolution *SE) const { 5318 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) 5319 return true; 5320 5321 if (!ExitNotTaken.ExitingBlock) 5322 return false; 5323 5324 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 5325 ENT != nullptr; ENT = ENT->getNextExit()) { 5326 5327 if (ENT->ExactNotTaken != SE->getCouldNotCompute() 5328 && SE->hasOperand(ENT->ExactNotTaken, S)) { 5329 return true; 5330 } 5331 } 5332 return false; 5333 } 5334 5335 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5336 /// computable exit into a persistent ExitNotTakenInfo array. 5337 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5338 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 5339 bool Complete, const SCEV *MaxCount) : Max(MaxCount) { 5340 5341 if (!Complete) 5342 ExitNotTaken.setIncomplete(); 5343 5344 unsigned NumExits = ExitCounts.size(); 5345 if (NumExits == 0) return; 5346 5347 ExitNotTaken.ExitingBlock = ExitCounts[0].first; 5348 ExitNotTaken.ExactNotTaken = ExitCounts[0].second; 5349 if (NumExits == 1) return; 5350 5351 // Handle the rare case of multiple computable exits. 5352 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; 5353 5354 ExitNotTakenInfo *PrevENT = &ExitNotTaken; 5355 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { 5356 PrevENT->setNextExit(ENT); 5357 ENT->ExitingBlock = ExitCounts[i].first; 5358 ENT->ExactNotTaken = ExitCounts[i].second; 5359 } 5360 } 5361 5362 /// clear - Invalidate this result and free the ExitNotTakenInfo array. 5363 void ScalarEvolution::BackedgeTakenInfo::clear() { 5364 ExitNotTaken.ExitingBlock = nullptr; 5365 ExitNotTaken.ExactNotTaken = nullptr; 5366 delete[] ExitNotTaken.getNextExit(); 5367 } 5368 5369 /// computeBackedgeTakenCount - Compute the number of times the backedge 5370 /// of the specified loop will execute. 5371 ScalarEvolution::BackedgeTakenInfo 5372 ScalarEvolution::computeBackedgeTakenCount(const Loop *L) { 5373 SmallVector<BasicBlock *, 8> ExitingBlocks; 5374 L->getExitingBlocks(ExitingBlocks); 5375 5376 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; 5377 bool CouldComputeBECount = true; 5378 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5379 const SCEV *MustExitMaxBECount = nullptr; 5380 const SCEV *MayExitMaxBECount = nullptr; 5381 5382 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5383 // and compute maxBECount. 5384 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5385 BasicBlock *ExitBB = ExitingBlocks[i]; 5386 ExitLimit EL = computeExitLimit(L, ExitBB); 5387 5388 // 1. For each exit that can be computed, add an entry to ExitCounts. 5389 // CouldComputeBECount is true only if all exits can be computed. 5390 if (EL.Exact == getCouldNotCompute()) 5391 // We couldn't compute an exact value for this exit, so 5392 // we won't be able to compute an exact value for the loop. 5393 CouldComputeBECount = false; 5394 else 5395 ExitCounts.push_back({ExitBB, EL.Exact}); 5396 5397 // 2. Derive the loop's MaxBECount from each exit's max number of 5398 // non-exiting iterations. Partition the loop exits into two kinds: 5399 // LoopMustExits and LoopMayExits. 5400 // 5401 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5402 // is a LoopMayExit. If any computable LoopMustExit is found, then 5403 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, 5404 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is 5405 // considered greater than any computable EL.Max. 5406 if (EL.Max != getCouldNotCompute() && Latch && 5407 DT.dominates(ExitBB, Latch)) { 5408 if (!MustExitMaxBECount) 5409 MustExitMaxBECount = EL.Max; 5410 else { 5411 MustExitMaxBECount = 5412 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); 5413 } 5414 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5415 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) 5416 MayExitMaxBECount = EL.Max; 5417 else { 5418 MayExitMaxBECount = 5419 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); 5420 } 5421 } 5422 } 5423 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5424 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5425 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); 5426 } 5427 5428 ScalarEvolution::ExitLimit 5429 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { 5430 5431 // Okay, we've chosen an exiting block. See what condition causes us to exit 5432 // at this block and remember the exit block and whether all other targets 5433 // lead to the loop header. 5434 bool MustExecuteLoopHeader = true; 5435 BasicBlock *Exit = nullptr; 5436 for (auto *SBB : successors(ExitingBlock)) 5437 if (!L->contains(SBB)) { 5438 if (Exit) // Multiple exit successors. 5439 return getCouldNotCompute(); 5440 Exit = SBB; 5441 } else if (SBB != L->getHeader()) { 5442 MustExecuteLoopHeader = false; 5443 } 5444 5445 // At this point, we know we have a conditional branch that determines whether 5446 // the loop is exited. However, we don't know if the branch is executed each 5447 // time through the loop. If not, then the execution count of the branch will 5448 // not be equal to the trip count of the loop. 5449 // 5450 // Currently we check for this by checking to see if the Exit branch goes to 5451 // the loop header. If so, we know it will always execute the same number of 5452 // times as the loop. We also handle the case where the exit block *is* the 5453 // loop header. This is common for un-rotated loops. 5454 // 5455 // If both of those tests fail, walk up the unique predecessor chain to the 5456 // header, stopping if there is an edge that doesn't exit the loop. If the 5457 // header is reached, the execution count of the branch will be equal to the 5458 // trip count of the loop. 5459 // 5460 // More extensive analysis could be done to handle more cases here. 5461 // 5462 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5463 // The simple checks failed, try climbing the unique predecessor chain 5464 // up to the header. 5465 bool Ok = false; 5466 for (BasicBlock *BB = ExitingBlock; BB; ) { 5467 BasicBlock *Pred = BB->getUniquePredecessor(); 5468 if (!Pred) 5469 return getCouldNotCompute(); 5470 TerminatorInst *PredTerm = Pred->getTerminator(); 5471 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5472 if (PredSucc == BB) 5473 continue; 5474 // If the predecessor has a successor that isn't BB and isn't 5475 // outside the loop, assume the worst. 5476 if (L->contains(PredSucc)) 5477 return getCouldNotCompute(); 5478 } 5479 if (Pred == L->getHeader()) { 5480 Ok = true; 5481 break; 5482 } 5483 BB = Pred; 5484 } 5485 if (!Ok) 5486 return getCouldNotCompute(); 5487 } 5488 5489 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5490 TerminatorInst *Term = ExitingBlock->getTerminator(); 5491 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5492 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5493 // Proceed to the next level to examine the exit condition expression. 5494 return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0), 5495 BI->getSuccessor(1), 5496 /*ControlsExit=*/IsOnlyExit); 5497 } 5498 5499 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5500 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5501 /*ControlsExit=*/IsOnlyExit); 5502 5503 return getCouldNotCompute(); 5504 } 5505 5506 /// computeExitLimitFromCond - Compute the number of times the 5507 /// backedge of the specified loop will execute if its exit condition 5508 /// were a conditional branch of ExitCond, TBB, and FBB. 5509 /// 5510 /// @param ControlsExit is true if ExitCond directly controls the exit 5511 /// branch. In this case, we can assume that the loop exits only if the 5512 /// condition is true and can infer that failing to meet the condition prior to 5513 /// integer wraparound results in undefined behavior. 5514 ScalarEvolution::ExitLimit 5515 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5516 Value *ExitCond, 5517 BasicBlock *TBB, 5518 BasicBlock *FBB, 5519 bool ControlsExit) { 5520 // Check if the controlling expression for this loop is an And or Or. 5521 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5522 if (BO->getOpcode() == Instruction::And) { 5523 // Recurse on the operands of the and. 5524 bool EitherMayExit = L->contains(TBB); 5525 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5526 ControlsExit && !EitherMayExit); 5527 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5528 ControlsExit && !EitherMayExit); 5529 const SCEV *BECount = getCouldNotCompute(); 5530 const SCEV *MaxBECount = getCouldNotCompute(); 5531 if (EitherMayExit) { 5532 // Both conditions must be true for the loop to continue executing. 5533 // Choose the less conservative count. 5534 if (EL0.Exact == getCouldNotCompute() || 5535 EL1.Exact == getCouldNotCompute()) 5536 BECount = getCouldNotCompute(); 5537 else 5538 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5539 if (EL0.Max == getCouldNotCompute()) 5540 MaxBECount = EL1.Max; 5541 else if (EL1.Max == getCouldNotCompute()) 5542 MaxBECount = EL0.Max; 5543 else 5544 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5545 } else { 5546 // Both conditions must be true at the same time for the loop to exit. 5547 // For now, be conservative. 5548 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5549 if (EL0.Max == EL1.Max) 5550 MaxBECount = EL0.Max; 5551 if (EL0.Exact == EL1.Exact) 5552 BECount = EL0.Exact; 5553 } 5554 5555 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5556 // to be more aggressive when computing BECount than when computing 5557 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact 5558 // to match, but for EL0.Max and EL1.Max to not. 5559 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5560 !isa<SCEVCouldNotCompute>(BECount)) 5561 MaxBECount = BECount; 5562 5563 return ExitLimit(BECount, MaxBECount); 5564 } 5565 if (BO->getOpcode() == Instruction::Or) { 5566 // Recurse on the operands of the or. 5567 bool EitherMayExit = L->contains(FBB); 5568 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5569 ControlsExit && !EitherMayExit); 5570 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5571 ControlsExit && !EitherMayExit); 5572 const SCEV *BECount = getCouldNotCompute(); 5573 const SCEV *MaxBECount = getCouldNotCompute(); 5574 if (EitherMayExit) { 5575 // Both conditions must be false for the loop to continue executing. 5576 // Choose the less conservative count. 5577 if (EL0.Exact == getCouldNotCompute() || 5578 EL1.Exact == getCouldNotCompute()) 5579 BECount = getCouldNotCompute(); 5580 else 5581 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5582 if (EL0.Max == getCouldNotCompute()) 5583 MaxBECount = EL1.Max; 5584 else if (EL1.Max == getCouldNotCompute()) 5585 MaxBECount = EL0.Max; 5586 else 5587 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5588 } else { 5589 // Both conditions must be false at the same time for the loop to exit. 5590 // For now, be conservative. 5591 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5592 if (EL0.Max == EL1.Max) 5593 MaxBECount = EL0.Max; 5594 if (EL0.Exact == EL1.Exact) 5595 BECount = EL0.Exact; 5596 } 5597 5598 return ExitLimit(BECount, MaxBECount); 5599 } 5600 } 5601 5602 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5603 // Proceed to the next level to examine the icmp. 5604 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) 5605 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5606 5607 // Check for a constant condition. These are normally stripped out by 5608 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5609 // preserve the CFG and is temporarily leaving constant conditions 5610 // in place. 5611 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5612 if (L->contains(FBB) == !CI->getZExtValue()) 5613 // The backedge is always taken. 5614 return getCouldNotCompute(); 5615 else 5616 // The backedge is never taken. 5617 return getZero(CI->getType()); 5618 } 5619 5620 // If it's not an integer or pointer comparison then compute it the hard way. 5621 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5622 } 5623 5624 ScalarEvolution::ExitLimit 5625 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 5626 ICmpInst *ExitCond, 5627 BasicBlock *TBB, 5628 BasicBlock *FBB, 5629 bool ControlsExit) { 5630 5631 // If the condition was exit on true, convert the condition to exit on false 5632 ICmpInst::Predicate Cond; 5633 if (!L->contains(FBB)) 5634 Cond = ExitCond->getPredicate(); 5635 else 5636 Cond = ExitCond->getInversePredicate(); 5637 5638 // Handle common loops like: for (X = "string"; *X; ++X) 5639 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 5640 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 5641 ExitLimit ItCnt = 5642 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 5643 if (ItCnt.hasAnyInfo()) 5644 return ItCnt; 5645 } 5646 5647 ExitLimit ShiftEL = computeShiftCompareExitLimit( 5648 ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond); 5649 if (ShiftEL.hasAnyInfo()) 5650 return ShiftEL; 5651 5652 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 5653 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 5654 5655 // Try to evaluate any dependencies out of the loop. 5656 LHS = getSCEVAtScope(LHS, L); 5657 RHS = getSCEVAtScope(RHS, L); 5658 5659 // At this point, we would like to compute how many iterations of the 5660 // loop the predicate will return true for these inputs. 5661 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 5662 // If there is a loop-invariant, force it into the RHS. 5663 std::swap(LHS, RHS); 5664 Cond = ICmpInst::getSwappedPredicate(Cond); 5665 } 5666 5667 // Simplify the operands before analyzing them. 5668 (void)SimplifyICmpOperands(Cond, LHS, RHS); 5669 5670 // If we have a comparison of a chrec against a constant, try to use value 5671 // ranges to answer this query. 5672 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 5673 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 5674 if (AddRec->getLoop() == L) { 5675 // Form the constant range. 5676 ConstantRange CompRange( 5677 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); 5678 5679 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 5680 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 5681 } 5682 5683 switch (Cond) { 5684 case ICmpInst::ICMP_NE: { // while (X != Y) 5685 // Convert to: while (X-Y != 0) 5686 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 5687 if (EL.hasAnyInfo()) return EL; 5688 break; 5689 } 5690 case ICmpInst::ICMP_EQ: { // while (X == Y) 5691 // Convert to: while (X-Y == 0) 5692 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 5693 if (EL.hasAnyInfo()) return EL; 5694 break; 5695 } 5696 case ICmpInst::ICMP_SLT: 5697 case ICmpInst::ICMP_ULT: { // while (X < Y) 5698 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 5699 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit); 5700 if (EL.hasAnyInfo()) return EL; 5701 break; 5702 } 5703 case ICmpInst::ICMP_SGT: 5704 case ICmpInst::ICMP_UGT: { // while (X > Y) 5705 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 5706 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit); 5707 if (EL.hasAnyInfo()) return EL; 5708 break; 5709 } 5710 default: 5711 break; 5712 } 5713 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5714 } 5715 5716 ScalarEvolution::ExitLimit 5717 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 5718 SwitchInst *Switch, 5719 BasicBlock *ExitingBlock, 5720 bool ControlsExit) { 5721 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 5722 5723 // Give up if the exit is the default dest of a switch. 5724 if (Switch->getDefaultDest() == ExitingBlock) 5725 return getCouldNotCompute(); 5726 5727 assert(L->contains(Switch->getDefaultDest()) && 5728 "Default case must not exit the loop!"); 5729 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 5730 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 5731 5732 // while (X != Y) --> while (X-Y != 0) 5733 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 5734 if (EL.hasAnyInfo()) 5735 return EL; 5736 5737 return getCouldNotCompute(); 5738 } 5739 5740 static ConstantInt * 5741 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 5742 ScalarEvolution &SE) { 5743 const SCEV *InVal = SE.getConstant(C); 5744 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 5745 assert(isa<SCEVConstant>(Val) && 5746 "Evaluation of SCEV at constant didn't fold correctly?"); 5747 return cast<SCEVConstant>(Val)->getValue(); 5748 } 5749 5750 /// computeLoadConstantCompareExitLimit - Given an exit condition of 5751 /// 'icmp op load X, cst', try to see if we can compute the backedge 5752 /// execution count. 5753 ScalarEvolution::ExitLimit 5754 ScalarEvolution::computeLoadConstantCompareExitLimit( 5755 LoadInst *LI, 5756 Constant *RHS, 5757 const Loop *L, 5758 ICmpInst::Predicate predicate) { 5759 5760 if (LI->isVolatile()) return getCouldNotCompute(); 5761 5762 // Check to see if the loaded pointer is a getelementptr of a global. 5763 // TODO: Use SCEV instead of manually grubbing with GEPs. 5764 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 5765 if (!GEP) return getCouldNotCompute(); 5766 5767 // Make sure that it is really a constant global we are gepping, with an 5768 // initializer, and make sure the first IDX is really 0. 5769 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 5770 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 5771 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 5772 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 5773 return getCouldNotCompute(); 5774 5775 // Okay, we allow one non-constant index into the GEP instruction. 5776 Value *VarIdx = nullptr; 5777 std::vector<Constant*> Indexes; 5778 unsigned VarIdxNum = 0; 5779 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 5780 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 5781 Indexes.push_back(CI); 5782 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 5783 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 5784 VarIdx = GEP->getOperand(i); 5785 VarIdxNum = i-2; 5786 Indexes.push_back(nullptr); 5787 } 5788 5789 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 5790 if (!VarIdx) 5791 return getCouldNotCompute(); 5792 5793 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 5794 // Check to see if X is a loop variant variable value now. 5795 const SCEV *Idx = getSCEV(VarIdx); 5796 Idx = getSCEVAtScope(Idx, L); 5797 5798 // We can only recognize very limited forms of loop index expressions, in 5799 // particular, only affine AddRec's like {C1,+,C2}. 5800 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 5801 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 5802 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 5803 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 5804 return getCouldNotCompute(); 5805 5806 unsigned MaxSteps = MaxBruteForceIterations; 5807 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 5808 ConstantInt *ItCst = ConstantInt::get( 5809 cast<IntegerType>(IdxExpr->getType()), IterationNum); 5810 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 5811 5812 // Form the GEP offset. 5813 Indexes[VarIdxNum] = Val; 5814 5815 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 5816 Indexes); 5817 if (!Result) break; // Cannot compute! 5818 5819 // Evaluate the condition for this iteration. 5820 Result = ConstantExpr::getICmp(predicate, Result, RHS); 5821 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 5822 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 5823 ++NumArrayLenItCounts; 5824 return getConstant(ItCst); // Found terminating iteration! 5825 } 5826 } 5827 return getCouldNotCompute(); 5828 } 5829 5830 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 5831 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 5832 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 5833 if (!RHS) 5834 return getCouldNotCompute(); 5835 5836 const BasicBlock *Latch = L->getLoopLatch(); 5837 if (!Latch) 5838 return getCouldNotCompute(); 5839 5840 const BasicBlock *Predecessor = L->getLoopPredecessor(); 5841 if (!Predecessor) 5842 return getCouldNotCompute(); 5843 5844 // Return true if V is of the form "LHS `shift_op` <positive constant>". 5845 // Return LHS in OutLHS and shift_opt in OutOpCode. 5846 auto MatchPositiveShift = 5847 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 5848 5849 using namespace PatternMatch; 5850 5851 ConstantInt *ShiftAmt; 5852 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 5853 OutOpCode = Instruction::LShr; 5854 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 5855 OutOpCode = Instruction::AShr; 5856 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 5857 OutOpCode = Instruction::Shl; 5858 else 5859 return false; 5860 5861 return ShiftAmt->getValue().isStrictlyPositive(); 5862 }; 5863 5864 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 5865 // 5866 // loop: 5867 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 5868 // %iv.shifted = lshr i32 %iv, <positive constant> 5869 // 5870 // Return true on a succesful match. Return the corresponding PHI node (%iv 5871 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 5872 auto MatchShiftRecurrence = 5873 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 5874 Optional<Instruction::BinaryOps> PostShiftOpCode; 5875 5876 { 5877 Instruction::BinaryOps OpC; 5878 Value *V; 5879 5880 // If we encounter a shift instruction, "peel off" the shift operation, 5881 // and remember that we did so. Later when we inspect %iv's backedge 5882 // value, we will make sure that the backedge value uses the same 5883 // operation. 5884 // 5885 // Note: the peeled shift operation does not have to be the same 5886 // instruction as the one feeding into the PHI's backedge value. We only 5887 // really care about it being the same *kind* of shift instruction -- 5888 // that's all that is required for our later inferences to hold. 5889 if (MatchPositiveShift(LHS, V, OpC)) { 5890 PostShiftOpCode = OpC; 5891 LHS = V; 5892 } 5893 } 5894 5895 PNOut = dyn_cast<PHINode>(LHS); 5896 if (!PNOut || PNOut->getParent() != L->getHeader()) 5897 return false; 5898 5899 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 5900 Value *OpLHS; 5901 5902 return 5903 // The backedge value for the PHI node must be a shift by a positive 5904 // amount 5905 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 5906 5907 // of the PHI node itself 5908 OpLHS == PNOut && 5909 5910 // and the kind of shift should be match the kind of shift we peeled 5911 // off, if any. 5912 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 5913 }; 5914 5915 PHINode *PN; 5916 Instruction::BinaryOps OpCode; 5917 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 5918 return getCouldNotCompute(); 5919 5920 const DataLayout &DL = getDataLayout(); 5921 5922 // The key rationale for this optimization is that for some kinds of shift 5923 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 5924 // within a finite number of iterations. If the condition guarding the 5925 // backedge (in the sense that the backedge is taken if the condition is true) 5926 // is false for the value the shift recurrence stabilizes to, then we know 5927 // that the backedge is taken only a finite number of times. 5928 5929 ConstantInt *StableValue = nullptr; 5930 switch (OpCode) { 5931 default: 5932 llvm_unreachable("Impossible case!"); 5933 5934 case Instruction::AShr: { 5935 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 5936 // bitwidth(K) iterations. 5937 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 5938 bool KnownZero, KnownOne; 5939 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 5940 Predecessor->getTerminator(), &DT); 5941 auto *Ty = cast<IntegerType>(RHS->getType()); 5942 if (KnownZero) 5943 StableValue = ConstantInt::get(Ty, 0); 5944 else if (KnownOne) 5945 StableValue = ConstantInt::get(Ty, -1, true); 5946 else 5947 return getCouldNotCompute(); 5948 5949 break; 5950 } 5951 case Instruction::LShr: 5952 case Instruction::Shl: 5953 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 5954 // stabilize to 0 in at most bitwidth(K) iterations. 5955 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 5956 break; 5957 } 5958 5959 auto *Result = 5960 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 5961 assert(Result->getType()->isIntegerTy(1) && 5962 "Otherwise cannot be an operand to a branch instruction"); 5963 5964 if (Result->isZeroValue()) { 5965 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 5966 const SCEV *UpperBound = 5967 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 5968 return ExitLimit(getCouldNotCompute(), UpperBound); 5969 } 5970 5971 return getCouldNotCompute(); 5972 } 5973 5974 /// CanConstantFold - Return true if we can constant fold an instruction of the 5975 /// specified type, assuming that all operands were constants. 5976 static bool CanConstantFold(const Instruction *I) { 5977 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 5978 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 5979 isa<LoadInst>(I)) 5980 return true; 5981 5982 if (const CallInst *CI = dyn_cast<CallInst>(I)) 5983 if (const Function *F = CI->getCalledFunction()) 5984 return canConstantFoldCallTo(F); 5985 return false; 5986 } 5987 5988 /// Determine whether this instruction can constant evolve within this loop 5989 /// assuming its operands can all constant evolve. 5990 static bool canConstantEvolve(Instruction *I, const Loop *L) { 5991 // An instruction outside of the loop can't be derived from a loop PHI. 5992 if (!L->contains(I)) return false; 5993 5994 if (isa<PHINode>(I)) { 5995 // We don't currently keep track of the control flow needed to evaluate 5996 // PHIs, so we cannot handle PHIs inside of loops. 5997 return L->getHeader() == I->getParent(); 5998 } 5999 6000 // If we won't be able to constant fold this expression even if the operands 6001 // are constants, bail early. 6002 return CanConstantFold(I); 6003 } 6004 6005 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6006 /// recursing through each instruction operand until reaching a loop header phi. 6007 static PHINode * 6008 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6009 DenseMap<Instruction *, PHINode *> &PHIMap) { 6010 6011 // Otherwise, we can evaluate this instruction if all of its operands are 6012 // constant or derived from a PHI node themselves. 6013 PHINode *PHI = nullptr; 6014 for (Value *Op : UseInst->operands()) { 6015 if (isa<Constant>(Op)) continue; 6016 6017 Instruction *OpInst = dyn_cast<Instruction>(Op); 6018 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6019 6020 PHINode *P = dyn_cast<PHINode>(OpInst); 6021 if (!P) 6022 // If this operand is already visited, reuse the prior result. 6023 // We may have P != PHI if this is the deepest point at which the 6024 // inconsistent paths meet. 6025 P = PHIMap.lookup(OpInst); 6026 if (!P) { 6027 // Recurse and memoize the results, whether a phi is found or not. 6028 // This recursive call invalidates pointers into PHIMap. 6029 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6030 PHIMap[OpInst] = P; 6031 } 6032 if (!P) 6033 return nullptr; // Not evolving from PHI 6034 if (PHI && PHI != P) 6035 return nullptr; // Evolving from multiple different PHIs. 6036 PHI = P; 6037 } 6038 // This is a expression evolving from a constant PHI! 6039 return PHI; 6040 } 6041 6042 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6043 /// in the loop that V is derived from. We allow arbitrary operations along the 6044 /// way, but the operands of an operation must either be constants or a value 6045 /// derived from a constant PHI. If this expression does not fit with these 6046 /// constraints, return null. 6047 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6048 Instruction *I = dyn_cast<Instruction>(V); 6049 if (!I || !canConstantEvolve(I, L)) return nullptr; 6050 6051 if (PHINode *PN = dyn_cast<PHINode>(I)) 6052 return PN; 6053 6054 // Record non-constant instructions contained by the loop. 6055 DenseMap<Instruction *, PHINode *> PHIMap; 6056 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6057 } 6058 6059 /// EvaluateExpression - Given an expression that passes the 6060 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6061 /// in the loop has the value PHIVal. If we can't fold this expression for some 6062 /// reason, return null. 6063 static Constant *EvaluateExpression(Value *V, const Loop *L, 6064 DenseMap<Instruction *, Constant *> &Vals, 6065 const DataLayout &DL, 6066 const TargetLibraryInfo *TLI) { 6067 // Convenient constant check, but redundant for recursive calls. 6068 if (Constant *C = dyn_cast<Constant>(V)) return C; 6069 Instruction *I = dyn_cast<Instruction>(V); 6070 if (!I) return nullptr; 6071 6072 if (Constant *C = Vals.lookup(I)) return C; 6073 6074 // An instruction inside the loop depends on a value outside the loop that we 6075 // weren't given a mapping for, or a value such as a call inside the loop. 6076 if (!canConstantEvolve(I, L)) return nullptr; 6077 6078 // An unmapped PHI can be due to a branch or another loop inside this loop, 6079 // or due to this not being the initial iteration through a loop where we 6080 // couldn't compute the evolution of this particular PHI last time. 6081 if (isa<PHINode>(I)) return nullptr; 6082 6083 std::vector<Constant*> Operands(I->getNumOperands()); 6084 6085 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6086 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6087 if (!Operand) { 6088 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6089 if (!Operands[i]) return nullptr; 6090 continue; 6091 } 6092 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6093 Vals[Operand] = C; 6094 if (!C) return nullptr; 6095 Operands[i] = C; 6096 } 6097 6098 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6099 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6100 Operands[1], DL, TLI); 6101 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6102 if (!LI->isVolatile()) 6103 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6104 } 6105 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6106 } 6107 6108 6109 // If every incoming value to PN except the one for BB is a specific Constant, 6110 // return that, else return nullptr. 6111 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6112 Constant *IncomingVal = nullptr; 6113 6114 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6115 if (PN->getIncomingBlock(i) == BB) 6116 continue; 6117 6118 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6119 if (!CurrentVal) 6120 return nullptr; 6121 6122 if (IncomingVal != CurrentVal) { 6123 if (IncomingVal) 6124 return nullptr; 6125 IncomingVal = CurrentVal; 6126 } 6127 } 6128 6129 return IncomingVal; 6130 } 6131 6132 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6133 /// in the header of its containing loop, we know the loop executes a 6134 /// constant number of times, and the PHI node is just a recurrence 6135 /// involving constants, fold it. 6136 Constant * 6137 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6138 const APInt &BEs, 6139 const Loop *L) { 6140 auto I = ConstantEvolutionLoopExitValue.find(PN); 6141 if (I != ConstantEvolutionLoopExitValue.end()) 6142 return I->second; 6143 6144 if (BEs.ugt(MaxBruteForceIterations)) 6145 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6146 6147 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6148 6149 DenseMap<Instruction *, Constant *> CurrentIterVals; 6150 BasicBlock *Header = L->getHeader(); 6151 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6152 6153 BasicBlock *Latch = L->getLoopLatch(); 6154 if (!Latch) 6155 return nullptr; 6156 6157 for (auto &I : *Header) { 6158 PHINode *PHI = dyn_cast<PHINode>(&I); 6159 if (!PHI) break; 6160 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6161 if (!StartCST) continue; 6162 CurrentIterVals[PHI] = StartCST; 6163 } 6164 if (!CurrentIterVals.count(PN)) 6165 return RetVal = nullptr; 6166 6167 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6168 6169 // Execute the loop symbolically to determine the exit value. 6170 if (BEs.getActiveBits() >= 32) 6171 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6172 6173 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6174 unsigned IterationNum = 0; 6175 const DataLayout &DL = getDataLayout(); 6176 for (; ; ++IterationNum) { 6177 if (IterationNum == NumIterations) 6178 return RetVal = CurrentIterVals[PN]; // Got exit value! 6179 6180 // Compute the value of the PHIs for the next iteration. 6181 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6182 DenseMap<Instruction *, Constant *> NextIterVals; 6183 Constant *NextPHI = 6184 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6185 if (!NextPHI) 6186 return nullptr; // Couldn't evaluate! 6187 NextIterVals[PN] = NextPHI; 6188 6189 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6190 6191 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6192 // cease to be able to evaluate one of them or if they stop evolving, 6193 // because that doesn't necessarily prevent us from computing PN. 6194 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6195 for (const auto &I : CurrentIterVals) { 6196 PHINode *PHI = dyn_cast<PHINode>(I.first); 6197 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6198 PHIsToCompute.emplace_back(PHI, I.second); 6199 } 6200 // We use two distinct loops because EvaluateExpression may invalidate any 6201 // iterators into CurrentIterVals. 6202 for (const auto &I : PHIsToCompute) { 6203 PHINode *PHI = I.first; 6204 Constant *&NextPHI = NextIterVals[PHI]; 6205 if (!NextPHI) { // Not already computed. 6206 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6207 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6208 } 6209 if (NextPHI != I.second) 6210 StoppedEvolving = false; 6211 } 6212 6213 // If all entries in CurrentIterVals == NextIterVals then we can stop 6214 // iterating, the loop can't continue to change. 6215 if (StoppedEvolving) 6216 return RetVal = CurrentIterVals[PN]; 6217 6218 CurrentIterVals.swap(NextIterVals); 6219 } 6220 } 6221 6222 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6223 Value *Cond, 6224 bool ExitWhen) { 6225 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6226 if (!PN) return getCouldNotCompute(); 6227 6228 // If the loop is canonicalized, the PHI will have exactly two entries. 6229 // That's the only form we support here. 6230 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6231 6232 DenseMap<Instruction *, Constant *> CurrentIterVals; 6233 BasicBlock *Header = L->getHeader(); 6234 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6235 6236 BasicBlock *Latch = L->getLoopLatch(); 6237 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6238 6239 for (auto &I : *Header) { 6240 PHINode *PHI = dyn_cast<PHINode>(&I); 6241 if (!PHI) 6242 break; 6243 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6244 if (!StartCST) continue; 6245 CurrentIterVals[PHI] = StartCST; 6246 } 6247 if (!CurrentIterVals.count(PN)) 6248 return getCouldNotCompute(); 6249 6250 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6251 // the loop symbolically to determine when the condition gets a value of 6252 // "ExitWhen". 6253 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6254 const DataLayout &DL = getDataLayout(); 6255 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6256 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6257 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6258 6259 // Couldn't symbolically evaluate. 6260 if (!CondVal) return getCouldNotCompute(); 6261 6262 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6263 ++NumBruteForceTripCountsComputed; 6264 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6265 } 6266 6267 // Update all the PHI nodes for the next iteration. 6268 DenseMap<Instruction *, Constant *> NextIterVals; 6269 6270 // Create a list of which PHIs we need to compute. We want to do this before 6271 // calling EvaluateExpression on them because that may invalidate iterators 6272 // into CurrentIterVals. 6273 SmallVector<PHINode *, 8> PHIsToCompute; 6274 for (const auto &I : CurrentIterVals) { 6275 PHINode *PHI = dyn_cast<PHINode>(I.first); 6276 if (!PHI || PHI->getParent() != Header) continue; 6277 PHIsToCompute.push_back(PHI); 6278 } 6279 for (PHINode *PHI : PHIsToCompute) { 6280 Constant *&NextPHI = NextIterVals[PHI]; 6281 if (NextPHI) continue; // Already computed! 6282 6283 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6284 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6285 } 6286 CurrentIterVals.swap(NextIterVals); 6287 } 6288 6289 // Too many iterations were needed to evaluate. 6290 return getCouldNotCompute(); 6291 } 6292 6293 /// getSCEVAtScope - Return a SCEV expression for the specified value 6294 /// at the specified scope in the program. The L value specifies a loop 6295 /// nest to evaluate the expression at, where null is the top-level or a 6296 /// specified loop is immediately inside of the loop. 6297 /// 6298 /// This method can be used to compute the exit value for a variable defined 6299 /// in a loop by querying what the value will hold in the parent loop. 6300 /// 6301 /// In the case that a relevant loop exit value cannot be computed, the 6302 /// original value V is returned. 6303 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6304 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6305 ValuesAtScopes[V]; 6306 // Check to see if we've folded this expression at this loop before. 6307 for (auto &LS : Values) 6308 if (LS.first == L) 6309 return LS.second ? LS.second : V; 6310 6311 Values.emplace_back(L, nullptr); 6312 6313 // Otherwise compute it. 6314 const SCEV *C = computeSCEVAtScope(V, L); 6315 for (auto &LS : reverse(ValuesAtScopes[V])) 6316 if (LS.first == L) { 6317 LS.second = C; 6318 break; 6319 } 6320 return C; 6321 } 6322 6323 /// This builds up a Constant using the ConstantExpr interface. That way, we 6324 /// will return Constants for objects which aren't represented by a 6325 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6326 /// Returns NULL if the SCEV isn't representable as a Constant. 6327 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6328 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6329 case scCouldNotCompute: 6330 case scAddRecExpr: 6331 break; 6332 case scConstant: 6333 return cast<SCEVConstant>(V)->getValue(); 6334 case scUnknown: 6335 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6336 case scSignExtend: { 6337 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6338 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6339 return ConstantExpr::getSExt(CastOp, SS->getType()); 6340 break; 6341 } 6342 case scZeroExtend: { 6343 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6344 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6345 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6346 break; 6347 } 6348 case scTruncate: { 6349 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6350 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6351 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6352 break; 6353 } 6354 case scAddExpr: { 6355 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6356 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6357 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6358 unsigned AS = PTy->getAddressSpace(); 6359 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6360 C = ConstantExpr::getBitCast(C, DestPtrTy); 6361 } 6362 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6363 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6364 if (!C2) return nullptr; 6365 6366 // First pointer! 6367 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6368 unsigned AS = C2->getType()->getPointerAddressSpace(); 6369 std::swap(C, C2); 6370 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6371 // The offsets have been converted to bytes. We can add bytes to an 6372 // i8* by GEP with the byte count in the first index. 6373 C = ConstantExpr::getBitCast(C, DestPtrTy); 6374 } 6375 6376 // Don't bother trying to sum two pointers. We probably can't 6377 // statically compute a load that results from it anyway. 6378 if (C2->getType()->isPointerTy()) 6379 return nullptr; 6380 6381 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6382 if (PTy->getElementType()->isStructTy()) 6383 C2 = ConstantExpr::getIntegerCast( 6384 C2, Type::getInt32Ty(C->getContext()), true); 6385 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6386 } else 6387 C = ConstantExpr::getAdd(C, C2); 6388 } 6389 return C; 6390 } 6391 break; 6392 } 6393 case scMulExpr: { 6394 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6395 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6396 // Don't bother with pointers at all. 6397 if (C->getType()->isPointerTy()) return nullptr; 6398 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6399 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6400 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6401 C = ConstantExpr::getMul(C, C2); 6402 } 6403 return C; 6404 } 6405 break; 6406 } 6407 case scUDivExpr: { 6408 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6409 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6410 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6411 if (LHS->getType() == RHS->getType()) 6412 return ConstantExpr::getUDiv(LHS, RHS); 6413 break; 6414 } 6415 case scSMaxExpr: 6416 case scUMaxExpr: 6417 break; // TODO: smax, umax. 6418 } 6419 return nullptr; 6420 } 6421 6422 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6423 if (isa<SCEVConstant>(V)) return V; 6424 6425 // If this instruction is evolved from a constant-evolving PHI, compute the 6426 // exit value from the loop without using SCEVs. 6427 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6428 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6429 const Loop *LI = this->LI[I->getParent()]; 6430 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6431 if (PHINode *PN = dyn_cast<PHINode>(I)) 6432 if (PN->getParent() == LI->getHeader()) { 6433 // Okay, there is no closed form solution for the PHI node. Check 6434 // to see if the loop that contains it has a known backedge-taken 6435 // count. If so, we may be able to force computation of the exit 6436 // value. 6437 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6438 if (const SCEVConstant *BTCC = 6439 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6440 // Okay, we know how many times the containing loop executes. If 6441 // this is a constant evolving PHI node, get the final value at 6442 // the specified iteration number. 6443 Constant *RV = 6444 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6445 if (RV) return getSCEV(RV); 6446 } 6447 } 6448 6449 // Okay, this is an expression that we cannot symbolically evaluate 6450 // into a SCEV. Check to see if it's possible to symbolically evaluate 6451 // the arguments into constants, and if so, try to constant propagate the 6452 // result. This is particularly useful for computing loop exit values. 6453 if (CanConstantFold(I)) { 6454 SmallVector<Constant *, 4> Operands; 6455 bool MadeImprovement = false; 6456 for (Value *Op : I->operands()) { 6457 if (Constant *C = dyn_cast<Constant>(Op)) { 6458 Operands.push_back(C); 6459 continue; 6460 } 6461 6462 // If any of the operands is non-constant and if they are 6463 // non-integer and non-pointer, don't even try to analyze them 6464 // with scev techniques. 6465 if (!isSCEVable(Op->getType())) 6466 return V; 6467 6468 const SCEV *OrigV = getSCEV(Op); 6469 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6470 MadeImprovement |= OrigV != OpV; 6471 6472 Constant *C = BuildConstantFromSCEV(OpV); 6473 if (!C) return V; 6474 if (C->getType() != Op->getType()) 6475 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6476 Op->getType(), 6477 false), 6478 C, Op->getType()); 6479 Operands.push_back(C); 6480 } 6481 6482 // Check to see if getSCEVAtScope actually made an improvement. 6483 if (MadeImprovement) { 6484 Constant *C = nullptr; 6485 const DataLayout &DL = getDataLayout(); 6486 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6487 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6488 Operands[1], DL, &TLI); 6489 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6490 if (!LI->isVolatile()) 6491 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6492 } else 6493 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6494 if (!C) return V; 6495 return getSCEV(C); 6496 } 6497 } 6498 } 6499 6500 // This is some other type of SCEVUnknown, just return it. 6501 return V; 6502 } 6503 6504 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6505 // Avoid performing the look-up in the common case where the specified 6506 // expression has no loop-variant portions. 6507 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6508 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6509 if (OpAtScope != Comm->getOperand(i)) { 6510 // Okay, at least one of these operands is loop variant but might be 6511 // foldable. Build a new instance of the folded commutative expression. 6512 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6513 Comm->op_begin()+i); 6514 NewOps.push_back(OpAtScope); 6515 6516 for (++i; i != e; ++i) { 6517 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6518 NewOps.push_back(OpAtScope); 6519 } 6520 if (isa<SCEVAddExpr>(Comm)) 6521 return getAddExpr(NewOps); 6522 if (isa<SCEVMulExpr>(Comm)) 6523 return getMulExpr(NewOps); 6524 if (isa<SCEVSMaxExpr>(Comm)) 6525 return getSMaxExpr(NewOps); 6526 if (isa<SCEVUMaxExpr>(Comm)) 6527 return getUMaxExpr(NewOps); 6528 llvm_unreachable("Unknown commutative SCEV type!"); 6529 } 6530 } 6531 // If we got here, all operands are loop invariant. 6532 return Comm; 6533 } 6534 6535 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6536 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6537 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6538 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6539 return Div; // must be loop invariant 6540 return getUDivExpr(LHS, RHS); 6541 } 6542 6543 // If this is a loop recurrence for a loop that does not contain L, then we 6544 // are dealing with the final value computed by the loop. 6545 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6546 // First, attempt to evaluate each operand. 6547 // Avoid performing the look-up in the common case where the specified 6548 // expression has no loop-variant portions. 6549 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6550 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6551 if (OpAtScope == AddRec->getOperand(i)) 6552 continue; 6553 6554 // Okay, at least one of these operands is loop variant but might be 6555 // foldable. Build a new instance of the folded commutative expression. 6556 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6557 AddRec->op_begin()+i); 6558 NewOps.push_back(OpAtScope); 6559 for (++i; i != e; ++i) 6560 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6561 6562 const SCEV *FoldedRec = 6563 getAddRecExpr(NewOps, AddRec->getLoop(), 6564 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6565 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6566 // The addrec may be folded to a nonrecurrence, for example, if the 6567 // induction variable is multiplied by zero after constant folding. Go 6568 // ahead and return the folded value. 6569 if (!AddRec) 6570 return FoldedRec; 6571 break; 6572 } 6573 6574 // If the scope is outside the addrec's loop, evaluate it by using the 6575 // loop exit value of the addrec. 6576 if (!AddRec->getLoop()->contains(L)) { 6577 // To evaluate this recurrence, we need to know how many times the AddRec 6578 // loop iterates. Compute this now. 6579 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6580 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6581 6582 // Then, evaluate the AddRec. 6583 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6584 } 6585 6586 return AddRec; 6587 } 6588 6589 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6590 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6591 if (Op == Cast->getOperand()) 6592 return Cast; // must be loop invariant 6593 return getZeroExtendExpr(Op, Cast->getType()); 6594 } 6595 6596 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6597 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6598 if (Op == Cast->getOperand()) 6599 return Cast; // must be loop invariant 6600 return getSignExtendExpr(Op, Cast->getType()); 6601 } 6602 6603 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6604 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6605 if (Op == Cast->getOperand()) 6606 return Cast; // must be loop invariant 6607 return getTruncateExpr(Op, Cast->getType()); 6608 } 6609 6610 llvm_unreachable("Unknown SCEV type!"); 6611 } 6612 6613 /// getSCEVAtScope - This is a convenience function which does 6614 /// getSCEVAtScope(getSCEV(V), L). 6615 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6616 return getSCEVAtScope(getSCEV(V), L); 6617 } 6618 6619 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 6620 /// following equation: 6621 /// 6622 /// A * X = B (mod N) 6623 /// 6624 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6625 /// A and B isn't important. 6626 /// 6627 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6628 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6629 ScalarEvolution &SE) { 6630 uint32_t BW = A.getBitWidth(); 6631 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6632 assert(A != 0 && "A must be non-zero."); 6633 6634 // 1. D = gcd(A, N) 6635 // 6636 // The gcd of A and N may have only one prime factor: 2. The number of 6637 // trailing zeros in A is its multiplicity 6638 uint32_t Mult2 = A.countTrailingZeros(); 6639 // D = 2^Mult2 6640 6641 // 2. Check if B is divisible by D. 6642 // 6643 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 6644 // is not less than multiplicity of this prime factor for D. 6645 if (B.countTrailingZeros() < Mult2) 6646 return SE.getCouldNotCompute(); 6647 6648 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 6649 // modulo (N / D). 6650 // 6651 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 6652 // bit width during computations. 6653 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 6654 APInt Mod(BW + 1, 0); 6655 Mod.setBit(BW - Mult2); // Mod = N / D 6656 APInt I = AD.multiplicativeInverse(Mod); 6657 6658 // 4. Compute the minimum unsigned root of the equation: 6659 // I * (B / D) mod (N / D) 6660 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 6661 6662 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 6663 // bits. 6664 return SE.getConstant(Result.trunc(BW)); 6665 } 6666 6667 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 6668 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 6669 /// might be the same) or two SCEVCouldNotCompute objects. 6670 /// 6671 static std::pair<const SCEV *,const SCEV *> 6672 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 6673 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 6674 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 6675 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 6676 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 6677 6678 // We currently can only solve this if the coefficients are constants. 6679 if (!LC || !MC || !NC) { 6680 const SCEV *CNC = SE.getCouldNotCompute(); 6681 return {CNC, CNC}; 6682 } 6683 6684 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 6685 const APInt &L = LC->getAPInt(); 6686 const APInt &M = MC->getAPInt(); 6687 const APInt &N = NC->getAPInt(); 6688 APInt Two(BitWidth, 2); 6689 APInt Four(BitWidth, 4); 6690 6691 { 6692 using namespace APIntOps; 6693 const APInt& C = L; 6694 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 6695 // The B coefficient is M-N/2 6696 APInt B(M); 6697 B -= sdiv(N,Two); 6698 6699 // The A coefficient is N/2 6700 APInt A(N.sdiv(Two)); 6701 6702 // Compute the B^2-4ac term. 6703 APInt SqrtTerm(B); 6704 SqrtTerm *= B; 6705 SqrtTerm -= Four * (A * C); 6706 6707 if (SqrtTerm.isNegative()) { 6708 // The loop is provably infinite. 6709 const SCEV *CNC = SE.getCouldNotCompute(); 6710 return {CNC, CNC}; 6711 } 6712 6713 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 6714 // integer value or else APInt::sqrt() will assert. 6715 APInt SqrtVal(SqrtTerm.sqrt()); 6716 6717 // Compute the two solutions for the quadratic formula. 6718 // The divisions must be performed as signed divisions. 6719 APInt NegB(-B); 6720 APInt TwoA(A << 1); 6721 if (TwoA.isMinValue()) { 6722 const SCEV *CNC = SE.getCouldNotCompute(); 6723 return {CNC, CNC}; 6724 } 6725 6726 LLVMContext &Context = SE.getContext(); 6727 6728 ConstantInt *Solution1 = 6729 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 6730 ConstantInt *Solution2 = 6731 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 6732 6733 return {SE.getConstant(Solution1), SE.getConstant(Solution2)}; 6734 } // end APIntOps namespace 6735 } 6736 6737 /// HowFarToZero - Return the number of times a backedge comparing the specified 6738 /// value to zero will execute. If not computable, return CouldNotCompute. 6739 /// 6740 /// This is only used for loops with a "x != y" exit test. The exit condition is 6741 /// now expressed as a single expression, V = x-y. So the exit test is 6742 /// effectively V != 0. We know and take advantage of the fact that this 6743 /// expression only being used in a comparison by zero context. 6744 ScalarEvolution::ExitLimit 6745 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) { 6746 // If the value is a constant 6747 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 6748 // If the value is already zero, the branch will execute zero times. 6749 if (C->getValue()->isZero()) return C; 6750 return getCouldNotCompute(); // Otherwise it will loop infinitely. 6751 } 6752 6753 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 6754 if (!AddRec || AddRec->getLoop() != L) 6755 return getCouldNotCompute(); 6756 6757 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 6758 // the quadratic equation to solve it. 6759 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 6760 std::pair<const SCEV *,const SCEV *> Roots = 6761 SolveQuadraticEquation(AddRec, *this); 6762 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 6763 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 6764 if (R1 && R2) { 6765 // Pick the smallest positive root value. 6766 if (ConstantInt *CB = 6767 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, 6768 R1->getValue(), 6769 R2->getValue()))) { 6770 if (!CB->getZExtValue()) 6771 std::swap(R1, R2); // R1 is the minimum root now. 6772 6773 // We can only use this value if the chrec ends up with an exact zero 6774 // value at this index. When solving for "X*X != 5", for example, we 6775 // should not accept a root of 2. 6776 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 6777 if (Val->isZero()) 6778 return R1; // We found a quadratic root! 6779 } 6780 } 6781 return getCouldNotCompute(); 6782 } 6783 6784 // Otherwise we can only handle this if it is affine. 6785 if (!AddRec->isAffine()) 6786 return getCouldNotCompute(); 6787 6788 // If this is an affine expression, the execution count of this branch is 6789 // the minimum unsigned root of the following equation: 6790 // 6791 // Start + Step*N = 0 (mod 2^BW) 6792 // 6793 // equivalent to: 6794 // 6795 // Step*N = -Start (mod 2^BW) 6796 // 6797 // where BW is the common bit width of Start and Step. 6798 6799 // Get the initial value for the loop. 6800 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 6801 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 6802 6803 // For now we handle only constant steps. 6804 // 6805 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 6806 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 6807 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 6808 // We have not yet seen any such cases. 6809 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 6810 if (!StepC || StepC->getValue()->equalsInt(0)) 6811 return getCouldNotCompute(); 6812 6813 // For positive steps (counting up until unsigned overflow): 6814 // N = -Start/Step (as unsigned) 6815 // For negative steps (counting down to zero): 6816 // N = Start/-Step 6817 // First compute the unsigned distance from zero in the direction of Step. 6818 bool CountDown = StepC->getAPInt().isNegative(); 6819 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 6820 6821 // Handle unitary steps, which cannot wraparound. 6822 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 6823 // N = Distance (as unsigned) 6824 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 6825 ConstantRange CR = getUnsignedRange(Start); 6826 const SCEV *MaxBECount; 6827 if (!CountDown && CR.getUnsignedMin().isMinValue()) 6828 // When counting up, the worst starting value is 1, not 0. 6829 MaxBECount = CR.getUnsignedMax().isMinValue() 6830 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 6831 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 6832 else 6833 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 6834 : -CR.getUnsignedMin()); 6835 return ExitLimit(Distance, MaxBECount); 6836 } 6837 6838 // As a special case, handle the instance where Step is a positive power of 6839 // two. In this case, determining whether Step divides Distance evenly can be 6840 // done by counting and comparing the number of trailing zeros of Step and 6841 // Distance. 6842 if (!CountDown) { 6843 const APInt &StepV = StepC->getAPInt(); 6844 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 6845 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 6846 // case is not handled as this code is guarded by !CountDown. 6847 if (StepV.isPowerOf2() && 6848 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 6849 // Here we've constrained the equation to be of the form 6850 // 6851 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 6852 // 6853 // where we're operating on a W bit wide integer domain and k is 6854 // non-negative. The smallest unsigned solution for X is the trip count. 6855 // 6856 // (0) is equivalent to: 6857 // 6858 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 6859 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 6860 // <=> 2^k * Distance' - X = L * 2^(W - N) 6861 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 6862 // 6863 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 6864 // by 2^(W - N). 6865 // 6866 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 6867 // 6868 // E.g. say we're solving 6869 // 6870 // 2 * Val = 2 * X (in i8) ... (3) 6871 // 6872 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 6873 // 6874 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 6875 // necessarily the smallest unsigned value of X that satisfies (3). 6876 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 6877 // is i8 1, not i8 -127 6878 6879 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 6880 6881 // Since SCEV does not have a URem node, we construct one using a truncate 6882 // and a zero extend. 6883 6884 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 6885 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 6886 auto *WideTy = Distance->getType(); 6887 6888 return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 6889 } 6890 } 6891 6892 // If the condition controls loop exit (the loop exits only if the expression 6893 // is true) and the addition is no-wrap we can use unsigned divide to 6894 // compute the backedge count. In this case, the step may not divide the 6895 // distance, but we don't care because if the condition is "missed" the loop 6896 // will have undefined behavior due to wrapping. 6897 if (ControlsExit && AddRec->hasNoSelfWrap()) { 6898 const SCEV *Exact = 6899 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 6900 return ExitLimit(Exact, Exact); 6901 } 6902 6903 // Then, try to solve the above equation provided that Start is constant. 6904 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 6905 return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(), 6906 *this); 6907 return getCouldNotCompute(); 6908 } 6909 6910 /// HowFarToNonZero - Return the number of times a backedge checking the 6911 /// specified value for nonzero will execute. If not computable, return 6912 /// CouldNotCompute 6913 ScalarEvolution::ExitLimit 6914 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { 6915 // Loops that look like: while (X == 0) are very strange indeed. We don't 6916 // handle them yet except for the trivial case. This could be expanded in the 6917 // future as needed. 6918 6919 // If the value is a constant, check to see if it is known to be non-zero 6920 // already. If so, the backedge will execute zero times. 6921 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 6922 if (!C->getValue()->isNullValue()) 6923 return getZero(C->getType()); 6924 return getCouldNotCompute(); // Otherwise it will loop infinitely. 6925 } 6926 6927 // We could implement others, but I really doubt anyone writes loops like 6928 // this, and if they did, they would already be constant folded. 6929 return getCouldNotCompute(); 6930 } 6931 6932 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 6933 /// (which may not be an immediate predecessor) which has exactly one 6934 /// successor from which BB is reachable, or null if no such block is 6935 /// found. 6936 /// 6937 std::pair<BasicBlock *, BasicBlock *> 6938 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 6939 // If the block has a unique predecessor, then there is no path from the 6940 // predecessor to the block that does not go through the direct edge 6941 // from the predecessor to the block. 6942 if (BasicBlock *Pred = BB->getSinglePredecessor()) 6943 return {Pred, BB}; 6944 6945 // A loop's header is defined to be a block that dominates the loop. 6946 // If the header has a unique predecessor outside the loop, it must be 6947 // a block that has exactly one successor that can reach the loop. 6948 if (Loop *L = LI.getLoopFor(BB)) 6949 return {L->getLoopPredecessor(), L->getHeader()}; 6950 6951 return {nullptr, nullptr}; 6952 } 6953 6954 /// HasSameValue - SCEV structural equivalence is usually sufficient for 6955 /// testing whether two expressions are equal, however for the purposes of 6956 /// looking for a condition guarding a loop, it can be useful to be a little 6957 /// more general, since a front-end may have replicated the controlling 6958 /// expression. 6959 /// 6960 static bool HasSameValue(const SCEV *A, const SCEV *B) { 6961 // Quick check to see if they are the same SCEV. 6962 if (A == B) return true; 6963 6964 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 6965 // Not all instructions that are "identical" compute the same value. For 6966 // instance, two distinct alloca instructions allocating the same type are 6967 // identical and do not read memory; but compute distinct values. 6968 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 6969 }; 6970 6971 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 6972 // two different instructions with the same value. Check for this case. 6973 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 6974 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 6975 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 6976 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 6977 if (ComputesEqualValues(AI, BI)) 6978 return true; 6979 6980 // Otherwise assume they may have a different value. 6981 return false; 6982 } 6983 6984 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 6985 /// predicate Pred. Return true iff any changes were made. 6986 /// 6987 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 6988 const SCEV *&LHS, const SCEV *&RHS, 6989 unsigned Depth) { 6990 bool Changed = false; 6991 6992 // If we hit the max recursion limit bail out. 6993 if (Depth >= 3) 6994 return false; 6995 6996 // Canonicalize a constant to the right side. 6997 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 6998 // Check for both operands constant. 6999 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7000 if (ConstantExpr::getICmp(Pred, 7001 LHSC->getValue(), 7002 RHSC->getValue())->isNullValue()) 7003 goto trivially_false; 7004 else 7005 goto trivially_true; 7006 } 7007 // Otherwise swap the operands to put the constant on the right. 7008 std::swap(LHS, RHS); 7009 Pred = ICmpInst::getSwappedPredicate(Pred); 7010 Changed = true; 7011 } 7012 7013 // If we're comparing an addrec with a value which is loop-invariant in the 7014 // addrec's loop, put the addrec on the left. Also make a dominance check, 7015 // as both operands could be addrecs loop-invariant in each other's loop. 7016 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7017 const Loop *L = AR->getLoop(); 7018 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7019 std::swap(LHS, RHS); 7020 Pred = ICmpInst::getSwappedPredicate(Pred); 7021 Changed = true; 7022 } 7023 } 7024 7025 // If there's a constant operand, canonicalize comparisons with boundary 7026 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7027 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7028 const APInt &RA = RC->getAPInt(); 7029 switch (Pred) { 7030 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 7031 case ICmpInst::ICMP_EQ: 7032 case ICmpInst::ICMP_NE: 7033 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7034 if (!RA) 7035 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7036 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7037 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7038 ME->getOperand(0)->isAllOnesValue()) { 7039 RHS = AE->getOperand(1); 7040 LHS = ME->getOperand(1); 7041 Changed = true; 7042 } 7043 break; 7044 case ICmpInst::ICMP_UGE: 7045 if ((RA - 1).isMinValue()) { 7046 Pred = ICmpInst::ICMP_NE; 7047 RHS = getConstant(RA - 1); 7048 Changed = true; 7049 break; 7050 } 7051 if (RA.isMaxValue()) { 7052 Pred = ICmpInst::ICMP_EQ; 7053 Changed = true; 7054 break; 7055 } 7056 if (RA.isMinValue()) goto trivially_true; 7057 7058 Pred = ICmpInst::ICMP_UGT; 7059 RHS = getConstant(RA - 1); 7060 Changed = true; 7061 break; 7062 case ICmpInst::ICMP_ULE: 7063 if ((RA + 1).isMaxValue()) { 7064 Pred = ICmpInst::ICMP_NE; 7065 RHS = getConstant(RA + 1); 7066 Changed = true; 7067 break; 7068 } 7069 if (RA.isMinValue()) { 7070 Pred = ICmpInst::ICMP_EQ; 7071 Changed = true; 7072 break; 7073 } 7074 if (RA.isMaxValue()) goto trivially_true; 7075 7076 Pred = ICmpInst::ICMP_ULT; 7077 RHS = getConstant(RA + 1); 7078 Changed = true; 7079 break; 7080 case ICmpInst::ICMP_SGE: 7081 if ((RA - 1).isMinSignedValue()) { 7082 Pred = ICmpInst::ICMP_NE; 7083 RHS = getConstant(RA - 1); 7084 Changed = true; 7085 break; 7086 } 7087 if (RA.isMaxSignedValue()) { 7088 Pred = ICmpInst::ICMP_EQ; 7089 Changed = true; 7090 break; 7091 } 7092 if (RA.isMinSignedValue()) goto trivially_true; 7093 7094 Pred = ICmpInst::ICMP_SGT; 7095 RHS = getConstant(RA - 1); 7096 Changed = true; 7097 break; 7098 case ICmpInst::ICMP_SLE: 7099 if ((RA + 1).isMaxSignedValue()) { 7100 Pred = ICmpInst::ICMP_NE; 7101 RHS = getConstant(RA + 1); 7102 Changed = true; 7103 break; 7104 } 7105 if (RA.isMinSignedValue()) { 7106 Pred = ICmpInst::ICMP_EQ; 7107 Changed = true; 7108 break; 7109 } 7110 if (RA.isMaxSignedValue()) goto trivially_true; 7111 7112 Pred = ICmpInst::ICMP_SLT; 7113 RHS = getConstant(RA + 1); 7114 Changed = true; 7115 break; 7116 case ICmpInst::ICMP_UGT: 7117 if (RA.isMinValue()) { 7118 Pred = ICmpInst::ICMP_NE; 7119 Changed = true; 7120 break; 7121 } 7122 if ((RA + 1).isMaxValue()) { 7123 Pred = ICmpInst::ICMP_EQ; 7124 RHS = getConstant(RA + 1); 7125 Changed = true; 7126 break; 7127 } 7128 if (RA.isMaxValue()) goto trivially_false; 7129 break; 7130 case ICmpInst::ICMP_ULT: 7131 if (RA.isMaxValue()) { 7132 Pred = ICmpInst::ICMP_NE; 7133 Changed = true; 7134 break; 7135 } 7136 if ((RA - 1).isMinValue()) { 7137 Pred = ICmpInst::ICMP_EQ; 7138 RHS = getConstant(RA - 1); 7139 Changed = true; 7140 break; 7141 } 7142 if (RA.isMinValue()) goto trivially_false; 7143 break; 7144 case ICmpInst::ICMP_SGT: 7145 if (RA.isMinSignedValue()) { 7146 Pred = ICmpInst::ICMP_NE; 7147 Changed = true; 7148 break; 7149 } 7150 if ((RA + 1).isMaxSignedValue()) { 7151 Pred = ICmpInst::ICMP_EQ; 7152 RHS = getConstant(RA + 1); 7153 Changed = true; 7154 break; 7155 } 7156 if (RA.isMaxSignedValue()) goto trivially_false; 7157 break; 7158 case ICmpInst::ICMP_SLT: 7159 if (RA.isMaxSignedValue()) { 7160 Pred = ICmpInst::ICMP_NE; 7161 Changed = true; 7162 break; 7163 } 7164 if ((RA - 1).isMinSignedValue()) { 7165 Pred = ICmpInst::ICMP_EQ; 7166 RHS = getConstant(RA - 1); 7167 Changed = true; 7168 break; 7169 } 7170 if (RA.isMinSignedValue()) goto trivially_false; 7171 break; 7172 } 7173 } 7174 7175 // Check for obvious equality. 7176 if (HasSameValue(LHS, RHS)) { 7177 if (ICmpInst::isTrueWhenEqual(Pred)) 7178 goto trivially_true; 7179 if (ICmpInst::isFalseWhenEqual(Pred)) 7180 goto trivially_false; 7181 } 7182 7183 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7184 // adding or subtracting 1 from one of the operands. 7185 switch (Pred) { 7186 case ICmpInst::ICMP_SLE: 7187 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7188 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7189 SCEV::FlagNSW); 7190 Pred = ICmpInst::ICMP_SLT; 7191 Changed = true; 7192 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7193 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7194 SCEV::FlagNSW); 7195 Pred = ICmpInst::ICMP_SLT; 7196 Changed = true; 7197 } 7198 break; 7199 case ICmpInst::ICMP_SGE: 7200 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7201 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7202 SCEV::FlagNSW); 7203 Pred = ICmpInst::ICMP_SGT; 7204 Changed = true; 7205 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7206 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7207 SCEV::FlagNSW); 7208 Pred = ICmpInst::ICMP_SGT; 7209 Changed = true; 7210 } 7211 break; 7212 case ICmpInst::ICMP_ULE: 7213 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7214 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7215 SCEV::FlagNUW); 7216 Pred = ICmpInst::ICMP_ULT; 7217 Changed = true; 7218 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7219 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7220 Pred = ICmpInst::ICMP_ULT; 7221 Changed = true; 7222 } 7223 break; 7224 case ICmpInst::ICMP_UGE: 7225 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7226 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7227 Pred = ICmpInst::ICMP_UGT; 7228 Changed = true; 7229 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7230 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7231 SCEV::FlagNUW); 7232 Pred = ICmpInst::ICMP_UGT; 7233 Changed = true; 7234 } 7235 break; 7236 default: 7237 break; 7238 } 7239 7240 // TODO: More simplifications are possible here. 7241 7242 // Recursively simplify until we either hit a recursion limit or nothing 7243 // changes. 7244 if (Changed) 7245 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7246 7247 return Changed; 7248 7249 trivially_true: 7250 // Return 0 == 0. 7251 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7252 Pred = ICmpInst::ICMP_EQ; 7253 return true; 7254 7255 trivially_false: 7256 // Return 0 != 0. 7257 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7258 Pred = ICmpInst::ICMP_NE; 7259 return true; 7260 } 7261 7262 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7263 return getSignedRange(S).getSignedMax().isNegative(); 7264 } 7265 7266 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7267 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7268 } 7269 7270 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7271 return !getSignedRange(S).getSignedMin().isNegative(); 7272 } 7273 7274 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7275 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7276 } 7277 7278 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7279 return isKnownNegative(S) || isKnownPositive(S); 7280 } 7281 7282 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7283 const SCEV *LHS, const SCEV *RHS) { 7284 // Canonicalize the inputs first. 7285 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7286 7287 // If LHS or RHS is an addrec, check to see if the condition is true in 7288 // every iteration of the loop. 7289 // If LHS and RHS are both addrec, both conditions must be true in 7290 // every iteration of the loop. 7291 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7292 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7293 bool LeftGuarded = false; 7294 bool RightGuarded = false; 7295 if (LAR) { 7296 const Loop *L = LAR->getLoop(); 7297 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7298 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7299 if (!RAR) return true; 7300 LeftGuarded = true; 7301 } 7302 } 7303 if (RAR) { 7304 const Loop *L = RAR->getLoop(); 7305 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7306 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7307 if (!LAR) return true; 7308 RightGuarded = true; 7309 } 7310 } 7311 if (LeftGuarded && RightGuarded) 7312 return true; 7313 7314 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7315 return true; 7316 7317 // Otherwise see what can be done with known constant ranges. 7318 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7319 } 7320 7321 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7322 ICmpInst::Predicate Pred, 7323 bool &Increasing) { 7324 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7325 7326 #ifndef NDEBUG 7327 // Verify an invariant: inverting the predicate should turn a monotonically 7328 // increasing change to a monotonically decreasing one, and vice versa. 7329 bool IncreasingSwapped; 7330 bool ResultSwapped = isMonotonicPredicateImpl( 7331 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7332 7333 assert(Result == ResultSwapped && "should be able to analyze both!"); 7334 if (ResultSwapped) 7335 assert(Increasing == !IncreasingSwapped && 7336 "monotonicity should flip as we flip the predicate"); 7337 #endif 7338 7339 return Result; 7340 } 7341 7342 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7343 ICmpInst::Predicate Pred, 7344 bool &Increasing) { 7345 7346 // A zero step value for LHS means the induction variable is essentially a 7347 // loop invariant value. We don't really depend on the predicate actually 7348 // flipping from false to true (for increasing predicates, and the other way 7349 // around for decreasing predicates), all we care about is that *if* the 7350 // predicate changes then it only changes from false to true. 7351 // 7352 // A zero step value in itself is not very useful, but there may be places 7353 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7354 // as general as possible. 7355 7356 switch (Pred) { 7357 default: 7358 return false; // Conservative answer 7359 7360 case ICmpInst::ICMP_UGT: 7361 case ICmpInst::ICMP_UGE: 7362 case ICmpInst::ICMP_ULT: 7363 case ICmpInst::ICMP_ULE: 7364 if (!LHS->hasNoUnsignedWrap()) 7365 return false; 7366 7367 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7368 return true; 7369 7370 case ICmpInst::ICMP_SGT: 7371 case ICmpInst::ICMP_SGE: 7372 case ICmpInst::ICMP_SLT: 7373 case ICmpInst::ICMP_SLE: { 7374 if (!LHS->hasNoSignedWrap()) 7375 return false; 7376 7377 const SCEV *Step = LHS->getStepRecurrence(*this); 7378 7379 if (isKnownNonNegative(Step)) { 7380 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7381 return true; 7382 } 7383 7384 if (isKnownNonPositive(Step)) { 7385 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7386 return true; 7387 } 7388 7389 return false; 7390 } 7391 7392 } 7393 7394 llvm_unreachable("switch has default clause!"); 7395 } 7396 7397 bool ScalarEvolution::isLoopInvariantPredicate( 7398 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7399 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7400 const SCEV *&InvariantRHS) { 7401 7402 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7403 if (!isLoopInvariant(RHS, L)) { 7404 if (!isLoopInvariant(LHS, L)) 7405 return false; 7406 7407 std::swap(LHS, RHS); 7408 Pred = ICmpInst::getSwappedPredicate(Pred); 7409 } 7410 7411 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7412 if (!ArLHS || ArLHS->getLoop() != L) 7413 return false; 7414 7415 bool Increasing; 7416 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7417 return false; 7418 7419 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7420 // true as the loop iterates, and the backedge is control dependent on 7421 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7422 // 7423 // * if the predicate was false in the first iteration then the predicate 7424 // is never evaluated again, since the loop exits without taking the 7425 // backedge. 7426 // * if the predicate was true in the first iteration then it will 7427 // continue to be true for all future iterations since it is 7428 // monotonically increasing. 7429 // 7430 // For both the above possibilities, we can replace the loop varying 7431 // predicate with its value on the first iteration of the loop (which is 7432 // loop invariant). 7433 // 7434 // A similar reasoning applies for a monotonically decreasing predicate, by 7435 // replacing true with false and false with true in the above two bullets. 7436 7437 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7438 7439 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7440 return false; 7441 7442 InvariantPred = Pred; 7443 InvariantLHS = ArLHS->getStart(); 7444 InvariantRHS = RHS; 7445 return true; 7446 } 7447 7448 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7449 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7450 if (HasSameValue(LHS, RHS)) 7451 return ICmpInst::isTrueWhenEqual(Pred); 7452 7453 // This code is split out from isKnownPredicate because it is called from 7454 // within isLoopEntryGuardedByCond. 7455 7456 auto CheckRanges = 7457 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7458 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7459 .contains(RangeLHS); 7460 }; 7461 7462 // The check at the top of the function catches the case where the values are 7463 // known to be equal. 7464 if (Pred == CmpInst::ICMP_EQ) 7465 return false; 7466 7467 if (Pred == CmpInst::ICMP_NE) 7468 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7469 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7470 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7471 7472 if (CmpInst::isSigned(Pred)) 7473 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7474 7475 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7476 } 7477 7478 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7479 const SCEV *LHS, 7480 const SCEV *RHS) { 7481 7482 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7483 // Return Y via OutY. 7484 auto MatchBinaryAddToConst = 7485 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7486 SCEV::NoWrapFlags ExpectedFlags) { 7487 const SCEV *NonConstOp, *ConstOp; 7488 SCEV::NoWrapFlags FlagsPresent; 7489 7490 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7491 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7492 return false; 7493 7494 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7495 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7496 }; 7497 7498 APInt C; 7499 7500 switch (Pred) { 7501 default: 7502 break; 7503 7504 case ICmpInst::ICMP_SGE: 7505 std::swap(LHS, RHS); 7506 case ICmpInst::ICMP_SLE: 7507 // X s<= (X + C)<nsw> if C >= 0 7508 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7509 return true; 7510 7511 // (X + C)<nsw> s<= X if C <= 0 7512 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7513 !C.isStrictlyPositive()) 7514 return true; 7515 break; 7516 7517 case ICmpInst::ICMP_SGT: 7518 std::swap(LHS, RHS); 7519 case ICmpInst::ICMP_SLT: 7520 // X s< (X + C)<nsw> if C > 0 7521 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7522 C.isStrictlyPositive()) 7523 return true; 7524 7525 // (X + C)<nsw> s< X if C < 0 7526 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7527 return true; 7528 break; 7529 } 7530 7531 return false; 7532 } 7533 7534 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7535 const SCEV *LHS, 7536 const SCEV *RHS) { 7537 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7538 return false; 7539 7540 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7541 // the stack can result in exponential time complexity. 7542 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7543 7544 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7545 // 7546 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7547 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7548 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7549 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7550 // use isKnownPredicate later if needed. 7551 return isKnownNonNegative(RHS) && 7552 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7553 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7554 } 7555 7556 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7557 /// protected by a conditional between LHS and RHS. This is used to 7558 /// to eliminate casts. 7559 bool 7560 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7561 ICmpInst::Predicate Pred, 7562 const SCEV *LHS, const SCEV *RHS) { 7563 // Interpret a null as meaning no loop, where there is obviously no guard 7564 // (interprocedural conditions notwithstanding). 7565 if (!L) return true; 7566 7567 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7568 return true; 7569 7570 BasicBlock *Latch = L->getLoopLatch(); 7571 if (!Latch) 7572 return false; 7573 7574 BranchInst *LoopContinuePredicate = 7575 dyn_cast<BranchInst>(Latch->getTerminator()); 7576 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7577 isImpliedCond(Pred, LHS, RHS, 7578 LoopContinuePredicate->getCondition(), 7579 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7580 return true; 7581 7582 // We don't want more than one activation of the following loops on the stack 7583 // -- that can lead to O(n!) time complexity. 7584 if (WalkingBEDominatingConds) 7585 return false; 7586 7587 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7588 7589 // See if we can exploit a trip count to prove the predicate. 7590 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7591 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7592 if (LatchBECount != getCouldNotCompute()) { 7593 // We know that Latch branches back to the loop header exactly 7594 // LatchBECount times. This means the backdege condition at Latch is 7595 // equivalent to "{0,+,1} u< LatchBECount". 7596 Type *Ty = LatchBECount->getType(); 7597 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7598 const SCEV *LoopCounter = 7599 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7600 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7601 LatchBECount)) 7602 return true; 7603 } 7604 7605 // Check conditions due to any @llvm.assume intrinsics. 7606 for (auto &AssumeVH : AC.assumptions()) { 7607 if (!AssumeVH) 7608 continue; 7609 auto *CI = cast<CallInst>(AssumeVH); 7610 if (!DT.dominates(CI, Latch->getTerminator())) 7611 continue; 7612 7613 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7614 return true; 7615 } 7616 7617 // If the loop is not reachable from the entry block, we risk running into an 7618 // infinite loop as we walk up into the dom tree. These loops do not matter 7619 // anyway, so we just return a conservative answer when we see them. 7620 if (!DT.isReachableFromEntry(L->getHeader())) 7621 return false; 7622 7623 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7624 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7625 7626 assert(DTN && "should reach the loop header before reaching the root!"); 7627 7628 BasicBlock *BB = DTN->getBlock(); 7629 BasicBlock *PBB = BB->getSinglePredecessor(); 7630 if (!PBB) 7631 continue; 7632 7633 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7634 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7635 continue; 7636 7637 Value *Condition = ContinuePredicate->getCondition(); 7638 7639 // If we have an edge `E` within the loop body that dominates the only 7640 // latch, the condition guarding `E` also guards the backedge. This 7641 // reasoning works only for loops with a single latch. 7642 7643 BasicBlockEdge DominatingEdge(PBB, BB); 7644 if (DominatingEdge.isSingleEdge()) { 7645 // We're constructively (and conservatively) enumerating edges within the 7646 // loop body that dominate the latch. The dominator tree better agree 7647 // with us on this: 7648 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7649 7650 if (isImpliedCond(Pred, LHS, RHS, Condition, 7651 BB != ContinuePredicate->getSuccessor(0))) 7652 return true; 7653 } 7654 } 7655 7656 return false; 7657 } 7658 7659 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 7660 /// by a conditional between LHS and RHS. This is used to help avoid max 7661 /// expressions in loop trip counts, and to eliminate casts. 7662 bool 7663 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7664 ICmpInst::Predicate Pred, 7665 const SCEV *LHS, const SCEV *RHS) { 7666 // Interpret a null as meaning no loop, where there is obviously no guard 7667 // (interprocedural conditions notwithstanding). 7668 if (!L) return false; 7669 7670 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7671 return true; 7672 7673 // Starting at the loop predecessor, climb up the predecessor chain, as long 7674 // as there are predecessors that can be found that have unique successors 7675 // leading to the original header. 7676 for (std::pair<BasicBlock *, BasicBlock *> 7677 Pair(L->getLoopPredecessor(), L->getHeader()); 7678 Pair.first; 7679 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7680 7681 BranchInst *LoopEntryPredicate = 7682 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7683 if (!LoopEntryPredicate || 7684 LoopEntryPredicate->isUnconditional()) 7685 continue; 7686 7687 if (isImpliedCond(Pred, LHS, RHS, 7688 LoopEntryPredicate->getCondition(), 7689 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7690 return true; 7691 } 7692 7693 // Check conditions due to any @llvm.assume intrinsics. 7694 for (auto &AssumeVH : AC.assumptions()) { 7695 if (!AssumeVH) 7696 continue; 7697 auto *CI = cast<CallInst>(AssumeVH); 7698 if (!DT.dominates(CI, L->getHeader())) 7699 continue; 7700 7701 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7702 return true; 7703 } 7704 7705 return false; 7706 } 7707 7708 namespace { 7709 /// RAII wrapper to prevent recursive application of isImpliedCond. 7710 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are 7711 /// currently evaluating isImpliedCond. 7712 struct MarkPendingLoopPredicate { 7713 Value *Cond; 7714 DenseSet<Value*> &LoopPreds; 7715 bool Pending; 7716 7717 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) 7718 : Cond(C), LoopPreds(LP) { 7719 Pending = !LoopPreds.insert(Cond).second; 7720 } 7721 ~MarkPendingLoopPredicate() { 7722 if (!Pending) 7723 LoopPreds.erase(Cond); 7724 } 7725 }; 7726 } // end anonymous namespace 7727 7728 /// isImpliedCond - Test whether the condition described by Pred, LHS, 7729 /// and RHS is true whenever the given Cond value evaluates to true. 7730 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 7731 const SCEV *LHS, const SCEV *RHS, 7732 Value *FoundCondValue, 7733 bool Inverse) { 7734 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); 7735 if (Mark.Pending) 7736 return false; 7737 7738 // Recursively handle And and Or conditions. 7739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 7740 if (BO->getOpcode() == Instruction::And) { 7741 if (!Inverse) 7742 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 7743 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 7744 } else if (BO->getOpcode() == Instruction::Or) { 7745 if (Inverse) 7746 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 7747 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 7748 } 7749 } 7750 7751 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 7752 if (!ICI) return false; 7753 7754 // Now that we found a conditional branch that dominates the loop or controls 7755 // the loop latch. Check to see if it is the comparison we are looking for. 7756 ICmpInst::Predicate FoundPred; 7757 if (Inverse) 7758 FoundPred = ICI->getInversePredicate(); 7759 else 7760 FoundPred = ICI->getPredicate(); 7761 7762 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 7763 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 7764 7765 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 7766 } 7767 7768 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 7769 const SCEV *RHS, 7770 ICmpInst::Predicate FoundPred, 7771 const SCEV *FoundLHS, 7772 const SCEV *FoundRHS) { 7773 // Balance the types. 7774 if (getTypeSizeInBits(LHS->getType()) < 7775 getTypeSizeInBits(FoundLHS->getType())) { 7776 if (CmpInst::isSigned(Pred)) { 7777 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 7778 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 7779 } else { 7780 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 7781 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 7782 } 7783 } else if (getTypeSizeInBits(LHS->getType()) > 7784 getTypeSizeInBits(FoundLHS->getType())) { 7785 if (CmpInst::isSigned(FoundPred)) { 7786 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 7787 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 7788 } else { 7789 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 7790 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 7791 } 7792 } 7793 7794 // Canonicalize the query to match the way instcombine will have 7795 // canonicalized the comparison. 7796 if (SimplifyICmpOperands(Pred, LHS, RHS)) 7797 if (LHS == RHS) 7798 return CmpInst::isTrueWhenEqual(Pred); 7799 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 7800 if (FoundLHS == FoundRHS) 7801 return CmpInst::isFalseWhenEqual(FoundPred); 7802 7803 // Check to see if we can make the LHS or RHS match. 7804 if (LHS == FoundRHS || RHS == FoundLHS) { 7805 if (isa<SCEVConstant>(RHS)) { 7806 std::swap(FoundLHS, FoundRHS); 7807 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 7808 } else { 7809 std::swap(LHS, RHS); 7810 Pred = ICmpInst::getSwappedPredicate(Pred); 7811 } 7812 } 7813 7814 // Check whether the found predicate is the same as the desired predicate. 7815 if (FoundPred == Pred) 7816 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 7817 7818 // Check whether swapping the found predicate makes it the same as the 7819 // desired predicate. 7820 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 7821 if (isa<SCEVConstant>(RHS)) 7822 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 7823 else 7824 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 7825 RHS, LHS, FoundLHS, FoundRHS); 7826 } 7827 7828 // Unsigned comparison is the same as signed comparison when both the operands 7829 // are non-negative. 7830 if (CmpInst::isUnsigned(FoundPred) && 7831 CmpInst::getSignedPredicate(FoundPred) == Pred && 7832 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 7833 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 7834 7835 // Check if we can make progress by sharpening ranges. 7836 if (FoundPred == ICmpInst::ICMP_NE && 7837 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 7838 7839 const SCEVConstant *C = nullptr; 7840 const SCEV *V = nullptr; 7841 7842 if (isa<SCEVConstant>(FoundLHS)) { 7843 C = cast<SCEVConstant>(FoundLHS); 7844 V = FoundRHS; 7845 } else { 7846 C = cast<SCEVConstant>(FoundRHS); 7847 V = FoundLHS; 7848 } 7849 7850 // The guarding predicate tells us that C != V. If the known range 7851 // of V is [C, t), we can sharpen the range to [C + 1, t). The 7852 // range we consider has to correspond to same signedness as the 7853 // predicate we're interested in folding. 7854 7855 APInt Min = ICmpInst::isSigned(Pred) ? 7856 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 7857 7858 if (Min == C->getAPInt()) { 7859 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 7860 // This is true even if (Min + 1) wraps around -- in case of 7861 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 7862 7863 APInt SharperMin = Min + 1; 7864 7865 switch (Pred) { 7866 case ICmpInst::ICMP_SGE: 7867 case ICmpInst::ICMP_UGE: 7868 // We know V `Pred` SharperMin. If this implies LHS `Pred` 7869 // RHS, we're done. 7870 if (isImpliedCondOperands(Pred, LHS, RHS, V, 7871 getConstant(SharperMin))) 7872 return true; 7873 7874 case ICmpInst::ICMP_SGT: 7875 case ICmpInst::ICMP_UGT: 7876 // We know from the range information that (V `Pred` Min || 7877 // V == Min). We know from the guarding condition that !(V 7878 // == Min). This gives us 7879 // 7880 // V `Pred` Min || V == Min && !(V == Min) 7881 // => V `Pred` Min 7882 // 7883 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 7884 7885 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 7886 return true; 7887 7888 default: 7889 // No change 7890 break; 7891 } 7892 } 7893 } 7894 7895 // Check whether the actual condition is beyond sufficient. 7896 if (FoundPred == ICmpInst::ICMP_EQ) 7897 if (ICmpInst::isTrueWhenEqual(Pred)) 7898 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 7899 return true; 7900 if (Pred == ICmpInst::ICMP_NE) 7901 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 7902 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 7903 return true; 7904 7905 // Otherwise assume the worst. 7906 return false; 7907 } 7908 7909 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 7910 const SCEV *&L, const SCEV *&R, 7911 SCEV::NoWrapFlags &Flags) { 7912 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 7913 if (!AE || AE->getNumOperands() != 2) 7914 return false; 7915 7916 L = AE->getOperand(0); 7917 R = AE->getOperand(1); 7918 Flags = AE->getNoWrapFlags(); 7919 return true; 7920 } 7921 7922 bool ScalarEvolution::computeConstantDifference(const SCEV *Less, 7923 const SCEV *More, 7924 APInt &C) { 7925 // We avoid subtracting expressions here because this function is usually 7926 // fairly deep in the call stack (i.e. is called many times). 7927 7928 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 7929 const auto *LAR = cast<SCEVAddRecExpr>(Less); 7930 const auto *MAR = cast<SCEVAddRecExpr>(More); 7931 7932 if (LAR->getLoop() != MAR->getLoop()) 7933 return false; 7934 7935 // We look at affine expressions only; not for correctness but to keep 7936 // getStepRecurrence cheap. 7937 if (!LAR->isAffine() || !MAR->isAffine()) 7938 return false; 7939 7940 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 7941 return false; 7942 7943 Less = LAR->getStart(); 7944 More = MAR->getStart(); 7945 7946 // fall through 7947 } 7948 7949 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 7950 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 7951 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 7952 C = M - L; 7953 return true; 7954 } 7955 7956 const SCEV *L, *R; 7957 SCEV::NoWrapFlags Flags; 7958 if (splitBinaryAdd(Less, L, R, Flags)) 7959 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 7960 if (R == More) { 7961 C = -(LC->getAPInt()); 7962 return true; 7963 } 7964 7965 if (splitBinaryAdd(More, L, R, Flags)) 7966 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 7967 if (R == Less) { 7968 C = LC->getAPInt(); 7969 return true; 7970 } 7971 7972 return false; 7973 } 7974 7975 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 7976 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 7977 const SCEV *FoundLHS, const SCEV *FoundRHS) { 7978 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 7979 return false; 7980 7981 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7982 if (!AddRecLHS) 7983 return false; 7984 7985 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 7986 if (!AddRecFoundLHS) 7987 return false; 7988 7989 // We'd like to let SCEV reason about control dependencies, so we constrain 7990 // both the inequalities to be about add recurrences on the same loop. This 7991 // way we can use isLoopEntryGuardedByCond later. 7992 7993 const Loop *L = AddRecFoundLHS->getLoop(); 7994 if (L != AddRecLHS->getLoop()) 7995 return false; 7996 7997 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 7998 // 7999 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8000 // ... (2) 8001 // 8002 // Informal proof for (2), assuming (1) [*]: 8003 // 8004 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8005 // 8006 // Then 8007 // 8008 // FoundLHS s< FoundRHS s< INT_MIN - C 8009 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8010 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8011 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8012 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8013 // <=> FoundLHS + C s< FoundRHS + C 8014 // 8015 // [*]: (1) can be proved by ruling out overflow. 8016 // 8017 // [**]: This can be proved by analyzing all the four possibilities: 8018 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8019 // (A s>= 0, B s>= 0). 8020 // 8021 // Note: 8022 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8023 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8024 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8025 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8026 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8027 // C)". 8028 8029 APInt LDiff, RDiff; 8030 if (!computeConstantDifference(FoundLHS, LHS, LDiff) || 8031 !computeConstantDifference(FoundRHS, RHS, RDiff) || 8032 LDiff != RDiff) 8033 return false; 8034 8035 if (LDiff == 0) 8036 return true; 8037 8038 APInt FoundRHSLimit; 8039 8040 if (Pred == CmpInst::ICMP_ULT) { 8041 FoundRHSLimit = -RDiff; 8042 } else { 8043 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8044 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff; 8045 } 8046 8047 // Try to prove (1) or (2), as needed. 8048 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8049 getConstant(FoundRHSLimit)); 8050 } 8051 8052 /// isImpliedCondOperands - Test whether the condition described by Pred, 8053 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 8054 /// and FoundRHS is true. 8055 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8056 const SCEV *LHS, const SCEV *RHS, 8057 const SCEV *FoundLHS, 8058 const SCEV *FoundRHS) { 8059 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8060 return true; 8061 8062 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8063 return true; 8064 8065 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8066 FoundLHS, FoundRHS) || 8067 // ~x < ~y --> x > y 8068 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8069 getNotSCEV(FoundRHS), 8070 getNotSCEV(FoundLHS)); 8071 } 8072 8073 8074 /// If Expr computes ~A, return A else return nullptr 8075 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8076 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8077 if (!Add || Add->getNumOperands() != 2 || 8078 !Add->getOperand(0)->isAllOnesValue()) 8079 return nullptr; 8080 8081 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8082 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8083 !AddRHS->getOperand(0)->isAllOnesValue()) 8084 return nullptr; 8085 8086 return AddRHS->getOperand(1); 8087 } 8088 8089 8090 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8091 template<typename MaxExprType> 8092 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8093 const SCEV *Candidate) { 8094 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8095 if (!MaxExpr) return false; 8096 8097 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8098 } 8099 8100 8101 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8102 template<typename MaxExprType> 8103 static bool IsMinConsistingOf(ScalarEvolution &SE, 8104 const SCEV *MaybeMinExpr, 8105 const SCEV *Candidate) { 8106 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8107 if (!MaybeMaxExpr) 8108 return false; 8109 8110 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8111 } 8112 8113 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8114 ICmpInst::Predicate Pred, 8115 const SCEV *LHS, const SCEV *RHS) { 8116 8117 // If both sides are affine addrecs for the same loop, with equal 8118 // steps, and we know the recurrences don't wrap, then we only 8119 // need to check the predicate on the starting values. 8120 8121 if (!ICmpInst::isRelational(Pred)) 8122 return false; 8123 8124 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8125 if (!LAR) 8126 return false; 8127 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8128 if (!RAR) 8129 return false; 8130 if (LAR->getLoop() != RAR->getLoop()) 8131 return false; 8132 if (!LAR->isAffine() || !RAR->isAffine()) 8133 return false; 8134 8135 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8136 return false; 8137 8138 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8139 SCEV::FlagNSW : SCEV::FlagNUW; 8140 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8141 return false; 8142 8143 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8144 } 8145 8146 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8147 /// expression? 8148 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8149 ICmpInst::Predicate Pred, 8150 const SCEV *LHS, const SCEV *RHS) { 8151 switch (Pred) { 8152 default: 8153 return false; 8154 8155 case ICmpInst::ICMP_SGE: 8156 std::swap(LHS, RHS); 8157 // fall through 8158 case ICmpInst::ICMP_SLE: 8159 return 8160 // min(A, ...) <= A 8161 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8162 // A <= max(A, ...) 8163 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8164 8165 case ICmpInst::ICMP_UGE: 8166 std::swap(LHS, RHS); 8167 // fall through 8168 case ICmpInst::ICMP_ULE: 8169 return 8170 // min(A, ...) <= A 8171 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8172 // A <= max(A, ...) 8173 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8174 } 8175 8176 llvm_unreachable("covered switch fell through?!"); 8177 } 8178 8179 /// isImpliedCondOperandsHelper - Test whether the condition described by 8180 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 8181 /// FoundLHS, and FoundRHS is true. 8182 bool 8183 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8184 const SCEV *LHS, const SCEV *RHS, 8185 const SCEV *FoundLHS, 8186 const SCEV *FoundRHS) { 8187 auto IsKnownPredicateFull = 8188 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8189 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8190 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8191 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8192 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8193 }; 8194 8195 switch (Pred) { 8196 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8197 case ICmpInst::ICMP_EQ: 8198 case ICmpInst::ICMP_NE: 8199 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8200 return true; 8201 break; 8202 case ICmpInst::ICMP_SLT: 8203 case ICmpInst::ICMP_SLE: 8204 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8205 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8206 return true; 8207 break; 8208 case ICmpInst::ICMP_SGT: 8209 case ICmpInst::ICMP_SGE: 8210 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8211 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8212 return true; 8213 break; 8214 case ICmpInst::ICMP_ULT: 8215 case ICmpInst::ICMP_ULE: 8216 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8217 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8218 return true; 8219 break; 8220 case ICmpInst::ICMP_UGT: 8221 case ICmpInst::ICMP_UGE: 8222 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8223 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8224 return true; 8225 break; 8226 } 8227 8228 return false; 8229 } 8230 8231 /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. 8232 /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". 8233 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8234 const SCEV *LHS, 8235 const SCEV *RHS, 8236 const SCEV *FoundLHS, 8237 const SCEV *FoundRHS) { 8238 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8239 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8240 // reduce the compile time impact of this optimization. 8241 return false; 8242 8243 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); 8244 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || 8245 !isa<SCEVConstant>(AddLHS->getOperand(0))) 8246 return false; 8247 8248 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8249 8250 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8251 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8252 ConstantRange FoundLHSRange = 8253 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8254 8255 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range 8256 // for `LHS`: 8257 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt(); 8258 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); 8259 8260 // We can also compute the range of values for `LHS` that satisfy the 8261 // consequent, "`LHS` `Pred` `RHS`": 8262 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8263 ConstantRange SatisfyingLHSRange = 8264 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8265 8266 // The antecedent implies the consequent if every value of `LHS` that 8267 // satisfies the antecedent also satisfies the consequent. 8268 return SatisfyingLHSRange.contains(LHSRange); 8269 } 8270 8271 // Verify if an linear IV with positive stride can overflow when in a 8272 // less-than comparison, knowing the invariant term of the comparison, the 8273 // stride and the knowledge of NSW/NUW flags on the recurrence. 8274 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8275 bool IsSigned, bool NoWrap) { 8276 if (NoWrap) return false; 8277 8278 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8279 const SCEV *One = getOne(Stride->getType()); 8280 8281 if (IsSigned) { 8282 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8283 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8284 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8285 .getSignedMax(); 8286 8287 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8288 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8289 } 8290 8291 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8292 APInt MaxValue = APInt::getMaxValue(BitWidth); 8293 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8294 .getUnsignedMax(); 8295 8296 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8297 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8298 } 8299 8300 // Verify if an linear IV with negative stride can overflow when in a 8301 // greater-than comparison, knowing the invariant term of the comparison, 8302 // the stride and the knowledge of NSW/NUW flags on the recurrence. 8303 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8304 bool IsSigned, bool NoWrap) { 8305 if (NoWrap) return false; 8306 8307 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8308 const SCEV *One = getOne(Stride->getType()); 8309 8310 if (IsSigned) { 8311 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8312 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8313 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8314 .getSignedMax(); 8315 8316 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8317 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8318 } 8319 8320 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8321 APInt MinValue = APInt::getMinValue(BitWidth); 8322 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8323 .getUnsignedMax(); 8324 8325 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8326 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8327 } 8328 8329 // Compute the backedge taken count knowing the interval difference, the 8330 // stride and presence of the equality in the comparison. 8331 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8332 bool Equality) { 8333 const SCEV *One = getOne(Step->getType()); 8334 Delta = Equality ? getAddExpr(Delta, Step) 8335 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8336 return getUDivExpr(Delta, Step); 8337 } 8338 8339 /// HowManyLessThans - Return the number of times a backedge containing the 8340 /// specified less-than comparison will execute. If not computable, return 8341 /// CouldNotCompute. 8342 /// 8343 /// @param ControlsExit is true when the LHS < RHS condition directly controls 8344 /// the branch (loops exits only if condition is true). In this case, we can use 8345 /// NoWrapFlags to skip overflow checks. 8346 ScalarEvolution::ExitLimit 8347 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 8348 const Loop *L, bool IsSigned, 8349 bool ControlsExit) { 8350 // We handle only IV < Invariant 8351 if (!isLoopInvariant(RHS, L)) 8352 return getCouldNotCompute(); 8353 8354 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8355 8356 // Avoid weird loops 8357 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8358 return getCouldNotCompute(); 8359 8360 bool NoWrap = ControlsExit && 8361 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8362 8363 const SCEV *Stride = IV->getStepRecurrence(*this); 8364 8365 // Avoid negative or zero stride values 8366 if (!isKnownPositive(Stride)) 8367 return getCouldNotCompute(); 8368 8369 // Avoid proven overflow cases: this will ensure that the backedge taken count 8370 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8371 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8372 // behaviors like the case of C language. 8373 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8374 return getCouldNotCompute(); 8375 8376 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8377 : ICmpInst::ICMP_ULT; 8378 const SCEV *Start = IV->getStart(); 8379 const SCEV *End = RHS; 8380 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { 8381 const SCEV *Diff = getMinusSCEV(RHS, Start); 8382 // If we have NoWrap set, then we can assume that the increment won't 8383 // overflow, in which case if RHS - Start is a constant, we don't need to 8384 // do a max operation since we can just figure it out statically 8385 if (NoWrap && isa<SCEVConstant>(Diff)) { 8386 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); 8387 if (D.isNegative()) 8388 End = Start; 8389 } else 8390 End = IsSigned ? getSMaxExpr(RHS, Start) 8391 : getUMaxExpr(RHS, Start); 8392 } 8393 8394 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8395 8396 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8397 : getUnsignedRange(Start).getUnsignedMin(); 8398 8399 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8400 : getUnsignedRange(Stride).getUnsignedMin(); 8401 8402 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8403 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) 8404 : APInt::getMaxValue(BitWidth) - (MinStride - 1); 8405 8406 // Although End can be a MAX expression we estimate MaxEnd considering only 8407 // the case End = RHS. This is safe because in the other case (End - Start) 8408 // is zero, leading to a zero maximum backedge taken count. 8409 APInt MaxEnd = 8410 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8411 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8412 8413 const SCEV *MaxBECount; 8414 if (isa<SCEVConstant>(BECount)) 8415 MaxBECount = BECount; 8416 else 8417 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8418 getConstant(MinStride), false); 8419 8420 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8421 MaxBECount = BECount; 8422 8423 return ExitLimit(BECount, MaxBECount); 8424 } 8425 8426 ScalarEvolution::ExitLimit 8427 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8428 const Loop *L, bool IsSigned, 8429 bool ControlsExit) { 8430 // We handle only IV > Invariant 8431 if (!isLoopInvariant(RHS, L)) 8432 return getCouldNotCompute(); 8433 8434 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8435 8436 // Avoid weird loops 8437 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8438 return getCouldNotCompute(); 8439 8440 bool NoWrap = ControlsExit && 8441 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8442 8443 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8444 8445 // Avoid negative or zero stride values 8446 if (!isKnownPositive(Stride)) 8447 return getCouldNotCompute(); 8448 8449 // Avoid proven overflow cases: this will ensure that the backedge taken count 8450 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8451 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8452 // behaviors like the case of C language. 8453 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8454 return getCouldNotCompute(); 8455 8456 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8457 : ICmpInst::ICMP_UGT; 8458 8459 const SCEV *Start = IV->getStart(); 8460 const SCEV *End = RHS; 8461 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 8462 const SCEV *Diff = getMinusSCEV(RHS, Start); 8463 // If we have NoWrap set, then we can assume that the increment won't 8464 // overflow, in which case if RHS - Start is a constant, we don't need to 8465 // do a max operation since we can just figure it out statically 8466 if (NoWrap && isa<SCEVConstant>(Diff)) { 8467 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); 8468 if (!D.isNegative()) 8469 End = Start; 8470 } else 8471 End = IsSigned ? getSMinExpr(RHS, Start) 8472 : getUMinExpr(RHS, Start); 8473 } 8474 8475 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8476 8477 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8478 : getUnsignedRange(Start).getUnsignedMax(); 8479 8480 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8481 : getUnsignedRange(Stride).getUnsignedMin(); 8482 8483 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8484 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8485 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8486 8487 // Although End can be a MIN expression we estimate MinEnd considering only 8488 // the case End = RHS. This is safe because in the other case (Start - End) 8489 // is zero, leading to a zero maximum backedge taken count. 8490 APInt MinEnd = 8491 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8492 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8493 8494 8495 const SCEV *MaxBECount = getCouldNotCompute(); 8496 if (isa<SCEVConstant>(BECount)) 8497 MaxBECount = BECount; 8498 else 8499 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8500 getConstant(MinStride), false); 8501 8502 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8503 MaxBECount = BECount; 8504 8505 return ExitLimit(BECount, MaxBECount); 8506 } 8507 8508 /// getNumIterationsInRange - Return the number of iterations of this loop that 8509 /// produce values in the specified constant range. Another way of looking at 8510 /// this is that it returns the first iteration number where the value is not in 8511 /// the condition, thus computing the exit count. If the iteration count can't 8512 /// be computed, an instance of SCEVCouldNotCompute is returned. 8513 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 8514 ScalarEvolution &SE) const { 8515 if (Range.isFullSet()) // Infinite loop. 8516 return SE.getCouldNotCompute(); 8517 8518 // If the start is a non-zero constant, shift the range to simplify things. 8519 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8520 if (!SC->getValue()->isZero()) { 8521 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8522 Operands[0] = SE.getZero(SC->getType()); 8523 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8524 getNoWrapFlags(FlagNW)); 8525 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8526 return ShiftedAddRec->getNumIterationsInRange( 8527 Range.subtract(SC->getAPInt()), SE); 8528 // This is strange and shouldn't happen. 8529 return SE.getCouldNotCompute(); 8530 } 8531 8532 // The only time we can solve this is when we have all constant indices. 8533 // Otherwise, we cannot determine the overflow conditions. 8534 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8535 return SE.getCouldNotCompute(); 8536 8537 // Okay at this point we know that all elements of the chrec are constants and 8538 // that the start element is zero. 8539 8540 // First check to see if the range contains zero. If not, the first 8541 // iteration exits. 8542 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8543 if (!Range.contains(APInt(BitWidth, 0))) 8544 return SE.getZero(getType()); 8545 8546 if (isAffine()) { 8547 // If this is an affine expression then we have this situation: 8548 // Solve {0,+,A} in Range === Ax in Range 8549 8550 // We know that zero is in the range. If A is positive then we know that 8551 // the upper value of the range must be the first possible exit value. 8552 // If A is negative then the lower of the range is the last possible loop 8553 // value. Also note that we already checked for a full range. 8554 APInt One(BitWidth,1); 8555 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8556 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8557 8558 // The exit value should be (End+A)/A. 8559 APInt ExitVal = (End + A).udiv(A); 8560 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8561 8562 // Evaluate at the exit value. If we really did fall out of the valid 8563 // range, then we computed our trip count, otherwise wrap around or other 8564 // things must have happened. 8565 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8566 if (Range.contains(Val->getValue())) 8567 return SE.getCouldNotCompute(); // Something strange happened 8568 8569 // Ensure that the previous value is in the range. This is a sanity check. 8570 assert(Range.contains( 8571 EvaluateConstantChrecAtConstant(this, 8572 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8573 "Linear scev computation is off in a bad way!"); 8574 return SE.getConstant(ExitValue); 8575 } else if (isQuadratic()) { 8576 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8577 // quadratic equation to solve it. To do this, we must frame our problem in 8578 // terms of figuring out when zero is crossed, instead of when 8579 // Range.getUpper() is crossed. 8580 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8581 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8582 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), 8583 // getNoWrapFlags(FlagNW) 8584 FlagAnyWrap); 8585 8586 // Next, solve the constructed addrec 8587 auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 8588 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 8589 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 8590 if (R1) { 8591 // Pick the smallest positive root value. 8592 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8593 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8594 if (!CB->getZExtValue()) 8595 std::swap(R1, R2); // R1 is the minimum root now. 8596 8597 // Make sure the root is not off by one. The returned iteration should 8598 // not be in the range, but the previous one should be. When solving 8599 // for "X*X < 5", for example, we should not return a root of 2. 8600 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 8601 R1->getValue(), 8602 SE); 8603 if (Range.contains(R1Val->getValue())) { 8604 // The next iteration must be out of the range... 8605 ConstantInt *NextVal = 8606 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8607 8608 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8609 if (!Range.contains(R1Val->getValue())) 8610 return SE.getConstant(NextVal); 8611 return SE.getCouldNotCompute(); // Something strange happened 8612 } 8613 8614 // If R1 was not in the range, then it is a good return value. Make 8615 // sure that R1-1 WAS in the range though, just in case. 8616 ConstantInt *NextVal = 8617 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8618 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8619 if (Range.contains(R1Val->getValue())) 8620 return R1; 8621 return SE.getCouldNotCompute(); // Something strange happened 8622 } 8623 } 8624 } 8625 8626 return SE.getCouldNotCompute(); 8627 } 8628 8629 namespace { 8630 struct FindUndefs { 8631 bool Found; 8632 FindUndefs() : Found(false) {} 8633 8634 bool follow(const SCEV *S) { 8635 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 8636 if (isa<UndefValue>(C->getValue())) 8637 Found = true; 8638 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 8639 if (isa<UndefValue>(C->getValue())) 8640 Found = true; 8641 } 8642 8643 // Keep looking if we haven't found it yet. 8644 return !Found; 8645 } 8646 bool isDone() const { 8647 // Stop recursion if we have found an undef. 8648 return Found; 8649 } 8650 }; 8651 } 8652 8653 // Return true when S contains at least an undef value. 8654 static inline bool 8655 containsUndefs(const SCEV *S) { 8656 FindUndefs F; 8657 SCEVTraversal<FindUndefs> ST(F); 8658 ST.visitAll(S); 8659 8660 return F.Found; 8661 } 8662 8663 namespace { 8664 // Collect all steps of SCEV expressions. 8665 struct SCEVCollectStrides { 8666 ScalarEvolution &SE; 8667 SmallVectorImpl<const SCEV *> &Strides; 8668 8669 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 8670 : SE(SE), Strides(S) {} 8671 8672 bool follow(const SCEV *S) { 8673 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 8674 Strides.push_back(AR->getStepRecurrence(SE)); 8675 return true; 8676 } 8677 bool isDone() const { return false; } 8678 }; 8679 8680 // Collect all SCEVUnknown and SCEVMulExpr expressions. 8681 struct SCEVCollectTerms { 8682 SmallVectorImpl<const SCEV *> &Terms; 8683 8684 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 8685 : Terms(T) {} 8686 8687 bool follow(const SCEV *S) { 8688 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { 8689 if (!containsUndefs(S)) 8690 Terms.push_back(S); 8691 8692 // Stop recursion: once we collected a term, do not walk its operands. 8693 return false; 8694 } 8695 8696 // Keep looking. 8697 return true; 8698 } 8699 bool isDone() const { return false; } 8700 }; 8701 8702 // Check if a SCEV contains an AddRecExpr. 8703 struct SCEVHasAddRec { 8704 bool &ContainsAddRec; 8705 8706 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 8707 ContainsAddRec = false; 8708 } 8709 8710 bool follow(const SCEV *S) { 8711 if (isa<SCEVAddRecExpr>(S)) { 8712 ContainsAddRec = true; 8713 8714 // Stop recursion: once we collected a term, do not walk its operands. 8715 return false; 8716 } 8717 8718 // Keep looking. 8719 return true; 8720 } 8721 bool isDone() const { return false; } 8722 }; 8723 8724 // Find factors that are multiplied with an expression that (possibly as a 8725 // subexpression) contains an AddRecExpr. In the expression: 8726 // 8727 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 8728 // 8729 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 8730 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 8731 // parameters as they form a product with an induction variable. 8732 // 8733 // This collector expects all array size parameters to be in the same MulExpr. 8734 // It might be necessary to later add support for collecting parameters that are 8735 // spread over different nested MulExpr. 8736 struct SCEVCollectAddRecMultiplies { 8737 SmallVectorImpl<const SCEV *> &Terms; 8738 ScalarEvolution &SE; 8739 8740 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 8741 : Terms(T), SE(SE) {} 8742 8743 bool follow(const SCEV *S) { 8744 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 8745 bool HasAddRec = false; 8746 SmallVector<const SCEV *, 0> Operands; 8747 for (auto Op : Mul->operands()) { 8748 if (isa<SCEVUnknown>(Op)) { 8749 Operands.push_back(Op); 8750 } else { 8751 bool ContainsAddRec; 8752 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 8753 visitAll(Op, ContiansAddRec); 8754 HasAddRec |= ContainsAddRec; 8755 } 8756 } 8757 if (Operands.size() == 0) 8758 return true; 8759 8760 if (!HasAddRec) 8761 return false; 8762 8763 Terms.push_back(SE.getMulExpr(Operands)); 8764 // Stop recursion: once we collected a term, do not walk its operands. 8765 return false; 8766 } 8767 8768 // Keep looking. 8769 return true; 8770 } 8771 bool isDone() const { return false; } 8772 }; 8773 } 8774 8775 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 8776 /// two places: 8777 /// 1) The strides of AddRec expressions. 8778 /// 2) Unknowns that are multiplied with AddRec expressions. 8779 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 8780 SmallVectorImpl<const SCEV *> &Terms) { 8781 SmallVector<const SCEV *, 4> Strides; 8782 SCEVCollectStrides StrideCollector(*this, Strides); 8783 visitAll(Expr, StrideCollector); 8784 8785 DEBUG({ 8786 dbgs() << "Strides:\n"; 8787 for (const SCEV *S : Strides) 8788 dbgs() << *S << "\n"; 8789 }); 8790 8791 for (const SCEV *S : Strides) { 8792 SCEVCollectTerms TermCollector(Terms); 8793 visitAll(S, TermCollector); 8794 } 8795 8796 DEBUG({ 8797 dbgs() << "Terms:\n"; 8798 for (const SCEV *T : Terms) 8799 dbgs() << *T << "\n"; 8800 }); 8801 8802 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 8803 visitAll(Expr, MulCollector); 8804 } 8805 8806 static bool findArrayDimensionsRec(ScalarEvolution &SE, 8807 SmallVectorImpl<const SCEV *> &Terms, 8808 SmallVectorImpl<const SCEV *> &Sizes) { 8809 int Last = Terms.size() - 1; 8810 const SCEV *Step = Terms[Last]; 8811 8812 // End of recursion. 8813 if (Last == 0) { 8814 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 8815 SmallVector<const SCEV *, 2> Qs; 8816 for (const SCEV *Op : M->operands()) 8817 if (!isa<SCEVConstant>(Op)) 8818 Qs.push_back(Op); 8819 8820 Step = SE.getMulExpr(Qs); 8821 } 8822 8823 Sizes.push_back(Step); 8824 return true; 8825 } 8826 8827 for (const SCEV *&Term : Terms) { 8828 // Normalize the terms before the next call to findArrayDimensionsRec. 8829 const SCEV *Q, *R; 8830 SCEVDivision::divide(SE, Term, Step, &Q, &R); 8831 8832 // Bail out when GCD does not evenly divide one of the terms. 8833 if (!R->isZero()) 8834 return false; 8835 8836 Term = Q; 8837 } 8838 8839 // Remove all SCEVConstants. 8840 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { 8841 return isa<SCEVConstant>(E); 8842 }), 8843 Terms.end()); 8844 8845 if (Terms.size() > 0) 8846 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 8847 return false; 8848 8849 Sizes.push_back(Step); 8850 return true; 8851 } 8852 8853 // Returns true when S contains at least a SCEVUnknown parameter. 8854 static inline bool 8855 containsParameters(const SCEV *S) { 8856 struct FindParameter { 8857 bool FoundParameter; 8858 FindParameter() : FoundParameter(false) {} 8859 8860 bool follow(const SCEV *S) { 8861 if (isa<SCEVUnknown>(S)) { 8862 FoundParameter = true; 8863 // Stop recursion: we found a parameter. 8864 return false; 8865 } 8866 // Keep looking. 8867 return true; 8868 } 8869 bool isDone() const { 8870 // Stop recursion if we have found a parameter. 8871 return FoundParameter; 8872 } 8873 }; 8874 8875 FindParameter F; 8876 SCEVTraversal<FindParameter> ST(F); 8877 ST.visitAll(S); 8878 8879 return F.FoundParameter; 8880 } 8881 8882 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 8883 static inline bool 8884 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 8885 for (const SCEV *T : Terms) 8886 if (containsParameters(T)) 8887 return true; 8888 return false; 8889 } 8890 8891 // Return the number of product terms in S. 8892 static inline int numberOfTerms(const SCEV *S) { 8893 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 8894 return Expr->getNumOperands(); 8895 return 1; 8896 } 8897 8898 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 8899 if (isa<SCEVConstant>(T)) 8900 return nullptr; 8901 8902 if (isa<SCEVUnknown>(T)) 8903 return T; 8904 8905 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 8906 SmallVector<const SCEV *, 2> Factors; 8907 for (const SCEV *Op : M->operands()) 8908 if (!isa<SCEVConstant>(Op)) 8909 Factors.push_back(Op); 8910 8911 return SE.getMulExpr(Factors); 8912 } 8913 8914 return T; 8915 } 8916 8917 /// Return the size of an element read or written by Inst. 8918 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 8919 Type *Ty; 8920 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 8921 Ty = Store->getValueOperand()->getType(); 8922 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 8923 Ty = Load->getType(); 8924 else 8925 return nullptr; 8926 8927 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 8928 return getSizeOfExpr(ETy, Ty); 8929 } 8930 8931 /// Second step of delinearization: compute the array dimensions Sizes from the 8932 /// set of Terms extracted from the memory access function of this SCEVAddRec. 8933 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 8934 SmallVectorImpl<const SCEV *> &Sizes, 8935 const SCEV *ElementSize) const { 8936 8937 if (Terms.size() < 1 || !ElementSize) 8938 return; 8939 8940 // Early return when Terms do not contain parameters: we do not delinearize 8941 // non parametric SCEVs. 8942 if (!containsParameters(Terms)) 8943 return; 8944 8945 DEBUG({ 8946 dbgs() << "Terms:\n"; 8947 for (const SCEV *T : Terms) 8948 dbgs() << *T << "\n"; 8949 }); 8950 8951 // Remove duplicates. 8952 std::sort(Terms.begin(), Terms.end()); 8953 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 8954 8955 // Put larger terms first. 8956 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 8957 return numberOfTerms(LHS) > numberOfTerms(RHS); 8958 }); 8959 8960 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 8961 8962 // Try to divide all terms by the element size. If term is not divisible by 8963 // element size, proceed with the original term. 8964 for (const SCEV *&Term : Terms) { 8965 const SCEV *Q, *R; 8966 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 8967 if (!Q->isZero()) 8968 Term = Q; 8969 } 8970 8971 SmallVector<const SCEV *, 4> NewTerms; 8972 8973 // Remove constant factors. 8974 for (const SCEV *T : Terms) 8975 if (const SCEV *NewT = removeConstantFactors(SE, T)) 8976 NewTerms.push_back(NewT); 8977 8978 DEBUG({ 8979 dbgs() << "Terms after sorting:\n"; 8980 for (const SCEV *T : NewTerms) 8981 dbgs() << *T << "\n"; 8982 }); 8983 8984 if (NewTerms.empty() || 8985 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 8986 Sizes.clear(); 8987 return; 8988 } 8989 8990 // The last element to be pushed into Sizes is the size of an element. 8991 Sizes.push_back(ElementSize); 8992 8993 DEBUG({ 8994 dbgs() << "Sizes:\n"; 8995 for (const SCEV *S : Sizes) 8996 dbgs() << *S << "\n"; 8997 }); 8998 } 8999 9000 /// Third step of delinearization: compute the access functions for the 9001 /// Subscripts based on the dimensions in Sizes. 9002 void ScalarEvolution::computeAccessFunctions( 9003 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9004 SmallVectorImpl<const SCEV *> &Sizes) { 9005 9006 // Early exit in case this SCEV is not an affine multivariate function. 9007 if (Sizes.empty()) 9008 return; 9009 9010 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9011 if (!AR->isAffine()) 9012 return; 9013 9014 const SCEV *Res = Expr; 9015 int Last = Sizes.size() - 1; 9016 for (int i = Last; i >= 0; i--) { 9017 const SCEV *Q, *R; 9018 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9019 9020 DEBUG({ 9021 dbgs() << "Res: " << *Res << "\n"; 9022 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9023 dbgs() << "Res divided by Sizes[i]:\n"; 9024 dbgs() << "Quotient: " << *Q << "\n"; 9025 dbgs() << "Remainder: " << *R << "\n"; 9026 }); 9027 9028 Res = Q; 9029 9030 // Do not record the last subscript corresponding to the size of elements in 9031 // the array. 9032 if (i == Last) { 9033 9034 // Bail out if the remainder is too complex. 9035 if (isa<SCEVAddRecExpr>(R)) { 9036 Subscripts.clear(); 9037 Sizes.clear(); 9038 return; 9039 } 9040 9041 continue; 9042 } 9043 9044 // Record the access function for the current subscript. 9045 Subscripts.push_back(R); 9046 } 9047 9048 // Also push in last position the remainder of the last division: it will be 9049 // the access function of the innermost dimension. 9050 Subscripts.push_back(Res); 9051 9052 std::reverse(Subscripts.begin(), Subscripts.end()); 9053 9054 DEBUG({ 9055 dbgs() << "Subscripts:\n"; 9056 for (const SCEV *S : Subscripts) 9057 dbgs() << *S << "\n"; 9058 }); 9059 } 9060 9061 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9062 /// sizes of an array access. Returns the remainder of the delinearization that 9063 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9064 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9065 /// expressions in the stride and base of a SCEV corresponding to the 9066 /// computation of a GCD (greatest common divisor) of base and stride. When 9067 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9068 /// 9069 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9070 /// 9071 /// void foo(long n, long m, long o, double A[n][m][o]) { 9072 /// 9073 /// for (long i = 0; i < n; i++) 9074 /// for (long j = 0; j < m; j++) 9075 /// for (long k = 0; k < o; k++) 9076 /// A[i][j][k] = 1.0; 9077 /// } 9078 /// 9079 /// the delinearization input is the following AddRec SCEV: 9080 /// 9081 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9082 /// 9083 /// From this SCEV, we are able to say that the base offset of the access is %A 9084 /// because it appears as an offset that does not divide any of the strides in 9085 /// the loops: 9086 /// 9087 /// CHECK: Base offset: %A 9088 /// 9089 /// and then SCEV->delinearize determines the size of some of the dimensions of 9090 /// the array as these are the multiples by which the strides are happening: 9091 /// 9092 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9093 /// 9094 /// Note that the outermost dimension remains of UnknownSize because there are 9095 /// no strides that would help identifying the size of the last dimension: when 9096 /// the array has been statically allocated, one could compute the size of that 9097 /// dimension by dividing the overall size of the array by the size of the known 9098 /// dimensions: %m * %o * 8. 9099 /// 9100 /// Finally delinearize provides the access functions for the array reference 9101 /// that does correspond to A[i][j][k] of the above C testcase: 9102 /// 9103 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9104 /// 9105 /// The testcases are checking the output of a function pass: 9106 /// DelinearizationPass that walks through all loads and stores of a function 9107 /// asking for the SCEV of the memory access with respect to all enclosing 9108 /// loops, calling SCEV->delinearize on that and printing the results. 9109 9110 void ScalarEvolution::delinearize(const SCEV *Expr, 9111 SmallVectorImpl<const SCEV *> &Subscripts, 9112 SmallVectorImpl<const SCEV *> &Sizes, 9113 const SCEV *ElementSize) { 9114 // First step: collect parametric terms. 9115 SmallVector<const SCEV *, 4> Terms; 9116 collectParametricTerms(Expr, Terms); 9117 9118 if (Terms.empty()) 9119 return; 9120 9121 // Second step: find subscript sizes. 9122 findArrayDimensions(Terms, Sizes, ElementSize); 9123 9124 if (Sizes.empty()) 9125 return; 9126 9127 // Third step: compute the access functions for each subscript. 9128 computeAccessFunctions(Expr, Subscripts, Sizes); 9129 9130 if (Subscripts.empty()) 9131 return; 9132 9133 DEBUG({ 9134 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9135 dbgs() << "ArrayDecl[UnknownSize]"; 9136 for (const SCEV *S : Sizes) 9137 dbgs() << "[" << *S << "]"; 9138 9139 dbgs() << "\nArrayRef"; 9140 for (const SCEV *S : Subscripts) 9141 dbgs() << "[" << *S << "]"; 9142 dbgs() << "\n"; 9143 }); 9144 } 9145 9146 //===----------------------------------------------------------------------===// 9147 // SCEVCallbackVH Class Implementation 9148 //===----------------------------------------------------------------------===// 9149 9150 void ScalarEvolution::SCEVCallbackVH::deleted() { 9151 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9152 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9153 SE->ConstantEvolutionLoopExitValue.erase(PN); 9154 SE->eraseValueFromMap(getValPtr()); 9155 // this now dangles! 9156 } 9157 9158 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9159 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9160 9161 // Forget all the expressions associated with users of the old value, 9162 // so that future queries will recompute the expressions using the new 9163 // value. 9164 Value *Old = getValPtr(); 9165 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9166 SmallPtrSet<User *, 8> Visited; 9167 while (!Worklist.empty()) { 9168 User *U = Worklist.pop_back_val(); 9169 // Deleting the Old value will cause this to dangle. Postpone 9170 // that until everything else is done. 9171 if (U == Old) 9172 continue; 9173 if (!Visited.insert(U).second) 9174 continue; 9175 if (PHINode *PN = dyn_cast<PHINode>(U)) 9176 SE->ConstantEvolutionLoopExitValue.erase(PN); 9177 SE->eraseValueFromMap(U); 9178 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9179 } 9180 // Delete the Old value. 9181 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9182 SE->ConstantEvolutionLoopExitValue.erase(PN); 9183 SE->eraseValueFromMap(Old); 9184 // this now dangles! 9185 } 9186 9187 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9188 : CallbackVH(V), SE(se) {} 9189 9190 //===----------------------------------------------------------------------===// 9191 // ScalarEvolution Class Implementation 9192 //===----------------------------------------------------------------------===// 9193 9194 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9195 AssumptionCache &AC, DominatorTree &DT, 9196 LoopInfo &LI) 9197 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9198 CouldNotCompute(new SCEVCouldNotCompute()), 9199 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9200 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9201 FirstUnknown(nullptr) {} 9202 9203 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9204 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), 9205 CouldNotCompute(std::move(Arg.CouldNotCompute)), 9206 ValueExprMap(std::move(Arg.ValueExprMap)), 9207 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9208 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9209 ConstantEvolutionLoopExitValue( 9210 std::move(Arg.ConstantEvolutionLoopExitValue)), 9211 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9212 LoopDispositions(std::move(Arg.LoopDispositions)), 9213 BlockDispositions(std::move(Arg.BlockDispositions)), 9214 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9215 SignedRanges(std::move(Arg.SignedRanges)), 9216 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9217 UniquePreds(std::move(Arg.UniquePreds)), 9218 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9219 FirstUnknown(Arg.FirstUnknown) { 9220 Arg.FirstUnknown = nullptr; 9221 } 9222 9223 ScalarEvolution::~ScalarEvolution() { 9224 // Iterate through all the SCEVUnknown instances and call their 9225 // destructors, so that they release their references to their values. 9226 for (SCEVUnknown *U = FirstUnknown; U;) { 9227 SCEVUnknown *Tmp = U; 9228 U = U->Next; 9229 Tmp->~SCEVUnknown(); 9230 } 9231 FirstUnknown = nullptr; 9232 9233 ExprValueMap.clear(); 9234 ValueExprMap.clear(); 9235 HasRecMap.clear(); 9236 9237 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9238 // that a loop had multiple computable exits. 9239 for (auto &BTCI : BackedgeTakenCounts) 9240 BTCI.second.clear(); 9241 9242 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9243 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9244 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9245 } 9246 9247 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9248 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9249 } 9250 9251 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9252 const Loop *L) { 9253 // Print all inner loops first 9254 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 9255 PrintLoopInfo(OS, SE, *I); 9256 9257 OS << "Loop "; 9258 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9259 OS << ": "; 9260 9261 SmallVector<BasicBlock *, 8> ExitBlocks; 9262 L->getExitBlocks(ExitBlocks); 9263 if (ExitBlocks.size() != 1) 9264 OS << "<multiple exits> "; 9265 9266 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9267 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9268 } else { 9269 OS << "Unpredictable backedge-taken count. "; 9270 } 9271 9272 OS << "\n" 9273 "Loop "; 9274 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9275 OS << ": "; 9276 9277 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9278 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9279 } else { 9280 OS << "Unpredictable max backedge-taken count. "; 9281 } 9282 9283 OS << "\n"; 9284 } 9285 9286 void ScalarEvolution::print(raw_ostream &OS) const { 9287 // ScalarEvolution's implementation of the print method is to print 9288 // out SCEV values of all instructions that are interesting. Doing 9289 // this potentially causes it to create new SCEV objects though, 9290 // which technically conflicts with the const qualifier. This isn't 9291 // observable from outside the class though, so casting away the 9292 // const isn't dangerous. 9293 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9294 9295 OS << "Classifying expressions for: "; 9296 F.printAsOperand(OS, /*PrintType=*/false); 9297 OS << "\n"; 9298 for (Instruction &I : instructions(F)) 9299 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9300 OS << I << '\n'; 9301 OS << " --> "; 9302 const SCEV *SV = SE.getSCEV(&I); 9303 SV->print(OS); 9304 if (!isa<SCEVCouldNotCompute>(SV)) { 9305 OS << " U: "; 9306 SE.getUnsignedRange(SV).print(OS); 9307 OS << " S: "; 9308 SE.getSignedRange(SV).print(OS); 9309 } 9310 9311 const Loop *L = LI.getLoopFor(I.getParent()); 9312 9313 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9314 if (AtUse != SV) { 9315 OS << " --> "; 9316 AtUse->print(OS); 9317 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9318 OS << " U: "; 9319 SE.getUnsignedRange(AtUse).print(OS); 9320 OS << " S: "; 9321 SE.getSignedRange(AtUse).print(OS); 9322 } 9323 } 9324 9325 if (L) { 9326 OS << "\t\t" "Exits: "; 9327 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9328 if (!SE.isLoopInvariant(ExitValue, L)) { 9329 OS << "<<Unknown>>"; 9330 } else { 9331 OS << *ExitValue; 9332 } 9333 } 9334 9335 OS << "\n"; 9336 } 9337 9338 OS << "Determining loop execution counts for: "; 9339 F.printAsOperand(OS, /*PrintType=*/false); 9340 OS << "\n"; 9341 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 9342 PrintLoopInfo(OS, &SE, *I); 9343 } 9344 9345 ScalarEvolution::LoopDisposition 9346 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9347 auto &Values = LoopDispositions[S]; 9348 for (auto &V : Values) { 9349 if (V.getPointer() == L) 9350 return V.getInt(); 9351 } 9352 Values.emplace_back(L, LoopVariant); 9353 LoopDisposition D = computeLoopDisposition(S, L); 9354 auto &Values2 = LoopDispositions[S]; 9355 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9356 if (V.getPointer() == L) { 9357 V.setInt(D); 9358 break; 9359 } 9360 } 9361 return D; 9362 } 9363 9364 ScalarEvolution::LoopDisposition 9365 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9366 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9367 case scConstant: 9368 return LoopInvariant; 9369 case scTruncate: 9370 case scZeroExtend: 9371 case scSignExtend: 9372 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9373 case scAddRecExpr: { 9374 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9375 9376 // If L is the addrec's loop, it's computable. 9377 if (AR->getLoop() == L) 9378 return LoopComputable; 9379 9380 // Add recurrences are never invariant in the function-body (null loop). 9381 if (!L) 9382 return LoopVariant; 9383 9384 // This recurrence is variant w.r.t. L if L contains AR's loop. 9385 if (L->contains(AR->getLoop())) 9386 return LoopVariant; 9387 9388 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9389 if (AR->getLoop()->contains(L)) 9390 return LoopInvariant; 9391 9392 // This recurrence is variant w.r.t. L if any of its operands 9393 // are variant. 9394 for (auto *Op : AR->operands()) 9395 if (!isLoopInvariant(Op, L)) 9396 return LoopVariant; 9397 9398 // Otherwise it's loop-invariant. 9399 return LoopInvariant; 9400 } 9401 case scAddExpr: 9402 case scMulExpr: 9403 case scUMaxExpr: 9404 case scSMaxExpr: { 9405 bool HasVarying = false; 9406 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9407 LoopDisposition D = getLoopDisposition(Op, L); 9408 if (D == LoopVariant) 9409 return LoopVariant; 9410 if (D == LoopComputable) 9411 HasVarying = true; 9412 } 9413 return HasVarying ? LoopComputable : LoopInvariant; 9414 } 9415 case scUDivExpr: { 9416 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9417 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9418 if (LD == LoopVariant) 9419 return LoopVariant; 9420 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9421 if (RD == LoopVariant) 9422 return LoopVariant; 9423 return (LD == LoopInvariant && RD == LoopInvariant) ? 9424 LoopInvariant : LoopComputable; 9425 } 9426 case scUnknown: 9427 // All non-instruction values are loop invariant. All instructions are loop 9428 // invariant if they are not contained in the specified loop. 9429 // Instructions are never considered invariant in the function body 9430 // (null loop) because they are defined within the "loop". 9431 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9432 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9433 return LoopInvariant; 9434 case scCouldNotCompute: 9435 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9436 } 9437 llvm_unreachable("Unknown SCEV kind!"); 9438 } 9439 9440 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9441 return getLoopDisposition(S, L) == LoopInvariant; 9442 } 9443 9444 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9445 return getLoopDisposition(S, L) == LoopComputable; 9446 } 9447 9448 ScalarEvolution::BlockDisposition 9449 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9450 auto &Values = BlockDispositions[S]; 9451 for (auto &V : Values) { 9452 if (V.getPointer() == BB) 9453 return V.getInt(); 9454 } 9455 Values.emplace_back(BB, DoesNotDominateBlock); 9456 BlockDisposition D = computeBlockDisposition(S, BB); 9457 auto &Values2 = BlockDispositions[S]; 9458 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9459 if (V.getPointer() == BB) { 9460 V.setInt(D); 9461 break; 9462 } 9463 } 9464 return D; 9465 } 9466 9467 ScalarEvolution::BlockDisposition 9468 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9469 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9470 case scConstant: 9471 return ProperlyDominatesBlock; 9472 case scTruncate: 9473 case scZeroExtend: 9474 case scSignExtend: 9475 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9476 case scAddRecExpr: { 9477 // This uses a "dominates" query instead of "properly dominates" query 9478 // to test for proper dominance too, because the instruction which 9479 // produces the addrec's value is a PHI, and a PHI effectively properly 9480 // dominates its entire containing block. 9481 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9482 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9483 return DoesNotDominateBlock; 9484 } 9485 // FALL THROUGH into SCEVNAryExpr handling. 9486 case scAddExpr: 9487 case scMulExpr: 9488 case scUMaxExpr: 9489 case scSMaxExpr: { 9490 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9491 bool Proper = true; 9492 for (const SCEV *NAryOp : NAry->operands()) { 9493 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9494 if (D == DoesNotDominateBlock) 9495 return DoesNotDominateBlock; 9496 if (D == DominatesBlock) 9497 Proper = false; 9498 } 9499 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9500 } 9501 case scUDivExpr: { 9502 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9503 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9504 BlockDisposition LD = getBlockDisposition(LHS, BB); 9505 if (LD == DoesNotDominateBlock) 9506 return DoesNotDominateBlock; 9507 BlockDisposition RD = getBlockDisposition(RHS, BB); 9508 if (RD == DoesNotDominateBlock) 9509 return DoesNotDominateBlock; 9510 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9511 ProperlyDominatesBlock : DominatesBlock; 9512 } 9513 case scUnknown: 9514 if (Instruction *I = 9515 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9516 if (I->getParent() == BB) 9517 return DominatesBlock; 9518 if (DT.properlyDominates(I->getParent(), BB)) 9519 return ProperlyDominatesBlock; 9520 return DoesNotDominateBlock; 9521 } 9522 return ProperlyDominatesBlock; 9523 case scCouldNotCompute: 9524 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9525 } 9526 llvm_unreachable("Unknown SCEV kind!"); 9527 } 9528 9529 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9530 return getBlockDisposition(S, BB) >= DominatesBlock; 9531 } 9532 9533 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9534 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9535 } 9536 9537 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9538 // Search for a SCEV expression node within an expression tree. 9539 // Implements SCEVTraversal::Visitor. 9540 struct SCEVSearch { 9541 const SCEV *Node; 9542 bool IsFound; 9543 9544 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 9545 9546 bool follow(const SCEV *S) { 9547 IsFound |= (S == Node); 9548 return !IsFound; 9549 } 9550 bool isDone() const { return IsFound; } 9551 }; 9552 9553 SCEVSearch Search(Op); 9554 visitAll(S, Search); 9555 return Search.IsFound; 9556 } 9557 9558 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9559 ValuesAtScopes.erase(S); 9560 LoopDispositions.erase(S); 9561 BlockDispositions.erase(S); 9562 UnsignedRanges.erase(S); 9563 SignedRanges.erase(S); 9564 ExprValueMap.erase(S); 9565 HasRecMap.erase(S); 9566 9567 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = 9568 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) { 9569 BackedgeTakenInfo &BEInfo = I->second; 9570 if (BEInfo.hasOperand(S, this)) { 9571 BEInfo.clear(); 9572 BackedgeTakenCounts.erase(I++); 9573 } 9574 else 9575 ++I; 9576 } 9577 } 9578 9579 typedef DenseMap<const Loop *, std::string> VerifyMap; 9580 9581 /// replaceSubString - Replaces all occurrences of From in Str with To. 9582 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9583 size_t Pos = 0; 9584 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9585 Str.replace(Pos, From.size(), To.data(), To.size()); 9586 Pos += To.size(); 9587 } 9588 } 9589 9590 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9591 static void 9592 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9593 std::string &S = Map[L]; 9594 if (S.empty()) { 9595 raw_string_ostream OS(S); 9596 SE.getBackedgeTakenCount(L)->print(OS); 9597 9598 // false and 0 are semantically equivalent. This can happen in dead loops. 9599 replaceSubString(OS.str(), "false", "0"); 9600 // Remove wrap flags, their use in SCEV is highly fragile. 9601 // FIXME: Remove this when SCEV gets smarter about them. 9602 replaceSubString(OS.str(), "<nw>", ""); 9603 replaceSubString(OS.str(), "<nsw>", ""); 9604 replaceSubString(OS.str(), "<nuw>", ""); 9605 } 9606 9607 for (auto *R : reverse(*L)) 9608 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 9609 } 9610 9611 void ScalarEvolution::verify() const { 9612 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9613 9614 // Gather stringified backedge taken counts for all loops using SCEV's caches. 9615 // FIXME: It would be much better to store actual values instead of strings, 9616 // but SCEV pointers will change if we drop the caches. 9617 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 9618 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9619 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 9620 9621 // Gather stringified backedge taken counts for all loops using a fresh 9622 // ScalarEvolution object. 9623 ScalarEvolution SE2(F, TLI, AC, DT, LI); 9624 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9625 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 9626 9627 // Now compare whether they're the same with and without caches. This allows 9628 // verifying that no pass changed the cache. 9629 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 9630 "New loops suddenly appeared!"); 9631 9632 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 9633 OldE = BackedgeDumpsOld.end(), 9634 NewI = BackedgeDumpsNew.begin(); 9635 OldI != OldE; ++OldI, ++NewI) { 9636 assert(OldI->first == NewI->first && "Loop order changed!"); 9637 9638 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 9639 // changes. 9640 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 9641 // means that a pass is buggy or SCEV has to learn a new pattern but is 9642 // usually not harmful. 9643 if (OldI->second != NewI->second && 9644 OldI->second.find("undef") == std::string::npos && 9645 NewI->second.find("undef") == std::string::npos && 9646 OldI->second != "***COULDNOTCOMPUTE***" && 9647 NewI->second != "***COULDNOTCOMPUTE***") { 9648 dbgs() << "SCEVValidator: SCEV for loop '" 9649 << OldI->first->getHeader()->getName() 9650 << "' changed from '" << OldI->second 9651 << "' to '" << NewI->second << "'!\n"; 9652 std::abort(); 9653 } 9654 } 9655 9656 // TODO: Verify more things. 9657 } 9658 9659 template class llvm::AnalysisBase<ScalarEvolutionAnalysis>; 9660 9661 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 9662 AnalysisManager<Function> *AM) { 9663 return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F), 9664 AM->getResult<AssumptionAnalysis>(F), 9665 AM->getResult<DominatorTreeAnalysis>(F), 9666 AM->getResult<LoopAnalysis>(F)); 9667 } 9668 9669 PreservedAnalyses 9670 ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) { 9671 AM->getResult<ScalarEvolutionAnalysis>(F).print(OS); 9672 return PreservedAnalyses::all(); 9673 } 9674 9675 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 9676 "Scalar Evolution Analysis", false, true) 9677 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 9678 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 9679 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 9680 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 9681 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 9682 "Scalar Evolution Analysis", false, true) 9683 char ScalarEvolutionWrapperPass::ID = 0; 9684 9685 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 9686 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 9687 } 9688 9689 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 9690 SE.reset(new ScalarEvolution( 9691 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 9692 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 9693 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 9694 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 9695 return false; 9696 } 9697 9698 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 9699 9700 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 9701 SE->print(OS); 9702 } 9703 9704 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 9705 if (!VerifySCEV) 9706 return; 9707 9708 SE->verify(); 9709 } 9710 9711 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 9712 AU.setPreservesAll(); 9713 AU.addRequiredTransitive<AssumptionCacheTracker>(); 9714 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 9715 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 9716 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 9717 } 9718 9719 const SCEVPredicate * 9720 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 9721 const SCEVConstant *RHS) { 9722 FoldingSetNodeID ID; 9723 // Unique this node based on the arguments 9724 ID.AddInteger(SCEVPredicate::P_Equal); 9725 ID.AddPointer(LHS); 9726 ID.AddPointer(RHS); 9727 void *IP = nullptr; 9728 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 9729 return S; 9730 SCEVEqualPredicate *Eq = new (SCEVAllocator) 9731 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 9732 UniquePreds.InsertNode(Eq, IP); 9733 return Eq; 9734 } 9735 9736 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 9737 const SCEVAddRecExpr *AR, 9738 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 9739 FoldingSetNodeID ID; 9740 // Unique this node based on the arguments 9741 ID.AddInteger(SCEVPredicate::P_Wrap); 9742 ID.AddPointer(AR); 9743 ID.AddInteger(AddedFlags); 9744 void *IP = nullptr; 9745 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 9746 return S; 9747 auto *OF = new (SCEVAllocator) 9748 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 9749 UniquePreds.InsertNode(OF, IP); 9750 return OF; 9751 } 9752 9753 namespace { 9754 9755 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 9756 public: 9757 // Rewrites \p S in the context of a loop L and the predicate A. 9758 // If Assume is true, rewrite is free to add further predicates to A 9759 // such that the result will be an AddRecExpr. 9760 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 9761 SCEVUnionPredicate &A, bool Assume) { 9762 SCEVPredicateRewriter Rewriter(L, SE, A, Assume); 9763 return Rewriter.visit(S); 9764 } 9765 9766 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 9767 SCEVUnionPredicate &P, bool Assume) 9768 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} 9769 9770 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 9771 auto ExprPreds = P.getPredicatesForExpr(Expr); 9772 for (auto *Pred : ExprPreds) 9773 if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred)) 9774 if (IPred->getLHS() == Expr) 9775 return IPred->getRHS(); 9776 9777 return Expr; 9778 } 9779 9780 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 9781 const SCEV *Operand = visit(Expr->getOperand()); 9782 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); 9783 if (AR && AR->getLoop() == L && AR->isAffine()) { 9784 // This couldn't be folded because the operand didn't have the nuw 9785 // flag. Add the nusw flag as an assumption that we could make. 9786 const SCEV *Step = AR->getStepRecurrence(SE); 9787 Type *Ty = Expr->getType(); 9788 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 9789 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 9790 SE.getSignExtendExpr(Step, Ty), L, 9791 AR->getNoWrapFlags()); 9792 } 9793 return SE.getZeroExtendExpr(Operand, Expr->getType()); 9794 } 9795 9796 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 9797 const SCEV *Operand = visit(Expr->getOperand()); 9798 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); 9799 if (AR && AR->getLoop() == L && AR->isAffine()) { 9800 // This couldn't be folded because the operand didn't have the nsw 9801 // flag. Add the nssw flag as an assumption that we could make. 9802 const SCEV *Step = AR->getStepRecurrence(SE); 9803 Type *Ty = Expr->getType(); 9804 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 9805 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 9806 SE.getSignExtendExpr(Step, Ty), L, 9807 AR->getNoWrapFlags()); 9808 } 9809 return SE.getSignExtendExpr(Operand, Expr->getType()); 9810 } 9811 9812 private: 9813 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 9814 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 9815 auto *A = SE.getWrapPredicate(AR, AddedFlags); 9816 if (!Assume) { 9817 // Check if we've already made this assumption. 9818 if (P.implies(A)) 9819 return true; 9820 return false; 9821 } 9822 P.add(A); 9823 return true; 9824 } 9825 9826 SCEVUnionPredicate &P; 9827 const Loop *L; 9828 bool Assume; 9829 }; 9830 } // end anonymous namespace 9831 9832 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 9833 SCEVUnionPredicate &Preds) { 9834 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); 9835 } 9836 9837 const SCEV * 9838 ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, 9839 SCEVUnionPredicate &Preds) { 9840 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, true); 9841 } 9842 9843 /// SCEV predicates 9844 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 9845 SCEVPredicateKind Kind) 9846 : FastID(ID), Kind(Kind) {} 9847 9848 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 9849 const SCEVUnknown *LHS, 9850 const SCEVConstant *RHS) 9851 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 9852 9853 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 9854 const auto *Op = dyn_cast<const SCEVEqualPredicate>(N); 9855 9856 if (!Op) 9857 return false; 9858 9859 return Op->LHS == LHS && Op->RHS == RHS; 9860 } 9861 9862 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 9863 9864 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 9865 9866 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 9867 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 9868 } 9869 9870 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 9871 const SCEVAddRecExpr *AR, 9872 IncrementWrapFlags Flags) 9873 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 9874 9875 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 9876 9877 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 9878 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 9879 9880 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 9881 } 9882 9883 bool SCEVWrapPredicate::isAlwaysTrue() const { 9884 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 9885 IncrementWrapFlags IFlags = Flags; 9886 9887 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 9888 IFlags = clearFlags(IFlags, IncrementNSSW); 9889 9890 return IFlags == IncrementAnyWrap; 9891 } 9892 9893 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 9894 OS.indent(Depth) << *getExpr() << " Added Flags: "; 9895 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 9896 OS << "<nusw>"; 9897 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 9898 OS << "<nssw>"; 9899 OS << "\n"; 9900 } 9901 9902 SCEVWrapPredicate::IncrementWrapFlags 9903 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 9904 ScalarEvolution &SE) { 9905 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 9906 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 9907 9908 // We can safely transfer the NSW flag as NSSW. 9909 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 9910 ImpliedFlags = IncrementNSSW; 9911 9912 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 9913 // If the increment is positive, the SCEV NUW flag will also imply the 9914 // WrapPredicate NUSW flag. 9915 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 9916 if (Step->getValue()->getValue().isNonNegative()) 9917 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 9918 } 9919 9920 return ImpliedFlags; 9921 } 9922 9923 /// Union predicates don't get cached so create a dummy set ID for it. 9924 SCEVUnionPredicate::SCEVUnionPredicate() 9925 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 9926 9927 bool SCEVUnionPredicate::isAlwaysTrue() const { 9928 return all_of(Preds, 9929 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 9930 } 9931 9932 ArrayRef<const SCEVPredicate *> 9933 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 9934 auto I = SCEVToPreds.find(Expr); 9935 if (I == SCEVToPreds.end()) 9936 return ArrayRef<const SCEVPredicate *>(); 9937 return I->second; 9938 } 9939 9940 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 9941 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) 9942 return all_of(Set->Preds, 9943 [this](const SCEVPredicate *I) { return this->implies(I); }); 9944 9945 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 9946 if (ScevPredsIt == SCEVToPreds.end()) 9947 return false; 9948 auto &SCEVPreds = ScevPredsIt->second; 9949 9950 return any_of(SCEVPreds, 9951 [N](const SCEVPredicate *I) { return I->implies(N); }); 9952 } 9953 9954 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 9955 9956 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 9957 for (auto Pred : Preds) 9958 Pred->print(OS, Depth); 9959 } 9960 9961 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 9962 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) { 9963 for (auto Pred : Set->Preds) 9964 add(Pred); 9965 return; 9966 } 9967 9968 if (implies(N)) 9969 return; 9970 9971 const SCEV *Key = N->getExpr(); 9972 assert(Key && "Only SCEVUnionPredicate doesn't have an " 9973 " associated expression!"); 9974 9975 SCEVToPreds[Key].push_back(N); 9976 Preds.push_back(N); 9977 } 9978 9979 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 9980 Loop &L) 9981 : SE(SE), L(L), Generation(0) {} 9982 9983 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 9984 const SCEV *Expr = SE.getSCEV(V); 9985 RewriteEntry &Entry = RewriteMap[Expr]; 9986 9987 // If we already have an entry and the version matches, return it. 9988 if (Entry.second && Generation == Entry.first) 9989 return Entry.second; 9990 9991 // We found an entry but it's stale. Rewrite the stale entry 9992 // acording to the current predicate. 9993 if (Entry.second) 9994 Expr = Entry.second; 9995 9996 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 9997 Entry = {Generation, NewSCEV}; 9998 9999 return NewSCEV; 10000 } 10001 10002 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10003 if (Preds.implies(&Pred)) 10004 return; 10005 Preds.add(&Pred); 10006 updateGeneration(); 10007 } 10008 10009 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10010 return Preds; 10011 } 10012 10013 void PredicatedScalarEvolution::updateGeneration() { 10014 // If the generation number wrapped recompute everything. 10015 if (++Generation == 0) { 10016 for (auto &II : RewriteMap) { 10017 const SCEV *Rewritten = II.second.second; 10018 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10019 } 10020 } 10021 } 10022 10023 void PredicatedScalarEvolution::setNoOverflow( 10024 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10025 const SCEV *Expr = getSCEV(V); 10026 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10027 10028 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10029 10030 // Clear the statically implied flags. 10031 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10032 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10033 10034 auto II = FlagsMap.insert({V, Flags}); 10035 if (!II.second) 10036 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10037 } 10038 10039 bool PredicatedScalarEvolution::hasNoOverflow( 10040 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10041 const SCEV *Expr = getSCEV(V); 10042 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10043 10044 Flags = SCEVWrapPredicate::clearFlags( 10045 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10046 10047 auto II = FlagsMap.find(V); 10048 10049 if (II != FlagsMap.end()) 10050 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10051 10052 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10053 } 10054 10055 const SCEV *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10056 const SCEV *Expr = this->getSCEV(V); 10057 const SCEV *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); 10058 updateGeneration(); 10059 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10060 return New; 10061 } 10062 10063 PredicatedScalarEvolution:: 10064 PredicatedScalarEvolution(const PredicatedScalarEvolution &Init) : 10065 RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10066 Generation(Init.Generation) { 10067 for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I) 10068 FlagsMap.insert(*I); 10069 } 10070