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