1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/SmallPtrSet.h" 66 #include "llvm/ADT/Statistic.h" 67 #include "llvm/Analysis/AssumptionCache.h" 68 #include "llvm/Analysis/ConstantFolding.h" 69 #include "llvm/Analysis/InstructionSimplify.h" 70 #include "llvm/Analysis/LoopInfo.h" 71 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 72 #include "llvm/Analysis/TargetLibraryInfo.h" 73 #include "llvm/Analysis/ValueTracking.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Dominators.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/GlobalAlias.h" 81 #include "llvm/IR/GlobalVariable.h" 82 #include "llvm/IR/InstIterator.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/LLVMContext.h" 85 #include "llvm/IR/Metadata.h" 86 #include "llvm/IR/Operator.h" 87 #include "llvm/IR/PatternMatch.h" 88 #include "llvm/Support/CommandLine.h" 89 #include "llvm/Support/Debug.h" 90 #include "llvm/Support/ErrorHandling.h" 91 #include "llvm/Support/MathExtras.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include "llvm/Support/SaveAndRestore.h" 94 #include <algorithm> 95 using namespace llvm; 96 97 #define DEBUG_TYPE "scalar-evolution" 98 99 STATISTIC(NumArrayLenItCounts, 100 "Number of trip counts computed with array length"); 101 STATISTIC(NumTripCountsComputed, 102 "Number of loops with predictable loop counts"); 103 STATISTIC(NumTripCountsNotComputed, 104 "Number of loops without predictable loop counts"); 105 STATISTIC(NumBruteForceTripCountsComputed, 106 "Number of loops with trip counts computed by force"); 107 108 static cl::opt<unsigned> 109 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 110 cl::desc("Maximum number of iterations SCEV will " 111 "symbolically execute a constant " 112 "derived loop"), 113 cl::init(100)); 114 115 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 116 static cl::opt<bool> 117 VerifySCEV("verify-scev", 118 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 119 static cl::opt<bool> 120 VerifySCEVMap("verify-scev-maps", 121 cl::desc("Verify no dangling value in ScalarEvolution's " 122 "ExprValueMap (slow)")); 123 124 //===----------------------------------------------------------------------===// 125 // SCEV class definitions 126 //===----------------------------------------------------------------------===// 127 128 //===----------------------------------------------------------------------===// 129 // Implementation of the SCEV class. 130 // 131 132 LLVM_DUMP_METHOD 133 void SCEV::dump() const { 134 print(dbgs()); 135 dbgs() << '\n'; 136 } 137 138 void SCEV::print(raw_ostream &OS) const { 139 switch (static_cast<SCEVTypes>(getSCEVType())) { 140 case scConstant: 141 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 142 return; 143 case scTruncate: { 144 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 145 const SCEV *Op = Trunc->getOperand(); 146 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 147 << *Trunc->getType() << ")"; 148 return; 149 } 150 case scZeroExtend: { 151 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 152 const SCEV *Op = ZExt->getOperand(); 153 OS << "(zext " << *Op->getType() << " " << *Op << " to " 154 << *ZExt->getType() << ")"; 155 return; 156 } 157 case scSignExtend: { 158 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 159 const SCEV *Op = SExt->getOperand(); 160 OS << "(sext " << *Op->getType() << " " << *Op << " to " 161 << *SExt->getType() << ")"; 162 return; 163 } 164 case scAddRecExpr: { 165 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 166 OS << "{" << *AR->getOperand(0); 167 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 168 OS << ",+," << *AR->getOperand(i); 169 OS << "}<"; 170 if (AR->hasNoUnsignedWrap()) 171 OS << "nuw><"; 172 if (AR->hasNoSignedWrap()) 173 OS << "nsw><"; 174 if (AR->hasNoSelfWrap() && 175 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 176 OS << "nw><"; 177 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 178 OS << ">"; 179 return; 180 } 181 case scAddExpr: 182 case scMulExpr: 183 case scUMaxExpr: 184 case scSMaxExpr: { 185 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 186 const char *OpStr = nullptr; 187 switch (NAry->getSCEVType()) { 188 case scAddExpr: OpStr = " + "; break; 189 case scMulExpr: OpStr = " * "; break; 190 case scUMaxExpr: OpStr = " umax "; break; 191 case scSMaxExpr: OpStr = " smax "; break; 192 } 193 OS << "("; 194 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 195 I != E; ++I) { 196 OS << **I; 197 if (std::next(I) != E) 198 OS << OpStr; 199 } 200 OS << ")"; 201 switch (NAry->getSCEVType()) { 202 case scAddExpr: 203 case scMulExpr: 204 if (NAry->hasNoUnsignedWrap()) 205 OS << "<nuw>"; 206 if (NAry->hasNoSignedWrap()) 207 OS << "<nsw>"; 208 } 209 return; 210 } 211 case scUDivExpr: { 212 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 213 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 214 return; 215 } 216 case scUnknown: { 217 const SCEVUnknown *U = cast<SCEVUnknown>(this); 218 Type *AllocTy; 219 if (U->isSizeOf(AllocTy)) { 220 OS << "sizeof(" << *AllocTy << ")"; 221 return; 222 } 223 if (U->isAlignOf(AllocTy)) { 224 OS << "alignof(" << *AllocTy << ")"; 225 return; 226 } 227 228 Type *CTy; 229 Constant *FieldNo; 230 if (U->isOffsetOf(CTy, FieldNo)) { 231 OS << "offsetof(" << *CTy << ", "; 232 FieldNo->printAsOperand(OS, false); 233 OS << ")"; 234 return; 235 } 236 237 // Otherwise just print it normally. 238 U->getValue()->printAsOperand(OS, false); 239 return; 240 } 241 case scCouldNotCompute: 242 OS << "***COULDNOTCOMPUTE***"; 243 return; 244 } 245 llvm_unreachable("Unknown SCEV kind!"); 246 } 247 248 Type *SCEV::getType() const { 249 switch (static_cast<SCEVTypes>(getSCEVType())) { 250 case scConstant: 251 return cast<SCEVConstant>(this)->getType(); 252 case scTruncate: 253 case scZeroExtend: 254 case scSignExtend: 255 return cast<SCEVCastExpr>(this)->getType(); 256 case scAddRecExpr: 257 case scMulExpr: 258 case scUMaxExpr: 259 case scSMaxExpr: 260 return cast<SCEVNAryExpr>(this)->getType(); 261 case scAddExpr: 262 return cast<SCEVAddExpr>(this)->getType(); 263 case scUDivExpr: 264 return cast<SCEVUDivExpr>(this)->getType(); 265 case scUnknown: 266 return cast<SCEVUnknown>(this)->getType(); 267 case scCouldNotCompute: 268 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 269 } 270 llvm_unreachable("Unknown SCEV kind!"); 271 } 272 273 bool SCEV::isZero() const { 274 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 275 return SC->getValue()->isZero(); 276 return false; 277 } 278 279 bool SCEV::isOne() const { 280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 281 return SC->getValue()->isOne(); 282 return false; 283 } 284 285 bool SCEV::isAllOnesValue() const { 286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 287 return SC->getValue()->isAllOnesValue(); 288 return false; 289 } 290 291 bool SCEV::isNonConstantNegative() const { 292 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 293 if (!Mul) return false; 294 295 // If there is a constant factor, it will be first. 296 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 297 if (!SC) return false; 298 299 // Return true if the value is negative, this matches things like (-42 * V). 300 return SC->getAPInt().isNegative(); 301 } 302 303 SCEVCouldNotCompute::SCEVCouldNotCompute() : 304 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 305 306 bool SCEVCouldNotCompute::classof(const SCEV *S) { 307 return S->getSCEVType() == scCouldNotCompute; 308 } 309 310 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 311 FoldingSetNodeID ID; 312 ID.AddInteger(scConstant); 313 ID.AddPointer(V); 314 void *IP = nullptr; 315 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 316 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 317 UniqueSCEVs.InsertNode(S, IP); 318 return S; 319 } 320 321 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 322 return getConstant(ConstantInt::get(getContext(), Val)); 323 } 324 325 const SCEV * 326 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 327 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 328 return getConstant(ConstantInt::get(ITy, V, isSigned)); 329 } 330 331 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 332 unsigned SCEVTy, const SCEV *op, Type *ty) 333 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 334 335 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 336 const SCEV *op, Type *ty) 337 : SCEVCastExpr(ID, scTruncate, op, ty) { 338 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 339 (Ty->isIntegerTy() || Ty->isPointerTy()) && 340 "Cannot truncate non-integer value!"); 341 } 342 343 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 344 const SCEV *op, Type *ty) 345 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 346 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 347 (Ty->isIntegerTy() || Ty->isPointerTy()) && 348 "Cannot zero extend non-integer value!"); 349 } 350 351 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 352 const SCEV *op, Type *ty) 353 : SCEVCastExpr(ID, scSignExtend, op, ty) { 354 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 355 (Ty->isIntegerTy() || Ty->isPointerTy()) && 356 "Cannot sign extend non-integer value!"); 357 } 358 359 void SCEVUnknown::deleted() { 360 // Clear this SCEVUnknown from various maps. 361 SE->forgetMemoizedResults(this); 362 363 // Remove this SCEVUnknown from the uniquing map. 364 SE->UniqueSCEVs.RemoveNode(this); 365 366 // Release the value. 367 setValPtr(nullptr); 368 } 369 370 void SCEVUnknown::allUsesReplacedWith(Value *New) { 371 // Clear this SCEVUnknown from various maps. 372 SE->forgetMemoizedResults(this); 373 374 // Remove this SCEVUnknown from the uniquing map. 375 SE->UniqueSCEVs.RemoveNode(this); 376 377 // Update this SCEVUnknown to point to the new value. This is needed 378 // because there may still be outstanding SCEVs which still point to 379 // this SCEVUnknown. 380 setValPtr(New); 381 } 382 383 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 384 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 385 if (VCE->getOpcode() == Instruction::PtrToInt) 386 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 387 if (CE->getOpcode() == Instruction::GetElementPtr && 388 CE->getOperand(0)->isNullValue() && 389 CE->getNumOperands() == 2) 390 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 391 if (CI->isOne()) { 392 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 393 ->getElementType(); 394 return true; 395 } 396 397 return false; 398 } 399 400 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 401 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 402 if (VCE->getOpcode() == Instruction::PtrToInt) 403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 404 if (CE->getOpcode() == Instruction::GetElementPtr && 405 CE->getOperand(0)->isNullValue()) { 406 Type *Ty = 407 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 408 if (StructType *STy = dyn_cast<StructType>(Ty)) 409 if (!STy->isPacked() && 410 CE->getNumOperands() == 3 && 411 CE->getOperand(1)->isNullValue()) { 412 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 413 if (CI->isOne() && 414 STy->getNumElements() == 2 && 415 STy->getElementType(0)->isIntegerTy(1)) { 416 AllocTy = STy->getElementType(1); 417 return true; 418 } 419 } 420 } 421 422 return false; 423 } 424 425 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 426 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 427 if (VCE->getOpcode() == Instruction::PtrToInt) 428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 429 if (CE->getOpcode() == Instruction::GetElementPtr && 430 CE->getNumOperands() == 3 && 431 CE->getOperand(0)->isNullValue() && 432 CE->getOperand(1)->isNullValue()) { 433 Type *Ty = 434 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 435 // Ignore vector types here so that ScalarEvolutionExpander doesn't 436 // emit getelementptrs that index into vectors. 437 if (Ty->isStructTy() || Ty->isArrayTy()) { 438 CTy = Ty; 439 FieldNo = CE->getOperand(2); 440 return true; 441 } 442 } 443 444 return false; 445 } 446 447 //===----------------------------------------------------------------------===// 448 // SCEV Utilities 449 //===----------------------------------------------------------------------===// 450 451 static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, 452 Value *RV) { 453 // Order pointer values after integer values. This helps SCEVExpander form 454 // GEPs. 455 bool LIsPointer = LV->getType()->isPointerTy(), 456 RIsPointer = RV->getType()->isPointerTy(); 457 if (LIsPointer != RIsPointer) 458 return (int)LIsPointer - (int)RIsPointer; 459 460 // Compare getValueID values. 461 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 462 if (LID != RID) 463 return (int)LID - (int)RID; 464 465 // Sort arguments by their position. 466 if (const Argument *LA = dyn_cast<Argument>(LV)) { 467 const Argument *RA = cast<Argument>(RV); 468 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 469 return (int)LArgNo - (int)RArgNo; 470 } 471 472 // For instructions, compare their loop depth, and their operand count. This 473 // is pretty loose. 474 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { 475 const Instruction *RInst = cast<Instruction>(RV); 476 477 // Compare loop depths. 478 const BasicBlock *LParent = LInst->getParent(), 479 *RParent = RInst->getParent(); 480 if (LParent != RParent) { 481 unsigned LDepth = LI->getLoopDepth(LParent), 482 RDepth = LI->getLoopDepth(RParent); 483 if (LDepth != RDepth) 484 return (int)LDepth - (int)RDepth; 485 } 486 487 // Compare the number of operands. 488 unsigned LNumOps = LInst->getNumOperands(), 489 RNumOps = RInst->getNumOperands(); 490 return (int)LNumOps - (int)RNumOps; 491 } 492 493 return 0; 494 } 495 496 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 497 // than RHS, respectively. A three-way result allows recursive comparisons to be 498 // more efficient. 499 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, 500 const SCEV *RHS) { 501 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 502 if (LHS == RHS) 503 return 0; 504 505 // Primarily, sort the SCEVs by their getSCEVType(). 506 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 507 if (LType != RType) 508 return (int)LType - (int)RType; 509 510 // Aside from the getSCEVType() ordering, the particular ordering 511 // isn't very important except that it's beneficial to be consistent, 512 // so that (a + b) and (b + a) don't end up as different expressions. 513 switch (static_cast<SCEVTypes>(LType)) { 514 case scUnknown: { 515 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 516 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 517 518 return CompareValueComplexity(LI, LU->getValue(), RU->getValue()); 519 } 520 521 case scConstant: { 522 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 523 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 524 525 // Compare constant values. 526 const APInt &LA = LC->getAPInt(); 527 const APInt &RA = RC->getAPInt(); 528 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 529 if (LBitWidth != RBitWidth) 530 return (int)LBitWidth - (int)RBitWidth; 531 return LA.ult(RA) ? -1 : 1; 532 } 533 534 case scAddRecExpr: { 535 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 536 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 537 538 // Compare addrec loop depths. 539 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 540 if (LLoop != RLoop) { 541 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 542 if (LDepth != RDepth) 543 return (int)LDepth - (int)RDepth; 544 } 545 546 // Addrec complexity grows with operand count. 547 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 548 if (LNumOps != RNumOps) 549 return (int)LNumOps - (int)RNumOps; 550 551 // Lexicographically compare. 552 for (unsigned i = 0; i != LNumOps; ++i) { 553 long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i)); 554 if (X != 0) 555 return X; 556 } 557 558 return 0; 559 } 560 561 case scAddExpr: 562 case scMulExpr: 563 case scSMaxExpr: 564 case scUMaxExpr: { 565 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 566 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 567 568 // Lexicographically compare n-ary expressions. 569 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 570 if (LNumOps != RNumOps) 571 return (int)LNumOps - (int)RNumOps; 572 573 for (unsigned i = 0; i != LNumOps; ++i) { 574 if (i >= RNumOps) 575 return 1; 576 long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i)); 577 if (X != 0) 578 return X; 579 } 580 return (int)LNumOps - (int)RNumOps; 581 } 582 583 case scUDivExpr: { 584 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 585 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 586 587 // Lexicographically compare udiv expressions. 588 long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS()); 589 if (X != 0) 590 return X; 591 return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS()); 592 } 593 594 case scTruncate: 595 case scZeroExtend: 596 case scSignExtend: { 597 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 598 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 599 600 // Compare cast expressions by operand. 601 return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand()); 602 } 603 604 case scCouldNotCompute: 605 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 606 } 607 llvm_unreachable("Unknown SCEV kind!"); 608 } 609 610 /// Given a list of SCEV objects, order them by their complexity, and group 611 /// objects of the same complexity together by value. When this routine is 612 /// finished, we know that any duplicates in the vector are consecutive and that 613 /// complexity is monotonically increasing. 614 /// 615 /// Note that we go take special precautions to ensure that we get deterministic 616 /// results from this routine. In other words, we don't want the results of 617 /// this to depend on where the addresses of various SCEV objects happened to 618 /// land in memory. 619 /// 620 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 621 LoopInfo *LI) { 622 if (Ops.size() < 2) return; // Noop 623 if (Ops.size() == 2) { 624 // This is the common case, which also happens to be trivially simple. 625 // Special case it. 626 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 627 if (CompareSCEVComplexity(LI, RHS, LHS) < 0) 628 std::swap(LHS, RHS); 629 return; 630 } 631 632 // Do the rough sort by complexity. 633 std::stable_sort(Ops.begin(), Ops.end(), 634 [LI](const SCEV *LHS, const SCEV *RHS) { 635 return CompareSCEVComplexity(LI, LHS, RHS) < 0; 636 }); 637 638 // Now that we are sorted by complexity, group elements of the same 639 // complexity. Note that this is, at worst, N^2, but the vector is likely to 640 // be extremely short in practice. Note that we take this approach because we 641 // do not want to depend on the addresses of the objects we are grouping. 642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 643 const SCEV *S = Ops[i]; 644 unsigned Complexity = S->getSCEVType(); 645 646 // If there are any objects of the same complexity and same value as this 647 // one, group them. 648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 649 if (Ops[j] == S) { // Found a duplicate. 650 // Move it to immediately after i'th element. 651 std::swap(Ops[i+1], Ops[j]); 652 ++i; // no need to rescan it. 653 if (i == e-2) return; // Done! 654 } 655 } 656 } 657 } 658 659 // Returns the size of the SCEV S. 660 static inline int sizeOfSCEV(const SCEV *S) { 661 struct FindSCEVSize { 662 int Size; 663 FindSCEVSize() : Size(0) {} 664 665 bool follow(const SCEV *S) { 666 ++Size; 667 // Keep looking at all operands of S. 668 return true; 669 } 670 bool isDone() const { 671 return false; 672 } 673 }; 674 675 FindSCEVSize F; 676 SCEVTraversal<FindSCEVSize> ST(F); 677 ST.visitAll(S); 678 return F.Size; 679 } 680 681 namespace { 682 683 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 684 public: 685 // Computes the Quotient and Remainder of the division of Numerator by 686 // Denominator. 687 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 688 const SCEV *Denominator, const SCEV **Quotient, 689 const SCEV **Remainder) { 690 assert(Numerator && Denominator && "Uninitialized SCEV"); 691 692 SCEVDivision D(SE, Numerator, Denominator); 693 694 // Check for the trivial case here to avoid having to check for it in the 695 // rest of the code. 696 if (Numerator == Denominator) { 697 *Quotient = D.One; 698 *Remainder = D.Zero; 699 return; 700 } 701 702 if (Numerator->isZero()) { 703 *Quotient = D.Zero; 704 *Remainder = D.Zero; 705 return; 706 } 707 708 // A simple case when N/1. The quotient is N. 709 if (Denominator->isOne()) { 710 *Quotient = Numerator; 711 *Remainder = D.Zero; 712 return; 713 } 714 715 // Split the Denominator when it is a product. 716 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 717 const SCEV *Q, *R; 718 *Quotient = Numerator; 719 for (const SCEV *Op : T->operands()) { 720 divide(SE, *Quotient, Op, &Q, &R); 721 *Quotient = Q; 722 723 // Bail out when the Numerator is not divisible by one of the terms of 724 // the Denominator. 725 if (!R->isZero()) { 726 *Quotient = D.Zero; 727 *Remainder = Numerator; 728 return; 729 } 730 } 731 *Remainder = D.Zero; 732 return; 733 } 734 735 D.visit(Numerator); 736 *Quotient = D.Quotient; 737 *Remainder = D.Remainder; 738 } 739 740 // Except in the trivial case described above, we do not know how to divide 741 // Expr by Denominator for the following functions with empty implementation. 742 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 743 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 744 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 745 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 746 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 747 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 748 void visitUnknown(const SCEVUnknown *Numerator) {} 749 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 750 751 void visitConstant(const SCEVConstant *Numerator) { 752 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 753 APInt NumeratorVal = Numerator->getAPInt(); 754 APInt DenominatorVal = D->getAPInt(); 755 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 756 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 757 758 if (NumeratorBW > DenominatorBW) 759 DenominatorVal = DenominatorVal.sext(NumeratorBW); 760 else if (NumeratorBW < DenominatorBW) 761 NumeratorVal = NumeratorVal.sext(DenominatorBW); 762 763 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 764 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 765 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 766 Quotient = SE.getConstant(QuotientVal); 767 Remainder = SE.getConstant(RemainderVal); 768 return; 769 } 770 } 771 772 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 773 const SCEV *StartQ, *StartR, *StepQ, *StepR; 774 if (!Numerator->isAffine()) 775 return cannotDivide(Numerator); 776 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 777 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 778 // Bail out if the types do not match. 779 Type *Ty = Denominator->getType(); 780 if (Ty != StartQ->getType() || Ty != StartR->getType() || 781 Ty != StepQ->getType() || Ty != StepR->getType()) 782 return cannotDivide(Numerator); 783 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 784 Numerator->getNoWrapFlags()); 785 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 786 Numerator->getNoWrapFlags()); 787 } 788 789 void visitAddExpr(const SCEVAddExpr *Numerator) { 790 SmallVector<const SCEV *, 2> Qs, Rs; 791 Type *Ty = Denominator->getType(); 792 793 for (const SCEV *Op : Numerator->operands()) { 794 const SCEV *Q, *R; 795 divide(SE, Op, Denominator, &Q, &R); 796 797 // Bail out if types do not match. 798 if (Ty != Q->getType() || Ty != R->getType()) 799 return cannotDivide(Numerator); 800 801 Qs.push_back(Q); 802 Rs.push_back(R); 803 } 804 805 if (Qs.size() == 1) { 806 Quotient = Qs[0]; 807 Remainder = Rs[0]; 808 return; 809 } 810 811 Quotient = SE.getAddExpr(Qs); 812 Remainder = SE.getAddExpr(Rs); 813 } 814 815 void visitMulExpr(const SCEVMulExpr *Numerator) { 816 SmallVector<const SCEV *, 2> Qs; 817 Type *Ty = Denominator->getType(); 818 819 bool FoundDenominatorTerm = false; 820 for (const SCEV *Op : Numerator->operands()) { 821 // Bail out if types do not match. 822 if (Ty != Op->getType()) 823 return cannotDivide(Numerator); 824 825 if (FoundDenominatorTerm) { 826 Qs.push_back(Op); 827 continue; 828 } 829 830 // Check whether Denominator divides one of the product operands. 831 const SCEV *Q, *R; 832 divide(SE, Op, Denominator, &Q, &R); 833 if (!R->isZero()) { 834 Qs.push_back(Op); 835 continue; 836 } 837 838 // Bail out if types do not match. 839 if (Ty != Q->getType()) 840 return cannotDivide(Numerator); 841 842 FoundDenominatorTerm = true; 843 Qs.push_back(Q); 844 } 845 846 if (FoundDenominatorTerm) { 847 Remainder = Zero; 848 if (Qs.size() == 1) 849 Quotient = Qs[0]; 850 else 851 Quotient = SE.getMulExpr(Qs); 852 return; 853 } 854 855 if (!isa<SCEVUnknown>(Denominator)) 856 return cannotDivide(Numerator); 857 858 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 859 ValueToValueMap RewriteMap; 860 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 861 cast<SCEVConstant>(Zero)->getValue(); 862 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 863 864 if (Remainder->isZero()) { 865 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 866 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 867 cast<SCEVConstant>(One)->getValue(); 868 Quotient = 869 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 870 return; 871 } 872 873 // Quotient is (Numerator - Remainder) divided by Denominator. 874 const SCEV *Q, *R; 875 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 876 // This SCEV does not seem to simplify: fail the division here. 877 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 878 return cannotDivide(Numerator); 879 divide(SE, Diff, Denominator, &Q, &R); 880 if (R != Zero) 881 return cannotDivide(Numerator); 882 Quotient = Q; 883 } 884 885 private: 886 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 887 const SCEV *Denominator) 888 : SE(S), Denominator(Denominator) { 889 Zero = SE.getZero(Denominator->getType()); 890 One = SE.getOne(Denominator->getType()); 891 892 // We generally do not know how to divide Expr by Denominator. We 893 // initialize the division to a "cannot divide" state to simplify the rest 894 // of the code. 895 cannotDivide(Numerator); 896 } 897 898 // Convenience function for giving up on the division. We set the quotient to 899 // be equal to zero and the remainder to be equal to the numerator. 900 void cannotDivide(const SCEV *Numerator) { 901 Quotient = Zero; 902 Remainder = Numerator; 903 } 904 905 ScalarEvolution &SE; 906 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 907 }; 908 909 } 910 911 //===----------------------------------------------------------------------===// 912 // Simple SCEV method implementations 913 //===----------------------------------------------------------------------===// 914 915 /// Compute BC(It, K). The result has width W. Assume, K > 0. 916 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 917 ScalarEvolution &SE, 918 Type *ResultTy) { 919 // Handle the simplest case efficiently. 920 if (K == 1) 921 return SE.getTruncateOrZeroExtend(It, ResultTy); 922 923 // We are using the following formula for BC(It, K): 924 // 925 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 926 // 927 // Suppose, W is the bitwidth of the return value. We must be prepared for 928 // overflow. Hence, we must assure that the result of our computation is 929 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 930 // safe in modular arithmetic. 931 // 932 // However, this code doesn't use exactly that formula; the formula it uses 933 // is something like the following, where T is the number of factors of 2 in 934 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 935 // exponentiation: 936 // 937 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 938 // 939 // This formula is trivially equivalent to the previous formula. However, 940 // this formula can be implemented much more efficiently. The trick is that 941 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 942 // arithmetic. To do exact division in modular arithmetic, all we have 943 // to do is multiply by the inverse. Therefore, this step can be done at 944 // width W. 945 // 946 // The next issue is how to safely do the division by 2^T. The way this 947 // is done is by doing the multiplication step at a width of at least W + T 948 // bits. This way, the bottom W+T bits of the product are accurate. Then, 949 // when we perform the division by 2^T (which is equivalent to a right shift 950 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 951 // truncated out after the division by 2^T. 952 // 953 // In comparison to just directly using the first formula, this technique 954 // is much more efficient; using the first formula requires W * K bits, 955 // but this formula less than W + K bits. Also, the first formula requires 956 // a division step, whereas this formula only requires multiplies and shifts. 957 // 958 // It doesn't matter whether the subtraction step is done in the calculation 959 // width or the input iteration count's width; if the subtraction overflows, 960 // the result must be zero anyway. We prefer here to do it in the width of 961 // the induction variable because it helps a lot for certain cases; CodeGen 962 // isn't smart enough to ignore the overflow, which leads to much less 963 // efficient code if the width of the subtraction is wider than the native 964 // register width. 965 // 966 // (It's possible to not widen at all by pulling out factors of 2 before 967 // the multiplication; for example, K=2 can be calculated as 968 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 969 // extra arithmetic, so it's not an obvious win, and it gets 970 // much more complicated for K > 3.) 971 972 // Protection from insane SCEVs; this bound is conservative, 973 // but it probably doesn't matter. 974 if (K > 1000) 975 return SE.getCouldNotCompute(); 976 977 unsigned W = SE.getTypeSizeInBits(ResultTy); 978 979 // Calculate K! / 2^T and T; we divide out the factors of two before 980 // multiplying for calculating K! / 2^T to avoid overflow. 981 // Other overflow doesn't matter because we only care about the bottom 982 // W bits of the result. 983 APInt OddFactorial(W, 1); 984 unsigned T = 1; 985 for (unsigned i = 3; i <= K; ++i) { 986 APInt Mult(W, i); 987 unsigned TwoFactors = Mult.countTrailingZeros(); 988 T += TwoFactors; 989 Mult = Mult.lshr(TwoFactors); 990 OddFactorial *= Mult; 991 } 992 993 // We need at least W + T bits for the multiplication step 994 unsigned CalculationBits = W + T; 995 996 // Calculate 2^T, at width T+W. 997 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 998 999 // Calculate the multiplicative inverse of K! / 2^T; 1000 // this multiplication factor will perform the exact division by 1001 // K! / 2^T. 1002 APInt Mod = APInt::getSignedMinValue(W+1); 1003 APInt MultiplyFactor = OddFactorial.zext(W+1); 1004 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1005 MultiplyFactor = MultiplyFactor.trunc(W); 1006 1007 // Calculate the product, at width T+W 1008 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1009 CalculationBits); 1010 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1011 for (unsigned i = 1; i != K; ++i) { 1012 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1013 Dividend = SE.getMulExpr(Dividend, 1014 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1015 } 1016 1017 // Divide by 2^T 1018 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1019 1020 // Truncate the result, and divide by K! / 2^T. 1021 1022 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1023 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1024 } 1025 1026 /// Return the value of this chain of recurrences at the specified iteration 1027 /// number. We can evaluate this recurrence by multiplying each element in the 1028 /// chain by the binomial coefficient corresponding to it. In other words, we 1029 /// can evaluate {A,+,B,+,C,+,D} as: 1030 /// 1031 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1032 /// 1033 /// where BC(It, k) stands for binomial coefficient. 1034 /// 1035 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1036 ScalarEvolution &SE) const { 1037 const SCEV *Result = getStart(); 1038 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1039 // The computation is correct in the face of overflow provided that the 1040 // multiplication is performed _after_ the evaluation of the binomial 1041 // coefficient. 1042 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1043 if (isa<SCEVCouldNotCompute>(Coeff)) 1044 return Coeff; 1045 1046 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1047 } 1048 return Result; 1049 } 1050 1051 //===----------------------------------------------------------------------===// 1052 // SCEV Expression folder implementations 1053 //===----------------------------------------------------------------------===// 1054 1055 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1056 Type *Ty) { 1057 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1058 "This is not a truncating conversion!"); 1059 assert(isSCEVable(Ty) && 1060 "This is not a conversion to a SCEVable type!"); 1061 Ty = getEffectiveSCEVType(Ty); 1062 1063 FoldingSetNodeID ID; 1064 ID.AddInteger(scTruncate); 1065 ID.AddPointer(Op); 1066 ID.AddPointer(Ty); 1067 void *IP = nullptr; 1068 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1069 1070 // Fold if the operand is constant. 1071 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1072 return getConstant( 1073 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1074 1075 // trunc(trunc(x)) --> trunc(x) 1076 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1077 return getTruncateExpr(ST->getOperand(), Ty); 1078 1079 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1080 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1081 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1082 1083 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1084 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1085 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1086 1087 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1088 // eliminate all the truncates, or we replace other casts with truncates. 1089 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1090 SmallVector<const SCEV *, 4> Operands; 1091 bool hasTrunc = false; 1092 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1093 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1094 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1095 hasTrunc = isa<SCEVTruncateExpr>(S); 1096 Operands.push_back(S); 1097 } 1098 if (!hasTrunc) 1099 return getAddExpr(Operands); 1100 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1101 } 1102 1103 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1104 // eliminate all the truncates, or we replace other casts with truncates. 1105 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1106 SmallVector<const SCEV *, 4> Operands; 1107 bool hasTrunc = false; 1108 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1109 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1110 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1111 hasTrunc = isa<SCEVTruncateExpr>(S); 1112 Operands.push_back(S); 1113 } 1114 if (!hasTrunc) 1115 return getMulExpr(Operands); 1116 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1117 } 1118 1119 // If the input value is a chrec scev, truncate the chrec's operands. 1120 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1121 SmallVector<const SCEV *, 4> Operands; 1122 for (const SCEV *Op : AddRec->operands()) 1123 Operands.push_back(getTruncateExpr(Op, Ty)); 1124 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1125 } 1126 1127 // The cast wasn't folded; create an explicit cast node. We can reuse 1128 // the existing insert position since if we get here, we won't have 1129 // made any changes which would invalidate it. 1130 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1131 Op, Ty); 1132 UniqueSCEVs.InsertNode(S, IP); 1133 return S; 1134 } 1135 1136 // Get the limit of a recurrence such that incrementing by Step cannot cause 1137 // signed overflow as long as the value of the recurrence within the 1138 // loop does not exceed this limit before incrementing. 1139 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1140 ICmpInst::Predicate *Pred, 1141 ScalarEvolution *SE) { 1142 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1143 if (SE->isKnownPositive(Step)) { 1144 *Pred = ICmpInst::ICMP_SLT; 1145 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1146 SE->getSignedRange(Step).getSignedMax()); 1147 } 1148 if (SE->isKnownNegative(Step)) { 1149 *Pred = ICmpInst::ICMP_SGT; 1150 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1151 SE->getSignedRange(Step).getSignedMin()); 1152 } 1153 return nullptr; 1154 } 1155 1156 // Get the limit of a recurrence such that incrementing by Step cannot cause 1157 // unsigned overflow as long as the value of the recurrence within the loop does 1158 // not exceed this limit before incrementing. 1159 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1160 ICmpInst::Predicate *Pred, 1161 ScalarEvolution *SE) { 1162 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1163 *Pred = ICmpInst::ICMP_ULT; 1164 1165 return SE->getConstant(APInt::getMinValue(BitWidth) - 1166 SE->getUnsignedRange(Step).getUnsignedMax()); 1167 } 1168 1169 namespace { 1170 1171 struct ExtendOpTraitsBase { 1172 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1173 }; 1174 1175 // Used to make code generic over signed and unsigned overflow. 1176 template <typename ExtendOp> struct ExtendOpTraits { 1177 // Members present: 1178 // 1179 // static const SCEV::NoWrapFlags WrapType; 1180 // 1181 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1182 // 1183 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1184 // ICmpInst::Predicate *Pred, 1185 // ScalarEvolution *SE); 1186 }; 1187 1188 template <> 1189 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1190 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1191 1192 static const GetExtendExprTy GetExtendExpr; 1193 1194 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1195 ICmpInst::Predicate *Pred, 1196 ScalarEvolution *SE) { 1197 return getSignedOverflowLimitForStep(Step, Pred, SE); 1198 } 1199 }; 1200 1201 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1202 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1203 1204 template <> 1205 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1206 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1207 1208 static const GetExtendExprTy GetExtendExpr; 1209 1210 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1211 ICmpInst::Predicate *Pred, 1212 ScalarEvolution *SE) { 1213 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1214 } 1215 }; 1216 1217 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1218 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1219 } 1220 1221 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1222 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1223 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1224 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1225 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1226 // expression "Step + sext/zext(PreIncAR)" is congruent with 1227 // "sext/zext(PostIncAR)" 1228 template <typename ExtendOpTy> 1229 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1230 ScalarEvolution *SE) { 1231 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1232 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1233 1234 const Loop *L = AR->getLoop(); 1235 const SCEV *Start = AR->getStart(); 1236 const SCEV *Step = AR->getStepRecurrence(*SE); 1237 1238 // Check for a simple looking step prior to loop entry. 1239 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1240 if (!SA) 1241 return nullptr; 1242 1243 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1244 // subtraction is expensive. For this purpose, perform a quick and dirty 1245 // difference, by checking for Step in the operand list. 1246 SmallVector<const SCEV *, 4> DiffOps; 1247 for (const SCEV *Op : SA->operands()) 1248 if (Op != Step) 1249 DiffOps.push_back(Op); 1250 1251 if (DiffOps.size() == SA->getNumOperands()) 1252 return nullptr; 1253 1254 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1255 // `Step`: 1256 1257 // 1. NSW/NUW flags on the step increment. 1258 auto PreStartFlags = 1259 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1260 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1261 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1262 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1263 1264 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1265 // "S+X does not sign/unsign-overflow". 1266 // 1267 1268 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1269 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1270 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1271 return PreStart; 1272 1273 // 2. Direct overflow check on the step operation's expression. 1274 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1275 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1276 const SCEV *OperandExtendedStart = 1277 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1278 (SE->*GetExtendExpr)(Step, WideTy)); 1279 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1280 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1281 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1282 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1283 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1284 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1285 } 1286 return PreStart; 1287 } 1288 1289 // 3. Loop precondition. 1290 ICmpInst::Predicate Pred; 1291 const SCEV *OverflowLimit = 1292 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1293 1294 if (OverflowLimit && 1295 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1296 return PreStart; 1297 1298 return nullptr; 1299 } 1300 1301 // Get the normalized zero or sign extended expression for this AddRec's Start. 1302 template <typename ExtendOpTy> 1303 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1304 ScalarEvolution *SE) { 1305 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1306 1307 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1308 if (!PreStart) 1309 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1310 1311 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1312 (SE->*GetExtendExpr)(PreStart, Ty)); 1313 } 1314 1315 // Try to prove away overflow by looking at "nearby" add recurrences. A 1316 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1317 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1318 // 1319 // Formally: 1320 // 1321 // {S,+,X} == {S-T,+,X} + T 1322 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1323 // 1324 // If ({S-T,+,X} + T) does not overflow ... (1) 1325 // 1326 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1327 // 1328 // If {S-T,+,X} does not overflow ... (2) 1329 // 1330 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1331 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1332 // 1333 // If (S-T)+T does not overflow ... (3) 1334 // 1335 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1336 // == {Ext(S),+,Ext(X)} == LHS 1337 // 1338 // Thus, if (1), (2) and (3) are true for some T, then 1339 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1340 // 1341 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1342 // does not overflow" restricted to the 0th iteration. Therefore we only need 1343 // to check for (1) and (2). 1344 // 1345 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1346 // is `Delta` (defined below). 1347 // 1348 template <typename ExtendOpTy> 1349 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1350 const SCEV *Step, 1351 const Loop *L) { 1352 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1353 1354 // We restrict `Start` to a constant to prevent SCEV from spending too much 1355 // time here. It is correct (but more expensive) to continue with a 1356 // non-constant `Start` and do a general SCEV subtraction to compute 1357 // `PreStart` below. 1358 // 1359 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1360 if (!StartC) 1361 return false; 1362 1363 APInt StartAI = StartC->getAPInt(); 1364 1365 for (unsigned Delta : {-2, -1, 1, 2}) { 1366 const SCEV *PreStart = getConstant(StartAI - Delta); 1367 1368 FoldingSetNodeID ID; 1369 ID.AddInteger(scAddRecExpr); 1370 ID.AddPointer(PreStart); 1371 ID.AddPointer(Step); 1372 ID.AddPointer(L); 1373 void *IP = nullptr; 1374 const auto *PreAR = 1375 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1376 1377 // Give up if we don't already have the add recurrence we need because 1378 // actually constructing an add recurrence is relatively expensive. 1379 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1380 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1381 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1382 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1383 DeltaS, &Pred, this); 1384 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1385 return true; 1386 } 1387 } 1388 1389 return false; 1390 } 1391 1392 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1393 Type *Ty) { 1394 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1395 "This is not an extending conversion!"); 1396 assert(isSCEVable(Ty) && 1397 "This is not a conversion to a SCEVable type!"); 1398 Ty = getEffectiveSCEVType(Ty); 1399 1400 // Fold if the operand is constant. 1401 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1402 return getConstant( 1403 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1404 1405 // zext(zext(x)) --> zext(x) 1406 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1407 return getZeroExtendExpr(SZ->getOperand(), Ty); 1408 1409 // Before doing any expensive analysis, check to see if we've already 1410 // computed a SCEV for this Op and Ty. 1411 FoldingSetNodeID ID; 1412 ID.AddInteger(scZeroExtend); 1413 ID.AddPointer(Op); 1414 ID.AddPointer(Ty); 1415 void *IP = nullptr; 1416 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1417 1418 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1419 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1420 // It's possible the bits taken off by the truncate were all zero bits. If 1421 // so, we should be able to simplify this further. 1422 const SCEV *X = ST->getOperand(); 1423 ConstantRange CR = getUnsignedRange(X); 1424 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1425 unsigned NewBits = getTypeSizeInBits(Ty); 1426 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1427 CR.zextOrTrunc(NewBits))) 1428 return getTruncateOrZeroExtend(X, Ty); 1429 } 1430 1431 // If the input value is a chrec scev, and we can prove that the value 1432 // did not overflow the old, smaller, value, we can zero extend all of the 1433 // operands (often constants). This allows analysis of something like 1434 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1435 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1436 if (AR->isAffine()) { 1437 const SCEV *Start = AR->getStart(); 1438 const SCEV *Step = AR->getStepRecurrence(*this); 1439 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1440 const Loop *L = AR->getLoop(); 1441 1442 if (!AR->hasNoUnsignedWrap()) { 1443 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1444 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1445 } 1446 1447 // If we have special knowledge that this addrec won't overflow, 1448 // we don't need to do any further analysis. 1449 if (AR->hasNoUnsignedWrap()) 1450 return getAddRecExpr( 1451 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1452 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1453 1454 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1455 // Note that this serves two purposes: It filters out loops that are 1456 // simply not analyzable, and it covers the case where this code is 1457 // being called from within backedge-taken count analysis, such that 1458 // attempting to ask for the backedge-taken count would likely result 1459 // in infinite recursion. In the later case, the analysis code will 1460 // cope with a conservative value, and it will take care to purge 1461 // that value once it has finished. 1462 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1463 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1464 // Manually compute the final value for AR, checking for 1465 // overflow. 1466 1467 // Check whether the backedge-taken count can be losslessly casted to 1468 // the addrec's type. The count is always unsigned. 1469 const SCEV *CastedMaxBECount = 1470 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1471 const SCEV *RecastedMaxBECount = 1472 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1473 if (MaxBECount == RecastedMaxBECount) { 1474 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1475 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1476 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1477 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1478 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1479 const SCEV *WideMaxBECount = 1480 getZeroExtendExpr(CastedMaxBECount, WideTy); 1481 const SCEV *OperandExtendedAdd = 1482 getAddExpr(WideStart, 1483 getMulExpr(WideMaxBECount, 1484 getZeroExtendExpr(Step, WideTy))); 1485 if (ZAdd == OperandExtendedAdd) { 1486 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1487 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1488 // Return the expression with the addrec on the outside. 1489 return getAddRecExpr( 1490 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1491 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1492 } 1493 // Similar to above, only this time treat the step value as signed. 1494 // This covers loops that count down. 1495 OperandExtendedAdd = 1496 getAddExpr(WideStart, 1497 getMulExpr(WideMaxBECount, 1498 getSignExtendExpr(Step, WideTy))); 1499 if (ZAdd == OperandExtendedAdd) { 1500 // Cache knowledge of AR NW, which is propagated to this AddRec. 1501 // Negative step causes unsigned wrap, but it still can't self-wrap. 1502 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1503 // Return the expression with the addrec on the outside. 1504 return getAddRecExpr( 1505 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1506 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1507 } 1508 } 1509 } 1510 1511 // Normally, in the cases we can prove no-overflow via a 1512 // backedge guarding condition, we can also compute a backedge 1513 // taken count for the loop. The exceptions are assumptions and 1514 // guards present in the loop -- SCEV is not great at exploiting 1515 // these to compute max backedge taken counts, but can still use 1516 // these to prove lack of overflow. Use this fact to avoid 1517 // doing extra work that may not pay off. 1518 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1519 !AC.assumptions().empty()) { 1520 // If the backedge is guarded by a comparison with the pre-inc 1521 // value the addrec is safe. Also, if the entry is guarded by 1522 // a comparison with the start value and the backedge is 1523 // guarded by a comparison with the post-inc value, the addrec 1524 // is safe. 1525 if (isKnownPositive(Step)) { 1526 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1527 getUnsignedRange(Step).getUnsignedMax()); 1528 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1529 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1530 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1531 AR->getPostIncExpr(*this), N))) { 1532 // Cache knowledge of AR NUW, which is propagated to this 1533 // AddRec. 1534 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1535 // Return the expression with the addrec on the outside. 1536 return getAddRecExpr( 1537 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1538 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1539 } 1540 } else if (isKnownNegative(Step)) { 1541 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1542 getSignedRange(Step).getSignedMin()); 1543 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1544 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1545 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1546 AR->getPostIncExpr(*this), N))) { 1547 // Cache knowledge of AR NW, which is propagated to this 1548 // AddRec. Negative step causes unsigned wrap, but it 1549 // still can't self-wrap. 1550 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1551 // Return the expression with the addrec on the outside. 1552 return getAddRecExpr( 1553 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1554 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1555 } 1556 } 1557 } 1558 1559 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1560 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1561 return getAddRecExpr( 1562 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1563 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1564 } 1565 } 1566 1567 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1568 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1569 if (SA->hasNoUnsignedWrap()) { 1570 // If the addition does not unsign overflow then we can, by definition, 1571 // commute the zero extension with the addition operation. 1572 SmallVector<const SCEV *, 4> Ops; 1573 for (const auto *Op : SA->operands()) 1574 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1575 return getAddExpr(Ops, SCEV::FlagNUW); 1576 } 1577 } 1578 1579 // The cast wasn't folded; create an explicit cast node. 1580 // Recompute the insert position, as it may have been invalidated. 1581 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1582 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1583 Op, Ty); 1584 UniqueSCEVs.InsertNode(S, IP); 1585 return S; 1586 } 1587 1588 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1589 Type *Ty) { 1590 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1591 "This is not an extending conversion!"); 1592 assert(isSCEVable(Ty) && 1593 "This is not a conversion to a SCEVable type!"); 1594 Ty = getEffectiveSCEVType(Ty); 1595 1596 // Fold if the operand is constant. 1597 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1598 return getConstant( 1599 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1600 1601 // sext(sext(x)) --> sext(x) 1602 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1603 return getSignExtendExpr(SS->getOperand(), Ty); 1604 1605 // sext(zext(x)) --> zext(x) 1606 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1607 return getZeroExtendExpr(SZ->getOperand(), Ty); 1608 1609 // Before doing any expensive analysis, check to see if we've already 1610 // computed a SCEV for this Op and Ty. 1611 FoldingSetNodeID ID; 1612 ID.AddInteger(scSignExtend); 1613 ID.AddPointer(Op); 1614 ID.AddPointer(Ty); 1615 void *IP = nullptr; 1616 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1617 1618 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1619 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1620 // It's possible the bits taken off by the truncate were all sign bits. If 1621 // so, we should be able to simplify this further. 1622 const SCEV *X = ST->getOperand(); 1623 ConstantRange CR = getSignedRange(X); 1624 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1625 unsigned NewBits = getTypeSizeInBits(Ty); 1626 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1627 CR.sextOrTrunc(NewBits))) 1628 return getTruncateOrSignExtend(X, Ty); 1629 } 1630 1631 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1632 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1633 if (SA->getNumOperands() == 2) { 1634 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1635 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1636 if (SMul && SC1) { 1637 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1638 const APInt &C1 = SC1->getAPInt(); 1639 const APInt &C2 = SC2->getAPInt(); 1640 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1641 C2.ugt(C1) && C2.isPowerOf2()) 1642 return getAddExpr(getSignExtendExpr(SC1, Ty), 1643 getSignExtendExpr(SMul, Ty)); 1644 } 1645 } 1646 } 1647 1648 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1649 if (SA->hasNoSignedWrap()) { 1650 // If the addition does not sign overflow then we can, by definition, 1651 // commute the sign extension with the addition operation. 1652 SmallVector<const SCEV *, 4> Ops; 1653 for (const auto *Op : SA->operands()) 1654 Ops.push_back(getSignExtendExpr(Op, Ty)); 1655 return getAddExpr(Ops, SCEV::FlagNSW); 1656 } 1657 } 1658 // If the input value is a chrec scev, and we can prove that the value 1659 // did not overflow the old, smaller, value, we can sign extend all of the 1660 // operands (often constants). This allows analysis of something like 1661 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1662 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1663 if (AR->isAffine()) { 1664 const SCEV *Start = AR->getStart(); 1665 const SCEV *Step = AR->getStepRecurrence(*this); 1666 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1667 const Loop *L = AR->getLoop(); 1668 1669 if (!AR->hasNoSignedWrap()) { 1670 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1671 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1672 } 1673 1674 // If we have special knowledge that this addrec won't overflow, 1675 // we don't need to do any further analysis. 1676 if (AR->hasNoSignedWrap()) 1677 return getAddRecExpr( 1678 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1679 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1680 1681 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1682 // Note that this serves two purposes: It filters out loops that are 1683 // simply not analyzable, and it covers the case where this code is 1684 // being called from within backedge-taken count analysis, such that 1685 // attempting to ask for the backedge-taken count would likely result 1686 // in infinite recursion. In the later case, the analysis code will 1687 // cope with a conservative value, and it will take care to purge 1688 // that value once it has finished. 1689 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1690 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1691 // Manually compute the final value for AR, checking for 1692 // overflow. 1693 1694 // Check whether the backedge-taken count can be losslessly casted to 1695 // the addrec's type. The count is always unsigned. 1696 const SCEV *CastedMaxBECount = 1697 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1698 const SCEV *RecastedMaxBECount = 1699 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1700 if (MaxBECount == RecastedMaxBECount) { 1701 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1702 // Check whether Start+Step*MaxBECount has no signed overflow. 1703 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1704 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1705 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1706 const SCEV *WideMaxBECount = 1707 getZeroExtendExpr(CastedMaxBECount, WideTy); 1708 const SCEV *OperandExtendedAdd = 1709 getAddExpr(WideStart, 1710 getMulExpr(WideMaxBECount, 1711 getSignExtendExpr(Step, WideTy))); 1712 if (SAdd == OperandExtendedAdd) { 1713 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1714 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1715 // Return the expression with the addrec on the outside. 1716 return getAddRecExpr( 1717 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1718 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1719 } 1720 // Similar to above, only this time treat the step value as unsigned. 1721 // This covers loops that count up with an unsigned step. 1722 OperandExtendedAdd = 1723 getAddExpr(WideStart, 1724 getMulExpr(WideMaxBECount, 1725 getZeroExtendExpr(Step, WideTy))); 1726 if (SAdd == OperandExtendedAdd) { 1727 // If AR wraps around then 1728 // 1729 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1730 // => SAdd != OperandExtendedAdd 1731 // 1732 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1733 // (SAdd == OperandExtendedAdd => AR is NW) 1734 1735 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1736 1737 // Return the expression with the addrec on the outside. 1738 return getAddRecExpr( 1739 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1740 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1741 } 1742 } 1743 } 1744 1745 // Normally, in the cases we can prove no-overflow via a 1746 // backedge guarding condition, we can also compute a backedge 1747 // taken count for the loop. The exceptions are assumptions and 1748 // guards present in the loop -- SCEV is not great at exploiting 1749 // these to compute max backedge taken counts, but can still use 1750 // these to prove lack of overflow. Use this fact to avoid 1751 // doing extra work that may not pay off. 1752 1753 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1754 !AC.assumptions().empty()) { 1755 // If the backedge is guarded by a comparison with the pre-inc 1756 // value the addrec is safe. Also, if the entry is guarded by 1757 // a comparison with the start value and the backedge is 1758 // guarded by a comparison with the post-inc value, the addrec 1759 // is safe. 1760 ICmpInst::Predicate Pred; 1761 const SCEV *OverflowLimit = 1762 getSignedOverflowLimitForStep(Step, &Pred, this); 1763 if (OverflowLimit && 1764 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1765 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1766 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1767 OverflowLimit)))) { 1768 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1769 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1770 return getAddRecExpr( 1771 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1772 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1773 } 1774 } 1775 1776 // If Start and Step are constants, check if we can apply this 1777 // transformation: 1778 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1779 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1780 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1781 if (SC1 && SC2) { 1782 const APInt &C1 = SC1->getAPInt(); 1783 const APInt &C2 = SC2->getAPInt(); 1784 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1785 C2.isPowerOf2()) { 1786 Start = getSignExtendExpr(Start, Ty); 1787 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1788 AR->getNoWrapFlags()); 1789 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1790 } 1791 } 1792 1793 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1794 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1795 return getAddRecExpr( 1796 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1797 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1798 } 1799 } 1800 1801 // If the input value is provably positive and we could not simplify 1802 // away the sext build a zext instead. 1803 if (isKnownNonNegative(Op)) 1804 return getZeroExtendExpr(Op, Ty); 1805 1806 // The cast wasn't folded; create an explicit cast node. 1807 // Recompute the insert position, as it may have been invalidated. 1808 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1809 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1810 Op, Ty); 1811 UniqueSCEVs.InsertNode(S, IP); 1812 return S; 1813 } 1814 1815 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1816 /// unspecified bits out to the given type. 1817 /// 1818 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1819 Type *Ty) { 1820 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1821 "This is not an extending conversion!"); 1822 assert(isSCEVable(Ty) && 1823 "This is not a conversion to a SCEVable type!"); 1824 Ty = getEffectiveSCEVType(Ty); 1825 1826 // Sign-extend negative constants. 1827 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1828 if (SC->getAPInt().isNegative()) 1829 return getSignExtendExpr(Op, Ty); 1830 1831 // Peel off a truncate cast. 1832 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1833 const SCEV *NewOp = T->getOperand(); 1834 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1835 return getAnyExtendExpr(NewOp, Ty); 1836 return getTruncateOrNoop(NewOp, Ty); 1837 } 1838 1839 // Next try a zext cast. If the cast is folded, use it. 1840 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1841 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1842 return ZExt; 1843 1844 // Next try a sext cast. If the cast is folded, use it. 1845 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1846 if (!isa<SCEVSignExtendExpr>(SExt)) 1847 return SExt; 1848 1849 // Force the cast to be folded into the operands of an addrec. 1850 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1851 SmallVector<const SCEV *, 4> Ops; 1852 for (const SCEV *Op : AR->operands()) 1853 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1854 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1855 } 1856 1857 // If the expression is obviously signed, use the sext cast value. 1858 if (isa<SCEVSMaxExpr>(Op)) 1859 return SExt; 1860 1861 // Absent any other information, use the zext cast value. 1862 return ZExt; 1863 } 1864 1865 /// Process the given Ops list, which is a list of operands to be added under 1866 /// the given scale, update the given map. This is a helper function for 1867 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1868 /// that would form an add expression like this: 1869 /// 1870 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1871 /// 1872 /// where A and B are constants, update the map with these values: 1873 /// 1874 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1875 /// 1876 /// and add 13 + A*B*29 to AccumulatedConstant. 1877 /// This will allow getAddRecExpr to produce this: 1878 /// 1879 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1880 /// 1881 /// This form often exposes folding opportunities that are hidden in 1882 /// the original operand list. 1883 /// 1884 /// Return true iff it appears that any interesting folding opportunities 1885 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1886 /// the common case where no interesting opportunities are present, and 1887 /// is also used as a check to avoid infinite recursion. 1888 /// 1889 static bool 1890 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1891 SmallVectorImpl<const SCEV *> &NewOps, 1892 APInt &AccumulatedConstant, 1893 const SCEV *const *Ops, size_t NumOperands, 1894 const APInt &Scale, 1895 ScalarEvolution &SE) { 1896 bool Interesting = false; 1897 1898 // Iterate over the add operands. They are sorted, with constants first. 1899 unsigned i = 0; 1900 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1901 ++i; 1902 // Pull a buried constant out to the outside. 1903 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1904 Interesting = true; 1905 AccumulatedConstant += Scale * C->getAPInt(); 1906 } 1907 1908 // Next comes everything else. We're especially interested in multiplies 1909 // here, but they're in the middle, so just visit the rest with one loop. 1910 for (; i != NumOperands; ++i) { 1911 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1912 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1913 APInt NewScale = 1914 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1915 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1916 // A multiplication of a constant with another add; recurse. 1917 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1918 Interesting |= 1919 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1920 Add->op_begin(), Add->getNumOperands(), 1921 NewScale, SE); 1922 } else { 1923 // A multiplication of a constant with some other value. Update 1924 // the map. 1925 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1926 const SCEV *Key = SE.getMulExpr(MulOps); 1927 auto Pair = M.insert({Key, NewScale}); 1928 if (Pair.second) { 1929 NewOps.push_back(Pair.first->first); 1930 } else { 1931 Pair.first->second += NewScale; 1932 // The map already had an entry for this value, which may indicate 1933 // a folding opportunity. 1934 Interesting = true; 1935 } 1936 } 1937 } else { 1938 // An ordinary operand. Update the map. 1939 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1940 M.insert({Ops[i], Scale}); 1941 if (Pair.second) { 1942 NewOps.push_back(Pair.first->first); 1943 } else { 1944 Pair.first->second += Scale; 1945 // The map already had an entry for this value, which may indicate 1946 // a folding opportunity. 1947 Interesting = true; 1948 } 1949 } 1950 } 1951 1952 return Interesting; 1953 } 1954 1955 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 1956 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 1957 // can't-overflow flags for the operation if possible. 1958 static SCEV::NoWrapFlags 1959 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 1960 const SmallVectorImpl<const SCEV *> &Ops, 1961 SCEV::NoWrapFlags Flags) { 1962 using namespace std::placeholders; 1963 typedef OverflowingBinaryOperator OBO; 1964 1965 bool CanAnalyze = 1966 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 1967 (void)CanAnalyze; 1968 assert(CanAnalyze && "don't call from other places!"); 1969 1970 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1971 SCEV::NoWrapFlags SignOrUnsignWrap = 1972 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1973 1974 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1975 auto IsKnownNonNegative = [&](const SCEV *S) { 1976 return SE->isKnownNonNegative(S); 1977 }; 1978 1979 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 1980 Flags = 1981 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1982 1983 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1984 1985 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 1986 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 1987 1988 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 1989 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 1990 1991 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 1992 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 1993 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 1994 Instruction::Add, C, OBO::NoSignedWrap); 1995 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 1996 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 1997 } 1998 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 1999 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2000 Instruction::Add, C, OBO::NoUnsignedWrap); 2001 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2002 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2003 } 2004 } 2005 2006 return Flags; 2007 } 2008 2009 /// Get a canonical add expression, or something simpler if possible. 2010 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2011 SCEV::NoWrapFlags Flags) { 2012 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2013 "only nuw or nsw allowed"); 2014 assert(!Ops.empty() && "Cannot get empty add!"); 2015 if (Ops.size() == 1) return Ops[0]; 2016 #ifndef NDEBUG 2017 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2018 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2019 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2020 "SCEVAddExpr operand types don't match!"); 2021 #endif 2022 2023 // Sort by complexity, this groups all similar expression types together. 2024 GroupByComplexity(Ops, &LI); 2025 2026 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2027 2028 // If there are any constants, fold them together. 2029 unsigned Idx = 0; 2030 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2031 ++Idx; 2032 assert(Idx < Ops.size()); 2033 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2034 // We found two constants, fold them together! 2035 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2036 if (Ops.size() == 2) return Ops[0]; 2037 Ops.erase(Ops.begin()+1); // Erase the folded element 2038 LHSC = cast<SCEVConstant>(Ops[0]); 2039 } 2040 2041 // If we are left with a constant zero being added, strip it off. 2042 if (LHSC->getValue()->isZero()) { 2043 Ops.erase(Ops.begin()); 2044 --Idx; 2045 } 2046 2047 if (Ops.size() == 1) return Ops[0]; 2048 } 2049 2050 // Okay, check to see if the same value occurs in the operand list more than 2051 // once. If so, merge them together into an multiply expression. Since we 2052 // sorted the list, these values are required to be adjacent. 2053 Type *Ty = Ops[0]->getType(); 2054 bool FoundMatch = false; 2055 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2056 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2057 // Scan ahead to count how many equal operands there are. 2058 unsigned Count = 2; 2059 while (i+Count != e && Ops[i+Count] == Ops[i]) 2060 ++Count; 2061 // Merge the values into a multiply. 2062 const SCEV *Scale = getConstant(Ty, Count); 2063 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2064 if (Ops.size() == Count) 2065 return Mul; 2066 Ops[i] = Mul; 2067 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2068 --i; e -= Count - 1; 2069 FoundMatch = true; 2070 } 2071 if (FoundMatch) 2072 return getAddExpr(Ops, Flags); 2073 2074 // Check for truncates. If all the operands are truncated from the same 2075 // type, see if factoring out the truncate would permit the result to be 2076 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2077 // if the contents of the resulting outer trunc fold to something simple. 2078 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2079 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2080 Type *DstType = Trunc->getType(); 2081 Type *SrcType = Trunc->getOperand()->getType(); 2082 SmallVector<const SCEV *, 8> LargeOps; 2083 bool Ok = true; 2084 // Check all the operands to see if they can be represented in the 2085 // source type of the truncate. 2086 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2087 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2088 if (T->getOperand()->getType() != SrcType) { 2089 Ok = false; 2090 break; 2091 } 2092 LargeOps.push_back(T->getOperand()); 2093 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2094 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2095 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2096 SmallVector<const SCEV *, 8> LargeMulOps; 2097 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2098 if (const SCEVTruncateExpr *T = 2099 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2100 if (T->getOperand()->getType() != SrcType) { 2101 Ok = false; 2102 break; 2103 } 2104 LargeMulOps.push_back(T->getOperand()); 2105 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2106 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2107 } else { 2108 Ok = false; 2109 break; 2110 } 2111 } 2112 if (Ok) 2113 LargeOps.push_back(getMulExpr(LargeMulOps)); 2114 } else { 2115 Ok = false; 2116 break; 2117 } 2118 } 2119 if (Ok) { 2120 // Evaluate the expression in the larger type. 2121 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2122 // If it folds to something simple, use it. Otherwise, don't. 2123 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2124 return getTruncateExpr(Fold, DstType); 2125 } 2126 } 2127 2128 // Skip past any other cast SCEVs. 2129 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2130 ++Idx; 2131 2132 // If there are add operands they would be next. 2133 if (Idx < Ops.size()) { 2134 bool DeletedAdd = false; 2135 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2136 // If we have an add, expand the add operands onto the end of the operands 2137 // list. 2138 Ops.erase(Ops.begin()+Idx); 2139 Ops.append(Add->op_begin(), Add->op_end()); 2140 DeletedAdd = true; 2141 } 2142 2143 // If we deleted at least one add, we added operands to the end of the list, 2144 // and they are not necessarily sorted. Recurse to resort and resimplify 2145 // any operands we just acquired. 2146 if (DeletedAdd) 2147 return getAddExpr(Ops); 2148 } 2149 2150 // Skip over the add expression until we get to a multiply. 2151 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2152 ++Idx; 2153 2154 // Check to see if there are any folding opportunities present with 2155 // operands multiplied by constant values. 2156 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2157 uint64_t BitWidth = getTypeSizeInBits(Ty); 2158 DenseMap<const SCEV *, APInt> M; 2159 SmallVector<const SCEV *, 8> NewOps; 2160 APInt AccumulatedConstant(BitWidth, 0); 2161 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2162 Ops.data(), Ops.size(), 2163 APInt(BitWidth, 1), *this)) { 2164 struct APIntCompare { 2165 bool operator()(const APInt &LHS, const APInt &RHS) const { 2166 return LHS.ult(RHS); 2167 } 2168 }; 2169 2170 // Some interesting folding opportunity is present, so its worthwhile to 2171 // re-generate the operands list. Group the operands by constant scale, 2172 // to avoid multiplying by the same constant scale multiple times. 2173 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2174 for (const SCEV *NewOp : NewOps) 2175 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2176 // Re-generate the operands list. 2177 Ops.clear(); 2178 if (AccumulatedConstant != 0) 2179 Ops.push_back(getConstant(AccumulatedConstant)); 2180 for (auto &MulOp : MulOpLists) 2181 if (MulOp.first != 0) 2182 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2183 getAddExpr(MulOp.second))); 2184 if (Ops.empty()) 2185 return getZero(Ty); 2186 if (Ops.size() == 1) 2187 return Ops[0]; 2188 return getAddExpr(Ops); 2189 } 2190 } 2191 2192 // If we are adding something to a multiply expression, make sure the 2193 // something is not already an operand of the multiply. If so, merge it into 2194 // the multiply. 2195 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2196 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2197 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2198 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2199 if (isa<SCEVConstant>(MulOpSCEV)) 2200 continue; 2201 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2202 if (MulOpSCEV == Ops[AddOp]) { 2203 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2204 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2205 if (Mul->getNumOperands() != 2) { 2206 // If the multiply has more than two operands, we must get the 2207 // Y*Z term. 2208 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2209 Mul->op_begin()+MulOp); 2210 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2211 InnerMul = getMulExpr(MulOps); 2212 } 2213 const SCEV *One = getOne(Ty); 2214 const SCEV *AddOne = getAddExpr(One, InnerMul); 2215 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2216 if (Ops.size() == 2) return OuterMul; 2217 if (AddOp < Idx) { 2218 Ops.erase(Ops.begin()+AddOp); 2219 Ops.erase(Ops.begin()+Idx-1); 2220 } else { 2221 Ops.erase(Ops.begin()+Idx); 2222 Ops.erase(Ops.begin()+AddOp-1); 2223 } 2224 Ops.push_back(OuterMul); 2225 return getAddExpr(Ops); 2226 } 2227 2228 // Check this multiply against other multiplies being added together. 2229 for (unsigned OtherMulIdx = Idx+1; 2230 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2231 ++OtherMulIdx) { 2232 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2233 // If MulOp occurs in OtherMul, we can fold the two multiplies 2234 // together. 2235 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2236 OMulOp != e; ++OMulOp) 2237 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2238 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2239 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2240 if (Mul->getNumOperands() != 2) { 2241 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2242 Mul->op_begin()+MulOp); 2243 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2244 InnerMul1 = getMulExpr(MulOps); 2245 } 2246 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2247 if (OtherMul->getNumOperands() != 2) { 2248 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2249 OtherMul->op_begin()+OMulOp); 2250 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2251 InnerMul2 = getMulExpr(MulOps); 2252 } 2253 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2254 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2255 if (Ops.size() == 2) return OuterMul; 2256 Ops.erase(Ops.begin()+Idx); 2257 Ops.erase(Ops.begin()+OtherMulIdx-1); 2258 Ops.push_back(OuterMul); 2259 return getAddExpr(Ops); 2260 } 2261 } 2262 } 2263 } 2264 2265 // If there are any add recurrences in the operands list, see if any other 2266 // added values are loop invariant. If so, we can fold them into the 2267 // recurrence. 2268 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2269 ++Idx; 2270 2271 // Scan over all recurrences, trying to fold loop invariants into them. 2272 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2273 // Scan all of the other operands to this add and add them to the vector if 2274 // they are loop invariant w.r.t. the recurrence. 2275 SmallVector<const SCEV *, 8> LIOps; 2276 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2277 const Loop *AddRecLoop = AddRec->getLoop(); 2278 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2279 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2280 LIOps.push_back(Ops[i]); 2281 Ops.erase(Ops.begin()+i); 2282 --i; --e; 2283 } 2284 2285 // If we found some loop invariants, fold them into the recurrence. 2286 if (!LIOps.empty()) { 2287 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2288 LIOps.push_back(AddRec->getStart()); 2289 2290 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2291 AddRec->op_end()); 2292 // This follows from the fact that the no-wrap flags on the outer add 2293 // expression are applicable on the 0th iteration, when the add recurrence 2294 // will be equal to its start value. 2295 AddRecOps[0] = getAddExpr(LIOps, Flags); 2296 2297 // Build the new addrec. Propagate the NUW and NSW flags if both the 2298 // outer add and the inner addrec are guaranteed to have no overflow. 2299 // Always propagate NW. 2300 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2301 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2302 2303 // If all of the other operands were loop invariant, we are done. 2304 if (Ops.size() == 1) return NewRec; 2305 2306 // Otherwise, add the folded AddRec by the non-invariant parts. 2307 for (unsigned i = 0;; ++i) 2308 if (Ops[i] == AddRec) { 2309 Ops[i] = NewRec; 2310 break; 2311 } 2312 return getAddExpr(Ops); 2313 } 2314 2315 // Okay, if there weren't any loop invariants to be folded, check to see if 2316 // there are multiple AddRec's with the same loop induction variable being 2317 // added together. If so, we can fold them. 2318 for (unsigned OtherIdx = Idx+1; 2319 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2320 ++OtherIdx) 2321 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2322 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2323 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2324 AddRec->op_end()); 2325 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2326 ++OtherIdx) 2327 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2328 if (OtherAddRec->getLoop() == AddRecLoop) { 2329 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2330 i != e; ++i) { 2331 if (i >= AddRecOps.size()) { 2332 AddRecOps.append(OtherAddRec->op_begin()+i, 2333 OtherAddRec->op_end()); 2334 break; 2335 } 2336 AddRecOps[i] = getAddExpr(AddRecOps[i], 2337 OtherAddRec->getOperand(i)); 2338 } 2339 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2340 } 2341 // Step size has changed, so we cannot guarantee no self-wraparound. 2342 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2343 return getAddExpr(Ops); 2344 } 2345 2346 // Otherwise couldn't fold anything into this recurrence. Move onto the 2347 // next one. 2348 } 2349 2350 // Okay, it looks like we really DO need an add expr. Check to see if we 2351 // already have one, otherwise create a new one. 2352 FoldingSetNodeID ID; 2353 ID.AddInteger(scAddExpr); 2354 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2355 ID.AddPointer(Ops[i]); 2356 void *IP = nullptr; 2357 SCEVAddExpr *S = 2358 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2359 if (!S) { 2360 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2361 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2362 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2363 O, Ops.size()); 2364 UniqueSCEVs.InsertNode(S, IP); 2365 } 2366 S->setNoWrapFlags(Flags); 2367 return S; 2368 } 2369 2370 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2371 uint64_t k = i*j; 2372 if (j > 1 && k / j != i) Overflow = true; 2373 return k; 2374 } 2375 2376 /// Compute the result of "n choose k", the binomial coefficient. If an 2377 /// intermediate computation overflows, Overflow will be set and the return will 2378 /// be garbage. Overflow is not cleared on absence of overflow. 2379 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2380 // We use the multiplicative formula: 2381 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2382 // At each iteration, we take the n-th term of the numeral and divide by the 2383 // (k-n)th term of the denominator. This division will always produce an 2384 // integral result, and helps reduce the chance of overflow in the 2385 // intermediate computations. However, we can still overflow even when the 2386 // final result would fit. 2387 2388 if (n == 0 || n == k) return 1; 2389 if (k > n) return 0; 2390 2391 if (k > n/2) 2392 k = n-k; 2393 2394 uint64_t r = 1; 2395 for (uint64_t i = 1; i <= k; ++i) { 2396 r = umul_ov(r, n-(i-1), Overflow); 2397 r /= i; 2398 } 2399 return r; 2400 } 2401 2402 /// Determine if any of the operands in this SCEV are a constant or if 2403 /// any of the add or multiply expressions in this SCEV contain a constant. 2404 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2405 SmallVector<const SCEV *, 4> Ops; 2406 Ops.push_back(StartExpr); 2407 while (!Ops.empty()) { 2408 const SCEV *CurrentExpr = Ops.pop_back_val(); 2409 if (isa<SCEVConstant>(*CurrentExpr)) 2410 return true; 2411 2412 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2413 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2414 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2415 } 2416 } 2417 return false; 2418 } 2419 2420 /// Get a canonical multiply expression, or something simpler if possible. 2421 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2422 SCEV::NoWrapFlags Flags) { 2423 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2424 "only nuw or nsw allowed"); 2425 assert(!Ops.empty() && "Cannot get empty mul!"); 2426 if (Ops.size() == 1) return Ops[0]; 2427 #ifndef NDEBUG 2428 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2429 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2430 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2431 "SCEVMulExpr operand types don't match!"); 2432 #endif 2433 2434 // Sort by complexity, this groups all similar expression types together. 2435 GroupByComplexity(Ops, &LI); 2436 2437 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2438 2439 // If there are any constants, fold them together. 2440 unsigned Idx = 0; 2441 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2442 2443 // C1*(C2+V) -> C1*C2 + C1*V 2444 if (Ops.size() == 2) 2445 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2446 // If any of Add's ops are Adds or Muls with a constant, 2447 // apply this transformation as well. 2448 if (Add->getNumOperands() == 2) 2449 if (containsConstantSomewhere(Add)) 2450 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2451 getMulExpr(LHSC, Add->getOperand(1))); 2452 2453 ++Idx; 2454 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2455 // We found two constants, fold them together! 2456 ConstantInt *Fold = 2457 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2458 Ops[0] = getConstant(Fold); 2459 Ops.erase(Ops.begin()+1); // Erase the folded element 2460 if (Ops.size() == 1) return Ops[0]; 2461 LHSC = cast<SCEVConstant>(Ops[0]); 2462 } 2463 2464 // If we are left with a constant one being multiplied, strip it off. 2465 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2466 Ops.erase(Ops.begin()); 2467 --Idx; 2468 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2469 // If we have a multiply of zero, it will always be zero. 2470 return Ops[0]; 2471 } else if (Ops[0]->isAllOnesValue()) { 2472 // If we have a mul by -1 of an add, try distributing the -1 among the 2473 // add operands. 2474 if (Ops.size() == 2) { 2475 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2476 SmallVector<const SCEV *, 4> NewOps; 2477 bool AnyFolded = false; 2478 for (const SCEV *AddOp : Add->operands()) { 2479 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2480 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2481 NewOps.push_back(Mul); 2482 } 2483 if (AnyFolded) 2484 return getAddExpr(NewOps); 2485 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2486 // Negation preserves a recurrence's no self-wrap property. 2487 SmallVector<const SCEV *, 4> Operands; 2488 for (const SCEV *AddRecOp : AddRec->operands()) 2489 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2490 2491 return getAddRecExpr(Operands, AddRec->getLoop(), 2492 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2493 } 2494 } 2495 } 2496 2497 if (Ops.size() == 1) 2498 return Ops[0]; 2499 } 2500 2501 // Skip over the add expression until we get to a multiply. 2502 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2503 ++Idx; 2504 2505 // If there are mul operands inline them all into this expression. 2506 if (Idx < Ops.size()) { 2507 bool DeletedMul = false; 2508 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2509 // If we have an mul, expand the mul operands onto the end of the operands 2510 // list. 2511 Ops.erase(Ops.begin()+Idx); 2512 Ops.append(Mul->op_begin(), Mul->op_end()); 2513 DeletedMul = true; 2514 } 2515 2516 // If we deleted at least one mul, we added operands to the end of the list, 2517 // and they are not necessarily sorted. Recurse to resort and resimplify 2518 // any operands we just acquired. 2519 if (DeletedMul) 2520 return getMulExpr(Ops); 2521 } 2522 2523 // If there are any add recurrences in the operands list, see if any other 2524 // added values are loop invariant. If so, we can fold them into the 2525 // recurrence. 2526 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2527 ++Idx; 2528 2529 // Scan over all recurrences, trying to fold loop invariants into them. 2530 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2531 // Scan all of the other operands to this mul and add them to the vector if 2532 // they are loop invariant w.r.t. the recurrence. 2533 SmallVector<const SCEV *, 8> LIOps; 2534 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2535 const Loop *AddRecLoop = AddRec->getLoop(); 2536 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2537 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2538 LIOps.push_back(Ops[i]); 2539 Ops.erase(Ops.begin()+i); 2540 --i; --e; 2541 } 2542 2543 // If we found some loop invariants, fold them into the recurrence. 2544 if (!LIOps.empty()) { 2545 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2546 SmallVector<const SCEV *, 4> NewOps; 2547 NewOps.reserve(AddRec->getNumOperands()); 2548 const SCEV *Scale = getMulExpr(LIOps); 2549 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2550 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2551 2552 // Build the new addrec. Propagate the NUW and NSW flags if both the 2553 // outer mul and the inner addrec are guaranteed to have no overflow. 2554 // 2555 // No self-wrap cannot be guaranteed after changing the step size, but 2556 // will be inferred if either NUW or NSW is true. 2557 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2558 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2559 2560 // If all of the other operands were loop invariant, we are done. 2561 if (Ops.size() == 1) return NewRec; 2562 2563 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2564 for (unsigned i = 0;; ++i) 2565 if (Ops[i] == AddRec) { 2566 Ops[i] = NewRec; 2567 break; 2568 } 2569 return getMulExpr(Ops); 2570 } 2571 2572 // Okay, if there weren't any loop invariants to be folded, check to see if 2573 // there are multiple AddRec's with the same loop induction variable being 2574 // multiplied together. If so, we can fold them. 2575 2576 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2577 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2578 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2579 // ]]],+,...up to x=2n}. 2580 // Note that the arguments to choose() are always integers with values 2581 // known at compile time, never SCEV objects. 2582 // 2583 // The implementation avoids pointless extra computations when the two 2584 // addrec's are of different length (mathematically, it's equivalent to 2585 // an infinite stream of zeros on the right). 2586 bool OpsModified = false; 2587 for (unsigned OtherIdx = Idx+1; 2588 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2589 ++OtherIdx) { 2590 const SCEVAddRecExpr *OtherAddRec = 2591 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2592 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2593 continue; 2594 2595 bool Overflow = false; 2596 Type *Ty = AddRec->getType(); 2597 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2598 SmallVector<const SCEV*, 7> AddRecOps; 2599 for (int x = 0, xe = AddRec->getNumOperands() + 2600 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2601 const SCEV *Term = getZero(Ty); 2602 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2603 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2604 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2605 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2606 z < ze && !Overflow; ++z) { 2607 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2608 uint64_t Coeff; 2609 if (LargerThan64Bits) 2610 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2611 else 2612 Coeff = Coeff1*Coeff2; 2613 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2614 const SCEV *Term1 = AddRec->getOperand(y-z); 2615 const SCEV *Term2 = OtherAddRec->getOperand(z); 2616 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2617 } 2618 } 2619 AddRecOps.push_back(Term); 2620 } 2621 if (!Overflow) { 2622 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2623 SCEV::FlagAnyWrap); 2624 if (Ops.size() == 2) return NewAddRec; 2625 Ops[Idx] = NewAddRec; 2626 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2627 OpsModified = true; 2628 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2629 if (!AddRec) 2630 break; 2631 } 2632 } 2633 if (OpsModified) 2634 return getMulExpr(Ops); 2635 2636 // Otherwise couldn't fold anything into this recurrence. Move onto the 2637 // next one. 2638 } 2639 2640 // Okay, it looks like we really DO need an mul expr. Check to see if we 2641 // already have one, otherwise create a new one. 2642 FoldingSetNodeID ID; 2643 ID.AddInteger(scMulExpr); 2644 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2645 ID.AddPointer(Ops[i]); 2646 void *IP = nullptr; 2647 SCEVMulExpr *S = 2648 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2649 if (!S) { 2650 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2651 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2652 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2653 O, Ops.size()); 2654 UniqueSCEVs.InsertNode(S, IP); 2655 } 2656 S->setNoWrapFlags(Flags); 2657 return S; 2658 } 2659 2660 /// Get a canonical unsigned division expression, or something simpler if 2661 /// possible. 2662 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2663 const SCEV *RHS) { 2664 assert(getEffectiveSCEVType(LHS->getType()) == 2665 getEffectiveSCEVType(RHS->getType()) && 2666 "SCEVUDivExpr operand types don't match!"); 2667 2668 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2669 if (RHSC->getValue()->equalsInt(1)) 2670 return LHS; // X udiv 1 --> x 2671 // If the denominator is zero, the result of the udiv is undefined. Don't 2672 // try to analyze it, because the resolution chosen here may differ from 2673 // the resolution chosen in other parts of the compiler. 2674 if (!RHSC->getValue()->isZero()) { 2675 // Determine if the division can be folded into the operands of 2676 // its operands. 2677 // TODO: Generalize this to non-constants by using known-bits information. 2678 Type *Ty = LHS->getType(); 2679 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2680 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2681 // For non-power-of-two values, effectively round the value up to the 2682 // nearest power of two. 2683 if (!RHSC->getAPInt().isPowerOf2()) 2684 ++MaxShiftAmt; 2685 IntegerType *ExtTy = 2686 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2688 if (const SCEVConstant *Step = 2689 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2690 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2691 const APInt &StepInt = Step->getAPInt(); 2692 const APInt &DivInt = RHSC->getAPInt(); 2693 if (!StepInt.urem(DivInt) && 2694 getZeroExtendExpr(AR, ExtTy) == 2695 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2696 getZeroExtendExpr(Step, ExtTy), 2697 AR->getLoop(), SCEV::FlagAnyWrap)) { 2698 SmallVector<const SCEV *, 4> Operands; 2699 for (const SCEV *Op : AR->operands()) 2700 Operands.push_back(getUDivExpr(Op, RHS)); 2701 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2702 } 2703 /// Get a canonical UDivExpr for a recurrence. 2704 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2705 // We can currently only fold X%N if X is constant. 2706 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2707 if (StartC && !DivInt.urem(StepInt) && 2708 getZeroExtendExpr(AR, ExtTy) == 2709 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2710 getZeroExtendExpr(Step, ExtTy), 2711 AR->getLoop(), SCEV::FlagAnyWrap)) { 2712 const APInt &StartInt = StartC->getAPInt(); 2713 const APInt &StartRem = StartInt.urem(StepInt); 2714 if (StartRem != 0) 2715 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2716 AR->getLoop(), SCEV::FlagNW); 2717 } 2718 } 2719 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2720 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2721 SmallVector<const SCEV *, 4> Operands; 2722 for (const SCEV *Op : M->operands()) 2723 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2724 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2725 // Find an operand that's safely divisible. 2726 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2727 const SCEV *Op = M->getOperand(i); 2728 const SCEV *Div = getUDivExpr(Op, RHSC); 2729 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2730 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2731 M->op_end()); 2732 Operands[i] = Div; 2733 return getMulExpr(Operands); 2734 } 2735 } 2736 } 2737 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2738 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2739 SmallVector<const SCEV *, 4> Operands; 2740 for (const SCEV *Op : A->operands()) 2741 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2742 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2743 Operands.clear(); 2744 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2745 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2746 if (isa<SCEVUDivExpr>(Op) || 2747 getMulExpr(Op, RHS) != A->getOperand(i)) 2748 break; 2749 Operands.push_back(Op); 2750 } 2751 if (Operands.size() == A->getNumOperands()) 2752 return getAddExpr(Operands); 2753 } 2754 } 2755 2756 // Fold if both operands are constant. 2757 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2758 Constant *LHSCV = LHSC->getValue(); 2759 Constant *RHSCV = RHSC->getValue(); 2760 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2761 RHSCV))); 2762 } 2763 } 2764 } 2765 2766 FoldingSetNodeID ID; 2767 ID.AddInteger(scUDivExpr); 2768 ID.AddPointer(LHS); 2769 ID.AddPointer(RHS); 2770 void *IP = nullptr; 2771 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2772 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2773 LHS, RHS); 2774 UniqueSCEVs.InsertNode(S, IP); 2775 return S; 2776 } 2777 2778 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2779 APInt A = C1->getAPInt().abs(); 2780 APInt B = C2->getAPInt().abs(); 2781 uint32_t ABW = A.getBitWidth(); 2782 uint32_t BBW = B.getBitWidth(); 2783 2784 if (ABW > BBW) 2785 B = B.zext(ABW); 2786 else if (ABW < BBW) 2787 A = A.zext(BBW); 2788 2789 return APIntOps::GreatestCommonDivisor(A, B); 2790 } 2791 2792 /// Get a canonical unsigned division expression, or something simpler if 2793 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2794 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2795 /// it's not exact because the udiv may be clearing bits. 2796 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2797 const SCEV *RHS) { 2798 // TODO: we could try to find factors in all sorts of things, but for now we 2799 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2800 // end of this file for inspiration. 2801 2802 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2803 if (!Mul) 2804 return getUDivExpr(LHS, RHS); 2805 2806 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2807 // If the mulexpr multiplies by a constant, then that constant must be the 2808 // first element of the mulexpr. 2809 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2810 if (LHSCst == RHSCst) { 2811 SmallVector<const SCEV *, 2> Operands; 2812 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2813 return getMulExpr(Operands); 2814 } 2815 2816 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2817 // that there's a factor provided by one of the other terms. We need to 2818 // check. 2819 APInt Factor = gcd(LHSCst, RHSCst); 2820 if (!Factor.isIntN(1)) { 2821 LHSCst = 2822 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2823 RHSCst = 2824 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2825 SmallVector<const SCEV *, 2> Operands; 2826 Operands.push_back(LHSCst); 2827 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2828 LHS = getMulExpr(Operands); 2829 RHS = RHSCst; 2830 Mul = dyn_cast<SCEVMulExpr>(LHS); 2831 if (!Mul) 2832 return getUDivExactExpr(LHS, RHS); 2833 } 2834 } 2835 } 2836 2837 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2838 if (Mul->getOperand(i) == RHS) { 2839 SmallVector<const SCEV *, 2> Operands; 2840 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2841 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2842 return getMulExpr(Operands); 2843 } 2844 } 2845 2846 return getUDivExpr(LHS, RHS); 2847 } 2848 2849 /// Get an add recurrence expression for the specified loop. Simplify the 2850 /// expression as much as possible. 2851 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2852 const Loop *L, 2853 SCEV::NoWrapFlags Flags) { 2854 SmallVector<const SCEV *, 4> Operands; 2855 Operands.push_back(Start); 2856 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2857 if (StepChrec->getLoop() == L) { 2858 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2859 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2860 } 2861 2862 Operands.push_back(Step); 2863 return getAddRecExpr(Operands, L, Flags); 2864 } 2865 2866 /// Get an add recurrence expression for the specified loop. Simplify the 2867 /// expression as much as possible. 2868 const SCEV * 2869 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2870 const Loop *L, SCEV::NoWrapFlags Flags) { 2871 if (Operands.size() == 1) return Operands[0]; 2872 #ifndef NDEBUG 2873 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2874 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2875 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2876 "SCEVAddRecExpr operand types don't match!"); 2877 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2878 assert(isLoopInvariant(Operands[i], L) && 2879 "SCEVAddRecExpr operand is not loop-invariant!"); 2880 #endif 2881 2882 if (Operands.back()->isZero()) { 2883 Operands.pop_back(); 2884 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2885 } 2886 2887 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2888 // use that information to infer NUW and NSW flags. However, computing a 2889 // BE count requires calling getAddRecExpr, so we may not yet have a 2890 // meaningful BE count at this point (and if we don't, we'd be stuck 2891 // with a SCEVCouldNotCompute as the cached BE count). 2892 2893 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2894 2895 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2896 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2897 const Loop *NestedLoop = NestedAR->getLoop(); 2898 if (L->contains(NestedLoop) 2899 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2900 : (!NestedLoop->contains(L) && 2901 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2902 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2903 NestedAR->op_end()); 2904 Operands[0] = NestedAR->getStart(); 2905 // AddRecs require their operands be loop-invariant with respect to their 2906 // loops. Don't perform this transformation if it would break this 2907 // requirement. 2908 bool AllInvariant = all_of( 2909 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2910 2911 if (AllInvariant) { 2912 // Create a recurrence for the outer loop with the same step size. 2913 // 2914 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2915 // inner recurrence has the same property. 2916 SCEV::NoWrapFlags OuterFlags = 2917 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2918 2919 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2920 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2921 return isLoopInvariant(Op, NestedLoop); 2922 }); 2923 2924 if (AllInvariant) { 2925 // Ok, both add recurrences are valid after the transformation. 2926 // 2927 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2928 // the outer recurrence has the same property. 2929 SCEV::NoWrapFlags InnerFlags = 2930 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2931 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2932 } 2933 } 2934 // Reset Operands to its original state. 2935 Operands[0] = NestedAR; 2936 } 2937 } 2938 2939 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2940 // already have one, otherwise create a new one. 2941 FoldingSetNodeID ID; 2942 ID.AddInteger(scAddRecExpr); 2943 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2944 ID.AddPointer(Operands[i]); 2945 ID.AddPointer(L); 2946 void *IP = nullptr; 2947 SCEVAddRecExpr *S = 2948 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2949 if (!S) { 2950 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2951 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2952 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2953 O, Operands.size(), L); 2954 UniqueSCEVs.InsertNode(S, IP); 2955 } 2956 S->setNoWrapFlags(Flags); 2957 return S; 2958 } 2959 2960 const SCEV * 2961 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 2962 const SmallVectorImpl<const SCEV *> &IndexExprs, 2963 bool InBounds) { 2964 // getSCEV(Base)->getType() has the same address space as Base->getType() 2965 // because SCEV::getType() preserves the address space. 2966 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 2967 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 2968 // instruction to its SCEV, because the Instruction may be guarded by control 2969 // flow and the no-overflow bits may not be valid for the expression in any 2970 // context. This can be fixed similarly to how these flags are handled for 2971 // adds. 2972 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 2973 2974 const SCEV *TotalOffset = getZero(IntPtrTy); 2975 // The address space is unimportant. The first thing we do on CurTy is getting 2976 // its element type. 2977 Type *CurTy = PointerType::getUnqual(PointeeType); 2978 for (const SCEV *IndexExpr : IndexExprs) { 2979 // Compute the (potentially symbolic) offset in bytes for this index. 2980 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2981 // For a struct, add the member offset. 2982 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 2983 unsigned FieldNo = Index->getZExtValue(); 2984 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 2985 2986 // Add the field offset to the running total offset. 2987 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 2988 2989 // Update CurTy to the type of the field at Index. 2990 CurTy = STy->getTypeAtIndex(Index); 2991 } else { 2992 // Update CurTy to its element type. 2993 CurTy = cast<SequentialType>(CurTy)->getElementType(); 2994 // For an array, add the element offset, explicitly scaled. 2995 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 2996 // Getelementptr indices are signed. 2997 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 2998 2999 // Multiply the index by the element size to compute the element offset. 3000 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3001 3002 // Add the element offset to the running total offset. 3003 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3004 } 3005 } 3006 3007 // Add the total offset from all the GEP indices to the base. 3008 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3009 } 3010 3011 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3012 const SCEV *RHS) { 3013 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3014 return getSMaxExpr(Ops); 3015 } 3016 3017 const SCEV * 3018 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3019 assert(!Ops.empty() && "Cannot get empty smax!"); 3020 if (Ops.size() == 1) return Ops[0]; 3021 #ifndef NDEBUG 3022 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3023 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3024 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3025 "SCEVSMaxExpr operand types don't match!"); 3026 #endif 3027 3028 // Sort by complexity, this groups all similar expression types together. 3029 GroupByComplexity(Ops, &LI); 3030 3031 // If there are any constants, fold them together. 3032 unsigned Idx = 0; 3033 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3034 ++Idx; 3035 assert(Idx < Ops.size()); 3036 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3037 // We found two constants, fold them together! 3038 ConstantInt *Fold = ConstantInt::get( 3039 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3040 Ops[0] = getConstant(Fold); 3041 Ops.erase(Ops.begin()+1); // Erase the folded element 3042 if (Ops.size() == 1) return Ops[0]; 3043 LHSC = cast<SCEVConstant>(Ops[0]); 3044 } 3045 3046 // If we are left with a constant minimum-int, strip it off. 3047 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3048 Ops.erase(Ops.begin()); 3049 --Idx; 3050 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3051 // If we have an smax with a constant maximum-int, it will always be 3052 // maximum-int. 3053 return Ops[0]; 3054 } 3055 3056 if (Ops.size() == 1) return Ops[0]; 3057 } 3058 3059 // Find the first SMax 3060 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3061 ++Idx; 3062 3063 // Check to see if one of the operands is an SMax. If so, expand its operands 3064 // onto our operand list, and recurse to simplify. 3065 if (Idx < Ops.size()) { 3066 bool DeletedSMax = false; 3067 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3068 Ops.erase(Ops.begin()+Idx); 3069 Ops.append(SMax->op_begin(), SMax->op_end()); 3070 DeletedSMax = true; 3071 } 3072 3073 if (DeletedSMax) 3074 return getSMaxExpr(Ops); 3075 } 3076 3077 // Okay, check to see if the same value occurs in the operand list twice. If 3078 // so, delete one. Since we sorted the list, these values are required to 3079 // be adjacent. 3080 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3081 // X smax Y smax Y --> X smax Y 3082 // X smax Y --> X, if X is always greater than Y 3083 if (Ops[i] == Ops[i+1] || 3084 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3085 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3086 --i; --e; 3087 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3088 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3089 --i; --e; 3090 } 3091 3092 if (Ops.size() == 1) return Ops[0]; 3093 3094 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3095 3096 // Okay, it looks like we really DO need an smax expr. Check to see if we 3097 // already have one, otherwise create a new one. 3098 FoldingSetNodeID ID; 3099 ID.AddInteger(scSMaxExpr); 3100 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3101 ID.AddPointer(Ops[i]); 3102 void *IP = nullptr; 3103 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3104 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3105 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3106 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3107 O, Ops.size()); 3108 UniqueSCEVs.InsertNode(S, IP); 3109 return S; 3110 } 3111 3112 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3113 const SCEV *RHS) { 3114 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3115 return getUMaxExpr(Ops); 3116 } 3117 3118 const SCEV * 3119 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3120 assert(!Ops.empty() && "Cannot get empty umax!"); 3121 if (Ops.size() == 1) return Ops[0]; 3122 #ifndef NDEBUG 3123 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3124 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3125 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3126 "SCEVUMaxExpr operand types don't match!"); 3127 #endif 3128 3129 // Sort by complexity, this groups all similar expression types together. 3130 GroupByComplexity(Ops, &LI); 3131 3132 // If there are any constants, fold them together. 3133 unsigned Idx = 0; 3134 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3135 ++Idx; 3136 assert(Idx < Ops.size()); 3137 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3138 // We found two constants, fold them together! 3139 ConstantInt *Fold = ConstantInt::get( 3140 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3141 Ops[0] = getConstant(Fold); 3142 Ops.erase(Ops.begin()+1); // Erase the folded element 3143 if (Ops.size() == 1) return Ops[0]; 3144 LHSC = cast<SCEVConstant>(Ops[0]); 3145 } 3146 3147 // If we are left with a constant minimum-int, strip it off. 3148 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3149 Ops.erase(Ops.begin()); 3150 --Idx; 3151 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3152 // If we have an umax with a constant maximum-int, it will always be 3153 // maximum-int. 3154 return Ops[0]; 3155 } 3156 3157 if (Ops.size() == 1) return Ops[0]; 3158 } 3159 3160 // Find the first UMax 3161 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3162 ++Idx; 3163 3164 // Check to see if one of the operands is a UMax. If so, expand its operands 3165 // onto our operand list, and recurse to simplify. 3166 if (Idx < Ops.size()) { 3167 bool DeletedUMax = false; 3168 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3169 Ops.erase(Ops.begin()+Idx); 3170 Ops.append(UMax->op_begin(), UMax->op_end()); 3171 DeletedUMax = true; 3172 } 3173 3174 if (DeletedUMax) 3175 return getUMaxExpr(Ops); 3176 } 3177 3178 // Okay, check to see if the same value occurs in the operand list twice. If 3179 // so, delete one. Since we sorted the list, these values are required to 3180 // be adjacent. 3181 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3182 // X umax Y umax Y --> X umax Y 3183 // X umax Y --> X, if X is always greater than Y 3184 if (Ops[i] == Ops[i+1] || 3185 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3186 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3187 --i; --e; 3188 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3189 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3190 --i; --e; 3191 } 3192 3193 if (Ops.size() == 1) return Ops[0]; 3194 3195 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3196 3197 // Okay, it looks like we really DO need a umax expr. Check to see if we 3198 // already have one, otherwise create a new one. 3199 FoldingSetNodeID ID; 3200 ID.AddInteger(scUMaxExpr); 3201 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3202 ID.AddPointer(Ops[i]); 3203 void *IP = nullptr; 3204 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3205 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3206 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3207 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3208 O, Ops.size()); 3209 UniqueSCEVs.InsertNode(S, IP); 3210 return S; 3211 } 3212 3213 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3214 const SCEV *RHS) { 3215 // ~smax(~x, ~y) == smin(x, y). 3216 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3217 } 3218 3219 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3220 const SCEV *RHS) { 3221 // ~umax(~x, ~y) == umin(x, y) 3222 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3223 } 3224 3225 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3226 // We can bypass creating a target-independent 3227 // constant expression and then folding it back into a ConstantInt. 3228 // This is just a compile-time optimization. 3229 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3230 } 3231 3232 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3233 StructType *STy, 3234 unsigned FieldNo) { 3235 // We can bypass creating a target-independent 3236 // constant expression and then folding it back into a ConstantInt. 3237 // This is just a compile-time optimization. 3238 return getConstant( 3239 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3240 } 3241 3242 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3243 // Don't attempt to do anything other than create a SCEVUnknown object 3244 // here. createSCEV only calls getUnknown after checking for all other 3245 // interesting possibilities, and any other code that calls getUnknown 3246 // is doing so in order to hide a value from SCEV canonicalization. 3247 3248 FoldingSetNodeID ID; 3249 ID.AddInteger(scUnknown); 3250 ID.AddPointer(V); 3251 void *IP = nullptr; 3252 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3253 assert(cast<SCEVUnknown>(S)->getValue() == V && 3254 "Stale SCEVUnknown in uniquing map!"); 3255 return S; 3256 } 3257 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3258 FirstUnknown); 3259 FirstUnknown = cast<SCEVUnknown>(S); 3260 UniqueSCEVs.InsertNode(S, IP); 3261 return S; 3262 } 3263 3264 //===----------------------------------------------------------------------===// 3265 // Basic SCEV Analysis and PHI Idiom Recognition Code 3266 // 3267 3268 /// Test if values of the given type are analyzable within the SCEV 3269 /// framework. This primarily includes integer types, and it can optionally 3270 /// include pointer types if the ScalarEvolution class has access to 3271 /// target-specific information. 3272 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3273 // Integers and pointers are always SCEVable. 3274 return Ty->isIntegerTy() || Ty->isPointerTy(); 3275 } 3276 3277 /// Return the size in bits of the specified type, for which isSCEVable must 3278 /// return true. 3279 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3280 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3281 return getDataLayout().getTypeSizeInBits(Ty); 3282 } 3283 3284 /// Return a type with the same bitwidth as the given type and which represents 3285 /// how SCEV will treat the given type, for which isSCEVable must return 3286 /// true. For pointer types, this is the pointer-sized integer type. 3287 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3288 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3289 3290 if (Ty->isIntegerTy()) 3291 return Ty; 3292 3293 // The only other support type is pointer. 3294 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3295 return getDataLayout().getIntPtrType(Ty); 3296 } 3297 3298 const SCEV *ScalarEvolution::getCouldNotCompute() { 3299 return CouldNotCompute.get(); 3300 } 3301 3302 3303 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3304 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3305 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3306 // is set iff if find such SCEVUnknown. 3307 // 3308 struct FindInvalidSCEVUnknown { 3309 bool FindOne; 3310 FindInvalidSCEVUnknown() { FindOne = false; } 3311 bool follow(const SCEV *S) { 3312 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3313 case scConstant: 3314 return false; 3315 case scUnknown: 3316 if (!cast<SCEVUnknown>(S)->getValue()) 3317 FindOne = true; 3318 return false; 3319 default: 3320 return true; 3321 } 3322 } 3323 bool isDone() const { return FindOne; } 3324 }; 3325 3326 FindInvalidSCEVUnknown F; 3327 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3328 ST.visitAll(S); 3329 3330 return !F.FindOne; 3331 } 3332 3333 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3334 // Helper class working with SCEVTraversal to figure out if a SCEV contains a 3335 // sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set iff 3336 // if such sub scAddRecExpr type SCEV is found. 3337 struct FindAddRecurrence { 3338 bool FoundOne; 3339 FindAddRecurrence() : FoundOne(false) {} 3340 3341 bool follow(const SCEV *S) { 3342 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3343 case scAddRecExpr: 3344 FoundOne = true; 3345 case scConstant: 3346 case scUnknown: 3347 case scCouldNotCompute: 3348 return false; 3349 default: 3350 return true; 3351 } 3352 } 3353 bool isDone() const { return FoundOne; } 3354 }; 3355 3356 HasRecMapType::iterator I = HasRecMap.find(S); 3357 if (I != HasRecMap.end()) 3358 return I->second; 3359 3360 FindAddRecurrence F; 3361 SCEVTraversal<FindAddRecurrence> ST(F); 3362 ST.visitAll(S); 3363 HasRecMap.insert({S, F.FoundOne}); 3364 return F.FoundOne; 3365 } 3366 3367 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3368 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3369 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3370 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3371 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3372 if (!Add) 3373 return {S, nullptr}; 3374 3375 if (Add->getNumOperands() != 2) 3376 return {S, nullptr}; 3377 3378 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3379 if (!ConstOp) 3380 return {S, nullptr}; 3381 3382 return {Add->getOperand(1), ConstOp->getValue()}; 3383 } 3384 3385 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3386 /// by the value and offset from any ValueOffsetPair in the set. 3387 SetVector<ScalarEvolution::ValueOffsetPair> * 3388 ScalarEvolution::getSCEVValues(const SCEV *S) { 3389 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3390 if (SI == ExprValueMap.end()) 3391 return nullptr; 3392 #ifndef NDEBUG 3393 if (VerifySCEVMap) { 3394 // Check there is no dangling Value in the set returned. 3395 for (const auto &VE : SI->second) 3396 assert(ValueExprMap.count(VE.first)); 3397 } 3398 #endif 3399 return &SI->second; 3400 } 3401 3402 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3403 /// cannot be used separately. eraseValueFromMap should be used to remove 3404 /// V from ValueExprMap and ExprValueMap at the same time. 3405 void ScalarEvolution::eraseValueFromMap(Value *V) { 3406 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3407 if (I != ValueExprMap.end()) { 3408 const SCEV *S = I->second; 3409 // Remove {V, 0} from the set of ExprValueMap[S] 3410 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3411 SV->remove({V, nullptr}); 3412 3413 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3414 const SCEV *Stripped; 3415 ConstantInt *Offset; 3416 std::tie(Stripped, Offset) = splitAddExpr(S); 3417 if (Offset != nullptr) { 3418 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3419 SV->remove({V, Offset}); 3420 } 3421 ValueExprMap.erase(V); 3422 } 3423 } 3424 3425 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3426 /// create a new one. 3427 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3428 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3429 3430 const SCEV *S = getExistingSCEV(V); 3431 if (S == nullptr) { 3432 S = createSCEV(V); 3433 // During PHI resolution, it is possible to create two SCEVs for the same 3434 // V, so it is needed to double check whether V->S is inserted into 3435 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3436 std::pair<ValueExprMapType::iterator, bool> Pair = 3437 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3438 if (Pair.second) { 3439 ExprValueMap[S].insert({V, nullptr}); 3440 3441 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3442 // ExprValueMap. 3443 const SCEV *Stripped = S; 3444 ConstantInt *Offset = nullptr; 3445 std::tie(Stripped, Offset) = splitAddExpr(S); 3446 // If stripped is SCEVUnknown, don't bother to save 3447 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3448 // increase the complexity of the expansion code. 3449 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3450 // because it may generate add/sub instead of GEP in SCEV expansion. 3451 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3452 !isa<GetElementPtrInst>(V)) 3453 ExprValueMap[Stripped].insert({V, Offset}); 3454 } 3455 } 3456 return S; 3457 } 3458 3459 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3460 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3461 3462 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3463 if (I != ValueExprMap.end()) { 3464 const SCEV *S = I->second; 3465 if (checkValidity(S)) 3466 return S; 3467 eraseValueFromMap(V); 3468 forgetMemoizedResults(S); 3469 } 3470 return nullptr; 3471 } 3472 3473 /// Return a SCEV corresponding to -V = -1*V 3474 /// 3475 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3476 SCEV::NoWrapFlags Flags) { 3477 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3478 return getConstant( 3479 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3480 3481 Type *Ty = V->getType(); 3482 Ty = getEffectiveSCEVType(Ty); 3483 return getMulExpr( 3484 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3485 } 3486 3487 /// Return a SCEV corresponding to ~V = -1-V 3488 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3489 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3490 return getConstant( 3491 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3492 3493 Type *Ty = V->getType(); 3494 Ty = getEffectiveSCEVType(Ty); 3495 const SCEV *AllOnes = 3496 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3497 return getMinusSCEV(AllOnes, V); 3498 } 3499 3500 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3501 SCEV::NoWrapFlags Flags) { 3502 // Fast path: X - X --> 0. 3503 if (LHS == RHS) 3504 return getZero(LHS->getType()); 3505 3506 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3507 // makes it so that we cannot make much use of NUW. 3508 auto AddFlags = SCEV::FlagAnyWrap; 3509 const bool RHSIsNotMinSigned = 3510 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3511 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3512 // Let M be the minimum representable signed value. Then (-1)*RHS 3513 // signed-wraps if and only if RHS is M. That can happen even for 3514 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3515 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3516 // (-1)*RHS, we need to prove that RHS != M. 3517 // 3518 // If LHS is non-negative and we know that LHS - RHS does not 3519 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3520 // either by proving that RHS > M or that LHS >= 0. 3521 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3522 AddFlags = SCEV::FlagNSW; 3523 } 3524 } 3525 3526 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3527 // RHS is NSW and LHS >= 0. 3528 // 3529 // The difficulty here is that the NSW flag may have been proven 3530 // relative to a loop that is to be found in a recurrence in LHS and 3531 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3532 // larger scope than intended. 3533 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3534 3535 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3536 } 3537 3538 const SCEV * 3539 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3540 Type *SrcTy = V->getType(); 3541 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3542 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3543 "Cannot truncate or zero extend with non-integer arguments!"); 3544 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3545 return V; // No conversion 3546 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3547 return getTruncateExpr(V, Ty); 3548 return getZeroExtendExpr(V, Ty); 3549 } 3550 3551 const SCEV * 3552 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3553 Type *Ty) { 3554 Type *SrcTy = V->getType(); 3555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3556 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3557 "Cannot truncate or zero extend with non-integer arguments!"); 3558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3559 return V; // No conversion 3560 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3561 return getTruncateExpr(V, Ty); 3562 return getSignExtendExpr(V, Ty); 3563 } 3564 3565 const SCEV * 3566 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3567 Type *SrcTy = V->getType(); 3568 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3569 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3570 "Cannot noop or zero extend with non-integer arguments!"); 3571 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3572 "getNoopOrZeroExtend cannot truncate!"); 3573 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3574 return V; // No conversion 3575 return getZeroExtendExpr(V, Ty); 3576 } 3577 3578 const SCEV * 3579 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3580 Type *SrcTy = V->getType(); 3581 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3582 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3583 "Cannot noop or sign extend with non-integer arguments!"); 3584 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3585 "getNoopOrSignExtend cannot truncate!"); 3586 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3587 return V; // No conversion 3588 return getSignExtendExpr(V, Ty); 3589 } 3590 3591 const SCEV * 3592 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3593 Type *SrcTy = V->getType(); 3594 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3595 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3596 "Cannot noop or any extend with non-integer arguments!"); 3597 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3598 "getNoopOrAnyExtend cannot truncate!"); 3599 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3600 return V; // No conversion 3601 return getAnyExtendExpr(V, Ty); 3602 } 3603 3604 const SCEV * 3605 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3606 Type *SrcTy = V->getType(); 3607 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3608 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3609 "Cannot truncate or noop with non-integer arguments!"); 3610 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3611 "getTruncateOrNoop cannot extend!"); 3612 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3613 return V; // No conversion 3614 return getTruncateExpr(V, Ty); 3615 } 3616 3617 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3618 const SCEV *RHS) { 3619 const SCEV *PromotedLHS = LHS; 3620 const SCEV *PromotedRHS = RHS; 3621 3622 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3623 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3624 else 3625 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3626 3627 return getUMaxExpr(PromotedLHS, PromotedRHS); 3628 } 3629 3630 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3631 const SCEV *RHS) { 3632 const SCEV *PromotedLHS = LHS; 3633 const SCEV *PromotedRHS = RHS; 3634 3635 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3636 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3637 else 3638 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3639 3640 return getUMinExpr(PromotedLHS, PromotedRHS); 3641 } 3642 3643 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3644 // A pointer operand may evaluate to a nonpointer expression, such as null. 3645 if (!V->getType()->isPointerTy()) 3646 return V; 3647 3648 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3649 return getPointerBase(Cast->getOperand()); 3650 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3651 const SCEV *PtrOp = nullptr; 3652 for (const SCEV *NAryOp : NAry->operands()) { 3653 if (NAryOp->getType()->isPointerTy()) { 3654 // Cannot find the base of an expression with multiple pointer operands. 3655 if (PtrOp) 3656 return V; 3657 PtrOp = NAryOp; 3658 } 3659 } 3660 if (!PtrOp) 3661 return V; 3662 return getPointerBase(PtrOp); 3663 } 3664 return V; 3665 } 3666 3667 /// Push users of the given Instruction onto the given Worklist. 3668 static void 3669 PushDefUseChildren(Instruction *I, 3670 SmallVectorImpl<Instruction *> &Worklist) { 3671 // Push the def-use children onto the Worklist stack. 3672 for (User *U : I->users()) 3673 Worklist.push_back(cast<Instruction>(U)); 3674 } 3675 3676 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3677 SmallVector<Instruction *, 16> Worklist; 3678 PushDefUseChildren(PN, Worklist); 3679 3680 SmallPtrSet<Instruction *, 8> Visited; 3681 Visited.insert(PN); 3682 while (!Worklist.empty()) { 3683 Instruction *I = Worklist.pop_back_val(); 3684 if (!Visited.insert(I).second) 3685 continue; 3686 3687 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3688 if (It != ValueExprMap.end()) { 3689 const SCEV *Old = It->second; 3690 3691 // Short-circuit the def-use traversal if the symbolic name 3692 // ceases to appear in expressions. 3693 if (Old != SymName && !hasOperand(Old, SymName)) 3694 continue; 3695 3696 // SCEVUnknown for a PHI either means that it has an unrecognized 3697 // structure, it's a PHI that's in the progress of being computed 3698 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3699 // additional loop trip count information isn't going to change anything. 3700 // In the second case, createNodeForPHI will perform the necessary 3701 // updates on its own when it gets to that point. In the third, we do 3702 // want to forget the SCEVUnknown. 3703 if (!isa<PHINode>(I) || 3704 !isa<SCEVUnknown>(Old) || 3705 (I != PN && Old == SymName)) { 3706 eraseValueFromMap(It->first); 3707 forgetMemoizedResults(Old); 3708 } 3709 } 3710 3711 PushDefUseChildren(I, Worklist); 3712 } 3713 } 3714 3715 namespace { 3716 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3717 public: 3718 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3719 ScalarEvolution &SE) { 3720 SCEVInitRewriter Rewriter(L, SE); 3721 const SCEV *Result = Rewriter.visit(S); 3722 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3723 } 3724 3725 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3726 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3727 3728 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3729 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3730 Valid = false; 3731 return Expr; 3732 } 3733 3734 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3735 // Only allow AddRecExprs for this loop. 3736 if (Expr->getLoop() == L) 3737 return Expr->getStart(); 3738 Valid = false; 3739 return Expr; 3740 } 3741 3742 bool isValid() { return Valid; } 3743 3744 private: 3745 const Loop *L; 3746 bool Valid; 3747 }; 3748 3749 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3750 public: 3751 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3752 ScalarEvolution &SE) { 3753 SCEVShiftRewriter Rewriter(L, SE); 3754 const SCEV *Result = Rewriter.visit(S); 3755 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3756 } 3757 3758 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3759 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3760 3761 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3762 // Only allow AddRecExprs for this loop. 3763 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3764 Valid = false; 3765 return Expr; 3766 } 3767 3768 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3769 if (Expr->getLoop() == L && Expr->isAffine()) 3770 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3771 Valid = false; 3772 return Expr; 3773 } 3774 bool isValid() { return Valid; } 3775 3776 private: 3777 const Loop *L; 3778 bool Valid; 3779 }; 3780 } // end anonymous namespace 3781 3782 SCEV::NoWrapFlags 3783 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3784 if (!AR->isAffine()) 3785 return SCEV::FlagAnyWrap; 3786 3787 typedef OverflowingBinaryOperator OBO; 3788 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3789 3790 if (!AR->hasNoSignedWrap()) { 3791 ConstantRange AddRecRange = getSignedRange(AR); 3792 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3793 3794 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3795 Instruction::Add, IncRange, OBO::NoSignedWrap); 3796 if (NSWRegion.contains(AddRecRange)) 3797 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3798 } 3799 3800 if (!AR->hasNoUnsignedWrap()) { 3801 ConstantRange AddRecRange = getUnsignedRange(AR); 3802 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3803 3804 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3805 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3806 if (NUWRegion.contains(AddRecRange)) 3807 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3808 } 3809 3810 return Result; 3811 } 3812 3813 namespace { 3814 /// Represents an abstract binary operation. This may exist as a 3815 /// normal instruction or constant expression, or may have been 3816 /// derived from an expression tree. 3817 struct BinaryOp { 3818 unsigned Opcode; 3819 Value *LHS; 3820 Value *RHS; 3821 bool IsNSW; 3822 bool IsNUW; 3823 3824 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3825 /// constant expression. 3826 Operator *Op; 3827 3828 explicit BinaryOp(Operator *Op) 3829 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3830 IsNSW(false), IsNUW(false), Op(Op) { 3831 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3832 IsNSW = OBO->hasNoSignedWrap(); 3833 IsNUW = OBO->hasNoUnsignedWrap(); 3834 } 3835 } 3836 3837 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3838 bool IsNUW = false) 3839 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3840 Op(nullptr) {} 3841 }; 3842 } 3843 3844 3845 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3846 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3847 auto *Op = dyn_cast<Operator>(V); 3848 if (!Op) 3849 return None; 3850 3851 // Implementation detail: all the cleverness here should happen without 3852 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3853 // SCEV expressions when possible, and we should not break that. 3854 3855 switch (Op->getOpcode()) { 3856 case Instruction::Add: 3857 case Instruction::Sub: 3858 case Instruction::Mul: 3859 case Instruction::UDiv: 3860 case Instruction::And: 3861 case Instruction::Or: 3862 case Instruction::AShr: 3863 case Instruction::Shl: 3864 return BinaryOp(Op); 3865 3866 case Instruction::Xor: 3867 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3868 // If the RHS of the xor is a signbit, then this is just an add. 3869 // Instcombine turns add of signbit into xor as a strength reduction step. 3870 if (RHSC->getValue().isSignBit()) 3871 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3872 return BinaryOp(Op); 3873 3874 case Instruction::LShr: 3875 // Turn logical shift right of a constant into a unsigned divide. 3876 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3877 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3878 3879 // If the shift count is not less than the bitwidth, the result of 3880 // the shift is undefined. Don't try to analyze it, because the 3881 // resolution chosen here may differ from the resolution chosen in 3882 // other parts of the compiler. 3883 if (SA->getValue().ult(BitWidth)) { 3884 Constant *X = 3885 ConstantInt::get(SA->getContext(), 3886 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3887 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3888 } 3889 } 3890 return BinaryOp(Op); 3891 3892 case Instruction::ExtractValue: { 3893 auto *EVI = cast<ExtractValueInst>(Op); 3894 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3895 break; 3896 3897 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3898 if (!CI) 3899 break; 3900 3901 if (auto *F = CI->getCalledFunction()) 3902 switch (F->getIntrinsicID()) { 3903 case Intrinsic::sadd_with_overflow: 3904 case Intrinsic::uadd_with_overflow: { 3905 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3906 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3907 CI->getArgOperand(1)); 3908 3909 // Now that we know that all uses of the arithmetic-result component of 3910 // CI are guarded by the overflow check, we can go ahead and pretend 3911 // that the arithmetic is non-overflowing. 3912 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3913 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3914 CI->getArgOperand(1), /* IsNSW = */ true, 3915 /* IsNUW = */ false); 3916 else 3917 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3918 CI->getArgOperand(1), /* IsNSW = */ false, 3919 /* IsNUW*/ true); 3920 } 3921 3922 case Intrinsic::ssub_with_overflow: 3923 case Intrinsic::usub_with_overflow: 3924 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3925 CI->getArgOperand(1)); 3926 3927 case Intrinsic::smul_with_overflow: 3928 case Intrinsic::umul_with_overflow: 3929 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3930 CI->getArgOperand(1)); 3931 default: 3932 break; 3933 } 3934 } 3935 3936 default: 3937 break; 3938 } 3939 3940 return None; 3941 } 3942 3943 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3944 const Loop *L = LI.getLoopFor(PN->getParent()); 3945 if (!L || L->getHeader() != PN->getParent()) 3946 return nullptr; 3947 3948 // The loop may have multiple entrances or multiple exits; we can analyze 3949 // this phi as an addrec if it has a unique entry value and a unique 3950 // backedge value. 3951 Value *BEValueV = nullptr, *StartValueV = nullptr; 3952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3953 Value *V = PN->getIncomingValue(i); 3954 if (L->contains(PN->getIncomingBlock(i))) { 3955 if (!BEValueV) { 3956 BEValueV = V; 3957 } else if (BEValueV != V) { 3958 BEValueV = nullptr; 3959 break; 3960 } 3961 } else if (!StartValueV) { 3962 StartValueV = V; 3963 } else if (StartValueV != V) { 3964 StartValueV = nullptr; 3965 break; 3966 } 3967 } 3968 if (BEValueV && StartValueV) { 3969 // While we are analyzing this PHI node, handle its value symbolically. 3970 const SCEV *SymbolicName = getUnknown(PN); 3971 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3972 "PHI node already processed?"); 3973 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 3974 3975 // Using this symbolic name for the PHI, analyze the value coming around 3976 // the back-edge. 3977 const SCEV *BEValue = getSCEV(BEValueV); 3978 3979 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3980 // has a special value for the first iteration of the loop. 3981 3982 // If the value coming around the backedge is an add with the symbolic 3983 // value we just inserted, then we found a simple induction variable! 3984 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3985 // If there is a single occurrence of the symbolic value, replace it 3986 // with a recurrence. 3987 unsigned FoundIndex = Add->getNumOperands(); 3988 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3989 if (Add->getOperand(i) == SymbolicName) 3990 if (FoundIndex == e) { 3991 FoundIndex = i; 3992 break; 3993 } 3994 3995 if (FoundIndex != Add->getNumOperands()) { 3996 // Create an add with everything but the specified operand. 3997 SmallVector<const SCEV *, 8> Ops; 3998 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3999 if (i != FoundIndex) 4000 Ops.push_back(Add->getOperand(i)); 4001 const SCEV *Accum = getAddExpr(Ops); 4002 4003 // This is not a valid addrec if the step amount is varying each 4004 // loop iteration, but is not itself an addrec in this loop. 4005 if (isLoopInvariant(Accum, L) || 4006 (isa<SCEVAddRecExpr>(Accum) && 4007 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4008 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4009 4010 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4011 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4012 if (BO->IsNUW) 4013 Flags = setFlags(Flags, SCEV::FlagNUW); 4014 if (BO->IsNSW) 4015 Flags = setFlags(Flags, SCEV::FlagNSW); 4016 } 4017 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4018 // If the increment is an inbounds GEP, then we know the address 4019 // space cannot be wrapped around. We cannot make any guarantee 4020 // about signed or unsigned overflow because pointers are 4021 // unsigned but we may have a negative index from the base 4022 // pointer. We can guarantee that no unsigned wrap occurs if the 4023 // indices form a positive value. 4024 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4025 Flags = setFlags(Flags, SCEV::FlagNW); 4026 4027 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4028 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4029 Flags = setFlags(Flags, SCEV::FlagNUW); 4030 } 4031 4032 // We cannot transfer nuw and nsw flags from subtraction 4033 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4034 // for instance. 4035 } 4036 4037 const SCEV *StartVal = getSCEV(StartValueV); 4038 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4039 4040 // Okay, for the entire analysis of this edge we assumed the PHI 4041 // to be symbolic. We now need to go back and purge all of the 4042 // entries for the scalars that use the symbolic expression. 4043 forgetSymbolicName(PN, SymbolicName); 4044 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4045 4046 // We can add Flags to the post-inc expression only if we 4047 // know that it us *undefined behavior* for BEValueV to 4048 // overflow. 4049 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4050 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4051 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4052 4053 return PHISCEV; 4054 } 4055 } 4056 } else { 4057 // Otherwise, this could be a loop like this: 4058 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4059 // In this case, j = {1,+,1} and BEValue is j. 4060 // Because the other in-value of i (0) fits the evolution of BEValue 4061 // i really is an addrec evolution. 4062 // 4063 // We can generalize this saying that i is the shifted value of BEValue 4064 // by one iteration: 4065 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4066 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4067 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4068 if (Shifted != getCouldNotCompute() && 4069 Start != getCouldNotCompute()) { 4070 const SCEV *StartVal = getSCEV(StartValueV); 4071 if (Start == StartVal) { 4072 // Okay, for the entire analysis of this edge we assumed the PHI 4073 // to be symbolic. We now need to go back and purge all of the 4074 // entries for the scalars that use the symbolic expression. 4075 forgetSymbolicName(PN, SymbolicName); 4076 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4077 return Shifted; 4078 } 4079 } 4080 } 4081 4082 // Remove the temporary PHI node SCEV that has been inserted while intending 4083 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4084 // as it will prevent later (possibly simpler) SCEV expressions to be added 4085 // to the ValueExprMap. 4086 eraseValueFromMap(PN); 4087 } 4088 4089 return nullptr; 4090 } 4091 4092 // Checks if the SCEV S is available at BB. S is considered available at BB 4093 // if S can be materialized at BB without introducing a fault. 4094 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4095 BasicBlock *BB) { 4096 struct CheckAvailable { 4097 bool TraversalDone = false; 4098 bool Available = true; 4099 4100 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4101 BasicBlock *BB = nullptr; 4102 DominatorTree &DT; 4103 4104 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4105 : L(L), BB(BB), DT(DT) {} 4106 4107 bool setUnavailable() { 4108 TraversalDone = true; 4109 Available = false; 4110 return false; 4111 } 4112 4113 bool follow(const SCEV *S) { 4114 switch (S->getSCEVType()) { 4115 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4116 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4117 // These expressions are available if their operand(s) is/are. 4118 return true; 4119 4120 case scAddRecExpr: { 4121 // We allow add recurrences that are on the loop BB is in, or some 4122 // outer loop. This guarantees availability because the value of the 4123 // add recurrence at BB is simply the "current" value of the induction 4124 // variable. We can relax this in the future; for instance an add 4125 // recurrence on a sibling dominating loop is also available at BB. 4126 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4127 if (L && (ARLoop == L || ARLoop->contains(L))) 4128 return true; 4129 4130 return setUnavailable(); 4131 } 4132 4133 case scUnknown: { 4134 // For SCEVUnknown, we check for simple dominance. 4135 const auto *SU = cast<SCEVUnknown>(S); 4136 Value *V = SU->getValue(); 4137 4138 if (isa<Argument>(V)) 4139 return false; 4140 4141 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4142 return false; 4143 4144 return setUnavailable(); 4145 } 4146 4147 case scUDivExpr: 4148 case scCouldNotCompute: 4149 // We do not try to smart about these at all. 4150 return setUnavailable(); 4151 } 4152 llvm_unreachable("switch should be fully covered!"); 4153 } 4154 4155 bool isDone() { return TraversalDone; } 4156 }; 4157 4158 CheckAvailable CA(L, BB, DT); 4159 SCEVTraversal<CheckAvailable> ST(CA); 4160 4161 ST.visitAll(S); 4162 return CA.Available; 4163 } 4164 4165 // Try to match a control flow sequence that branches out at BI and merges back 4166 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4167 // match. 4168 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4169 Value *&C, Value *&LHS, Value *&RHS) { 4170 C = BI->getCondition(); 4171 4172 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4173 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4174 4175 if (!LeftEdge.isSingleEdge()) 4176 return false; 4177 4178 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4179 4180 Use &LeftUse = Merge->getOperandUse(0); 4181 Use &RightUse = Merge->getOperandUse(1); 4182 4183 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4184 LHS = LeftUse; 4185 RHS = RightUse; 4186 return true; 4187 } 4188 4189 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4190 LHS = RightUse; 4191 RHS = LeftUse; 4192 return true; 4193 } 4194 4195 return false; 4196 } 4197 4198 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4199 auto IsReachable = 4200 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4201 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4202 const Loop *L = LI.getLoopFor(PN->getParent()); 4203 4204 // We don't want to break LCSSA, even in a SCEV expression tree. 4205 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4206 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4207 return nullptr; 4208 4209 // Try to match 4210 // 4211 // br %cond, label %left, label %right 4212 // left: 4213 // br label %merge 4214 // right: 4215 // br label %merge 4216 // merge: 4217 // V = phi [ %x, %left ], [ %y, %right ] 4218 // 4219 // as "select %cond, %x, %y" 4220 4221 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4222 assert(IDom && "At least the entry block should dominate PN"); 4223 4224 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4225 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4226 4227 if (BI && BI->isConditional() && 4228 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4229 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4230 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4231 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4232 } 4233 4234 return nullptr; 4235 } 4236 4237 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4238 if (const SCEV *S = createAddRecFromPHI(PN)) 4239 return S; 4240 4241 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4242 return S; 4243 4244 // If the PHI has a single incoming value, follow that value, unless the 4245 // PHI's incoming blocks are in a different loop, in which case doing so 4246 // risks breaking LCSSA form. Instcombine would normally zap these, but 4247 // it doesn't have DominatorTree information, so it may miss cases. 4248 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4249 if (LI.replacementPreservesLCSSAForm(PN, V)) 4250 return getSCEV(V); 4251 4252 // If it's not a loop phi, we can't handle it yet. 4253 return getUnknown(PN); 4254 } 4255 4256 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4257 Value *Cond, 4258 Value *TrueVal, 4259 Value *FalseVal) { 4260 // Handle "constant" branch or select. This can occur for instance when a 4261 // loop pass transforms an inner loop and moves on to process the outer loop. 4262 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4263 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4264 4265 // Try to match some simple smax or umax patterns. 4266 auto *ICI = dyn_cast<ICmpInst>(Cond); 4267 if (!ICI) 4268 return getUnknown(I); 4269 4270 Value *LHS = ICI->getOperand(0); 4271 Value *RHS = ICI->getOperand(1); 4272 4273 switch (ICI->getPredicate()) { 4274 case ICmpInst::ICMP_SLT: 4275 case ICmpInst::ICMP_SLE: 4276 std::swap(LHS, RHS); 4277 LLVM_FALLTHROUGH; 4278 case ICmpInst::ICMP_SGT: 4279 case ICmpInst::ICMP_SGE: 4280 // a >s b ? a+x : b+x -> smax(a, b)+x 4281 // a >s b ? b+x : a+x -> smin(a, b)+x 4282 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4283 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4284 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4285 const SCEV *LA = getSCEV(TrueVal); 4286 const SCEV *RA = getSCEV(FalseVal); 4287 const SCEV *LDiff = getMinusSCEV(LA, LS); 4288 const SCEV *RDiff = getMinusSCEV(RA, RS); 4289 if (LDiff == RDiff) 4290 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4291 LDiff = getMinusSCEV(LA, RS); 4292 RDiff = getMinusSCEV(RA, LS); 4293 if (LDiff == RDiff) 4294 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4295 } 4296 break; 4297 case ICmpInst::ICMP_ULT: 4298 case ICmpInst::ICMP_ULE: 4299 std::swap(LHS, RHS); 4300 LLVM_FALLTHROUGH; 4301 case ICmpInst::ICMP_UGT: 4302 case ICmpInst::ICMP_UGE: 4303 // a >u b ? a+x : b+x -> umax(a, b)+x 4304 // a >u b ? b+x : a+x -> umin(a, b)+x 4305 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4306 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4307 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4308 const SCEV *LA = getSCEV(TrueVal); 4309 const SCEV *RA = getSCEV(FalseVal); 4310 const SCEV *LDiff = getMinusSCEV(LA, LS); 4311 const SCEV *RDiff = getMinusSCEV(RA, RS); 4312 if (LDiff == RDiff) 4313 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4314 LDiff = getMinusSCEV(LA, RS); 4315 RDiff = getMinusSCEV(RA, LS); 4316 if (LDiff == RDiff) 4317 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4318 } 4319 break; 4320 case ICmpInst::ICMP_NE: 4321 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4322 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4323 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4324 const SCEV *One = getOne(I->getType()); 4325 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4326 const SCEV *LA = getSCEV(TrueVal); 4327 const SCEV *RA = getSCEV(FalseVal); 4328 const SCEV *LDiff = getMinusSCEV(LA, LS); 4329 const SCEV *RDiff = getMinusSCEV(RA, One); 4330 if (LDiff == RDiff) 4331 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4332 } 4333 break; 4334 case ICmpInst::ICMP_EQ: 4335 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4336 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4337 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4338 const SCEV *One = getOne(I->getType()); 4339 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4340 const SCEV *LA = getSCEV(TrueVal); 4341 const SCEV *RA = getSCEV(FalseVal); 4342 const SCEV *LDiff = getMinusSCEV(LA, One); 4343 const SCEV *RDiff = getMinusSCEV(RA, LS); 4344 if (LDiff == RDiff) 4345 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4346 } 4347 break; 4348 default: 4349 break; 4350 } 4351 4352 return getUnknown(I); 4353 } 4354 4355 /// Expand GEP instructions into add and multiply operations. This allows them 4356 /// to be analyzed by regular SCEV code. 4357 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4358 // Don't attempt to analyze GEPs over unsized objects. 4359 if (!GEP->getSourceElementType()->isSized()) 4360 return getUnknown(GEP); 4361 4362 SmallVector<const SCEV *, 4> IndexExprs; 4363 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4364 IndexExprs.push_back(getSCEV(*Index)); 4365 return getGEPExpr(GEP->getSourceElementType(), 4366 getSCEV(GEP->getPointerOperand()), 4367 IndexExprs, GEP->isInBounds()); 4368 } 4369 4370 uint32_t 4371 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4372 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4373 return C->getAPInt().countTrailingZeros(); 4374 4375 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4376 return std::min(GetMinTrailingZeros(T->getOperand()), 4377 (uint32_t)getTypeSizeInBits(T->getType())); 4378 4379 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4380 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4381 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4382 getTypeSizeInBits(E->getType()) : OpRes; 4383 } 4384 4385 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4386 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4387 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4388 getTypeSizeInBits(E->getType()) : OpRes; 4389 } 4390 4391 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4392 // The result is the min of all operands results. 4393 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4394 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4395 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4396 return MinOpRes; 4397 } 4398 4399 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4400 // The result is the sum of all operands results. 4401 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4402 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4403 for (unsigned i = 1, e = M->getNumOperands(); 4404 SumOpRes != BitWidth && i != e; ++i) 4405 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4406 BitWidth); 4407 return SumOpRes; 4408 } 4409 4410 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4411 // The result is the min of all operands results. 4412 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4413 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4414 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4415 return MinOpRes; 4416 } 4417 4418 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4419 // The result is the min of all operands results. 4420 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4421 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4422 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4423 return MinOpRes; 4424 } 4425 4426 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4427 // The result is the min of all operands results. 4428 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4429 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4430 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4431 return MinOpRes; 4432 } 4433 4434 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4435 // For a SCEVUnknown, ask ValueTracking. 4436 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4437 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4438 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4439 nullptr, &DT); 4440 return Zeros.countTrailingOnes(); 4441 } 4442 4443 // SCEVUDivExpr 4444 return 0; 4445 } 4446 4447 /// Helper method to assign a range to V from metadata present in the IR. 4448 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4449 if (Instruction *I = dyn_cast<Instruction>(V)) 4450 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4451 return getConstantRangeFromMetadata(*MD); 4452 4453 return None; 4454 } 4455 4456 /// Determine the range for a particular SCEV. If SignHint is 4457 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4458 /// with a "cleaner" unsigned (resp. signed) representation. 4459 ConstantRange 4460 ScalarEvolution::getRange(const SCEV *S, 4461 ScalarEvolution::RangeSignHint SignHint) { 4462 DenseMap<const SCEV *, ConstantRange> &Cache = 4463 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4464 : SignedRanges; 4465 4466 // See if we've computed this range already. 4467 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4468 if (I != Cache.end()) 4469 return I->second; 4470 4471 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4472 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4473 4474 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4475 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4476 4477 // If the value has known zeros, the maximum value will have those known zeros 4478 // as well. 4479 uint32_t TZ = GetMinTrailingZeros(S); 4480 if (TZ != 0) { 4481 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4482 ConservativeResult = 4483 ConstantRange(APInt::getMinValue(BitWidth), 4484 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4485 else 4486 ConservativeResult = ConstantRange( 4487 APInt::getSignedMinValue(BitWidth), 4488 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4489 } 4490 4491 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4492 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4493 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4494 X = X.add(getRange(Add->getOperand(i), SignHint)); 4495 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4496 } 4497 4498 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4499 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4500 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4501 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4502 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4503 } 4504 4505 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4506 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4507 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4508 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4509 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4510 } 4511 4512 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4513 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4514 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4515 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4516 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4517 } 4518 4519 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4520 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4521 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4522 return setRange(UDiv, SignHint, 4523 ConservativeResult.intersectWith(X.udiv(Y))); 4524 } 4525 4526 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4527 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4528 return setRange(ZExt, SignHint, 4529 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4530 } 4531 4532 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4533 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4534 return setRange(SExt, SignHint, 4535 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4536 } 4537 4538 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4539 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4540 return setRange(Trunc, SignHint, 4541 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4542 } 4543 4544 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4545 // If there's no unsigned wrap, the value will never be less than its 4546 // initial value. 4547 if (AddRec->hasNoUnsignedWrap()) 4548 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4549 if (!C->getValue()->isZero()) 4550 ConservativeResult = ConservativeResult.intersectWith( 4551 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4552 4553 // If there's no signed wrap, and all the operands have the same sign or 4554 // zero, the value won't ever change sign. 4555 if (AddRec->hasNoSignedWrap()) { 4556 bool AllNonNeg = true; 4557 bool AllNonPos = true; 4558 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4559 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4560 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4561 } 4562 if (AllNonNeg) 4563 ConservativeResult = ConservativeResult.intersectWith( 4564 ConstantRange(APInt(BitWidth, 0), 4565 APInt::getSignedMinValue(BitWidth))); 4566 else if (AllNonPos) 4567 ConservativeResult = ConservativeResult.intersectWith( 4568 ConstantRange(APInt::getSignedMinValue(BitWidth), 4569 APInt(BitWidth, 1))); 4570 } 4571 4572 // TODO: non-affine addrec 4573 if (AddRec->isAffine()) { 4574 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4575 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4576 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4577 auto RangeFromAffine = getRangeForAffineAR( 4578 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4579 BitWidth); 4580 if (!RangeFromAffine.isFullSet()) 4581 ConservativeResult = 4582 ConservativeResult.intersectWith(RangeFromAffine); 4583 4584 auto RangeFromFactoring = getRangeViaFactoring( 4585 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4586 BitWidth); 4587 if (!RangeFromFactoring.isFullSet()) 4588 ConservativeResult = 4589 ConservativeResult.intersectWith(RangeFromFactoring); 4590 } 4591 } 4592 4593 return setRange(AddRec, SignHint, ConservativeResult); 4594 } 4595 4596 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4597 // Check if the IR explicitly contains !range metadata. 4598 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4599 if (MDRange.hasValue()) 4600 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4601 4602 // Split here to avoid paying the compile-time cost of calling both 4603 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4604 // if needed. 4605 const DataLayout &DL = getDataLayout(); 4606 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4607 // For a SCEVUnknown, ask ValueTracking. 4608 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4609 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4610 if (Ones != ~Zeros + 1) 4611 ConservativeResult = 4612 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4613 } else { 4614 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4615 "generalize as needed!"); 4616 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4617 if (NS > 1) 4618 ConservativeResult = ConservativeResult.intersectWith( 4619 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4620 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4621 } 4622 4623 return setRange(U, SignHint, ConservativeResult); 4624 } 4625 4626 return setRange(S, SignHint, ConservativeResult); 4627 } 4628 4629 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4630 const SCEV *Step, 4631 const SCEV *MaxBECount, 4632 unsigned BitWidth) { 4633 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4634 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4635 "Precondition!"); 4636 4637 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4638 4639 // Check for overflow. This must be done with ConstantRange arithmetic 4640 // because we could be called from within the ScalarEvolution overflow 4641 // checking code. 4642 4643 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4644 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4645 ConstantRange ZExtMaxBECountRange = 4646 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4647 4648 ConstantRange StepSRange = getSignedRange(Step); 4649 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4650 4651 ConstantRange StartURange = getUnsignedRange(Start); 4652 ConstantRange EndURange = 4653 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4654 4655 // Check for unsigned overflow. 4656 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4657 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4658 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4659 ZExtEndURange) { 4660 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4661 EndURange.getUnsignedMin()); 4662 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4663 EndURange.getUnsignedMax()); 4664 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4665 if (!IsFullRange) 4666 Result = 4667 Result.intersectWith(ConstantRange(Min, Max + 1)); 4668 } 4669 4670 ConstantRange StartSRange = getSignedRange(Start); 4671 ConstantRange EndSRange = 4672 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4673 4674 // Check for signed overflow. This must be done with ConstantRange 4675 // arithmetic because we could be called from within the ScalarEvolution 4676 // overflow checking code. 4677 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4678 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4679 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4680 SExtEndSRange) { 4681 APInt Min = 4682 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4683 APInt Max = 4684 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4685 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4686 if (!IsFullRange) 4687 Result = 4688 Result.intersectWith(ConstantRange(Min, Max + 1)); 4689 } 4690 4691 return Result; 4692 } 4693 4694 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4695 const SCEV *Step, 4696 const SCEV *MaxBECount, 4697 unsigned BitWidth) { 4698 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4699 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4700 4701 struct SelectPattern { 4702 Value *Condition = nullptr; 4703 APInt TrueValue; 4704 APInt FalseValue; 4705 4706 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4707 const SCEV *S) { 4708 Optional<unsigned> CastOp; 4709 APInt Offset(BitWidth, 0); 4710 4711 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4712 "Should be!"); 4713 4714 // Peel off a constant offset: 4715 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4716 // In the future we could consider being smarter here and handle 4717 // {Start+Step,+,Step} too. 4718 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4719 return; 4720 4721 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4722 S = SA->getOperand(1); 4723 } 4724 4725 // Peel off a cast operation 4726 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4727 CastOp = SCast->getSCEVType(); 4728 S = SCast->getOperand(); 4729 } 4730 4731 using namespace llvm::PatternMatch; 4732 4733 auto *SU = dyn_cast<SCEVUnknown>(S); 4734 const APInt *TrueVal, *FalseVal; 4735 if (!SU || 4736 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4737 m_APInt(FalseVal)))) { 4738 Condition = nullptr; 4739 return; 4740 } 4741 4742 TrueValue = *TrueVal; 4743 FalseValue = *FalseVal; 4744 4745 // Re-apply the cast we peeled off earlier 4746 if (CastOp.hasValue()) 4747 switch (*CastOp) { 4748 default: 4749 llvm_unreachable("Unknown SCEV cast type!"); 4750 4751 case scTruncate: 4752 TrueValue = TrueValue.trunc(BitWidth); 4753 FalseValue = FalseValue.trunc(BitWidth); 4754 break; 4755 case scZeroExtend: 4756 TrueValue = TrueValue.zext(BitWidth); 4757 FalseValue = FalseValue.zext(BitWidth); 4758 break; 4759 case scSignExtend: 4760 TrueValue = TrueValue.sext(BitWidth); 4761 FalseValue = FalseValue.sext(BitWidth); 4762 break; 4763 } 4764 4765 // Re-apply the constant offset we peeled off earlier 4766 TrueValue += Offset; 4767 FalseValue += Offset; 4768 } 4769 4770 bool isRecognized() { return Condition != nullptr; } 4771 }; 4772 4773 SelectPattern StartPattern(*this, BitWidth, Start); 4774 if (!StartPattern.isRecognized()) 4775 return ConstantRange(BitWidth, /* isFullSet = */ true); 4776 4777 SelectPattern StepPattern(*this, BitWidth, Step); 4778 if (!StepPattern.isRecognized()) 4779 return ConstantRange(BitWidth, /* isFullSet = */ true); 4780 4781 if (StartPattern.Condition != StepPattern.Condition) { 4782 // We don't handle this case today; but we could, by considering four 4783 // possibilities below instead of two. I'm not sure if there are cases where 4784 // that will help over what getRange already does, though. 4785 return ConstantRange(BitWidth, /* isFullSet = */ true); 4786 } 4787 4788 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4789 // construct arbitrary general SCEV expressions here. This function is called 4790 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4791 // say) can end up caching a suboptimal value. 4792 4793 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4794 // C2352 and C2512 (otherwise it isn't needed). 4795 4796 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4797 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4798 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4799 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4800 4801 ConstantRange TrueRange = 4802 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4803 ConstantRange FalseRange = 4804 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4805 4806 return TrueRange.unionWith(FalseRange); 4807 } 4808 4809 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4810 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4811 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4812 4813 // Return early if there are no flags to propagate to the SCEV. 4814 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4815 if (BinOp->hasNoUnsignedWrap()) 4816 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4817 if (BinOp->hasNoSignedWrap()) 4818 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4819 if (Flags == SCEV::FlagAnyWrap) 4820 return SCEV::FlagAnyWrap; 4821 4822 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4823 } 4824 4825 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4826 // Here we check that I is in the header of the innermost loop containing I, 4827 // since we only deal with instructions in the loop header. The actual loop we 4828 // need to check later will come from an add recurrence, but getting that 4829 // requires computing the SCEV of the operands, which can be expensive. This 4830 // check we can do cheaply to rule out some cases early. 4831 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4832 if (InnermostContainingLoop == nullptr || 4833 InnermostContainingLoop->getHeader() != I->getParent()) 4834 return false; 4835 4836 // Only proceed if we can prove that I does not yield poison. 4837 if (!isKnownNotFullPoison(I)) return false; 4838 4839 // At this point we know that if I is executed, then it does not wrap 4840 // according to at least one of NSW or NUW. If I is not executed, then we do 4841 // not know if the calculation that I represents would wrap. Multiple 4842 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4843 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4844 // derived from other instructions that map to the same SCEV. We cannot make 4845 // that guarantee for cases where I is not executed. So we need to find the 4846 // loop that I is considered in relation to and prove that I is executed for 4847 // every iteration of that loop. That implies that the value that I 4848 // calculates does not wrap anywhere in the loop, so then we can apply the 4849 // flags to the SCEV. 4850 // 4851 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4852 // from different loops, so that we know which loop to prove that I is 4853 // executed in. 4854 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4855 // I could be an extractvalue from a call to an overflow intrinsic. 4856 // TODO: We can do better here in some cases. 4857 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4858 return false; 4859 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4860 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4861 bool AllOtherOpsLoopInvariant = true; 4862 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4863 ++OtherOpIndex) { 4864 if (OtherOpIndex != OpIndex) { 4865 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4866 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4867 AllOtherOpsLoopInvariant = false; 4868 break; 4869 } 4870 } 4871 } 4872 if (AllOtherOpsLoopInvariant && 4873 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4874 return true; 4875 } 4876 } 4877 return false; 4878 } 4879 4880 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4881 // If we know that \c I can never be poison period, then that's enough. 4882 if (isSCEVExprNeverPoison(I)) 4883 return true; 4884 4885 // For an add recurrence specifically, we assume that infinite loops without 4886 // side effects are undefined behavior, and then reason as follows: 4887 // 4888 // If the add recurrence is poison in any iteration, it is poison on all 4889 // future iterations (since incrementing poison yields poison). If the result 4890 // of the add recurrence is fed into the loop latch condition and the loop 4891 // does not contain any throws or exiting blocks other than the latch, we now 4892 // have the ability to "choose" whether the backedge is taken or not (by 4893 // choosing a sufficiently evil value for the poison feeding into the branch) 4894 // for every iteration including and after the one in which \p I first became 4895 // poison. There are two possibilities (let's call the iteration in which \p 4896 // I first became poison as K): 4897 // 4898 // 1. In the set of iterations including and after K, the loop body executes 4899 // no side effects. In this case executing the backege an infinte number 4900 // of times will yield undefined behavior. 4901 // 4902 // 2. In the set of iterations including and after K, the loop body executes 4903 // at least one side effect. In this case, that specific instance of side 4904 // effect is control dependent on poison, which also yields undefined 4905 // behavior. 4906 4907 auto *ExitingBB = L->getExitingBlock(); 4908 auto *LatchBB = L->getLoopLatch(); 4909 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4910 return false; 4911 4912 SmallPtrSet<const Instruction *, 16> Pushed; 4913 SmallVector<const Instruction *, 8> PoisonStack; 4914 4915 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4916 // things that are known to be fully poison under that assumption go on the 4917 // PoisonStack. 4918 Pushed.insert(I); 4919 PoisonStack.push_back(I); 4920 4921 bool LatchControlDependentOnPoison = false; 4922 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4923 const Instruction *Poison = PoisonStack.pop_back_val(); 4924 4925 for (auto *PoisonUser : Poison->users()) { 4926 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4927 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4928 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4929 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4930 assert(BI->isConditional() && "Only possibility!"); 4931 if (BI->getParent() == LatchBB) { 4932 LatchControlDependentOnPoison = true; 4933 break; 4934 } 4935 } 4936 } 4937 } 4938 4939 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4940 } 4941 4942 ScalarEvolution::LoopProperties 4943 ScalarEvolution::getLoopProperties(const Loop *L) { 4944 typedef ScalarEvolution::LoopProperties LoopProperties; 4945 4946 auto Itr = LoopPropertiesCache.find(L); 4947 if (Itr == LoopPropertiesCache.end()) { 4948 auto HasSideEffects = [](Instruction *I) { 4949 if (auto *SI = dyn_cast<StoreInst>(I)) 4950 return !SI->isSimple(); 4951 4952 return I->mayHaveSideEffects(); 4953 }; 4954 4955 LoopProperties LP = {/* HasNoAbnormalExits */ true, 4956 /*HasNoSideEffects*/ true}; 4957 4958 for (auto *BB : L->getBlocks()) 4959 for (auto &I : *BB) { 4960 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4961 LP.HasNoAbnormalExits = false; 4962 if (HasSideEffects(&I)) 4963 LP.HasNoSideEffects = false; 4964 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 4965 break; // We're already as pessimistic as we can get. 4966 } 4967 4968 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 4969 assert(InsertPair.second && "We just checked!"); 4970 Itr = InsertPair.first; 4971 } 4972 4973 return Itr->second; 4974 } 4975 4976 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4977 if (!isSCEVable(V->getType())) 4978 return getUnknown(V); 4979 4980 if (Instruction *I = dyn_cast<Instruction>(V)) { 4981 // Don't attempt to analyze instructions in blocks that aren't 4982 // reachable. Such instructions don't matter, and they aren't required 4983 // to obey basic rules for definitions dominating uses which this 4984 // analysis depends on. 4985 if (!DT.isReachableFromEntry(I->getParent())) 4986 return getUnknown(V); 4987 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 4988 return getConstant(CI); 4989 else if (isa<ConstantPointerNull>(V)) 4990 return getZero(V->getType()); 4991 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 4992 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 4993 else if (!isa<ConstantExpr>(V)) 4994 return getUnknown(V); 4995 4996 Operator *U = cast<Operator>(V); 4997 if (auto BO = MatchBinaryOp(U, DT)) { 4998 switch (BO->Opcode) { 4999 case Instruction::Add: { 5000 // The simple thing to do would be to just call getSCEV on both operands 5001 // and call getAddExpr with the result. However if we're looking at a 5002 // bunch of things all added together, this can be quite inefficient, 5003 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5004 // Instead, gather up all the operands and make a single getAddExpr call. 5005 // LLVM IR canonical form means we need only traverse the left operands. 5006 SmallVector<const SCEV *, 4> AddOps; 5007 do { 5008 if (BO->Op) { 5009 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5010 AddOps.push_back(OpSCEV); 5011 break; 5012 } 5013 5014 // If a NUW or NSW flag can be applied to the SCEV for this 5015 // addition, then compute the SCEV for this addition by itself 5016 // with a separate call to getAddExpr. We need to do that 5017 // instead of pushing the operands of the addition onto AddOps, 5018 // since the flags are only known to apply to this particular 5019 // addition - they may not apply to other additions that can be 5020 // formed with operands from AddOps. 5021 const SCEV *RHS = getSCEV(BO->RHS); 5022 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5023 if (Flags != SCEV::FlagAnyWrap) { 5024 const SCEV *LHS = getSCEV(BO->LHS); 5025 if (BO->Opcode == Instruction::Sub) 5026 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5027 else 5028 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5029 break; 5030 } 5031 } 5032 5033 if (BO->Opcode == Instruction::Sub) 5034 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5035 else 5036 AddOps.push_back(getSCEV(BO->RHS)); 5037 5038 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5039 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5040 NewBO->Opcode != Instruction::Sub)) { 5041 AddOps.push_back(getSCEV(BO->LHS)); 5042 break; 5043 } 5044 BO = NewBO; 5045 } while (true); 5046 5047 return getAddExpr(AddOps); 5048 } 5049 5050 case Instruction::Mul: { 5051 SmallVector<const SCEV *, 4> MulOps; 5052 do { 5053 if (BO->Op) { 5054 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5055 MulOps.push_back(OpSCEV); 5056 break; 5057 } 5058 5059 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5060 if (Flags != SCEV::FlagAnyWrap) { 5061 MulOps.push_back( 5062 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5063 break; 5064 } 5065 } 5066 5067 MulOps.push_back(getSCEV(BO->RHS)); 5068 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5069 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5070 MulOps.push_back(getSCEV(BO->LHS)); 5071 break; 5072 } 5073 BO = NewBO; 5074 } while (true); 5075 5076 return getMulExpr(MulOps); 5077 } 5078 case Instruction::UDiv: 5079 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5080 case Instruction::Sub: { 5081 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5082 if (BO->Op) 5083 Flags = getNoWrapFlagsFromUB(BO->Op); 5084 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5085 } 5086 case Instruction::And: 5087 // For an expression like x&255 that merely masks off the high bits, 5088 // use zext(trunc(x)) as the SCEV expression. 5089 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5090 if (CI->isNullValue()) 5091 return getSCEV(BO->RHS); 5092 if (CI->isAllOnesValue()) 5093 return getSCEV(BO->LHS); 5094 const APInt &A = CI->getValue(); 5095 5096 // Instcombine's ShrinkDemandedConstant may strip bits out of 5097 // constants, obscuring what would otherwise be a low-bits mask. 5098 // Use computeKnownBits to compute what ShrinkDemandedConstant 5099 // knew about to reconstruct a low-bits mask value. 5100 unsigned LZ = A.countLeadingZeros(); 5101 unsigned TZ = A.countTrailingZeros(); 5102 unsigned BitWidth = A.getBitWidth(); 5103 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5104 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5105 0, &AC, nullptr, &DT); 5106 5107 APInt EffectiveMask = 5108 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5109 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5110 const SCEV *MulCount = getConstant(ConstantInt::get( 5111 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5112 return getMulExpr( 5113 getZeroExtendExpr( 5114 getTruncateExpr( 5115 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5116 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5117 BO->LHS->getType()), 5118 MulCount); 5119 } 5120 } 5121 break; 5122 5123 case Instruction::Or: 5124 // If the RHS of the Or is a constant, we may have something like: 5125 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5126 // optimizations will transparently handle this case. 5127 // 5128 // In order for this transformation to be safe, the LHS must be of the 5129 // form X*(2^n) and the Or constant must be less than 2^n. 5130 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5131 const SCEV *LHS = getSCEV(BO->LHS); 5132 const APInt &CIVal = CI->getValue(); 5133 if (GetMinTrailingZeros(LHS) >= 5134 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5135 // Build a plain add SCEV. 5136 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5137 // If the LHS of the add was an addrec and it has no-wrap flags, 5138 // transfer the no-wrap flags, since an or won't introduce a wrap. 5139 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5140 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5141 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5142 OldAR->getNoWrapFlags()); 5143 } 5144 return S; 5145 } 5146 } 5147 break; 5148 5149 case Instruction::Xor: 5150 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5151 // If the RHS of xor is -1, then this is a not operation. 5152 if (CI->isAllOnesValue()) 5153 return getNotSCEV(getSCEV(BO->LHS)); 5154 5155 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5156 // This is a variant of the check for xor with -1, and it handles 5157 // the case where instcombine has trimmed non-demanded bits out 5158 // of an xor with -1. 5159 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5160 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5161 if (LBO->getOpcode() == Instruction::And && 5162 LCI->getValue() == CI->getValue()) 5163 if (const SCEVZeroExtendExpr *Z = 5164 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5165 Type *UTy = BO->LHS->getType(); 5166 const SCEV *Z0 = Z->getOperand(); 5167 Type *Z0Ty = Z0->getType(); 5168 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5169 5170 // If C is a low-bits mask, the zero extend is serving to 5171 // mask off the high bits. Complement the operand and 5172 // re-apply the zext. 5173 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5174 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5175 5176 // If C is a single bit, it may be in the sign-bit position 5177 // before the zero-extend. In this case, represent the xor 5178 // using an add, which is equivalent, and re-apply the zext. 5179 APInt Trunc = CI->getValue().trunc(Z0TySize); 5180 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5181 Trunc.isSignBit()) 5182 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5183 UTy); 5184 } 5185 } 5186 break; 5187 5188 case Instruction::Shl: 5189 // Turn shift left of a constant amount into a multiply. 5190 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5191 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5192 5193 // If the shift count is not less than the bitwidth, the result of 5194 // the shift is undefined. Don't try to analyze it, because the 5195 // resolution chosen here may differ from the resolution chosen in 5196 // other parts of the compiler. 5197 if (SA->getValue().uge(BitWidth)) 5198 break; 5199 5200 // It is currently not resolved how to interpret NSW for left 5201 // shift by BitWidth - 1, so we avoid applying flags in that 5202 // case. Remove this check (or this comment) once the situation 5203 // is resolved. See 5204 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5205 // and http://reviews.llvm.org/D8890 . 5206 auto Flags = SCEV::FlagAnyWrap; 5207 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5208 Flags = getNoWrapFlagsFromUB(BO->Op); 5209 5210 Constant *X = ConstantInt::get(getContext(), 5211 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5212 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5213 } 5214 break; 5215 5216 case Instruction::AShr: 5217 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5218 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5219 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5220 if (L->getOpcode() == Instruction::Shl && 5221 L->getOperand(1) == BO->RHS) { 5222 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5223 5224 // If the shift count is not less than the bitwidth, the result of 5225 // the shift is undefined. Don't try to analyze it, because the 5226 // resolution chosen here may differ from the resolution chosen in 5227 // other parts of the compiler. 5228 if (CI->getValue().uge(BitWidth)) 5229 break; 5230 5231 uint64_t Amt = BitWidth - CI->getZExtValue(); 5232 if (Amt == BitWidth) 5233 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5234 return getSignExtendExpr( 5235 getTruncateExpr(getSCEV(L->getOperand(0)), 5236 IntegerType::get(getContext(), Amt)), 5237 BO->LHS->getType()); 5238 } 5239 break; 5240 } 5241 } 5242 5243 switch (U->getOpcode()) { 5244 case Instruction::Trunc: 5245 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5246 5247 case Instruction::ZExt: 5248 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5249 5250 case Instruction::SExt: 5251 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5252 5253 case Instruction::BitCast: 5254 // BitCasts are no-op casts so we just eliminate the cast. 5255 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5256 return getSCEV(U->getOperand(0)); 5257 break; 5258 5259 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5260 // lead to pointer expressions which cannot safely be expanded to GEPs, 5261 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5262 // simplifying integer expressions. 5263 5264 case Instruction::GetElementPtr: 5265 return createNodeForGEP(cast<GEPOperator>(U)); 5266 5267 case Instruction::PHI: 5268 return createNodeForPHI(cast<PHINode>(U)); 5269 5270 case Instruction::Select: 5271 // U can also be a select constant expr, which let fall through. Since 5272 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5273 // constant expressions cannot have instructions as operands, we'd have 5274 // returned getUnknown for a select constant expressions anyway. 5275 if (isa<Instruction>(U)) 5276 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5277 U->getOperand(1), U->getOperand(2)); 5278 break; 5279 5280 case Instruction::Call: 5281 case Instruction::Invoke: 5282 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5283 return getSCEV(RV); 5284 break; 5285 } 5286 5287 return getUnknown(V); 5288 } 5289 5290 5291 5292 //===----------------------------------------------------------------------===// 5293 // Iteration Count Computation Code 5294 // 5295 5296 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5297 if (!ExitCount) 5298 return 0; 5299 5300 ConstantInt *ExitConst = ExitCount->getValue(); 5301 5302 // Guard against huge trip counts. 5303 if (ExitConst->getValue().getActiveBits() > 32) 5304 return 0; 5305 5306 // In case of integer overflow, this returns 0, which is correct. 5307 return ((unsigned)ExitConst->getZExtValue()) + 1; 5308 } 5309 5310 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5311 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5312 return getSmallConstantTripCount(L, ExitingBB); 5313 5314 // No trip count information for multiple exits. 5315 return 0; 5316 } 5317 5318 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5319 BasicBlock *ExitingBlock) { 5320 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5321 assert(L->isLoopExiting(ExitingBlock) && 5322 "Exiting block must actually branch out of the loop!"); 5323 const SCEVConstant *ExitCount = 5324 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5325 return getConstantTripCount(ExitCount); 5326 } 5327 5328 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5329 const auto *MaxExitCount = 5330 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5331 return getConstantTripCount(MaxExitCount); 5332 } 5333 5334 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5335 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5336 return getSmallConstantTripMultiple(L, ExitingBB); 5337 5338 // No trip multiple information for multiple exits. 5339 return 0; 5340 } 5341 5342 /// Returns the largest constant divisor of the trip count of this loop as a 5343 /// normal unsigned value, if possible. This means that the actual trip count is 5344 /// always a multiple of the returned value (don't forget the trip count could 5345 /// very well be zero as well!). 5346 /// 5347 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5348 /// multiple of a constant (which is also the case if the trip count is simply 5349 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5350 /// if the trip count is very large (>= 2^32). 5351 /// 5352 /// As explained in the comments for getSmallConstantTripCount, this assumes 5353 /// that control exits the loop via ExitingBlock. 5354 unsigned 5355 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5356 BasicBlock *ExitingBlock) { 5357 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5358 assert(L->isLoopExiting(ExitingBlock) && 5359 "Exiting block must actually branch out of the loop!"); 5360 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5361 if (ExitCount == getCouldNotCompute()) 5362 return 1; 5363 5364 // Get the trip count from the BE count by adding 1. 5365 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5366 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5367 // to factor simple cases. 5368 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5369 TCMul = Mul->getOperand(0); 5370 5371 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5372 if (!MulC) 5373 return 1; 5374 5375 ConstantInt *Result = MulC->getValue(); 5376 5377 // Guard against huge trip counts (this requires checking 5378 // for zero to handle the case where the trip count == -1 and the 5379 // addition wraps). 5380 if (!Result || Result->getValue().getActiveBits() > 32 || 5381 Result->getValue().getActiveBits() == 0) 5382 return 1; 5383 5384 return (unsigned)Result->getZExtValue(); 5385 } 5386 5387 /// Get the expression for the number of loop iterations for which this loop is 5388 /// guaranteed not to exit via ExitingBlock. Otherwise return 5389 /// SCEVCouldNotCompute. 5390 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5391 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5392 } 5393 5394 const SCEV * 5395 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5396 SCEVUnionPredicate &Preds) { 5397 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5398 } 5399 5400 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5401 return getBackedgeTakenInfo(L).getExact(this); 5402 } 5403 5404 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5405 /// known never to be less than the actual backedge taken count. 5406 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5407 return getBackedgeTakenInfo(L).getMax(this); 5408 } 5409 5410 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5411 static void 5412 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5413 BasicBlock *Header = L->getHeader(); 5414 5415 // Push all Loop-header PHIs onto the Worklist stack. 5416 for (BasicBlock::iterator I = Header->begin(); 5417 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5418 Worklist.push_back(PN); 5419 } 5420 5421 const ScalarEvolution::BackedgeTakenInfo & 5422 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5423 auto &BTI = getBackedgeTakenInfo(L); 5424 if (BTI.hasFullInfo()) 5425 return BTI; 5426 5427 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5428 5429 if (!Pair.second) 5430 return Pair.first->second; 5431 5432 BackedgeTakenInfo Result = 5433 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5434 5435 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5436 } 5437 5438 const ScalarEvolution::BackedgeTakenInfo & 5439 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5440 // Initially insert an invalid entry for this loop. If the insertion 5441 // succeeds, proceed to actually compute a backedge-taken count and 5442 // update the value. The temporary CouldNotCompute value tells SCEV 5443 // code elsewhere that it shouldn't attempt to request a new 5444 // backedge-taken count, which could result in infinite recursion. 5445 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5446 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5447 if (!Pair.second) 5448 return Pair.first->second; 5449 5450 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5451 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5452 // must be cleared in this scope. 5453 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5454 5455 if (Result.getExact(this) != getCouldNotCompute()) { 5456 assert(isLoopInvariant(Result.getExact(this), L) && 5457 isLoopInvariant(Result.getMax(this), L) && 5458 "Computed backedge-taken count isn't loop invariant for loop!"); 5459 ++NumTripCountsComputed; 5460 } 5461 else if (Result.getMax(this) == getCouldNotCompute() && 5462 isa<PHINode>(L->getHeader()->begin())) { 5463 // Only count loops that have phi nodes as not being computable. 5464 ++NumTripCountsNotComputed; 5465 } 5466 5467 // Now that we know more about the trip count for this loop, forget any 5468 // existing SCEV values for PHI nodes in this loop since they are only 5469 // conservative estimates made without the benefit of trip count 5470 // information. This is similar to the code in forgetLoop, except that 5471 // it handles SCEVUnknown PHI nodes specially. 5472 if (Result.hasAnyInfo()) { 5473 SmallVector<Instruction *, 16> Worklist; 5474 PushLoopPHIs(L, Worklist); 5475 5476 SmallPtrSet<Instruction *, 8> Visited; 5477 while (!Worklist.empty()) { 5478 Instruction *I = Worklist.pop_back_val(); 5479 if (!Visited.insert(I).second) 5480 continue; 5481 5482 ValueExprMapType::iterator It = 5483 ValueExprMap.find_as(static_cast<Value *>(I)); 5484 if (It != ValueExprMap.end()) { 5485 const SCEV *Old = It->second; 5486 5487 // SCEVUnknown for a PHI either means that it has an unrecognized 5488 // structure, or it's a PHI that's in the progress of being computed 5489 // by createNodeForPHI. In the former case, additional loop trip 5490 // count information isn't going to change anything. In the later 5491 // case, createNodeForPHI will perform the necessary updates on its 5492 // own when it gets to that point. 5493 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5494 eraseValueFromMap(It->first); 5495 forgetMemoizedResults(Old); 5496 } 5497 if (PHINode *PN = dyn_cast<PHINode>(I)) 5498 ConstantEvolutionLoopExitValue.erase(PN); 5499 } 5500 5501 PushDefUseChildren(I, Worklist); 5502 } 5503 } 5504 5505 // Re-lookup the insert position, since the call to 5506 // computeBackedgeTakenCount above could result in a 5507 // recusive call to getBackedgeTakenInfo (on a different 5508 // loop), which would invalidate the iterator computed 5509 // earlier. 5510 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5511 } 5512 5513 void ScalarEvolution::forgetLoop(const Loop *L) { 5514 // Drop any stored trip count value. 5515 auto RemoveLoopFromBackedgeMap = 5516 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5517 auto BTCPos = Map.find(L); 5518 if (BTCPos != Map.end()) { 5519 BTCPos->second.clear(); 5520 Map.erase(BTCPos); 5521 } 5522 }; 5523 5524 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5525 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5526 5527 // Drop information about expressions based on loop-header PHIs. 5528 SmallVector<Instruction *, 16> Worklist; 5529 PushLoopPHIs(L, Worklist); 5530 5531 SmallPtrSet<Instruction *, 8> Visited; 5532 while (!Worklist.empty()) { 5533 Instruction *I = Worklist.pop_back_val(); 5534 if (!Visited.insert(I).second) 5535 continue; 5536 5537 ValueExprMapType::iterator It = 5538 ValueExprMap.find_as(static_cast<Value *>(I)); 5539 if (It != ValueExprMap.end()) { 5540 eraseValueFromMap(It->first); 5541 forgetMemoizedResults(It->second); 5542 if (PHINode *PN = dyn_cast<PHINode>(I)) 5543 ConstantEvolutionLoopExitValue.erase(PN); 5544 } 5545 5546 PushDefUseChildren(I, Worklist); 5547 } 5548 5549 // Forget all contained loops too, to avoid dangling entries in the 5550 // ValuesAtScopes map. 5551 for (Loop *I : *L) 5552 forgetLoop(I); 5553 5554 LoopPropertiesCache.erase(L); 5555 } 5556 5557 void ScalarEvolution::forgetValue(Value *V) { 5558 Instruction *I = dyn_cast<Instruction>(V); 5559 if (!I) return; 5560 5561 // Drop information about expressions based on loop-header PHIs. 5562 SmallVector<Instruction *, 16> Worklist; 5563 Worklist.push_back(I); 5564 5565 SmallPtrSet<Instruction *, 8> Visited; 5566 while (!Worklist.empty()) { 5567 I = Worklist.pop_back_val(); 5568 if (!Visited.insert(I).second) 5569 continue; 5570 5571 ValueExprMapType::iterator It = 5572 ValueExprMap.find_as(static_cast<Value *>(I)); 5573 if (It != ValueExprMap.end()) { 5574 eraseValueFromMap(It->first); 5575 forgetMemoizedResults(It->second); 5576 if (PHINode *PN = dyn_cast<PHINode>(I)) 5577 ConstantEvolutionLoopExitValue.erase(PN); 5578 } 5579 5580 PushDefUseChildren(I, Worklist); 5581 } 5582 } 5583 5584 /// Get the exact loop backedge taken count considering all loop exits. A 5585 /// computable result can only be returned for loops with a single exit. 5586 /// Returning the minimum taken count among all exits is incorrect because one 5587 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5588 /// the limit of each loop test is never skipped. This is a valid assumption as 5589 /// long as the loop exits via that test. For precise results, it is the 5590 /// caller's responsibility to specify the relevant loop exit using 5591 /// getExact(ExitingBlock, SE). 5592 const SCEV * 5593 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5594 SCEVUnionPredicate *Preds) const { 5595 // If any exits were not computable, the loop is not computable. 5596 if (!isComplete() || ExitNotTaken.empty()) 5597 return SE->getCouldNotCompute(); 5598 5599 const SCEV *BECount = nullptr; 5600 for (auto &ENT : ExitNotTaken) { 5601 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5602 5603 if (!BECount) 5604 BECount = ENT.ExactNotTaken; 5605 else if (BECount != ENT.ExactNotTaken) 5606 return SE->getCouldNotCompute(); 5607 if (Preds && !ENT.hasAlwaysTruePredicate()) 5608 Preds->add(ENT.Predicate.get()); 5609 5610 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5611 "Predicate should be always true!"); 5612 } 5613 5614 assert(BECount && "Invalid not taken count for loop exit"); 5615 return BECount; 5616 } 5617 5618 /// Get the exact not taken count for this loop exit. 5619 const SCEV * 5620 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5621 ScalarEvolution *SE) const { 5622 for (auto &ENT : ExitNotTaken) 5623 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5624 return ENT.ExactNotTaken; 5625 5626 return SE->getCouldNotCompute(); 5627 } 5628 5629 /// getMax - Get the max backedge taken count for the loop. 5630 const SCEV * 5631 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5632 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5633 return !ENT.hasAlwaysTruePredicate(); 5634 }; 5635 5636 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5637 return SE->getCouldNotCompute(); 5638 5639 return getMax(); 5640 } 5641 5642 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5643 ScalarEvolution *SE) const { 5644 if (getMax() && getMax() != SE->getCouldNotCompute() && 5645 SE->hasOperand(getMax(), S)) 5646 return true; 5647 5648 for (auto &ENT : ExitNotTaken) 5649 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5650 SE->hasOperand(ENT.ExactNotTaken, S)) 5651 return true; 5652 5653 return false; 5654 } 5655 5656 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5657 /// computable exit into a persistent ExitNotTakenInfo array. 5658 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5659 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5660 &&ExitCounts, 5661 bool Complete, const SCEV *MaxCount) 5662 : MaxAndComplete(MaxCount, Complete) { 5663 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5664 ExitNotTaken.reserve(ExitCounts.size()); 5665 std::transform( 5666 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5667 [&](const EdgeExitInfo &EEI) { 5668 BasicBlock *ExitBB = EEI.first; 5669 const ExitLimit &EL = EEI.second; 5670 if (EL.Predicates.empty()) 5671 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5672 5673 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5674 for (auto *Pred : EL.Predicates) 5675 Predicate->add(Pred); 5676 5677 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5678 }); 5679 } 5680 5681 /// Invalidate this result and free the ExitNotTakenInfo array. 5682 void ScalarEvolution::BackedgeTakenInfo::clear() { 5683 ExitNotTaken.clear(); 5684 } 5685 5686 /// Compute the number of times the backedge of the specified loop will execute. 5687 ScalarEvolution::BackedgeTakenInfo 5688 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5689 bool AllowPredicates) { 5690 SmallVector<BasicBlock *, 8> ExitingBlocks; 5691 L->getExitingBlocks(ExitingBlocks); 5692 5693 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5694 5695 SmallVector<EdgeExitInfo, 4> ExitCounts; 5696 bool CouldComputeBECount = true; 5697 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5698 const SCEV *MustExitMaxBECount = nullptr; 5699 const SCEV *MayExitMaxBECount = nullptr; 5700 5701 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5702 // and compute maxBECount. 5703 // Do a union of all the predicates here. 5704 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5705 BasicBlock *ExitBB = ExitingBlocks[i]; 5706 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5707 5708 assert((AllowPredicates || EL.Predicates.empty()) && 5709 "Predicated exit limit when predicates are not allowed!"); 5710 5711 // 1. For each exit that can be computed, add an entry to ExitCounts. 5712 // CouldComputeBECount is true only if all exits can be computed. 5713 if (EL.ExactNotTaken == getCouldNotCompute()) 5714 // We couldn't compute an exact value for this exit, so 5715 // we won't be able to compute an exact value for the loop. 5716 CouldComputeBECount = false; 5717 else 5718 ExitCounts.emplace_back(ExitBB, EL); 5719 5720 // 2. Derive the loop's MaxBECount from each exit's max number of 5721 // non-exiting iterations. Partition the loop exits into two kinds: 5722 // LoopMustExits and LoopMayExits. 5723 // 5724 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5725 // is a LoopMayExit. If any computable LoopMustExit is found, then 5726 // MaxBECount is the minimum EL.MaxNotTaken of computable 5727 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5728 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5729 // computable EL.MaxNotTaken. 5730 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5731 DT.dominates(ExitBB, Latch)) { 5732 if (!MustExitMaxBECount) 5733 MustExitMaxBECount = EL.MaxNotTaken; 5734 else { 5735 MustExitMaxBECount = 5736 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5737 } 5738 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5739 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5740 MayExitMaxBECount = EL.MaxNotTaken; 5741 else { 5742 MayExitMaxBECount = 5743 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5744 } 5745 } 5746 } 5747 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5748 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5749 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5750 MaxBECount); 5751 } 5752 5753 ScalarEvolution::ExitLimit 5754 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5755 bool AllowPredicates) { 5756 5757 // Okay, we've chosen an exiting block. See what condition causes us to exit 5758 // at this block and remember the exit block and whether all other targets 5759 // lead to the loop header. 5760 bool MustExecuteLoopHeader = true; 5761 BasicBlock *Exit = nullptr; 5762 for (auto *SBB : successors(ExitingBlock)) 5763 if (!L->contains(SBB)) { 5764 if (Exit) // Multiple exit successors. 5765 return getCouldNotCompute(); 5766 Exit = SBB; 5767 } else if (SBB != L->getHeader()) { 5768 MustExecuteLoopHeader = false; 5769 } 5770 5771 // At this point, we know we have a conditional branch that determines whether 5772 // the loop is exited. However, we don't know if the branch is executed each 5773 // time through the loop. If not, then the execution count of the branch will 5774 // not be equal to the trip count of the loop. 5775 // 5776 // Currently we check for this by checking to see if the Exit branch goes to 5777 // the loop header. If so, we know it will always execute the same number of 5778 // times as the loop. We also handle the case where the exit block *is* the 5779 // loop header. This is common for un-rotated loops. 5780 // 5781 // If both of those tests fail, walk up the unique predecessor chain to the 5782 // header, stopping if there is an edge that doesn't exit the loop. If the 5783 // header is reached, the execution count of the branch will be equal to the 5784 // trip count of the loop. 5785 // 5786 // More extensive analysis could be done to handle more cases here. 5787 // 5788 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5789 // The simple checks failed, try climbing the unique predecessor chain 5790 // up to the header. 5791 bool Ok = false; 5792 for (BasicBlock *BB = ExitingBlock; BB; ) { 5793 BasicBlock *Pred = BB->getUniquePredecessor(); 5794 if (!Pred) 5795 return getCouldNotCompute(); 5796 TerminatorInst *PredTerm = Pred->getTerminator(); 5797 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5798 if (PredSucc == BB) 5799 continue; 5800 // If the predecessor has a successor that isn't BB and isn't 5801 // outside the loop, assume the worst. 5802 if (L->contains(PredSucc)) 5803 return getCouldNotCompute(); 5804 } 5805 if (Pred == L->getHeader()) { 5806 Ok = true; 5807 break; 5808 } 5809 BB = Pred; 5810 } 5811 if (!Ok) 5812 return getCouldNotCompute(); 5813 } 5814 5815 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5816 TerminatorInst *Term = ExitingBlock->getTerminator(); 5817 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5818 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5819 // Proceed to the next level to examine the exit condition expression. 5820 return computeExitLimitFromCond( 5821 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5822 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5823 } 5824 5825 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5826 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5827 /*ControlsExit=*/IsOnlyExit); 5828 5829 return getCouldNotCompute(); 5830 } 5831 5832 ScalarEvolution::ExitLimit 5833 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5834 Value *ExitCond, 5835 BasicBlock *TBB, 5836 BasicBlock *FBB, 5837 bool ControlsExit, 5838 bool AllowPredicates) { 5839 // Check if the controlling expression for this loop is an And or Or. 5840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5841 if (BO->getOpcode() == Instruction::And) { 5842 // Recurse on the operands of the and. 5843 bool EitherMayExit = L->contains(TBB); 5844 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5845 ControlsExit && !EitherMayExit, 5846 AllowPredicates); 5847 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5848 ControlsExit && !EitherMayExit, 5849 AllowPredicates); 5850 const SCEV *BECount = getCouldNotCompute(); 5851 const SCEV *MaxBECount = getCouldNotCompute(); 5852 if (EitherMayExit) { 5853 // Both conditions must be true for the loop to continue executing. 5854 // Choose the less conservative count. 5855 if (EL0.ExactNotTaken == getCouldNotCompute() || 5856 EL1.ExactNotTaken == getCouldNotCompute()) 5857 BECount = getCouldNotCompute(); 5858 else 5859 BECount = 5860 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5861 if (EL0.MaxNotTaken == getCouldNotCompute()) 5862 MaxBECount = EL1.MaxNotTaken; 5863 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5864 MaxBECount = EL0.MaxNotTaken; 5865 else 5866 MaxBECount = 5867 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5868 } else { 5869 // Both conditions must be true at the same time for the loop to exit. 5870 // For now, be conservative. 5871 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5872 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5873 MaxBECount = EL0.MaxNotTaken; 5874 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5875 BECount = EL0.ExactNotTaken; 5876 } 5877 5878 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5879 // to be more aggressive when computing BECount than when computing 5880 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5881 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5882 // to not. 5883 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5884 !isa<SCEVCouldNotCompute>(BECount)) 5885 MaxBECount = BECount; 5886 5887 return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates}); 5888 } 5889 if (BO->getOpcode() == Instruction::Or) { 5890 // Recurse on the operands of the or. 5891 bool EitherMayExit = L->contains(FBB); 5892 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5893 ControlsExit && !EitherMayExit, 5894 AllowPredicates); 5895 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5896 ControlsExit && !EitherMayExit, 5897 AllowPredicates); 5898 const SCEV *BECount = getCouldNotCompute(); 5899 const SCEV *MaxBECount = getCouldNotCompute(); 5900 if (EitherMayExit) { 5901 // Both conditions must be false for the loop to continue executing. 5902 // Choose the less conservative count. 5903 if (EL0.ExactNotTaken == getCouldNotCompute() || 5904 EL1.ExactNotTaken == getCouldNotCompute()) 5905 BECount = getCouldNotCompute(); 5906 else 5907 BECount = 5908 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5909 if (EL0.MaxNotTaken == getCouldNotCompute()) 5910 MaxBECount = EL1.MaxNotTaken; 5911 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5912 MaxBECount = EL0.MaxNotTaken; 5913 else 5914 MaxBECount = 5915 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5916 } else { 5917 // Both conditions must be false at the same time for the loop to exit. 5918 // For now, be conservative. 5919 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5920 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5921 MaxBECount = EL0.MaxNotTaken; 5922 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5923 BECount = EL0.ExactNotTaken; 5924 } 5925 5926 return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates}); 5927 } 5928 } 5929 5930 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5931 // Proceed to the next level to examine the icmp. 5932 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5933 ExitLimit EL = 5934 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5935 if (EL.hasFullInfo() || !AllowPredicates) 5936 return EL; 5937 5938 // Try again, but use SCEV predicates this time. 5939 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5940 /*AllowPredicates=*/true); 5941 } 5942 5943 // Check for a constant condition. These are normally stripped out by 5944 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5945 // preserve the CFG and is temporarily leaving constant conditions 5946 // in place. 5947 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5948 if (L->contains(FBB) == !CI->getZExtValue()) 5949 // The backedge is always taken. 5950 return getCouldNotCompute(); 5951 else 5952 // The backedge is never taken. 5953 return getZero(CI->getType()); 5954 } 5955 5956 // If it's not an integer or pointer comparison then compute it the hard way. 5957 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5958 } 5959 5960 ScalarEvolution::ExitLimit 5961 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 5962 ICmpInst *ExitCond, 5963 BasicBlock *TBB, 5964 BasicBlock *FBB, 5965 bool ControlsExit, 5966 bool AllowPredicates) { 5967 5968 // If the condition was exit on true, convert the condition to exit on false 5969 ICmpInst::Predicate Cond; 5970 if (!L->contains(FBB)) 5971 Cond = ExitCond->getPredicate(); 5972 else 5973 Cond = ExitCond->getInversePredicate(); 5974 5975 // Handle common loops like: for (X = "string"; *X; ++X) 5976 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 5977 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 5978 ExitLimit ItCnt = 5979 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 5980 if (ItCnt.hasAnyInfo()) 5981 return ItCnt; 5982 } 5983 5984 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 5985 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 5986 5987 // Try to evaluate any dependencies out of the loop. 5988 LHS = getSCEVAtScope(LHS, L); 5989 RHS = getSCEVAtScope(RHS, L); 5990 5991 // At this point, we would like to compute how many iterations of the 5992 // loop the predicate will return true for these inputs. 5993 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 5994 // If there is a loop-invariant, force it into the RHS. 5995 std::swap(LHS, RHS); 5996 Cond = ICmpInst::getSwappedPredicate(Cond); 5997 } 5998 5999 // Simplify the operands before analyzing them. 6000 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6001 6002 // If we have a comparison of a chrec against a constant, try to use value 6003 // ranges to answer this query. 6004 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6005 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6006 if (AddRec->getLoop() == L) { 6007 // Form the constant range. 6008 ConstantRange CompRange = 6009 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6010 6011 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6012 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6013 } 6014 6015 switch (Cond) { 6016 case ICmpInst::ICMP_NE: { // while (X != Y) 6017 // Convert to: while (X-Y != 0) 6018 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6019 AllowPredicates); 6020 if (EL.hasAnyInfo()) return EL; 6021 break; 6022 } 6023 case ICmpInst::ICMP_EQ: { // while (X == Y) 6024 // Convert to: while (X-Y == 0) 6025 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6026 if (EL.hasAnyInfo()) return EL; 6027 break; 6028 } 6029 case ICmpInst::ICMP_SLT: 6030 case ICmpInst::ICMP_ULT: { // while (X < Y) 6031 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6032 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6033 AllowPredicates); 6034 if (EL.hasAnyInfo()) return EL; 6035 break; 6036 } 6037 case ICmpInst::ICMP_SGT: 6038 case ICmpInst::ICMP_UGT: { // while (X > Y) 6039 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6040 ExitLimit EL = 6041 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6042 AllowPredicates); 6043 if (EL.hasAnyInfo()) return EL; 6044 break; 6045 } 6046 default: 6047 break; 6048 } 6049 6050 auto *ExhaustiveCount = 6051 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6052 6053 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6054 return ExhaustiveCount; 6055 6056 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6057 ExitCond->getOperand(1), L, Cond); 6058 } 6059 6060 ScalarEvolution::ExitLimit 6061 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6062 SwitchInst *Switch, 6063 BasicBlock *ExitingBlock, 6064 bool ControlsExit) { 6065 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6066 6067 // Give up if the exit is the default dest of a switch. 6068 if (Switch->getDefaultDest() == ExitingBlock) 6069 return getCouldNotCompute(); 6070 6071 assert(L->contains(Switch->getDefaultDest()) && 6072 "Default case must not exit the loop!"); 6073 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6074 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6075 6076 // while (X != Y) --> while (X-Y != 0) 6077 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6078 if (EL.hasAnyInfo()) 6079 return EL; 6080 6081 return getCouldNotCompute(); 6082 } 6083 6084 static ConstantInt * 6085 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6086 ScalarEvolution &SE) { 6087 const SCEV *InVal = SE.getConstant(C); 6088 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6089 assert(isa<SCEVConstant>(Val) && 6090 "Evaluation of SCEV at constant didn't fold correctly?"); 6091 return cast<SCEVConstant>(Val)->getValue(); 6092 } 6093 6094 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6095 /// compute the backedge execution count. 6096 ScalarEvolution::ExitLimit 6097 ScalarEvolution::computeLoadConstantCompareExitLimit( 6098 LoadInst *LI, 6099 Constant *RHS, 6100 const Loop *L, 6101 ICmpInst::Predicate predicate) { 6102 6103 if (LI->isVolatile()) return getCouldNotCompute(); 6104 6105 // Check to see if the loaded pointer is a getelementptr of a global. 6106 // TODO: Use SCEV instead of manually grubbing with GEPs. 6107 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6108 if (!GEP) return getCouldNotCompute(); 6109 6110 // Make sure that it is really a constant global we are gepping, with an 6111 // initializer, and make sure the first IDX is really 0. 6112 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6113 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6114 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6115 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6116 return getCouldNotCompute(); 6117 6118 // Okay, we allow one non-constant index into the GEP instruction. 6119 Value *VarIdx = nullptr; 6120 std::vector<Constant*> Indexes; 6121 unsigned VarIdxNum = 0; 6122 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6123 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6124 Indexes.push_back(CI); 6125 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6126 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6127 VarIdx = GEP->getOperand(i); 6128 VarIdxNum = i-2; 6129 Indexes.push_back(nullptr); 6130 } 6131 6132 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6133 if (!VarIdx) 6134 return getCouldNotCompute(); 6135 6136 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6137 // Check to see if X is a loop variant variable value now. 6138 const SCEV *Idx = getSCEV(VarIdx); 6139 Idx = getSCEVAtScope(Idx, L); 6140 6141 // We can only recognize very limited forms of loop index expressions, in 6142 // particular, only affine AddRec's like {C1,+,C2}. 6143 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6144 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6145 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6146 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6147 return getCouldNotCompute(); 6148 6149 unsigned MaxSteps = MaxBruteForceIterations; 6150 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6151 ConstantInt *ItCst = ConstantInt::get( 6152 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6153 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6154 6155 // Form the GEP offset. 6156 Indexes[VarIdxNum] = Val; 6157 6158 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6159 Indexes); 6160 if (!Result) break; // Cannot compute! 6161 6162 // Evaluate the condition for this iteration. 6163 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6164 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6165 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6166 ++NumArrayLenItCounts; 6167 return getConstant(ItCst); // Found terminating iteration! 6168 } 6169 } 6170 return getCouldNotCompute(); 6171 } 6172 6173 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6174 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6175 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6176 if (!RHS) 6177 return getCouldNotCompute(); 6178 6179 const BasicBlock *Latch = L->getLoopLatch(); 6180 if (!Latch) 6181 return getCouldNotCompute(); 6182 6183 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6184 if (!Predecessor) 6185 return getCouldNotCompute(); 6186 6187 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6188 // Return LHS in OutLHS and shift_opt in OutOpCode. 6189 auto MatchPositiveShift = 6190 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6191 6192 using namespace PatternMatch; 6193 6194 ConstantInt *ShiftAmt; 6195 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6196 OutOpCode = Instruction::LShr; 6197 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6198 OutOpCode = Instruction::AShr; 6199 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6200 OutOpCode = Instruction::Shl; 6201 else 6202 return false; 6203 6204 return ShiftAmt->getValue().isStrictlyPositive(); 6205 }; 6206 6207 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6208 // 6209 // loop: 6210 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6211 // %iv.shifted = lshr i32 %iv, <positive constant> 6212 // 6213 // Return true on a succesful match. Return the corresponding PHI node (%iv 6214 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6215 auto MatchShiftRecurrence = 6216 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6217 Optional<Instruction::BinaryOps> PostShiftOpCode; 6218 6219 { 6220 Instruction::BinaryOps OpC; 6221 Value *V; 6222 6223 // If we encounter a shift instruction, "peel off" the shift operation, 6224 // and remember that we did so. Later when we inspect %iv's backedge 6225 // value, we will make sure that the backedge value uses the same 6226 // operation. 6227 // 6228 // Note: the peeled shift operation does not have to be the same 6229 // instruction as the one feeding into the PHI's backedge value. We only 6230 // really care about it being the same *kind* of shift instruction -- 6231 // that's all that is required for our later inferences to hold. 6232 if (MatchPositiveShift(LHS, V, OpC)) { 6233 PostShiftOpCode = OpC; 6234 LHS = V; 6235 } 6236 } 6237 6238 PNOut = dyn_cast<PHINode>(LHS); 6239 if (!PNOut || PNOut->getParent() != L->getHeader()) 6240 return false; 6241 6242 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6243 Value *OpLHS; 6244 6245 return 6246 // The backedge value for the PHI node must be a shift by a positive 6247 // amount 6248 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6249 6250 // of the PHI node itself 6251 OpLHS == PNOut && 6252 6253 // and the kind of shift should be match the kind of shift we peeled 6254 // off, if any. 6255 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6256 }; 6257 6258 PHINode *PN; 6259 Instruction::BinaryOps OpCode; 6260 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6261 return getCouldNotCompute(); 6262 6263 const DataLayout &DL = getDataLayout(); 6264 6265 // The key rationale for this optimization is that for some kinds of shift 6266 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6267 // within a finite number of iterations. If the condition guarding the 6268 // backedge (in the sense that the backedge is taken if the condition is true) 6269 // is false for the value the shift recurrence stabilizes to, then we know 6270 // that the backedge is taken only a finite number of times. 6271 6272 ConstantInt *StableValue = nullptr; 6273 switch (OpCode) { 6274 default: 6275 llvm_unreachable("Impossible case!"); 6276 6277 case Instruction::AShr: { 6278 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6279 // bitwidth(K) iterations. 6280 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6281 bool KnownZero, KnownOne; 6282 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6283 Predecessor->getTerminator(), &DT); 6284 auto *Ty = cast<IntegerType>(RHS->getType()); 6285 if (KnownZero) 6286 StableValue = ConstantInt::get(Ty, 0); 6287 else if (KnownOne) 6288 StableValue = ConstantInt::get(Ty, -1, true); 6289 else 6290 return getCouldNotCompute(); 6291 6292 break; 6293 } 6294 case Instruction::LShr: 6295 case Instruction::Shl: 6296 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6297 // stabilize to 0 in at most bitwidth(K) iterations. 6298 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6299 break; 6300 } 6301 6302 auto *Result = 6303 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6304 assert(Result->getType()->isIntegerTy(1) && 6305 "Otherwise cannot be an operand to a branch instruction"); 6306 6307 if (Result->isZeroValue()) { 6308 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6309 const SCEV *UpperBound = 6310 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6311 return ExitLimit(getCouldNotCompute(), UpperBound); 6312 } 6313 6314 return getCouldNotCompute(); 6315 } 6316 6317 /// Return true if we can constant fold an instruction of the specified type, 6318 /// assuming that all operands were constants. 6319 static bool CanConstantFold(const Instruction *I) { 6320 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6321 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6322 isa<LoadInst>(I)) 6323 return true; 6324 6325 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6326 if (const Function *F = CI->getCalledFunction()) 6327 return canConstantFoldCallTo(F); 6328 return false; 6329 } 6330 6331 /// Determine whether this instruction can constant evolve within this loop 6332 /// assuming its operands can all constant evolve. 6333 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6334 // An instruction outside of the loop can't be derived from a loop PHI. 6335 if (!L->contains(I)) return false; 6336 6337 if (isa<PHINode>(I)) { 6338 // We don't currently keep track of the control flow needed to evaluate 6339 // PHIs, so we cannot handle PHIs inside of loops. 6340 return L->getHeader() == I->getParent(); 6341 } 6342 6343 // If we won't be able to constant fold this expression even if the operands 6344 // are constants, bail early. 6345 return CanConstantFold(I); 6346 } 6347 6348 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6349 /// recursing through each instruction operand until reaching a loop header phi. 6350 static PHINode * 6351 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6352 DenseMap<Instruction *, PHINode *> &PHIMap) { 6353 6354 // Otherwise, we can evaluate this instruction if all of its operands are 6355 // constant or derived from a PHI node themselves. 6356 PHINode *PHI = nullptr; 6357 for (Value *Op : UseInst->operands()) { 6358 if (isa<Constant>(Op)) continue; 6359 6360 Instruction *OpInst = dyn_cast<Instruction>(Op); 6361 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6362 6363 PHINode *P = dyn_cast<PHINode>(OpInst); 6364 if (!P) 6365 // If this operand is already visited, reuse the prior result. 6366 // We may have P != PHI if this is the deepest point at which the 6367 // inconsistent paths meet. 6368 P = PHIMap.lookup(OpInst); 6369 if (!P) { 6370 // Recurse and memoize the results, whether a phi is found or not. 6371 // This recursive call invalidates pointers into PHIMap. 6372 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6373 PHIMap[OpInst] = P; 6374 } 6375 if (!P) 6376 return nullptr; // Not evolving from PHI 6377 if (PHI && PHI != P) 6378 return nullptr; // Evolving from multiple different PHIs. 6379 PHI = P; 6380 } 6381 // This is a expression evolving from a constant PHI! 6382 return PHI; 6383 } 6384 6385 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6386 /// in the loop that V is derived from. We allow arbitrary operations along the 6387 /// way, but the operands of an operation must either be constants or a value 6388 /// derived from a constant PHI. If this expression does not fit with these 6389 /// constraints, return null. 6390 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6391 Instruction *I = dyn_cast<Instruction>(V); 6392 if (!I || !canConstantEvolve(I, L)) return nullptr; 6393 6394 if (PHINode *PN = dyn_cast<PHINode>(I)) 6395 return PN; 6396 6397 // Record non-constant instructions contained by the loop. 6398 DenseMap<Instruction *, PHINode *> PHIMap; 6399 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6400 } 6401 6402 /// EvaluateExpression - Given an expression that passes the 6403 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6404 /// in the loop has the value PHIVal. If we can't fold this expression for some 6405 /// reason, return null. 6406 static Constant *EvaluateExpression(Value *V, const Loop *L, 6407 DenseMap<Instruction *, Constant *> &Vals, 6408 const DataLayout &DL, 6409 const TargetLibraryInfo *TLI) { 6410 // Convenient constant check, but redundant for recursive calls. 6411 if (Constant *C = dyn_cast<Constant>(V)) return C; 6412 Instruction *I = dyn_cast<Instruction>(V); 6413 if (!I) return nullptr; 6414 6415 if (Constant *C = Vals.lookup(I)) return C; 6416 6417 // An instruction inside the loop depends on a value outside the loop that we 6418 // weren't given a mapping for, or a value such as a call inside the loop. 6419 if (!canConstantEvolve(I, L)) return nullptr; 6420 6421 // An unmapped PHI can be due to a branch or another loop inside this loop, 6422 // or due to this not being the initial iteration through a loop where we 6423 // couldn't compute the evolution of this particular PHI last time. 6424 if (isa<PHINode>(I)) return nullptr; 6425 6426 std::vector<Constant*> Operands(I->getNumOperands()); 6427 6428 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6429 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6430 if (!Operand) { 6431 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6432 if (!Operands[i]) return nullptr; 6433 continue; 6434 } 6435 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6436 Vals[Operand] = C; 6437 if (!C) return nullptr; 6438 Operands[i] = C; 6439 } 6440 6441 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6442 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6443 Operands[1], DL, TLI); 6444 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6445 if (!LI->isVolatile()) 6446 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6447 } 6448 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6449 } 6450 6451 6452 // If every incoming value to PN except the one for BB is a specific Constant, 6453 // return that, else return nullptr. 6454 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6455 Constant *IncomingVal = nullptr; 6456 6457 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6458 if (PN->getIncomingBlock(i) == BB) 6459 continue; 6460 6461 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6462 if (!CurrentVal) 6463 return nullptr; 6464 6465 if (IncomingVal != CurrentVal) { 6466 if (IncomingVal) 6467 return nullptr; 6468 IncomingVal = CurrentVal; 6469 } 6470 } 6471 6472 return IncomingVal; 6473 } 6474 6475 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6476 /// in the header of its containing loop, we know the loop executes a 6477 /// constant number of times, and the PHI node is just a recurrence 6478 /// involving constants, fold it. 6479 Constant * 6480 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6481 const APInt &BEs, 6482 const Loop *L) { 6483 auto I = ConstantEvolutionLoopExitValue.find(PN); 6484 if (I != ConstantEvolutionLoopExitValue.end()) 6485 return I->second; 6486 6487 if (BEs.ugt(MaxBruteForceIterations)) 6488 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6489 6490 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6491 6492 DenseMap<Instruction *, Constant *> CurrentIterVals; 6493 BasicBlock *Header = L->getHeader(); 6494 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6495 6496 BasicBlock *Latch = L->getLoopLatch(); 6497 if (!Latch) 6498 return nullptr; 6499 6500 for (auto &I : *Header) { 6501 PHINode *PHI = dyn_cast<PHINode>(&I); 6502 if (!PHI) break; 6503 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6504 if (!StartCST) continue; 6505 CurrentIterVals[PHI] = StartCST; 6506 } 6507 if (!CurrentIterVals.count(PN)) 6508 return RetVal = nullptr; 6509 6510 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6511 6512 // Execute the loop symbolically to determine the exit value. 6513 if (BEs.getActiveBits() >= 32) 6514 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6515 6516 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6517 unsigned IterationNum = 0; 6518 const DataLayout &DL = getDataLayout(); 6519 for (; ; ++IterationNum) { 6520 if (IterationNum == NumIterations) 6521 return RetVal = CurrentIterVals[PN]; // Got exit value! 6522 6523 // Compute the value of the PHIs for the next iteration. 6524 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6525 DenseMap<Instruction *, Constant *> NextIterVals; 6526 Constant *NextPHI = 6527 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6528 if (!NextPHI) 6529 return nullptr; // Couldn't evaluate! 6530 NextIterVals[PN] = NextPHI; 6531 6532 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6533 6534 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6535 // cease to be able to evaluate one of them or if they stop evolving, 6536 // because that doesn't necessarily prevent us from computing PN. 6537 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6538 for (const auto &I : CurrentIterVals) { 6539 PHINode *PHI = dyn_cast<PHINode>(I.first); 6540 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6541 PHIsToCompute.emplace_back(PHI, I.second); 6542 } 6543 // We use two distinct loops because EvaluateExpression may invalidate any 6544 // iterators into CurrentIterVals. 6545 for (const auto &I : PHIsToCompute) { 6546 PHINode *PHI = I.first; 6547 Constant *&NextPHI = NextIterVals[PHI]; 6548 if (!NextPHI) { // Not already computed. 6549 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6550 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6551 } 6552 if (NextPHI != I.second) 6553 StoppedEvolving = false; 6554 } 6555 6556 // If all entries in CurrentIterVals == NextIterVals then we can stop 6557 // iterating, the loop can't continue to change. 6558 if (StoppedEvolving) 6559 return RetVal = CurrentIterVals[PN]; 6560 6561 CurrentIterVals.swap(NextIterVals); 6562 } 6563 } 6564 6565 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6566 Value *Cond, 6567 bool ExitWhen) { 6568 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6569 if (!PN) return getCouldNotCompute(); 6570 6571 // If the loop is canonicalized, the PHI will have exactly two entries. 6572 // That's the only form we support here. 6573 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6574 6575 DenseMap<Instruction *, Constant *> CurrentIterVals; 6576 BasicBlock *Header = L->getHeader(); 6577 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6578 6579 BasicBlock *Latch = L->getLoopLatch(); 6580 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6581 6582 for (auto &I : *Header) { 6583 PHINode *PHI = dyn_cast<PHINode>(&I); 6584 if (!PHI) 6585 break; 6586 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6587 if (!StartCST) continue; 6588 CurrentIterVals[PHI] = StartCST; 6589 } 6590 if (!CurrentIterVals.count(PN)) 6591 return getCouldNotCompute(); 6592 6593 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6594 // the loop symbolically to determine when the condition gets a value of 6595 // "ExitWhen". 6596 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6597 const DataLayout &DL = getDataLayout(); 6598 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6599 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6600 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6601 6602 // Couldn't symbolically evaluate. 6603 if (!CondVal) return getCouldNotCompute(); 6604 6605 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6606 ++NumBruteForceTripCountsComputed; 6607 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6608 } 6609 6610 // Update all the PHI nodes for the next iteration. 6611 DenseMap<Instruction *, Constant *> NextIterVals; 6612 6613 // Create a list of which PHIs we need to compute. We want to do this before 6614 // calling EvaluateExpression on them because that may invalidate iterators 6615 // into CurrentIterVals. 6616 SmallVector<PHINode *, 8> PHIsToCompute; 6617 for (const auto &I : CurrentIterVals) { 6618 PHINode *PHI = dyn_cast<PHINode>(I.first); 6619 if (!PHI || PHI->getParent() != Header) continue; 6620 PHIsToCompute.push_back(PHI); 6621 } 6622 for (PHINode *PHI : PHIsToCompute) { 6623 Constant *&NextPHI = NextIterVals[PHI]; 6624 if (NextPHI) continue; // Already computed! 6625 6626 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6627 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6628 } 6629 CurrentIterVals.swap(NextIterVals); 6630 } 6631 6632 // Too many iterations were needed to evaluate. 6633 return getCouldNotCompute(); 6634 } 6635 6636 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6637 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6638 ValuesAtScopes[V]; 6639 // Check to see if we've folded this expression at this loop before. 6640 for (auto &LS : Values) 6641 if (LS.first == L) 6642 return LS.second ? LS.second : V; 6643 6644 Values.emplace_back(L, nullptr); 6645 6646 // Otherwise compute it. 6647 const SCEV *C = computeSCEVAtScope(V, L); 6648 for (auto &LS : reverse(ValuesAtScopes[V])) 6649 if (LS.first == L) { 6650 LS.second = C; 6651 break; 6652 } 6653 return C; 6654 } 6655 6656 /// This builds up a Constant using the ConstantExpr interface. That way, we 6657 /// will return Constants for objects which aren't represented by a 6658 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6659 /// Returns NULL if the SCEV isn't representable as a Constant. 6660 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6661 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6662 case scCouldNotCompute: 6663 case scAddRecExpr: 6664 break; 6665 case scConstant: 6666 return cast<SCEVConstant>(V)->getValue(); 6667 case scUnknown: 6668 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6669 case scSignExtend: { 6670 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6671 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6672 return ConstantExpr::getSExt(CastOp, SS->getType()); 6673 break; 6674 } 6675 case scZeroExtend: { 6676 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6677 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6678 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6679 break; 6680 } 6681 case scTruncate: { 6682 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6683 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6684 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6685 break; 6686 } 6687 case scAddExpr: { 6688 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6689 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6690 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6691 unsigned AS = PTy->getAddressSpace(); 6692 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6693 C = ConstantExpr::getBitCast(C, DestPtrTy); 6694 } 6695 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6696 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6697 if (!C2) return nullptr; 6698 6699 // First pointer! 6700 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6701 unsigned AS = C2->getType()->getPointerAddressSpace(); 6702 std::swap(C, C2); 6703 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6704 // The offsets have been converted to bytes. We can add bytes to an 6705 // i8* by GEP with the byte count in the first index. 6706 C = ConstantExpr::getBitCast(C, DestPtrTy); 6707 } 6708 6709 // Don't bother trying to sum two pointers. We probably can't 6710 // statically compute a load that results from it anyway. 6711 if (C2->getType()->isPointerTy()) 6712 return nullptr; 6713 6714 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6715 if (PTy->getElementType()->isStructTy()) 6716 C2 = ConstantExpr::getIntegerCast( 6717 C2, Type::getInt32Ty(C->getContext()), true); 6718 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6719 } else 6720 C = ConstantExpr::getAdd(C, C2); 6721 } 6722 return C; 6723 } 6724 break; 6725 } 6726 case scMulExpr: { 6727 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6728 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6729 // Don't bother with pointers at all. 6730 if (C->getType()->isPointerTy()) return nullptr; 6731 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6732 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6733 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6734 C = ConstantExpr::getMul(C, C2); 6735 } 6736 return C; 6737 } 6738 break; 6739 } 6740 case scUDivExpr: { 6741 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6742 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6743 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6744 if (LHS->getType() == RHS->getType()) 6745 return ConstantExpr::getUDiv(LHS, RHS); 6746 break; 6747 } 6748 case scSMaxExpr: 6749 case scUMaxExpr: 6750 break; // TODO: smax, umax. 6751 } 6752 return nullptr; 6753 } 6754 6755 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6756 if (isa<SCEVConstant>(V)) return V; 6757 6758 // If this instruction is evolved from a constant-evolving PHI, compute the 6759 // exit value from the loop without using SCEVs. 6760 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6761 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6762 const Loop *LI = this->LI[I->getParent()]; 6763 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6764 if (PHINode *PN = dyn_cast<PHINode>(I)) 6765 if (PN->getParent() == LI->getHeader()) { 6766 // Okay, there is no closed form solution for the PHI node. Check 6767 // to see if the loop that contains it has a known backedge-taken 6768 // count. If so, we may be able to force computation of the exit 6769 // value. 6770 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6771 if (const SCEVConstant *BTCC = 6772 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6773 // Okay, we know how many times the containing loop executes. If 6774 // this is a constant evolving PHI node, get the final value at 6775 // the specified iteration number. 6776 Constant *RV = 6777 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6778 if (RV) return getSCEV(RV); 6779 } 6780 } 6781 6782 // Okay, this is an expression that we cannot symbolically evaluate 6783 // into a SCEV. Check to see if it's possible to symbolically evaluate 6784 // the arguments into constants, and if so, try to constant propagate the 6785 // result. This is particularly useful for computing loop exit values. 6786 if (CanConstantFold(I)) { 6787 SmallVector<Constant *, 4> Operands; 6788 bool MadeImprovement = false; 6789 for (Value *Op : I->operands()) { 6790 if (Constant *C = dyn_cast<Constant>(Op)) { 6791 Operands.push_back(C); 6792 continue; 6793 } 6794 6795 // If any of the operands is non-constant and if they are 6796 // non-integer and non-pointer, don't even try to analyze them 6797 // with scev techniques. 6798 if (!isSCEVable(Op->getType())) 6799 return V; 6800 6801 const SCEV *OrigV = getSCEV(Op); 6802 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6803 MadeImprovement |= OrigV != OpV; 6804 6805 Constant *C = BuildConstantFromSCEV(OpV); 6806 if (!C) return V; 6807 if (C->getType() != Op->getType()) 6808 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6809 Op->getType(), 6810 false), 6811 C, Op->getType()); 6812 Operands.push_back(C); 6813 } 6814 6815 // Check to see if getSCEVAtScope actually made an improvement. 6816 if (MadeImprovement) { 6817 Constant *C = nullptr; 6818 const DataLayout &DL = getDataLayout(); 6819 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6820 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6821 Operands[1], DL, &TLI); 6822 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6823 if (!LI->isVolatile()) 6824 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6825 } else 6826 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6827 if (!C) return V; 6828 return getSCEV(C); 6829 } 6830 } 6831 } 6832 6833 // This is some other type of SCEVUnknown, just return it. 6834 return V; 6835 } 6836 6837 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6838 // Avoid performing the look-up in the common case where the specified 6839 // expression has no loop-variant portions. 6840 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6841 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6842 if (OpAtScope != Comm->getOperand(i)) { 6843 // Okay, at least one of these operands is loop variant but might be 6844 // foldable. Build a new instance of the folded commutative expression. 6845 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6846 Comm->op_begin()+i); 6847 NewOps.push_back(OpAtScope); 6848 6849 for (++i; i != e; ++i) { 6850 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6851 NewOps.push_back(OpAtScope); 6852 } 6853 if (isa<SCEVAddExpr>(Comm)) 6854 return getAddExpr(NewOps); 6855 if (isa<SCEVMulExpr>(Comm)) 6856 return getMulExpr(NewOps); 6857 if (isa<SCEVSMaxExpr>(Comm)) 6858 return getSMaxExpr(NewOps); 6859 if (isa<SCEVUMaxExpr>(Comm)) 6860 return getUMaxExpr(NewOps); 6861 llvm_unreachable("Unknown commutative SCEV type!"); 6862 } 6863 } 6864 // If we got here, all operands are loop invariant. 6865 return Comm; 6866 } 6867 6868 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6869 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6870 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6871 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6872 return Div; // must be loop invariant 6873 return getUDivExpr(LHS, RHS); 6874 } 6875 6876 // If this is a loop recurrence for a loop that does not contain L, then we 6877 // are dealing with the final value computed by the loop. 6878 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6879 // First, attempt to evaluate each operand. 6880 // Avoid performing the look-up in the common case where the specified 6881 // expression has no loop-variant portions. 6882 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6883 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6884 if (OpAtScope == AddRec->getOperand(i)) 6885 continue; 6886 6887 // Okay, at least one of these operands is loop variant but might be 6888 // foldable. Build a new instance of the folded commutative expression. 6889 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6890 AddRec->op_begin()+i); 6891 NewOps.push_back(OpAtScope); 6892 for (++i; i != e; ++i) 6893 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6894 6895 const SCEV *FoldedRec = 6896 getAddRecExpr(NewOps, AddRec->getLoop(), 6897 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6898 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6899 // The addrec may be folded to a nonrecurrence, for example, if the 6900 // induction variable is multiplied by zero after constant folding. Go 6901 // ahead and return the folded value. 6902 if (!AddRec) 6903 return FoldedRec; 6904 break; 6905 } 6906 6907 // If the scope is outside the addrec's loop, evaluate it by using the 6908 // loop exit value of the addrec. 6909 if (!AddRec->getLoop()->contains(L)) { 6910 // To evaluate this recurrence, we need to know how many times the AddRec 6911 // loop iterates. Compute this now. 6912 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6913 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6914 6915 // Then, evaluate the AddRec. 6916 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6917 } 6918 6919 return AddRec; 6920 } 6921 6922 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6923 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6924 if (Op == Cast->getOperand()) 6925 return Cast; // must be loop invariant 6926 return getZeroExtendExpr(Op, Cast->getType()); 6927 } 6928 6929 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6930 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6931 if (Op == Cast->getOperand()) 6932 return Cast; // must be loop invariant 6933 return getSignExtendExpr(Op, Cast->getType()); 6934 } 6935 6936 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6937 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6938 if (Op == Cast->getOperand()) 6939 return Cast; // must be loop invariant 6940 return getTruncateExpr(Op, Cast->getType()); 6941 } 6942 6943 llvm_unreachable("Unknown SCEV type!"); 6944 } 6945 6946 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6947 return getSCEVAtScope(getSCEV(V), L); 6948 } 6949 6950 /// Finds the minimum unsigned root of the following equation: 6951 /// 6952 /// A * X = B (mod N) 6953 /// 6954 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6955 /// A and B isn't important. 6956 /// 6957 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6958 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6959 ScalarEvolution &SE) { 6960 uint32_t BW = A.getBitWidth(); 6961 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6962 assert(A != 0 && "A must be non-zero."); 6963 6964 // 1. D = gcd(A, N) 6965 // 6966 // The gcd of A and N may have only one prime factor: 2. The number of 6967 // trailing zeros in A is its multiplicity 6968 uint32_t Mult2 = A.countTrailingZeros(); 6969 // D = 2^Mult2 6970 6971 // 2. Check if B is divisible by D. 6972 // 6973 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 6974 // is not less than multiplicity of this prime factor for D. 6975 if (B.countTrailingZeros() < Mult2) 6976 return SE.getCouldNotCompute(); 6977 6978 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 6979 // modulo (N / D). 6980 // 6981 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 6982 // bit width during computations. 6983 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 6984 APInt Mod(BW + 1, 0); 6985 Mod.setBit(BW - Mult2); // Mod = N / D 6986 APInt I = AD.multiplicativeInverse(Mod); 6987 6988 // 4. Compute the minimum unsigned root of the equation: 6989 // I * (B / D) mod (N / D) 6990 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 6991 6992 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 6993 // bits. 6994 return SE.getConstant(Result.trunc(BW)); 6995 } 6996 6997 /// Find the roots of the quadratic equation for the given quadratic chrec 6998 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 6999 /// two SCEVCouldNotCompute objects. 7000 /// 7001 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7002 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7003 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7004 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7005 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7006 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7007 7008 // We currently can only solve this if the coefficients are constants. 7009 if (!LC || !MC || !NC) 7010 return None; 7011 7012 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7013 const APInt &L = LC->getAPInt(); 7014 const APInt &M = MC->getAPInt(); 7015 const APInt &N = NC->getAPInt(); 7016 APInt Two(BitWidth, 2); 7017 APInt Four(BitWidth, 4); 7018 7019 { 7020 using namespace APIntOps; 7021 const APInt& C = L; 7022 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7023 // The B coefficient is M-N/2 7024 APInt B(M); 7025 B -= sdiv(N,Two); 7026 7027 // The A coefficient is N/2 7028 APInt A(N.sdiv(Two)); 7029 7030 // Compute the B^2-4ac term. 7031 APInt SqrtTerm(B); 7032 SqrtTerm *= B; 7033 SqrtTerm -= Four * (A * C); 7034 7035 if (SqrtTerm.isNegative()) { 7036 // The loop is provably infinite. 7037 return None; 7038 } 7039 7040 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7041 // integer value or else APInt::sqrt() will assert. 7042 APInt SqrtVal(SqrtTerm.sqrt()); 7043 7044 // Compute the two solutions for the quadratic formula. 7045 // The divisions must be performed as signed divisions. 7046 APInt NegB(-B); 7047 APInt TwoA(A << 1); 7048 if (TwoA.isMinValue()) 7049 return None; 7050 7051 LLVMContext &Context = SE.getContext(); 7052 7053 ConstantInt *Solution1 = 7054 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7055 ConstantInt *Solution2 = 7056 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7057 7058 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7059 cast<SCEVConstant>(SE.getConstant(Solution2))); 7060 } // end APIntOps namespace 7061 } 7062 7063 ScalarEvolution::ExitLimit 7064 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7065 bool AllowPredicates) { 7066 7067 // This is only used for loops with a "x != y" exit test. The exit condition 7068 // is now expressed as a single expression, V = x-y. So the exit test is 7069 // effectively V != 0. We know and take advantage of the fact that this 7070 // expression only being used in a comparison by zero context. 7071 7072 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7073 // If the value is a constant 7074 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7075 // If the value is already zero, the branch will execute zero times. 7076 if (C->getValue()->isZero()) return C; 7077 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7078 } 7079 7080 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7081 if (!AddRec && AllowPredicates) 7082 // Try to make this an AddRec using runtime tests, in the first X 7083 // iterations of this loop, where X is the SCEV expression found by the 7084 // algorithm below. 7085 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7086 7087 if (!AddRec || AddRec->getLoop() != L) 7088 return getCouldNotCompute(); 7089 7090 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7091 // the quadratic equation to solve it. 7092 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7093 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7094 const SCEVConstant *R1 = Roots->first; 7095 const SCEVConstant *R2 = Roots->second; 7096 // Pick the smallest positive root value. 7097 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7098 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7099 if (!CB->getZExtValue()) 7100 std::swap(R1, R2); // R1 is the minimum root now. 7101 7102 // We can only use this value if the chrec ends up with an exact zero 7103 // value at this index. When solving for "X*X != 5", for example, we 7104 // should not accept a root of 2. 7105 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7106 if (Val->isZero()) 7107 return ExitLimit(R1, R1, Predicates); // We found a quadratic root! 7108 } 7109 } 7110 return getCouldNotCompute(); 7111 } 7112 7113 // Otherwise we can only handle this if it is affine. 7114 if (!AddRec->isAffine()) 7115 return getCouldNotCompute(); 7116 7117 // If this is an affine expression, the execution count of this branch is 7118 // the minimum unsigned root of the following equation: 7119 // 7120 // Start + Step*N = 0 (mod 2^BW) 7121 // 7122 // equivalent to: 7123 // 7124 // Step*N = -Start (mod 2^BW) 7125 // 7126 // where BW is the common bit width of Start and Step. 7127 7128 // Get the initial value for the loop. 7129 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7130 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7131 7132 // For now we handle only constant steps. 7133 // 7134 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7135 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7136 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7137 // We have not yet seen any such cases. 7138 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7139 if (!StepC || StepC->getValue()->equalsInt(0)) 7140 return getCouldNotCompute(); 7141 7142 // For positive steps (counting up until unsigned overflow): 7143 // N = -Start/Step (as unsigned) 7144 // For negative steps (counting down to zero): 7145 // N = Start/-Step 7146 // First compute the unsigned distance from zero in the direction of Step. 7147 bool CountDown = StepC->getAPInt().isNegative(); 7148 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7149 7150 // Handle unitary steps, which cannot wraparound. 7151 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7152 // N = Distance (as unsigned) 7153 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7154 ConstantRange CR = getUnsignedRange(Start); 7155 const SCEV *MaxBECount; 7156 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7157 // When counting up, the worst starting value is 1, not 0. 7158 MaxBECount = CR.getUnsignedMax().isMinValue() 7159 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7160 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7161 else 7162 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7163 : -CR.getUnsignedMin()); 7164 return ExitLimit(Distance, MaxBECount, Predicates); 7165 } 7166 7167 // As a special case, handle the instance where Step is a positive power of 7168 // two. In this case, determining whether Step divides Distance evenly can be 7169 // done by counting and comparing the number of trailing zeros of Step and 7170 // Distance. 7171 if (!CountDown) { 7172 const APInt &StepV = StepC->getAPInt(); 7173 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7174 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7175 // case is not handled as this code is guarded by !CountDown. 7176 if (StepV.isPowerOf2() && 7177 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7178 // Here we've constrained the equation to be of the form 7179 // 7180 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7181 // 7182 // where we're operating on a W bit wide integer domain and k is 7183 // non-negative. The smallest unsigned solution for X is the trip count. 7184 // 7185 // (0) is equivalent to: 7186 // 7187 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7188 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7189 // <=> 2^k * Distance' - X = L * 2^(W - N) 7190 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7191 // 7192 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7193 // by 2^(W - N). 7194 // 7195 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7196 // 7197 // E.g. say we're solving 7198 // 7199 // 2 * Val = 2 * X (in i8) ... (3) 7200 // 7201 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7202 // 7203 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7204 // necessarily the smallest unsigned value of X that satisfies (3). 7205 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7206 // is i8 1, not i8 -127 7207 7208 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7209 7210 // Since SCEV does not have a URem node, we construct one using a truncate 7211 // and a zero extend. 7212 7213 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7214 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7215 auto *WideTy = Distance->getType(); 7216 7217 const SCEV *Limit = 7218 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7219 return ExitLimit(Limit, Limit, Predicates); 7220 } 7221 } 7222 7223 // If the condition controls loop exit (the loop exits only if the expression 7224 // is true) and the addition is no-wrap we can use unsigned divide to 7225 // compute the backedge count. In this case, the step may not divide the 7226 // distance, but we don't care because if the condition is "missed" the loop 7227 // will have undefined behavior due to wrapping. 7228 if (ControlsExit && AddRec->hasNoSelfWrap() && 7229 loopHasNoAbnormalExits(AddRec->getLoop())) { 7230 const SCEV *Exact = 7231 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7232 return ExitLimit(Exact, Exact, Predicates); 7233 } 7234 7235 // Then, try to solve the above equation provided that Start is constant. 7236 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7237 const SCEV *E = SolveLinEquationWithOverflow( 7238 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7239 return ExitLimit(E, E, Predicates); 7240 } 7241 return getCouldNotCompute(); 7242 } 7243 7244 ScalarEvolution::ExitLimit 7245 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7246 // Loops that look like: while (X == 0) are very strange indeed. We don't 7247 // handle them yet except for the trivial case. This could be expanded in the 7248 // future as needed. 7249 7250 // If the value is a constant, check to see if it is known to be non-zero 7251 // already. If so, the backedge will execute zero times. 7252 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7253 if (!C->getValue()->isNullValue()) 7254 return getZero(C->getType()); 7255 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7256 } 7257 7258 // We could implement others, but I really doubt anyone writes loops like 7259 // this, and if they did, they would already be constant folded. 7260 return getCouldNotCompute(); 7261 } 7262 7263 std::pair<BasicBlock *, BasicBlock *> 7264 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7265 // If the block has a unique predecessor, then there is no path from the 7266 // predecessor to the block that does not go through the direct edge 7267 // from the predecessor to the block. 7268 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7269 return {Pred, BB}; 7270 7271 // A loop's header is defined to be a block that dominates the loop. 7272 // If the header has a unique predecessor outside the loop, it must be 7273 // a block that has exactly one successor that can reach the loop. 7274 if (Loop *L = LI.getLoopFor(BB)) 7275 return {L->getLoopPredecessor(), L->getHeader()}; 7276 7277 return {nullptr, nullptr}; 7278 } 7279 7280 /// SCEV structural equivalence is usually sufficient for testing whether two 7281 /// expressions are equal, however for the purposes of looking for a condition 7282 /// guarding a loop, it can be useful to be a little more general, since a 7283 /// front-end may have replicated the controlling expression. 7284 /// 7285 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7286 // Quick check to see if they are the same SCEV. 7287 if (A == B) return true; 7288 7289 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7290 // Not all instructions that are "identical" compute the same value. For 7291 // instance, two distinct alloca instructions allocating the same type are 7292 // identical and do not read memory; but compute distinct values. 7293 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7294 }; 7295 7296 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7297 // two different instructions with the same value. Check for this case. 7298 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7299 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7300 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7301 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7302 if (ComputesEqualValues(AI, BI)) 7303 return true; 7304 7305 // Otherwise assume they may have a different value. 7306 return false; 7307 } 7308 7309 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7310 const SCEV *&LHS, const SCEV *&RHS, 7311 unsigned Depth) { 7312 bool Changed = false; 7313 7314 // If we hit the max recursion limit bail out. 7315 if (Depth >= 3) 7316 return false; 7317 7318 // Canonicalize a constant to the right side. 7319 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7320 // Check for both operands constant. 7321 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7322 if (ConstantExpr::getICmp(Pred, 7323 LHSC->getValue(), 7324 RHSC->getValue())->isNullValue()) 7325 goto trivially_false; 7326 else 7327 goto trivially_true; 7328 } 7329 // Otherwise swap the operands to put the constant on the right. 7330 std::swap(LHS, RHS); 7331 Pred = ICmpInst::getSwappedPredicate(Pred); 7332 Changed = true; 7333 } 7334 7335 // If we're comparing an addrec with a value which is loop-invariant in the 7336 // addrec's loop, put the addrec on the left. Also make a dominance check, 7337 // as both operands could be addrecs loop-invariant in each other's loop. 7338 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7339 const Loop *L = AR->getLoop(); 7340 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7341 std::swap(LHS, RHS); 7342 Pred = ICmpInst::getSwappedPredicate(Pred); 7343 Changed = true; 7344 } 7345 } 7346 7347 // If there's a constant operand, canonicalize comparisons with boundary 7348 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7349 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7350 const APInt &RA = RC->getAPInt(); 7351 7352 bool SimplifiedByConstantRange = false; 7353 7354 if (!ICmpInst::isEquality(Pred)) { 7355 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7356 if (ExactCR.isFullSet()) 7357 goto trivially_true; 7358 else if (ExactCR.isEmptySet()) 7359 goto trivially_false; 7360 7361 APInt NewRHS; 7362 CmpInst::Predicate NewPred; 7363 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7364 ICmpInst::isEquality(NewPred)) { 7365 // We were able to convert an inequality to an equality. 7366 Pred = NewPred; 7367 RHS = getConstant(NewRHS); 7368 Changed = SimplifiedByConstantRange = true; 7369 } 7370 } 7371 7372 if (!SimplifiedByConstantRange) { 7373 switch (Pred) { 7374 default: 7375 break; 7376 case ICmpInst::ICMP_EQ: 7377 case ICmpInst::ICMP_NE: 7378 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7379 if (!RA) 7380 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7381 if (const SCEVMulExpr *ME = 7382 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7383 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7384 ME->getOperand(0)->isAllOnesValue()) { 7385 RHS = AE->getOperand(1); 7386 LHS = ME->getOperand(1); 7387 Changed = true; 7388 } 7389 break; 7390 7391 7392 // The "Should have been caught earlier!" messages refer to the fact 7393 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7394 // should have fired on the corresponding cases, and canonicalized the 7395 // check to trivially_true or trivially_false. 7396 7397 case ICmpInst::ICMP_UGE: 7398 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7399 Pred = ICmpInst::ICMP_UGT; 7400 RHS = getConstant(RA - 1); 7401 Changed = true; 7402 break; 7403 case ICmpInst::ICMP_ULE: 7404 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7405 Pred = ICmpInst::ICMP_ULT; 7406 RHS = getConstant(RA + 1); 7407 Changed = true; 7408 break; 7409 case ICmpInst::ICMP_SGE: 7410 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7411 Pred = ICmpInst::ICMP_SGT; 7412 RHS = getConstant(RA - 1); 7413 Changed = true; 7414 break; 7415 case ICmpInst::ICMP_SLE: 7416 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7417 Pred = ICmpInst::ICMP_SLT; 7418 RHS = getConstant(RA + 1); 7419 Changed = true; 7420 break; 7421 } 7422 } 7423 } 7424 7425 // Check for obvious equality. 7426 if (HasSameValue(LHS, RHS)) { 7427 if (ICmpInst::isTrueWhenEqual(Pred)) 7428 goto trivially_true; 7429 if (ICmpInst::isFalseWhenEqual(Pred)) 7430 goto trivially_false; 7431 } 7432 7433 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7434 // adding or subtracting 1 from one of the operands. 7435 switch (Pred) { 7436 case ICmpInst::ICMP_SLE: 7437 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7438 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7439 SCEV::FlagNSW); 7440 Pred = ICmpInst::ICMP_SLT; 7441 Changed = true; 7442 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7443 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7444 SCEV::FlagNSW); 7445 Pred = ICmpInst::ICMP_SLT; 7446 Changed = true; 7447 } 7448 break; 7449 case ICmpInst::ICMP_SGE: 7450 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7451 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7452 SCEV::FlagNSW); 7453 Pred = ICmpInst::ICMP_SGT; 7454 Changed = true; 7455 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7456 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7457 SCEV::FlagNSW); 7458 Pred = ICmpInst::ICMP_SGT; 7459 Changed = true; 7460 } 7461 break; 7462 case ICmpInst::ICMP_ULE: 7463 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7464 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7465 SCEV::FlagNUW); 7466 Pred = ICmpInst::ICMP_ULT; 7467 Changed = true; 7468 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7469 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7470 Pred = ICmpInst::ICMP_ULT; 7471 Changed = true; 7472 } 7473 break; 7474 case ICmpInst::ICMP_UGE: 7475 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7476 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7477 Pred = ICmpInst::ICMP_UGT; 7478 Changed = true; 7479 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7480 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7481 SCEV::FlagNUW); 7482 Pred = ICmpInst::ICMP_UGT; 7483 Changed = true; 7484 } 7485 break; 7486 default: 7487 break; 7488 } 7489 7490 // TODO: More simplifications are possible here. 7491 7492 // Recursively simplify until we either hit a recursion limit or nothing 7493 // changes. 7494 if (Changed) 7495 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7496 7497 return Changed; 7498 7499 trivially_true: 7500 // Return 0 == 0. 7501 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7502 Pred = ICmpInst::ICMP_EQ; 7503 return true; 7504 7505 trivially_false: 7506 // Return 0 != 0. 7507 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7508 Pred = ICmpInst::ICMP_NE; 7509 return true; 7510 } 7511 7512 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7513 return getSignedRange(S).getSignedMax().isNegative(); 7514 } 7515 7516 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7517 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7518 } 7519 7520 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7521 return !getSignedRange(S).getSignedMin().isNegative(); 7522 } 7523 7524 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7525 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7526 } 7527 7528 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7529 return isKnownNegative(S) || isKnownPositive(S); 7530 } 7531 7532 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7533 const SCEV *LHS, const SCEV *RHS) { 7534 // Canonicalize the inputs first. 7535 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7536 7537 // If LHS or RHS is an addrec, check to see if the condition is true in 7538 // every iteration of the loop. 7539 // If LHS and RHS are both addrec, both conditions must be true in 7540 // every iteration of the loop. 7541 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7542 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7543 bool LeftGuarded = false; 7544 bool RightGuarded = false; 7545 if (LAR) { 7546 const Loop *L = LAR->getLoop(); 7547 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7548 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7549 if (!RAR) return true; 7550 LeftGuarded = true; 7551 } 7552 } 7553 if (RAR) { 7554 const Loop *L = RAR->getLoop(); 7555 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7556 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7557 if (!LAR) return true; 7558 RightGuarded = true; 7559 } 7560 } 7561 if (LeftGuarded && RightGuarded) 7562 return true; 7563 7564 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7565 return true; 7566 7567 // Otherwise see what can be done with known constant ranges. 7568 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7569 } 7570 7571 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7572 ICmpInst::Predicate Pred, 7573 bool &Increasing) { 7574 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7575 7576 #ifndef NDEBUG 7577 // Verify an invariant: inverting the predicate should turn a monotonically 7578 // increasing change to a monotonically decreasing one, and vice versa. 7579 bool IncreasingSwapped; 7580 bool ResultSwapped = isMonotonicPredicateImpl( 7581 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7582 7583 assert(Result == ResultSwapped && "should be able to analyze both!"); 7584 if (ResultSwapped) 7585 assert(Increasing == !IncreasingSwapped && 7586 "monotonicity should flip as we flip the predicate"); 7587 #endif 7588 7589 return Result; 7590 } 7591 7592 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7593 ICmpInst::Predicate Pred, 7594 bool &Increasing) { 7595 7596 // A zero step value for LHS means the induction variable is essentially a 7597 // loop invariant value. We don't really depend on the predicate actually 7598 // flipping from false to true (for increasing predicates, and the other way 7599 // around for decreasing predicates), all we care about is that *if* the 7600 // predicate changes then it only changes from false to true. 7601 // 7602 // A zero step value in itself is not very useful, but there may be places 7603 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7604 // as general as possible. 7605 7606 switch (Pred) { 7607 default: 7608 return false; // Conservative answer 7609 7610 case ICmpInst::ICMP_UGT: 7611 case ICmpInst::ICMP_UGE: 7612 case ICmpInst::ICMP_ULT: 7613 case ICmpInst::ICMP_ULE: 7614 if (!LHS->hasNoUnsignedWrap()) 7615 return false; 7616 7617 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7618 return true; 7619 7620 case ICmpInst::ICMP_SGT: 7621 case ICmpInst::ICMP_SGE: 7622 case ICmpInst::ICMP_SLT: 7623 case ICmpInst::ICMP_SLE: { 7624 if (!LHS->hasNoSignedWrap()) 7625 return false; 7626 7627 const SCEV *Step = LHS->getStepRecurrence(*this); 7628 7629 if (isKnownNonNegative(Step)) { 7630 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7631 return true; 7632 } 7633 7634 if (isKnownNonPositive(Step)) { 7635 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7636 return true; 7637 } 7638 7639 return false; 7640 } 7641 7642 } 7643 7644 llvm_unreachable("switch has default clause!"); 7645 } 7646 7647 bool ScalarEvolution::isLoopInvariantPredicate( 7648 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7649 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7650 const SCEV *&InvariantRHS) { 7651 7652 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7653 if (!isLoopInvariant(RHS, L)) { 7654 if (!isLoopInvariant(LHS, L)) 7655 return false; 7656 7657 std::swap(LHS, RHS); 7658 Pred = ICmpInst::getSwappedPredicate(Pred); 7659 } 7660 7661 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7662 if (!ArLHS || ArLHS->getLoop() != L) 7663 return false; 7664 7665 bool Increasing; 7666 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7667 return false; 7668 7669 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7670 // true as the loop iterates, and the backedge is control dependent on 7671 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7672 // 7673 // * if the predicate was false in the first iteration then the predicate 7674 // is never evaluated again, since the loop exits without taking the 7675 // backedge. 7676 // * if the predicate was true in the first iteration then it will 7677 // continue to be true for all future iterations since it is 7678 // monotonically increasing. 7679 // 7680 // For both the above possibilities, we can replace the loop varying 7681 // predicate with its value on the first iteration of the loop (which is 7682 // loop invariant). 7683 // 7684 // A similar reasoning applies for a monotonically decreasing predicate, by 7685 // replacing true with false and false with true in the above two bullets. 7686 7687 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7688 7689 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7690 return false; 7691 7692 InvariantPred = Pred; 7693 InvariantLHS = ArLHS->getStart(); 7694 InvariantRHS = RHS; 7695 return true; 7696 } 7697 7698 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7699 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7700 if (HasSameValue(LHS, RHS)) 7701 return ICmpInst::isTrueWhenEqual(Pred); 7702 7703 // This code is split out from isKnownPredicate because it is called from 7704 // within isLoopEntryGuardedByCond. 7705 7706 auto CheckRanges = 7707 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7708 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7709 .contains(RangeLHS); 7710 }; 7711 7712 // The check at the top of the function catches the case where the values are 7713 // known to be equal. 7714 if (Pred == CmpInst::ICMP_EQ) 7715 return false; 7716 7717 if (Pred == CmpInst::ICMP_NE) 7718 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7719 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7720 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7721 7722 if (CmpInst::isSigned(Pred)) 7723 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7724 7725 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7726 } 7727 7728 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7729 const SCEV *LHS, 7730 const SCEV *RHS) { 7731 7732 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7733 // Return Y via OutY. 7734 auto MatchBinaryAddToConst = 7735 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7736 SCEV::NoWrapFlags ExpectedFlags) { 7737 const SCEV *NonConstOp, *ConstOp; 7738 SCEV::NoWrapFlags FlagsPresent; 7739 7740 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7741 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7742 return false; 7743 7744 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7745 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7746 }; 7747 7748 APInt C; 7749 7750 switch (Pred) { 7751 default: 7752 break; 7753 7754 case ICmpInst::ICMP_SGE: 7755 std::swap(LHS, RHS); 7756 case ICmpInst::ICMP_SLE: 7757 // X s<= (X + C)<nsw> if C >= 0 7758 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7759 return true; 7760 7761 // (X + C)<nsw> s<= X if C <= 0 7762 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7763 !C.isStrictlyPositive()) 7764 return true; 7765 break; 7766 7767 case ICmpInst::ICMP_SGT: 7768 std::swap(LHS, RHS); 7769 case ICmpInst::ICMP_SLT: 7770 // X s< (X + C)<nsw> if C > 0 7771 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7772 C.isStrictlyPositive()) 7773 return true; 7774 7775 // (X + C)<nsw> s< X if C < 0 7776 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7777 return true; 7778 break; 7779 } 7780 7781 return false; 7782 } 7783 7784 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7785 const SCEV *LHS, 7786 const SCEV *RHS) { 7787 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7788 return false; 7789 7790 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7791 // the stack can result in exponential time complexity. 7792 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7793 7794 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7795 // 7796 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7797 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7798 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7799 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7800 // use isKnownPredicate later if needed. 7801 return isKnownNonNegative(RHS) && 7802 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7803 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7804 } 7805 7806 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7807 ICmpInst::Predicate Pred, 7808 const SCEV *LHS, const SCEV *RHS) { 7809 // No need to even try if we know the module has no guards. 7810 if (!HasGuards) 7811 return false; 7812 7813 return any_of(*BB, [&](Instruction &I) { 7814 using namespace llvm::PatternMatch; 7815 7816 Value *Condition; 7817 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7818 m_Value(Condition))) && 7819 isImpliedCond(Pred, LHS, RHS, Condition, false); 7820 }); 7821 } 7822 7823 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7824 /// protected by a conditional between LHS and RHS. This is used to 7825 /// to eliminate casts. 7826 bool 7827 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7828 ICmpInst::Predicate Pred, 7829 const SCEV *LHS, const SCEV *RHS) { 7830 // Interpret a null as meaning no loop, where there is obviously no guard 7831 // (interprocedural conditions notwithstanding). 7832 if (!L) return true; 7833 7834 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7835 return true; 7836 7837 BasicBlock *Latch = L->getLoopLatch(); 7838 if (!Latch) 7839 return false; 7840 7841 BranchInst *LoopContinuePredicate = 7842 dyn_cast<BranchInst>(Latch->getTerminator()); 7843 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7844 isImpliedCond(Pred, LHS, RHS, 7845 LoopContinuePredicate->getCondition(), 7846 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7847 return true; 7848 7849 // We don't want more than one activation of the following loops on the stack 7850 // -- that can lead to O(n!) time complexity. 7851 if (WalkingBEDominatingConds) 7852 return false; 7853 7854 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7855 7856 // See if we can exploit a trip count to prove the predicate. 7857 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7858 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7859 if (LatchBECount != getCouldNotCompute()) { 7860 // We know that Latch branches back to the loop header exactly 7861 // LatchBECount times. This means the backdege condition at Latch is 7862 // equivalent to "{0,+,1} u< LatchBECount". 7863 Type *Ty = LatchBECount->getType(); 7864 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7865 const SCEV *LoopCounter = 7866 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7867 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7868 LatchBECount)) 7869 return true; 7870 } 7871 7872 // Check conditions due to any @llvm.assume intrinsics. 7873 for (auto &AssumeVH : AC.assumptions()) { 7874 if (!AssumeVH) 7875 continue; 7876 auto *CI = cast<CallInst>(AssumeVH); 7877 if (!DT.dominates(CI, Latch->getTerminator())) 7878 continue; 7879 7880 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7881 return true; 7882 } 7883 7884 // If the loop is not reachable from the entry block, we risk running into an 7885 // infinite loop as we walk up into the dom tree. These loops do not matter 7886 // anyway, so we just return a conservative answer when we see them. 7887 if (!DT.isReachableFromEntry(L->getHeader())) 7888 return false; 7889 7890 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7891 return true; 7892 7893 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7894 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7895 7896 assert(DTN && "should reach the loop header before reaching the root!"); 7897 7898 BasicBlock *BB = DTN->getBlock(); 7899 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7900 return true; 7901 7902 BasicBlock *PBB = BB->getSinglePredecessor(); 7903 if (!PBB) 7904 continue; 7905 7906 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7907 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7908 continue; 7909 7910 Value *Condition = ContinuePredicate->getCondition(); 7911 7912 // If we have an edge `E` within the loop body that dominates the only 7913 // latch, the condition guarding `E` also guards the backedge. This 7914 // reasoning works only for loops with a single latch. 7915 7916 BasicBlockEdge DominatingEdge(PBB, BB); 7917 if (DominatingEdge.isSingleEdge()) { 7918 // We're constructively (and conservatively) enumerating edges within the 7919 // loop body that dominate the latch. The dominator tree better agree 7920 // with us on this: 7921 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7922 7923 if (isImpliedCond(Pred, LHS, RHS, Condition, 7924 BB != ContinuePredicate->getSuccessor(0))) 7925 return true; 7926 } 7927 } 7928 7929 return false; 7930 } 7931 7932 bool 7933 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7934 ICmpInst::Predicate Pred, 7935 const SCEV *LHS, const SCEV *RHS) { 7936 // Interpret a null as meaning no loop, where there is obviously no guard 7937 // (interprocedural conditions notwithstanding). 7938 if (!L) return false; 7939 7940 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7941 return true; 7942 7943 // Starting at the loop predecessor, climb up the predecessor chain, as long 7944 // as there are predecessors that can be found that have unique successors 7945 // leading to the original header. 7946 for (std::pair<BasicBlock *, BasicBlock *> 7947 Pair(L->getLoopPredecessor(), L->getHeader()); 7948 Pair.first; 7949 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7950 7951 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 7952 return true; 7953 7954 BranchInst *LoopEntryPredicate = 7955 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7956 if (!LoopEntryPredicate || 7957 LoopEntryPredicate->isUnconditional()) 7958 continue; 7959 7960 if (isImpliedCond(Pred, LHS, RHS, 7961 LoopEntryPredicate->getCondition(), 7962 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7963 return true; 7964 } 7965 7966 // Check conditions due to any @llvm.assume intrinsics. 7967 for (auto &AssumeVH : AC.assumptions()) { 7968 if (!AssumeVH) 7969 continue; 7970 auto *CI = cast<CallInst>(AssumeVH); 7971 if (!DT.dominates(CI, L->getHeader())) 7972 continue; 7973 7974 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7975 return true; 7976 } 7977 7978 return false; 7979 } 7980 7981 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 7982 const SCEV *LHS, const SCEV *RHS, 7983 Value *FoundCondValue, 7984 bool Inverse) { 7985 if (!PendingLoopPredicates.insert(FoundCondValue).second) 7986 return false; 7987 7988 auto ClearOnExit = 7989 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 7990 7991 // Recursively handle And and Or conditions. 7992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 7993 if (BO->getOpcode() == Instruction::And) { 7994 if (!Inverse) 7995 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 7996 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 7997 } else if (BO->getOpcode() == Instruction::Or) { 7998 if (Inverse) 7999 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8000 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8001 } 8002 } 8003 8004 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8005 if (!ICI) return false; 8006 8007 // Now that we found a conditional branch that dominates the loop or controls 8008 // the loop latch. Check to see if it is the comparison we are looking for. 8009 ICmpInst::Predicate FoundPred; 8010 if (Inverse) 8011 FoundPred = ICI->getInversePredicate(); 8012 else 8013 FoundPred = ICI->getPredicate(); 8014 8015 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8016 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8017 8018 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8019 } 8020 8021 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8022 const SCEV *RHS, 8023 ICmpInst::Predicate FoundPred, 8024 const SCEV *FoundLHS, 8025 const SCEV *FoundRHS) { 8026 // Balance the types. 8027 if (getTypeSizeInBits(LHS->getType()) < 8028 getTypeSizeInBits(FoundLHS->getType())) { 8029 if (CmpInst::isSigned(Pred)) { 8030 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8031 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8032 } else { 8033 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8034 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8035 } 8036 } else if (getTypeSizeInBits(LHS->getType()) > 8037 getTypeSizeInBits(FoundLHS->getType())) { 8038 if (CmpInst::isSigned(FoundPred)) { 8039 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8040 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8041 } else { 8042 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8043 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8044 } 8045 } 8046 8047 // Canonicalize the query to match the way instcombine will have 8048 // canonicalized the comparison. 8049 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8050 if (LHS == RHS) 8051 return CmpInst::isTrueWhenEqual(Pred); 8052 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8053 if (FoundLHS == FoundRHS) 8054 return CmpInst::isFalseWhenEqual(FoundPred); 8055 8056 // Check to see if we can make the LHS or RHS match. 8057 if (LHS == FoundRHS || RHS == FoundLHS) { 8058 if (isa<SCEVConstant>(RHS)) { 8059 std::swap(FoundLHS, FoundRHS); 8060 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8061 } else { 8062 std::swap(LHS, RHS); 8063 Pred = ICmpInst::getSwappedPredicate(Pred); 8064 } 8065 } 8066 8067 // Check whether the found predicate is the same as the desired predicate. 8068 if (FoundPred == Pred) 8069 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8070 8071 // Check whether swapping the found predicate makes it the same as the 8072 // desired predicate. 8073 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8074 if (isa<SCEVConstant>(RHS)) 8075 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8076 else 8077 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8078 RHS, LHS, FoundLHS, FoundRHS); 8079 } 8080 8081 // Unsigned comparison is the same as signed comparison when both the operands 8082 // are non-negative. 8083 if (CmpInst::isUnsigned(FoundPred) && 8084 CmpInst::getSignedPredicate(FoundPred) == Pred && 8085 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8086 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8087 8088 // Check if we can make progress by sharpening ranges. 8089 if (FoundPred == ICmpInst::ICMP_NE && 8090 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8091 8092 const SCEVConstant *C = nullptr; 8093 const SCEV *V = nullptr; 8094 8095 if (isa<SCEVConstant>(FoundLHS)) { 8096 C = cast<SCEVConstant>(FoundLHS); 8097 V = FoundRHS; 8098 } else { 8099 C = cast<SCEVConstant>(FoundRHS); 8100 V = FoundLHS; 8101 } 8102 8103 // The guarding predicate tells us that C != V. If the known range 8104 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8105 // range we consider has to correspond to same signedness as the 8106 // predicate we're interested in folding. 8107 8108 APInt Min = ICmpInst::isSigned(Pred) ? 8109 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8110 8111 if (Min == C->getAPInt()) { 8112 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8113 // This is true even if (Min + 1) wraps around -- in case of 8114 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8115 8116 APInt SharperMin = Min + 1; 8117 8118 switch (Pred) { 8119 case ICmpInst::ICMP_SGE: 8120 case ICmpInst::ICMP_UGE: 8121 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8122 // RHS, we're done. 8123 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8124 getConstant(SharperMin))) 8125 return true; 8126 8127 case ICmpInst::ICMP_SGT: 8128 case ICmpInst::ICMP_UGT: 8129 // We know from the range information that (V `Pred` Min || 8130 // V == Min). We know from the guarding condition that !(V 8131 // == Min). This gives us 8132 // 8133 // V `Pred` Min || V == Min && !(V == Min) 8134 // => V `Pred` Min 8135 // 8136 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8137 8138 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8139 return true; 8140 8141 default: 8142 // No change 8143 break; 8144 } 8145 } 8146 } 8147 8148 // Check whether the actual condition is beyond sufficient. 8149 if (FoundPred == ICmpInst::ICMP_EQ) 8150 if (ICmpInst::isTrueWhenEqual(Pred)) 8151 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8152 return true; 8153 if (Pred == ICmpInst::ICMP_NE) 8154 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8155 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8156 return true; 8157 8158 // Otherwise assume the worst. 8159 return false; 8160 } 8161 8162 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8163 const SCEV *&L, const SCEV *&R, 8164 SCEV::NoWrapFlags &Flags) { 8165 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8166 if (!AE || AE->getNumOperands() != 2) 8167 return false; 8168 8169 L = AE->getOperand(0); 8170 R = AE->getOperand(1); 8171 Flags = AE->getNoWrapFlags(); 8172 return true; 8173 } 8174 8175 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8176 const SCEV *Less) { 8177 // We avoid subtracting expressions here because this function is usually 8178 // fairly deep in the call stack (i.e. is called many times). 8179 8180 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8181 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8182 const auto *MAR = cast<SCEVAddRecExpr>(More); 8183 8184 if (LAR->getLoop() != MAR->getLoop()) 8185 return None; 8186 8187 // We look at affine expressions only; not for correctness but to keep 8188 // getStepRecurrence cheap. 8189 if (!LAR->isAffine() || !MAR->isAffine()) 8190 return None; 8191 8192 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8193 return None; 8194 8195 Less = LAR->getStart(); 8196 More = MAR->getStart(); 8197 8198 // fall through 8199 } 8200 8201 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8202 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8203 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8204 return M - L; 8205 } 8206 8207 const SCEV *L, *R; 8208 SCEV::NoWrapFlags Flags; 8209 if (splitBinaryAdd(Less, L, R, Flags)) 8210 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8211 if (R == More) 8212 return -(LC->getAPInt()); 8213 8214 if (splitBinaryAdd(More, L, R, Flags)) 8215 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8216 if (R == Less) 8217 return LC->getAPInt(); 8218 8219 return None; 8220 } 8221 8222 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8223 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8224 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8225 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8226 return false; 8227 8228 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8229 if (!AddRecLHS) 8230 return false; 8231 8232 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8233 if (!AddRecFoundLHS) 8234 return false; 8235 8236 // We'd like to let SCEV reason about control dependencies, so we constrain 8237 // both the inequalities to be about add recurrences on the same loop. This 8238 // way we can use isLoopEntryGuardedByCond later. 8239 8240 const Loop *L = AddRecFoundLHS->getLoop(); 8241 if (L != AddRecLHS->getLoop()) 8242 return false; 8243 8244 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8245 // 8246 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8247 // ... (2) 8248 // 8249 // Informal proof for (2), assuming (1) [*]: 8250 // 8251 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8252 // 8253 // Then 8254 // 8255 // FoundLHS s< FoundRHS s< INT_MIN - C 8256 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8257 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8258 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8259 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8260 // <=> FoundLHS + C s< FoundRHS + C 8261 // 8262 // [*]: (1) can be proved by ruling out overflow. 8263 // 8264 // [**]: This can be proved by analyzing all the four possibilities: 8265 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8266 // (A s>= 0, B s>= 0). 8267 // 8268 // Note: 8269 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8270 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8271 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8272 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8273 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8274 // C)". 8275 8276 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8277 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8278 if (!LDiff || !RDiff || *LDiff != *RDiff) 8279 return false; 8280 8281 if (LDiff->isMinValue()) 8282 return true; 8283 8284 APInt FoundRHSLimit; 8285 8286 if (Pred == CmpInst::ICMP_ULT) { 8287 FoundRHSLimit = -(*RDiff); 8288 } else { 8289 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8290 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8291 } 8292 8293 // Try to prove (1) or (2), as needed. 8294 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8295 getConstant(FoundRHSLimit)); 8296 } 8297 8298 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8299 const SCEV *LHS, const SCEV *RHS, 8300 const SCEV *FoundLHS, 8301 const SCEV *FoundRHS) { 8302 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8303 return true; 8304 8305 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8306 return true; 8307 8308 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8309 FoundLHS, FoundRHS) || 8310 // ~x < ~y --> x > y 8311 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8312 getNotSCEV(FoundRHS), 8313 getNotSCEV(FoundLHS)); 8314 } 8315 8316 8317 /// If Expr computes ~A, return A else return nullptr 8318 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8319 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8320 if (!Add || Add->getNumOperands() != 2 || 8321 !Add->getOperand(0)->isAllOnesValue()) 8322 return nullptr; 8323 8324 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8325 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8326 !AddRHS->getOperand(0)->isAllOnesValue()) 8327 return nullptr; 8328 8329 return AddRHS->getOperand(1); 8330 } 8331 8332 8333 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8334 template<typename MaxExprType> 8335 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8336 const SCEV *Candidate) { 8337 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8338 if (!MaxExpr) return false; 8339 8340 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8341 } 8342 8343 8344 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8345 template<typename MaxExprType> 8346 static bool IsMinConsistingOf(ScalarEvolution &SE, 8347 const SCEV *MaybeMinExpr, 8348 const SCEV *Candidate) { 8349 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8350 if (!MaybeMaxExpr) 8351 return false; 8352 8353 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8354 } 8355 8356 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8357 ICmpInst::Predicate Pred, 8358 const SCEV *LHS, const SCEV *RHS) { 8359 8360 // If both sides are affine addrecs for the same loop, with equal 8361 // steps, and we know the recurrences don't wrap, then we only 8362 // need to check the predicate on the starting values. 8363 8364 if (!ICmpInst::isRelational(Pred)) 8365 return false; 8366 8367 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8368 if (!LAR) 8369 return false; 8370 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8371 if (!RAR) 8372 return false; 8373 if (LAR->getLoop() != RAR->getLoop()) 8374 return false; 8375 if (!LAR->isAffine() || !RAR->isAffine()) 8376 return false; 8377 8378 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8379 return false; 8380 8381 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8382 SCEV::FlagNSW : SCEV::FlagNUW; 8383 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8384 return false; 8385 8386 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8387 } 8388 8389 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8390 /// expression? 8391 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8392 ICmpInst::Predicate Pred, 8393 const SCEV *LHS, const SCEV *RHS) { 8394 switch (Pred) { 8395 default: 8396 return false; 8397 8398 case ICmpInst::ICMP_SGE: 8399 std::swap(LHS, RHS); 8400 LLVM_FALLTHROUGH; 8401 case ICmpInst::ICMP_SLE: 8402 return 8403 // min(A, ...) <= A 8404 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8405 // A <= max(A, ...) 8406 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8407 8408 case ICmpInst::ICMP_UGE: 8409 std::swap(LHS, RHS); 8410 LLVM_FALLTHROUGH; 8411 case ICmpInst::ICMP_ULE: 8412 return 8413 // min(A, ...) <= A 8414 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8415 // A <= max(A, ...) 8416 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8417 } 8418 8419 llvm_unreachable("covered switch fell through?!"); 8420 } 8421 8422 bool 8423 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8424 const SCEV *LHS, const SCEV *RHS, 8425 const SCEV *FoundLHS, 8426 const SCEV *FoundRHS) { 8427 auto IsKnownPredicateFull = 8428 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8429 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8430 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8431 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8432 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8433 }; 8434 8435 switch (Pred) { 8436 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8437 case ICmpInst::ICMP_EQ: 8438 case ICmpInst::ICMP_NE: 8439 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8440 return true; 8441 break; 8442 case ICmpInst::ICMP_SLT: 8443 case ICmpInst::ICMP_SLE: 8444 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8445 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8446 return true; 8447 break; 8448 case ICmpInst::ICMP_SGT: 8449 case ICmpInst::ICMP_SGE: 8450 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8451 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8452 return true; 8453 break; 8454 case ICmpInst::ICMP_ULT: 8455 case ICmpInst::ICMP_ULE: 8456 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8457 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8458 return true; 8459 break; 8460 case ICmpInst::ICMP_UGT: 8461 case ICmpInst::ICMP_UGE: 8462 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8463 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8464 return true; 8465 break; 8466 } 8467 8468 return false; 8469 } 8470 8471 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8472 const SCEV *LHS, 8473 const SCEV *RHS, 8474 const SCEV *FoundLHS, 8475 const SCEV *FoundRHS) { 8476 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8477 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8478 // reduce the compile time impact of this optimization. 8479 return false; 8480 8481 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8482 if (!Addend) 8483 return false; 8484 8485 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8486 8487 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8488 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8489 ConstantRange FoundLHSRange = 8490 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8491 8492 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8493 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8494 8495 // We can also compute the range of values for `LHS` that satisfy the 8496 // consequent, "`LHS` `Pred` `RHS`": 8497 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8498 ConstantRange SatisfyingLHSRange = 8499 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8500 8501 // The antecedent implies the consequent if every value of `LHS` that 8502 // satisfies the antecedent also satisfies the consequent. 8503 return SatisfyingLHSRange.contains(LHSRange); 8504 } 8505 8506 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8507 bool IsSigned, bool NoWrap) { 8508 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8509 8510 if (NoWrap) return false; 8511 8512 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8513 const SCEV *One = getOne(Stride->getType()); 8514 8515 if (IsSigned) { 8516 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8517 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8518 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8519 .getSignedMax(); 8520 8521 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8522 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8523 } 8524 8525 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8526 APInt MaxValue = APInt::getMaxValue(BitWidth); 8527 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8528 .getUnsignedMax(); 8529 8530 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8531 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8532 } 8533 8534 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8535 bool IsSigned, bool NoWrap) { 8536 if (NoWrap) return false; 8537 8538 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8539 const SCEV *One = getOne(Stride->getType()); 8540 8541 if (IsSigned) { 8542 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8543 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8544 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8545 .getSignedMax(); 8546 8547 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8548 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8549 } 8550 8551 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8552 APInt MinValue = APInt::getMinValue(BitWidth); 8553 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8554 .getUnsignedMax(); 8555 8556 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8557 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8558 } 8559 8560 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8561 bool Equality) { 8562 const SCEV *One = getOne(Step->getType()); 8563 Delta = Equality ? getAddExpr(Delta, Step) 8564 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8565 return getUDivExpr(Delta, Step); 8566 } 8567 8568 ScalarEvolution::ExitLimit 8569 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8570 const Loop *L, bool IsSigned, 8571 bool ControlsExit, bool AllowPredicates) { 8572 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8573 // We handle only IV < Invariant 8574 if (!isLoopInvariant(RHS, L)) 8575 return getCouldNotCompute(); 8576 8577 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8578 bool PredicatedIV = false; 8579 8580 if (!IV && AllowPredicates) { 8581 // Try to make this an AddRec using runtime tests, in the first X 8582 // iterations of this loop, where X is the SCEV expression found by the 8583 // algorithm below. 8584 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8585 PredicatedIV = true; 8586 } 8587 8588 // Avoid weird loops 8589 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8590 return getCouldNotCompute(); 8591 8592 bool NoWrap = ControlsExit && 8593 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8594 8595 const SCEV *Stride = IV->getStepRecurrence(*this); 8596 8597 bool PositiveStride = isKnownPositive(Stride); 8598 8599 // Avoid negative or zero stride values. 8600 if (!PositiveStride) { 8601 // We can compute the correct backedge taken count for loops with unknown 8602 // strides if we can prove that the loop is not an infinite loop with side 8603 // effects. Here's the loop structure we are trying to handle - 8604 // 8605 // i = start 8606 // do { 8607 // A[i] = i; 8608 // i += s; 8609 // } while (i < end); 8610 // 8611 // The backedge taken count for such loops is evaluated as - 8612 // (max(end, start + stride) - start - 1) /u stride 8613 // 8614 // The additional preconditions that we need to check to prove correctness 8615 // of the above formula is as follows - 8616 // 8617 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8618 // NoWrap flag). 8619 // b) loop is single exit with no side effects. 8620 // 8621 // 8622 // Precondition a) implies that if the stride is negative, this is a single 8623 // trip loop. The backedge taken count formula reduces to zero in this case. 8624 // 8625 // Precondition b) implies that the unknown stride cannot be zero otherwise 8626 // we have UB. 8627 // 8628 // The positive stride case is the same as isKnownPositive(Stride) returning 8629 // true (original behavior of the function). 8630 // 8631 // We want to make sure that the stride is truly unknown as there are edge 8632 // cases where ScalarEvolution propagates no wrap flags to the 8633 // post-increment/decrement IV even though the increment/decrement operation 8634 // itself is wrapping. The computed backedge taken count may be wrong in 8635 // such cases. This is prevented by checking that the stride is not known to 8636 // be either positive or non-positive. For example, no wrap flags are 8637 // propagated to the post-increment IV of this loop with a trip count of 2 - 8638 // 8639 // unsigned char i; 8640 // for(i=127; i<128; i+=129) 8641 // A[i] = i; 8642 // 8643 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8644 !loopHasNoSideEffects(L)) 8645 return getCouldNotCompute(); 8646 8647 } else if (!Stride->isOne() && 8648 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8649 // Avoid proven overflow cases: this will ensure that the backedge taken 8650 // count will not generate any unsigned overflow. Relaxed no-overflow 8651 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8652 // undefined behaviors like the case of C language. 8653 return getCouldNotCompute(); 8654 8655 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8656 : ICmpInst::ICMP_ULT; 8657 const SCEV *Start = IV->getStart(); 8658 const SCEV *End = RHS; 8659 // If the backedge is taken at least once, then it will be taken 8660 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8661 // is the LHS value of the less-than comparison the first time it is evaluated 8662 // and End is the RHS. 8663 const SCEV *BECountIfBackedgeTaken = 8664 computeBECount(getMinusSCEV(End, Start), Stride, false); 8665 // If the loop entry is guarded by the result of the backedge test of the 8666 // first loop iteration, then we know the backedge will be taken at least 8667 // once and so the backedge taken count is as above. If not then we use the 8668 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8669 // as if the backedge is taken at least once max(End,Start) is End and so the 8670 // result is as above, and if not max(End,Start) is Start so we get a backedge 8671 // count of zero. 8672 const SCEV *BECount; 8673 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8674 BECount = BECountIfBackedgeTaken; 8675 else { 8676 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8677 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8678 } 8679 8680 const SCEV *MaxBECount; 8681 if (isa<SCEVConstant>(BECount)) 8682 MaxBECount = BECount; 8683 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) 8684 // If we know exactly how many times the backedge will be taken if it's 8685 // taken at least once, then the backedge count will either be that or 8686 // zero. 8687 MaxBECount = BECountIfBackedgeTaken; 8688 else { 8689 // Calculate the maximum backedge count based on the range of values 8690 // permitted by Start, End, and Stride. 8691 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8692 : getUnsignedRange(Start).getUnsignedMin(); 8693 8694 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8695 8696 APInt StrideForMaxBECount; 8697 8698 if (PositiveStride) 8699 StrideForMaxBECount = 8700 IsSigned ? getSignedRange(Stride).getSignedMin() 8701 : getUnsignedRange(Stride).getUnsignedMin(); 8702 else 8703 // Using a stride of 1 is safe when computing max backedge taken count for 8704 // a loop with unknown stride. 8705 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8706 8707 APInt Limit = 8708 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8709 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8710 8711 // Although End can be a MAX expression we estimate MaxEnd considering only 8712 // the case End = RHS. This is safe because in the other case (End - Start) 8713 // is zero, leading to a zero maximum backedge taken count. 8714 APInt MaxEnd = 8715 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8716 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8717 8718 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8719 getConstant(StrideForMaxBECount), false); 8720 } 8721 8722 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8723 MaxBECount = BECount; 8724 8725 return ExitLimit(BECount, MaxBECount, Predicates); 8726 } 8727 8728 ScalarEvolution::ExitLimit 8729 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8730 const Loop *L, bool IsSigned, 8731 bool ControlsExit, bool AllowPredicates) { 8732 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8733 // We handle only IV > Invariant 8734 if (!isLoopInvariant(RHS, L)) 8735 return getCouldNotCompute(); 8736 8737 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8738 if (!IV && AllowPredicates) 8739 // Try to make this an AddRec using runtime tests, in the first X 8740 // iterations of this loop, where X is the SCEV expression found by the 8741 // algorithm below. 8742 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8743 8744 // Avoid weird loops 8745 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8746 return getCouldNotCompute(); 8747 8748 bool NoWrap = ControlsExit && 8749 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8750 8751 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8752 8753 // Avoid negative or zero stride values 8754 if (!isKnownPositive(Stride)) 8755 return getCouldNotCompute(); 8756 8757 // Avoid proven overflow cases: this will ensure that the backedge taken count 8758 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8759 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8760 // behaviors like the case of C language. 8761 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8762 return getCouldNotCompute(); 8763 8764 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8765 : ICmpInst::ICMP_UGT; 8766 8767 const SCEV *Start = IV->getStart(); 8768 const SCEV *End = RHS; 8769 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8770 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8771 8772 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8773 8774 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8775 : getUnsignedRange(Start).getUnsignedMax(); 8776 8777 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8778 : getUnsignedRange(Stride).getUnsignedMin(); 8779 8780 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8781 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8782 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8783 8784 // Although End can be a MIN expression we estimate MinEnd considering only 8785 // the case End = RHS. This is safe because in the other case (Start - End) 8786 // is zero, leading to a zero maximum backedge taken count. 8787 APInt MinEnd = 8788 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8789 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8790 8791 8792 const SCEV *MaxBECount = getCouldNotCompute(); 8793 if (isa<SCEVConstant>(BECount)) 8794 MaxBECount = BECount; 8795 else 8796 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8797 getConstant(MinStride), false); 8798 8799 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8800 MaxBECount = BECount; 8801 8802 return ExitLimit(BECount, MaxBECount, Predicates); 8803 } 8804 8805 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8806 ScalarEvolution &SE) const { 8807 if (Range.isFullSet()) // Infinite loop. 8808 return SE.getCouldNotCompute(); 8809 8810 // If the start is a non-zero constant, shift the range to simplify things. 8811 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8812 if (!SC->getValue()->isZero()) { 8813 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8814 Operands[0] = SE.getZero(SC->getType()); 8815 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8816 getNoWrapFlags(FlagNW)); 8817 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8818 return ShiftedAddRec->getNumIterationsInRange( 8819 Range.subtract(SC->getAPInt()), SE); 8820 // This is strange and shouldn't happen. 8821 return SE.getCouldNotCompute(); 8822 } 8823 8824 // The only time we can solve this is when we have all constant indices. 8825 // Otherwise, we cannot determine the overflow conditions. 8826 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8827 return SE.getCouldNotCompute(); 8828 8829 // Okay at this point we know that all elements of the chrec are constants and 8830 // that the start element is zero. 8831 8832 // First check to see if the range contains zero. If not, the first 8833 // iteration exits. 8834 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8835 if (!Range.contains(APInt(BitWidth, 0))) 8836 return SE.getZero(getType()); 8837 8838 if (isAffine()) { 8839 // If this is an affine expression then we have this situation: 8840 // Solve {0,+,A} in Range === Ax in Range 8841 8842 // We know that zero is in the range. If A is positive then we know that 8843 // the upper value of the range must be the first possible exit value. 8844 // If A is negative then the lower of the range is the last possible loop 8845 // value. Also note that we already checked for a full range. 8846 APInt One(BitWidth,1); 8847 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8848 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8849 8850 // The exit value should be (End+A)/A. 8851 APInt ExitVal = (End + A).udiv(A); 8852 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8853 8854 // Evaluate at the exit value. If we really did fall out of the valid 8855 // range, then we computed our trip count, otherwise wrap around or other 8856 // things must have happened. 8857 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8858 if (Range.contains(Val->getValue())) 8859 return SE.getCouldNotCompute(); // Something strange happened 8860 8861 // Ensure that the previous value is in the range. This is a sanity check. 8862 assert(Range.contains( 8863 EvaluateConstantChrecAtConstant(this, 8864 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8865 "Linear scev computation is off in a bad way!"); 8866 return SE.getConstant(ExitValue); 8867 } else if (isQuadratic()) { 8868 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8869 // quadratic equation to solve it. To do this, we must frame our problem in 8870 // terms of figuring out when zero is crossed, instead of when 8871 // Range.getUpper() is crossed. 8872 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8873 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8874 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8875 8876 // Next, solve the constructed addrec 8877 if (auto Roots = 8878 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8879 const SCEVConstant *R1 = Roots->first; 8880 const SCEVConstant *R2 = Roots->second; 8881 // Pick the smallest positive root value. 8882 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8883 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8884 if (!CB->getZExtValue()) 8885 std::swap(R1, R2); // R1 is the minimum root now. 8886 8887 // Make sure the root is not off by one. The returned iteration should 8888 // not be in the range, but the previous one should be. When solving 8889 // for "X*X < 5", for example, we should not return a root of 2. 8890 ConstantInt *R1Val = 8891 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8892 if (Range.contains(R1Val->getValue())) { 8893 // The next iteration must be out of the range... 8894 ConstantInt *NextVal = 8895 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8896 8897 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8898 if (!Range.contains(R1Val->getValue())) 8899 return SE.getConstant(NextVal); 8900 return SE.getCouldNotCompute(); // Something strange happened 8901 } 8902 8903 // If R1 was not in the range, then it is a good return value. Make 8904 // sure that R1-1 WAS in the range though, just in case. 8905 ConstantInt *NextVal = 8906 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8907 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8908 if (Range.contains(R1Val->getValue())) 8909 return R1; 8910 return SE.getCouldNotCompute(); // Something strange happened 8911 } 8912 } 8913 } 8914 8915 return SE.getCouldNotCompute(); 8916 } 8917 8918 namespace { 8919 struct FindUndefs { 8920 bool Found; 8921 FindUndefs() : Found(false) {} 8922 8923 bool follow(const SCEV *S) { 8924 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 8925 if (isa<UndefValue>(C->getValue())) 8926 Found = true; 8927 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 8928 if (isa<UndefValue>(C->getValue())) 8929 Found = true; 8930 } 8931 8932 // Keep looking if we haven't found it yet. 8933 return !Found; 8934 } 8935 bool isDone() const { 8936 // Stop recursion if we have found an undef. 8937 return Found; 8938 } 8939 }; 8940 } 8941 8942 // Return true when S contains at least an undef value. 8943 static inline bool 8944 containsUndefs(const SCEV *S) { 8945 FindUndefs F; 8946 SCEVTraversal<FindUndefs> ST(F); 8947 ST.visitAll(S); 8948 8949 return F.Found; 8950 } 8951 8952 namespace { 8953 // Collect all steps of SCEV expressions. 8954 struct SCEVCollectStrides { 8955 ScalarEvolution &SE; 8956 SmallVectorImpl<const SCEV *> &Strides; 8957 8958 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 8959 : SE(SE), Strides(S) {} 8960 8961 bool follow(const SCEV *S) { 8962 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 8963 Strides.push_back(AR->getStepRecurrence(SE)); 8964 return true; 8965 } 8966 bool isDone() const { return false; } 8967 }; 8968 8969 // Collect all SCEVUnknown and SCEVMulExpr expressions. 8970 struct SCEVCollectTerms { 8971 SmallVectorImpl<const SCEV *> &Terms; 8972 8973 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 8974 : Terms(T) {} 8975 8976 bool follow(const SCEV *S) { 8977 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 8978 isa<SCEVSignExtendExpr>(S)) { 8979 if (!containsUndefs(S)) 8980 Terms.push_back(S); 8981 8982 // Stop recursion: once we collected a term, do not walk its operands. 8983 return false; 8984 } 8985 8986 // Keep looking. 8987 return true; 8988 } 8989 bool isDone() const { return false; } 8990 }; 8991 8992 // Check if a SCEV contains an AddRecExpr. 8993 struct SCEVHasAddRec { 8994 bool &ContainsAddRec; 8995 8996 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 8997 ContainsAddRec = false; 8998 } 8999 9000 bool follow(const SCEV *S) { 9001 if (isa<SCEVAddRecExpr>(S)) { 9002 ContainsAddRec = true; 9003 9004 // Stop recursion: once we collected a term, do not walk its operands. 9005 return false; 9006 } 9007 9008 // Keep looking. 9009 return true; 9010 } 9011 bool isDone() const { return false; } 9012 }; 9013 9014 // Find factors that are multiplied with an expression that (possibly as a 9015 // subexpression) contains an AddRecExpr. In the expression: 9016 // 9017 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9018 // 9019 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9020 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9021 // parameters as they form a product with an induction variable. 9022 // 9023 // This collector expects all array size parameters to be in the same MulExpr. 9024 // It might be necessary to later add support for collecting parameters that are 9025 // spread over different nested MulExpr. 9026 struct SCEVCollectAddRecMultiplies { 9027 SmallVectorImpl<const SCEV *> &Terms; 9028 ScalarEvolution &SE; 9029 9030 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9031 : Terms(T), SE(SE) {} 9032 9033 bool follow(const SCEV *S) { 9034 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9035 bool HasAddRec = false; 9036 SmallVector<const SCEV *, 0> Operands; 9037 for (auto Op : Mul->operands()) { 9038 if (isa<SCEVUnknown>(Op)) { 9039 Operands.push_back(Op); 9040 } else { 9041 bool ContainsAddRec; 9042 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9043 visitAll(Op, ContiansAddRec); 9044 HasAddRec |= ContainsAddRec; 9045 } 9046 } 9047 if (Operands.size() == 0) 9048 return true; 9049 9050 if (!HasAddRec) 9051 return false; 9052 9053 Terms.push_back(SE.getMulExpr(Operands)); 9054 // Stop recursion: once we collected a term, do not walk its operands. 9055 return false; 9056 } 9057 9058 // Keep looking. 9059 return true; 9060 } 9061 bool isDone() const { return false; } 9062 }; 9063 } 9064 9065 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9066 /// two places: 9067 /// 1) The strides of AddRec expressions. 9068 /// 2) Unknowns that are multiplied with AddRec expressions. 9069 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9070 SmallVectorImpl<const SCEV *> &Terms) { 9071 SmallVector<const SCEV *, 4> Strides; 9072 SCEVCollectStrides StrideCollector(*this, Strides); 9073 visitAll(Expr, StrideCollector); 9074 9075 DEBUG({ 9076 dbgs() << "Strides:\n"; 9077 for (const SCEV *S : Strides) 9078 dbgs() << *S << "\n"; 9079 }); 9080 9081 for (const SCEV *S : Strides) { 9082 SCEVCollectTerms TermCollector(Terms); 9083 visitAll(S, TermCollector); 9084 } 9085 9086 DEBUG({ 9087 dbgs() << "Terms:\n"; 9088 for (const SCEV *T : Terms) 9089 dbgs() << *T << "\n"; 9090 }); 9091 9092 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9093 visitAll(Expr, MulCollector); 9094 } 9095 9096 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9097 SmallVectorImpl<const SCEV *> &Terms, 9098 SmallVectorImpl<const SCEV *> &Sizes) { 9099 int Last = Terms.size() - 1; 9100 const SCEV *Step = Terms[Last]; 9101 9102 // End of recursion. 9103 if (Last == 0) { 9104 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9105 SmallVector<const SCEV *, 2> Qs; 9106 for (const SCEV *Op : M->operands()) 9107 if (!isa<SCEVConstant>(Op)) 9108 Qs.push_back(Op); 9109 9110 Step = SE.getMulExpr(Qs); 9111 } 9112 9113 Sizes.push_back(Step); 9114 return true; 9115 } 9116 9117 for (const SCEV *&Term : Terms) { 9118 // Normalize the terms before the next call to findArrayDimensionsRec. 9119 const SCEV *Q, *R; 9120 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9121 9122 // Bail out when GCD does not evenly divide one of the terms. 9123 if (!R->isZero()) 9124 return false; 9125 9126 Term = Q; 9127 } 9128 9129 // Remove all SCEVConstants. 9130 Terms.erase( 9131 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9132 Terms.end()); 9133 9134 if (Terms.size() > 0) 9135 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9136 return false; 9137 9138 Sizes.push_back(Step); 9139 return true; 9140 } 9141 9142 // Returns true when S contains at least a SCEVUnknown parameter. 9143 static inline bool 9144 containsParameters(const SCEV *S) { 9145 struct FindParameter { 9146 bool FoundParameter; 9147 FindParameter() : FoundParameter(false) {} 9148 9149 bool follow(const SCEV *S) { 9150 if (isa<SCEVUnknown>(S)) { 9151 FoundParameter = true; 9152 // Stop recursion: we found a parameter. 9153 return false; 9154 } 9155 // Keep looking. 9156 return true; 9157 } 9158 bool isDone() const { 9159 // Stop recursion if we have found a parameter. 9160 return FoundParameter; 9161 } 9162 }; 9163 9164 FindParameter F; 9165 SCEVTraversal<FindParameter> ST(F); 9166 ST.visitAll(S); 9167 9168 return F.FoundParameter; 9169 } 9170 9171 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9172 static inline bool 9173 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9174 for (const SCEV *T : Terms) 9175 if (containsParameters(T)) 9176 return true; 9177 return false; 9178 } 9179 9180 // Return the number of product terms in S. 9181 static inline int numberOfTerms(const SCEV *S) { 9182 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9183 return Expr->getNumOperands(); 9184 return 1; 9185 } 9186 9187 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9188 if (isa<SCEVConstant>(T)) 9189 return nullptr; 9190 9191 if (isa<SCEVUnknown>(T)) 9192 return T; 9193 9194 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9195 SmallVector<const SCEV *, 2> Factors; 9196 for (const SCEV *Op : M->operands()) 9197 if (!isa<SCEVConstant>(Op)) 9198 Factors.push_back(Op); 9199 9200 return SE.getMulExpr(Factors); 9201 } 9202 9203 return T; 9204 } 9205 9206 /// Return the size of an element read or written by Inst. 9207 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9208 Type *Ty; 9209 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9210 Ty = Store->getValueOperand()->getType(); 9211 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9212 Ty = Load->getType(); 9213 else 9214 return nullptr; 9215 9216 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9217 return getSizeOfExpr(ETy, Ty); 9218 } 9219 9220 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9221 SmallVectorImpl<const SCEV *> &Sizes, 9222 const SCEV *ElementSize) const { 9223 if (Terms.size() < 1 || !ElementSize) 9224 return; 9225 9226 // Early return when Terms do not contain parameters: we do not delinearize 9227 // non parametric SCEVs. 9228 if (!containsParameters(Terms)) 9229 return; 9230 9231 DEBUG({ 9232 dbgs() << "Terms:\n"; 9233 for (const SCEV *T : Terms) 9234 dbgs() << *T << "\n"; 9235 }); 9236 9237 // Remove duplicates. 9238 std::sort(Terms.begin(), Terms.end()); 9239 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9240 9241 // Put larger terms first. 9242 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9243 return numberOfTerms(LHS) > numberOfTerms(RHS); 9244 }); 9245 9246 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9247 9248 // Try to divide all terms by the element size. If term is not divisible by 9249 // element size, proceed with the original term. 9250 for (const SCEV *&Term : Terms) { 9251 const SCEV *Q, *R; 9252 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9253 if (!Q->isZero()) 9254 Term = Q; 9255 } 9256 9257 SmallVector<const SCEV *, 4> NewTerms; 9258 9259 // Remove constant factors. 9260 for (const SCEV *T : Terms) 9261 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9262 NewTerms.push_back(NewT); 9263 9264 DEBUG({ 9265 dbgs() << "Terms after sorting:\n"; 9266 for (const SCEV *T : NewTerms) 9267 dbgs() << *T << "\n"; 9268 }); 9269 9270 if (NewTerms.empty() || 9271 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9272 Sizes.clear(); 9273 return; 9274 } 9275 9276 // The last element to be pushed into Sizes is the size of an element. 9277 Sizes.push_back(ElementSize); 9278 9279 DEBUG({ 9280 dbgs() << "Sizes:\n"; 9281 for (const SCEV *S : Sizes) 9282 dbgs() << *S << "\n"; 9283 }); 9284 } 9285 9286 void ScalarEvolution::computeAccessFunctions( 9287 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9288 SmallVectorImpl<const SCEV *> &Sizes) { 9289 9290 // Early exit in case this SCEV is not an affine multivariate function. 9291 if (Sizes.empty()) 9292 return; 9293 9294 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9295 if (!AR->isAffine()) 9296 return; 9297 9298 const SCEV *Res = Expr; 9299 int Last = Sizes.size() - 1; 9300 for (int i = Last; i >= 0; i--) { 9301 const SCEV *Q, *R; 9302 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9303 9304 DEBUG({ 9305 dbgs() << "Res: " << *Res << "\n"; 9306 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9307 dbgs() << "Res divided by Sizes[i]:\n"; 9308 dbgs() << "Quotient: " << *Q << "\n"; 9309 dbgs() << "Remainder: " << *R << "\n"; 9310 }); 9311 9312 Res = Q; 9313 9314 // Do not record the last subscript corresponding to the size of elements in 9315 // the array. 9316 if (i == Last) { 9317 9318 // Bail out if the remainder is too complex. 9319 if (isa<SCEVAddRecExpr>(R)) { 9320 Subscripts.clear(); 9321 Sizes.clear(); 9322 return; 9323 } 9324 9325 continue; 9326 } 9327 9328 // Record the access function for the current subscript. 9329 Subscripts.push_back(R); 9330 } 9331 9332 // Also push in last position the remainder of the last division: it will be 9333 // the access function of the innermost dimension. 9334 Subscripts.push_back(Res); 9335 9336 std::reverse(Subscripts.begin(), Subscripts.end()); 9337 9338 DEBUG({ 9339 dbgs() << "Subscripts:\n"; 9340 for (const SCEV *S : Subscripts) 9341 dbgs() << *S << "\n"; 9342 }); 9343 } 9344 9345 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9346 /// sizes of an array access. Returns the remainder of the delinearization that 9347 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9348 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9349 /// expressions in the stride and base of a SCEV corresponding to the 9350 /// computation of a GCD (greatest common divisor) of base and stride. When 9351 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9352 /// 9353 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9354 /// 9355 /// void foo(long n, long m, long o, double A[n][m][o]) { 9356 /// 9357 /// for (long i = 0; i < n; i++) 9358 /// for (long j = 0; j < m; j++) 9359 /// for (long k = 0; k < o; k++) 9360 /// A[i][j][k] = 1.0; 9361 /// } 9362 /// 9363 /// the delinearization input is the following AddRec SCEV: 9364 /// 9365 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9366 /// 9367 /// From this SCEV, we are able to say that the base offset of the access is %A 9368 /// because it appears as an offset that does not divide any of the strides in 9369 /// the loops: 9370 /// 9371 /// CHECK: Base offset: %A 9372 /// 9373 /// and then SCEV->delinearize determines the size of some of the dimensions of 9374 /// the array as these are the multiples by which the strides are happening: 9375 /// 9376 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9377 /// 9378 /// Note that the outermost dimension remains of UnknownSize because there are 9379 /// no strides that would help identifying the size of the last dimension: when 9380 /// the array has been statically allocated, one could compute the size of that 9381 /// dimension by dividing the overall size of the array by the size of the known 9382 /// dimensions: %m * %o * 8. 9383 /// 9384 /// Finally delinearize provides the access functions for the array reference 9385 /// that does correspond to A[i][j][k] of the above C testcase: 9386 /// 9387 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9388 /// 9389 /// The testcases are checking the output of a function pass: 9390 /// DelinearizationPass that walks through all loads and stores of a function 9391 /// asking for the SCEV of the memory access with respect to all enclosing 9392 /// loops, calling SCEV->delinearize on that and printing the results. 9393 9394 void ScalarEvolution::delinearize(const SCEV *Expr, 9395 SmallVectorImpl<const SCEV *> &Subscripts, 9396 SmallVectorImpl<const SCEV *> &Sizes, 9397 const SCEV *ElementSize) { 9398 // First step: collect parametric terms. 9399 SmallVector<const SCEV *, 4> Terms; 9400 collectParametricTerms(Expr, Terms); 9401 9402 if (Terms.empty()) 9403 return; 9404 9405 // Second step: find subscript sizes. 9406 findArrayDimensions(Terms, Sizes, ElementSize); 9407 9408 if (Sizes.empty()) 9409 return; 9410 9411 // Third step: compute the access functions for each subscript. 9412 computeAccessFunctions(Expr, Subscripts, Sizes); 9413 9414 if (Subscripts.empty()) 9415 return; 9416 9417 DEBUG({ 9418 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9419 dbgs() << "ArrayDecl[UnknownSize]"; 9420 for (const SCEV *S : Sizes) 9421 dbgs() << "[" << *S << "]"; 9422 9423 dbgs() << "\nArrayRef"; 9424 for (const SCEV *S : Subscripts) 9425 dbgs() << "[" << *S << "]"; 9426 dbgs() << "\n"; 9427 }); 9428 } 9429 9430 //===----------------------------------------------------------------------===// 9431 // SCEVCallbackVH Class Implementation 9432 //===----------------------------------------------------------------------===// 9433 9434 void ScalarEvolution::SCEVCallbackVH::deleted() { 9435 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9436 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9437 SE->ConstantEvolutionLoopExitValue.erase(PN); 9438 SE->eraseValueFromMap(getValPtr()); 9439 // this now dangles! 9440 } 9441 9442 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9443 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9444 9445 // Forget all the expressions associated with users of the old value, 9446 // so that future queries will recompute the expressions using the new 9447 // value. 9448 Value *Old = getValPtr(); 9449 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9450 SmallPtrSet<User *, 8> Visited; 9451 while (!Worklist.empty()) { 9452 User *U = Worklist.pop_back_val(); 9453 // Deleting the Old value will cause this to dangle. Postpone 9454 // that until everything else is done. 9455 if (U == Old) 9456 continue; 9457 if (!Visited.insert(U).second) 9458 continue; 9459 if (PHINode *PN = dyn_cast<PHINode>(U)) 9460 SE->ConstantEvolutionLoopExitValue.erase(PN); 9461 SE->eraseValueFromMap(U); 9462 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9463 } 9464 // Delete the Old value. 9465 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9466 SE->ConstantEvolutionLoopExitValue.erase(PN); 9467 SE->eraseValueFromMap(Old); 9468 // this now dangles! 9469 } 9470 9471 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9472 : CallbackVH(V), SE(se) {} 9473 9474 //===----------------------------------------------------------------------===// 9475 // ScalarEvolution Class Implementation 9476 //===----------------------------------------------------------------------===// 9477 9478 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9479 AssumptionCache &AC, DominatorTree &DT, 9480 LoopInfo &LI) 9481 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9482 CouldNotCompute(new SCEVCouldNotCompute()), 9483 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9484 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9485 FirstUnknown(nullptr) { 9486 9487 // To use guards for proving predicates, we need to scan every instruction in 9488 // relevant basic blocks, and not just terminators. Doing this is a waste of 9489 // time if the IR does not actually contain any calls to 9490 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9491 // 9492 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9493 // to _add_ guards to the module when there weren't any before, and wants 9494 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9495 // efficient in lieu of being smart in that rather obscure case. 9496 9497 auto *GuardDecl = F.getParent()->getFunction( 9498 Intrinsic::getName(Intrinsic::experimental_guard)); 9499 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9500 } 9501 9502 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9503 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9504 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9505 ValueExprMap(std::move(Arg.ValueExprMap)), 9506 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9507 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9508 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9509 PredicatedBackedgeTakenCounts( 9510 std::move(Arg.PredicatedBackedgeTakenCounts)), 9511 ConstantEvolutionLoopExitValue( 9512 std::move(Arg.ConstantEvolutionLoopExitValue)), 9513 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9514 LoopDispositions(std::move(Arg.LoopDispositions)), 9515 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9516 BlockDispositions(std::move(Arg.BlockDispositions)), 9517 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9518 SignedRanges(std::move(Arg.SignedRanges)), 9519 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9520 UniquePreds(std::move(Arg.UniquePreds)), 9521 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9522 FirstUnknown(Arg.FirstUnknown) { 9523 Arg.FirstUnknown = nullptr; 9524 } 9525 9526 ScalarEvolution::~ScalarEvolution() { 9527 // Iterate through all the SCEVUnknown instances and call their 9528 // destructors, so that they release their references to their values. 9529 for (SCEVUnknown *U = FirstUnknown; U;) { 9530 SCEVUnknown *Tmp = U; 9531 U = U->Next; 9532 Tmp->~SCEVUnknown(); 9533 } 9534 FirstUnknown = nullptr; 9535 9536 ExprValueMap.clear(); 9537 ValueExprMap.clear(); 9538 HasRecMap.clear(); 9539 9540 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9541 // that a loop had multiple computable exits. 9542 for (auto &BTCI : BackedgeTakenCounts) 9543 BTCI.second.clear(); 9544 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9545 BTCI.second.clear(); 9546 9547 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9548 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9549 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9550 } 9551 9552 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9553 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9554 } 9555 9556 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9557 const Loop *L) { 9558 // Print all inner loops first 9559 for (Loop *I : *L) 9560 PrintLoopInfo(OS, SE, I); 9561 9562 OS << "Loop "; 9563 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9564 OS << ": "; 9565 9566 SmallVector<BasicBlock *, 8> ExitBlocks; 9567 L->getExitBlocks(ExitBlocks); 9568 if (ExitBlocks.size() != 1) 9569 OS << "<multiple exits> "; 9570 9571 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9572 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9573 } else { 9574 OS << "Unpredictable backedge-taken count. "; 9575 } 9576 9577 OS << "\n" 9578 "Loop "; 9579 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9580 OS << ": "; 9581 9582 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9583 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9584 } else { 9585 OS << "Unpredictable max backedge-taken count. "; 9586 } 9587 9588 OS << "\n" 9589 "Loop "; 9590 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9591 OS << ": "; 9592 9593 SCEVUnionPredicate Pred; 9594 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9595 if (!isa<SCEVCouldNotCompute>(PBT)) { 9596 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9597 OS << " Predicates:\n"; 9598 Pred.print(OS, 4); 9599 } else { 9600 OS << "Unpredictable predicated backedge-taken count. "; 9601 } 9602 OS << "\n"; 9603 } 9604 9605 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9606 switch (LD) { 9607 case ScalarEvolution::LoopVariant: 9608 return "Variant"; 9609 case ScalarEvolution::LoopInvariant: 9610 return "Invariant"; 9611 case ScalarEvolution::LoopComputable: 9612 return "Computable"; 9613 } 9614 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9615 } 9616 9617 void ScalarEvolution::print(raw_ostream &OS) const { 9618 // ScalarEvolution's implementation of the print method is to print 9619 // out SCEV values of all instructions that are interesting. Doing 9620 // this potentially causes it to create new SCEV objects though, 9621 // which technically conflicts with the const qualifier. This isn't 9622 // observable from outside the class though, so casting away the 9623 // const isn't dangerous. 9624 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9625 9626 OS << "Classifying expressions for: "; 9627 F.printAsOperand(OS, /*PrintType=*/false); 9628 OS << "\n"; 9629 for (Instruction &I : instructions(F)) 9630 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9631 OS << I << '\n'; 9632 OS << " --> "; 9633 const SCEV *SV = SE.getSCEV(&I); 9634 SV->print(OS); 9635 if (!isa<SCEVCouldNotCompute>(SV)) { 9636 OS << " U: "; 9637 SE.getUnsignedRange(SV).print(OS); 9638 OS << " S: "; 9639 SE.getSignedRange(SV).print(OS); 9640 } 9641 9642 const Loop *L = LI.getLoopFor(I.getParent()); 9643 9644 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9645 if (AtUse != SV) { 9646 OS << " --> "; 9647 AtUse->print(OS); 9648 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9649 OS << " U: "; 9650 SE.getUnsignedRange(AtUse).print(OS); 9651 OS << " S: "; 9652 SE.getSignedRange(AtUse).print(OS); 9653 } 9654 } 9655 9656 if (L) { 9657 OS << "\t\t" "Exits: "; 9658 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9659 if (!SE.isLoopInvariant(ExitValue, L)) { 9660 OS << "<<Unknown>>"; 9661 } else { 9662 OS << *ExitValue; 9663 } 9664 9665 bool First = true; 9666 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9667 if (First) { 9668 OS << "\t\t" "LoopDispositions: { "; 9669 First = false; 9670 } else { 9671 OS << ", "; 9672 } 9673 9674 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9675 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9676 } 9677 9678 for (auto *InnerL : depth_first(L)) { 9679 if (InnerL == L) 9680 continue; 9681 if (First) { 9682 OS << "\t\t" "LoopDispositions: { "; 9683 First = false; 9684 } else { 9685 OS << ", "; 9686 } 9687 9688 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9689 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9690 } 9691 9692 OS << " }"; 9693 } 9694 9695 OS << "\n"; 9696 } 9697 9698 OS << "Determining loop execution counts for: "; 9699 F.printAsOperand(OS, /*PrintType=*/false); 9700 OS << "\n"; 9701 for (Loop *I : LI) 9702 PrintLoopInfo(OS, &SE, I); 9703 } 9704 9705 ScalarEvolution::LoopDisposition 9706 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9707 auto &Values = LoopDispositions[S]; 9708 for (auto &V : Values) { 9709 if (V.getPointer() == L) 9710 return V.getInt(); 9711 } 9712 Values.emplace_back(L, LoopVariant); 9713 LoopDisposition D = computeLoopDisposition(S, L); 9714 auto &Values2 = LoopDispositions[S]; 9715 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9716 if (V.getPointer() == L) { 9717 V.setInt(D); 9718 break; 9719 } 9720 } 9721 return D; 9722 } 9723 9724 ScalarEvolution::LoopDisposition 9725 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9726 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9727 case scConstant: 9728 return LoopInvariant; 9729 case scTruncate: 9730 case scZeroExtend: 9731 case scSignExtend: 9732 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9733 case scAddRecExpr: { 9734 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9735 9736 // If L is the addrec's loop, it's computable. 9737 if (AR->getLoop() == L) 9738 return LoopComputable; 9739 9740 // Add recurrences are never invariant in the function-body (null loop). 9741 if (!L) 9742 return LoopVariant; 9743 9744 // This recurrence is variant w.r.t. L if L contains AR's loop. 9745 if (L->contains(AR->getLoop())) 9746 return LoopVariant; 9747 9748 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9749 if (AR->getLoop()->contains(L)) 9750 return LoopInvariant; 9751 9752 // This recurrence is variant w.r.t. L if any of its operands 9753 // are variant. 9754 for (auto *Op : AR->operands()) 9755 if (!isLoopInvariant(Op, L)) 9756 return LoopVariant; 9757 9758 // Otherwise it's loop-invariant. 9759 return LoopInvariant; 9760 } 9761 case scAddExpr: 9762 case scMulExpr: 9763 case scUMaxExpr: 9764 case scSMaxExpr: { 9765 bool HasVarying = false; 9766 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9767 LoopDisposition D = getLoopDisposition(Op, L); 9768 if (D == LoopVariant) 9769 return LoopVariant; 9770 if (D == LoopComputable) 9771 HasVarying = true; 9772 } 9773 return HasVarying ? LoopComputable : LoopInvariant; 9774 } 9775 case scUDivExpr: { 9776 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9777 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9778 if (LD == LoopVariant) 9779 return LoopVariant; 9780 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9781 if (RD == LoopVariant) 9782 return LoopVariant; 9783 return (LD == LoopInvariant && RD == LoopInvariant) ? 9784 LoopInvariant : LoopComputable; 9785 } 9786 case scUnknown: 9787 // All non-instruction values are loop invariant. All instructions are loop 9788 // invariant if they are not contained in the specified loop. 9789 // Instructions are never considered invariant in the function body 9790 // (null loop) because they are defined within the "loop". 9791 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9792 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9793 return LoopInvariant; 9794 case scCouldNotCompute: 9795 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9796 } 9797 llvm_unreachable("Unknown SCEV kind!"); 9798 } 9799 9800 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9801 return getLoopDisposition(S, L) == LoopInvariant; 9802 } 9803 9804 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9805 return getLoopDisposition(S, L) == LoopComputable; 9806 } 9807 9808 ScalarEvolution::BlockDisposition 9809 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9810 auto &Values = BlockDispositions[S]; 9811 for (auto &V : Values) { 9812 if (V.getPointer() == BB) 9813 return V.getInt(); 9814 } 9815 Values.emplace_back(BB, DoesNotDominateBlock); 9816 BlockDisposition D = computeBlockDisposition(S, BB); 9817 auto &Values2 = BlockDispositions[S]; 9818 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9819 if (V.getPointer() == BB) { 9820 V.setInt(D); 9821 break; 9822 } 9823 } 9824 return D; 9825 } 9826 9827 ScalarEvolution::BlockDisposition 9828 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9829 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9830 case scConstant: 9831 return ProperlyDominatesBlock; 9832 case scTruncate: 9833 case scZeroExtend: 9834 case scSignExtend: 9835 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9836 case scAddRecExpr: { 9837 // This uses a "dominates" query instead of "properly dominates" query 9838 // to test for proper dominance too, because the instruction which 9839 // produces the addrec's value is a PHI, and a PHI effectively properly 9840 // dominates its entire containing block. 9841 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9842 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9843 return DoesNotDominateBlock; 9844 9845 // Fall through into SCEVNAryExpr handling. 9846 LLVM_FALLTHROUGH; 9847 } 9848 case scAddExpr: 9849 case scMulExpr: 9850 case scUMaxExpr: 9851 case scSMaxExpr: { 9852 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9853 bool Proper = true; 9854 for (const SCEV *NAryOp : NAry->operands()) { 9855 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9856 if (D == DoesNotDominateBlock) 9857 return DoesNotDominateBlock; 9858 if (D == DominatesBlock) 9859 Proper = false; 9860 } 9861 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9862 } 9863 case scUDivExpr: { 9864 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9865 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9866 BlockDisposition LD = getBlockDisposition(LHS, BB); 9867 if (LD == DoesNotDominateBlock) 9868 return DoesNotDominateBlock; 9869 BlockDisposition RD = getBlockDisposition(RHS, BB); 9870 if (RD == DoesNotDominateBlock) 9871 return DoesNotDominateBlock; 9872 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9873 ProperlyDominatesBlock : DominatesBlock; 9874 } 9875 case scUnknown: 9876 if (Instruction *I = 9877 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9878 if (I->getParent() == BB) 9879 return DominatesBlock; 9880 if (DT.properlyDominates(I->getParent(), BB)) 9881 return ProperlyDominatesBlock; 9882 return DoesNotDominateBlock; 9883 } 9884 return ProperlyDominatesBlock; 9885 case scCouldNotCompute: 9886 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9887 } 9888 llvm_unreachable("Unknown SCEV kind!"); 9889 } 9890 9891 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9892 return getBlockDisposition(S, BB) >= DominatesBlock; 9893 } 9894 9895 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9896 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9897 } 9898 9899 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9900 // Search for a SCEV expression node within an expression tree. 9901 // Implements SCEVTraversal::Visitor. 9902 struct SCEVSearch { 9903 const SCEV *Node; 9904 bool IsFound; 9905 9906 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 9907 9908 bool follow(const SCEV *S) { 9909 IsFound |= (S == Node); 9910 return !IsFound; 9911 } 9912 bool isDone() const { return IsFound; } 9913 }; 9914 9915 SCEVSearch Search(Op); 9916 visitAll(S, Search); 9917 return Search.IsFound; 9918 } 9919 9920 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9921 ValuesAtScopes.erase(S); 9922 LoopDispositions.erase(S); 9923 BlockDispositions.erase(S); 9924 UnsignedRanges.erase(S); 9925 SignedRanges.erase(S); 9926 ExprValueMap.erase(S); 9927 HasRecMap.erase(S); 9928 9929 auto RemoveSCEVFromBackedgeMap = 9930 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 9931 for (auto I = Map.begin(), E = Map.end(); I != E;) { 9932 BackedgeTakenInfo &BEInfo = I->second; 9933 if (BEInfo.hasOperand(S, this)) { 9934 BEInfo.clear(); 9935 Map.erase(I++); 9936 } else 9937 ++I; 9938 } 9939 }; 9940 9941 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 9942 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 9943 } 9944 9945 typedef DenseMap<const Loop *, std::string> VerifyMap; 9946 9947 /// replaceSubString - Replaces all occurrences of From in Str with To. 9948 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9949 size_t Pos = 0; 9950 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9951 Str.replace(Pos, From.size(), To.data(), To.size()); 9952 Pos += To.size(); 9953 } 9954 } 9955 9956 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9957 static void 9958 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9959 std::string &S = Map[L]; 9960 if (S.empty()) { 9961 raw_string_ostream OS(S); 9962 SE.getBackedgeTakenCount(L)->print(OS); 9963 9964 // false and 0 are semantically equivalent. This can happen in dead loops. 9965 replaceSubString(OS.str(), "false", "0"); 9966 // Remove wrap flags, their use in SCEV is highly fragile. 9967 // FIXME: Remove this when SCEV gets smarter about them. 9968 replaceSubString(OS.str(), "<nw>", ""); 9969 replaceSubString(OS.str(), "<nsw>", ""); 9970 replaceSubString(OS.str(), "<nuw>", ""); 9971 } 9972 9973 for (auto *R : reverse(*L)) 9974 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 9975 } 9976 9977 void ScalarEvolution::verify() const { 9978 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9979 9980 // Gather stringified backedge taken counts for all loops using SCEV's caches. 9981 // FIXME: It would be much better to store actual values instead of strings, 9982 // but SCEV pointers will change if we drop the caches. 9983 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 9984 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9985 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 9986 9987 // Gather stringified backedge taken counts for all loops using a fresh 9988 // ScalarEvolution object. 9989 ScalarEvolution SE2(F, TLI, AC, DT, LI); 9990 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9991 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 9992 9993 // Now compare whether they're the same with and without caches. This allows 9994 // verifying that no pass changed the cache. 9995 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 9996 "New loops suddenly appeared!"); 9997 9998 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 9999 OldE = BackedgeDumpsOld.end(), 10000 NewI = BackedgeDumpsNew.begin(); 10001 OldI != OldE; ++OldI, ++NewI) { 10002 assert(OldI->first == NewI->first && "Loop order changed!"); 10003 10004 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10005 // changes. 10006 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10007 // means that a pass is buggy or SCEV has to learn a new pattern but is 10008 // usually not harmful. 10009 if (OldI->second != NewI->second && 10010 OldI->second.find("undef") == std::string::npos && 10011 NewI->second.find("undef") == std::string::npos && 10012 OldI->second != "***COULDNOTCOMPUTE***" && 10013 NewI->second != "***COULDNOTCOMPUTE***") { 10014 dbgs() << "SCEVValidator: SCEV for loop '" 10015 << OldI->first->getHeader()->getName() 10016 << "' changed from '" << OldI->second 10017 << "' to '" << NewI->second << "'!\n"; 10018 std::abort(); 10019 } 10020 } 10021 10022 // TODO: Verify more things. 10023 } 10024 10025 char ScalarEvolutionAnalysis::PassID; 10026 10027 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10028 FunctionAnalysisManager &AM) { 10029 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10030 AM.getResult<AssumptionAnalysis>(F), 10031 AM.getResult<DominatorTreeAnalysis>(F), 10032 AM.getResult<LoopAnalysis>(F)); 10033 } 10034 10035 PreservedAnalyses 10036 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10037 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10038 return PreservedAnalyses::all(); 10039 } 10040 10041 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10042 "Scalar Evolution Analysis", false, true) 10043 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10044 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10045 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10046 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10047 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10048 "Scalar Evolution Analysis", false, true) 10049 char ScalarEvolutionWrapperPass::ID = 0; 10050 10051 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10052 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10053 } 10054 10055 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10056 SE.reset(new ScalarEvolution( 10057 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10058 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10059 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10060 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10061 return false; 10062 } 10063 10064 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10065 10066 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10067 SE->print(OS); 10068 } 10069 10070 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10071 if (!VerifySCEV) 10072 return; 10073 10074 SE->verify(); 10075 } 10076 10077 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10078 AU.setPreservesAll(); 10079 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10080 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10081 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10082 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10083 } 10084 10085 const SCEVPredicate * 10086 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10087 const SCEVConstant *RHS) { 10088 FoldingSetNodeID ID; 10089 // Unique this node based on the arguments 10090 ID.AddInteger(SCEVPredicate::P_Equal); 10091 ID.AddPointer(LHS); 10092 ID.AddPointer(RHS); 10093 void *IP = nullptr; 10094 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10095 return S; 10096 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10097 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10098 UniquePreds.InsertNode(Eq, IP); 10099 return Eq; 10100 } 10101 10102 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10103 const SCEVAddRecExpr *AR, 10104 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10105 FoldingSetNodeID ID; 10106 // Unique this node based on the arguments 10107 ID.AddInteger(SCEVPredicate::P_Wrap); 10108 ID.AddPointer(AR); 10109 ID.AddInteger(AddedFlags); 10110 void *IP = nullptr; 10111 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10112 return S; 10113 auto *OF = new (SCEVAllocator) 10114 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10115 UniquePreds.InsertNode(OF, IP); 10116 return OF; 10117 } 10118 10119 namespace { 10120 10121 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10122 public: 10123 /// Rewrites \p S in the context of a loop L and the SCEV predication 10124 /// infrastructure. 10125 /// 10126 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10127 /// equivalences present in \p Pred. 10128 /// 10129 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10130 /// \p NewPreds such that the result will be an AddRecExpr. 10131 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10132 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10133 SCEVUnionPredicate *Pred) { 10134 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10135 return Rewriter.visit(S); 10136 } 10137 10138 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10139 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10140 SCEVUnionPredicate *Pred) 10141 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10142 10143 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10144 if (Pred) { 10145 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10146 for (auto *Pred : ExprPreds) 10147 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10148 if (IPred->getLHS() == Expr) 10149 return IPred->getRHS(); 10150 } 10151 10152 return Expr; 10153 } 10154 10155 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10156 const SCEV *Operand = visit(Expr->getOperand()); 10157 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10158 if (AR && AR->getLoop() == L && AR->isAffine()) { 10159 // This couldn't be folded because the operand didn't have the nuw 10160 // flag. Add the nusw flag as an assumption that we could make. 10161 const SCEV *Step = AR->getStepRecurrence(SE); 10162 Type *Ty = Expr->getType(); 10163 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10164 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10165 SE.getSignExtendExpr(Step, Ty), L, 10166 AR->getNoWrapFlags()); 10167 } 10168 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10169 } 10170 10171 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10172 const SCEV *Operand = visit(Expr->getOperand()); 10173 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10174 if (AR && AR->getLoop() == L && AR->isAffine()) { 10175 // This couldn't be folded because the operand didn't have the nsw 10176 // flag. Add the nssw flag as an assumption that we could make. 10177 const SCEV *Step = AR->getStepRecurrence(SE); 10178 Type *Ty = Expr->getType(); 10179 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10180 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10181 SE.getSignExtendExpr(Step, Ty), L, 10182 AR->getNoWrapFlags()); 10183 } 10184 return SE.getSignExtendExpr(Operand, Expr->getType()); 10185 } 10186 10187 private: 10188 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10189 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10190 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10191 if (!NewPreds) { 10192 // Check if we've already made this assumption. 10193 return Pred && Pred->implies(A); 10194 } 10195 NewPreds->insert(A); 10196 return true; 10197 } 10198 10199 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10200 SCEVUnionPredicate *Pred; 10201 const Loop *L; 10202 }; 10203 } // end anonymous namespace 10204 10205 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10206 SCEVUnionPredicate &Preds) { 10207 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10208 } 10209 10210 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10211 const SCEV *S, const Loop *L, 10212 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10213 10214 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10215 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10216 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10217 10218 if (!AddRec) 10219 return nullptr; 10220 10221 // Since the transformation was successful, we can now transfer the SCEV 10222 // predicates. 10223 for (auto *P : TransformPreds) 10224 Preds.insert(P); 10225 10226 return AddRec; 10227 } 10228 10229 /// SCEV predicates 10230 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10231 SCEVPredicateKind Kind) 10232 : FastID(ID), Kind(Kind) {} 10233 10234 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10235 const SCEVUnknown *LHS, 10236 const SCEVConstant *RHS) 10237 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10238 10239 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10240 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10241 10242 if (!Op) 10243 return false; 10244 10245 return Op->LHS == LHS && Op->RHS == RHS; 10246 } 10247 10248 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10249 10250 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10251 10252 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10253 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10254 } 10255 10256 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10257 const SCEVAddRecExpr *AR, 10258 IncrementWrapFlags Flags) 10259 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10260 10261 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10262 10263 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10264 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10265 10266 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10267 } 10268 10269 bool SCEVWrapPredicate::isAlwaysTrue() const { 10270 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10271 IncrementWrapFlags IFlags = Flags; 10272 10273 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10274 IFlags = clearFlags(IFlags, IncrementNSSW); 10275 10276 return IFlags == IncrementAnyWrap; 10277 } 10278 10279 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10280 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10281 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10282 OS << "<nusw>"; 10283 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10284 OS << "<nssw>"; 10285 OS << "\n"; 10286 } 10287 10288 SCEVWrapPredicate::IncrementWrapFlags 10289 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10290 ScalarEvolution &SE) { 10291 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10292 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10293 10294 // We can safely transfer the NSW flag as NSSW. 10295 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10296 ImpliedFlags = IncrementNSSW; 10297 10298 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10299 // If the increment is positive, the SCEV NUW flag will also imply the 10300 // WrapPredicate NUSW flag. 10301 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10302 if (Step->getValue()->getValue().isNonNegative()) 10303 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10304 } 10305 10306 return ImpliedFlags; 10307 } 10308 10309 /// Union predicates don't get cached so create a dummy set ID for it. 10310 SCEVUnionPredicate::SCEVUnionPredicate() 10311 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10312 10313 bool SCEVUnionPredicate::isAlwaysTrue() const { 10314 return all_of(Preds, 10315 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10316 } 10317 10318 ArrayRef<const SCEVPredicate *> 10319 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10320 auto I = SCEVToPreds.find(Expr); 10321 if (I == SCEVToPreds.end()) 10322 return ArrayRef<const SCEVPredicate *>(); 10323 return I->second; 10324 } 10325 10326 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10327 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10328 return all_of(Set->Preds, 10329 [this](const SCEVPredicate *I) { return this->implies(I); }); 10330 10331 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10332 if (ScevPredsIt == SCEVToPreds.end()) 10333 return false; 10334 auto &SCEVPreds = ScevPredsIt->second; 10335 10336 return any_of(SCEVPreds, 10337 [N](const SCEVPredicate *I) { return I->implies(N); }); 10338 } 10339 10340 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10341 10342 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10343 for (auto Pred : Preds) 10344 Pred->print(OS, Depth); 10345 } 10346 10347 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10348 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10349 for (auto Pred : Set->Preds) 10350 add(Pred); 10351 return; 10352 } 10353 10354 if (implies(N)) 10355 return; 10356 10357 const SCEV *Key = N->getExpr(); 10358 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10359 " associated expression!"); 10360 10361 SCEVToPreds[Key].push_back(N); 10362 Preds.push_back(N); 10363 } 10364 10365 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10366 Loop &L) 10367 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10368 10369 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10370 const SCEV *Expr = SE.getSCEV(V); 10371 RewriteEntry &Entry = RewriteMap[Expr]; 10372 10373 // If we already have an entry and the version matches, return it. 10374 if (Entry.second && Generation == Entry.first) 10375 return Entry.second; 10376 10377 // We found an entry but it's stale. Rewrite the stale entry 10378 // acording to the current predicate. 10379 if (Entry.second) 10380 Expr = Entry.second; 10381 10382 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10383 Entry = {Generation, NewSCEV}; 10384 10385 return NewSCEV; 10386 } 10387 10388 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10389 if (!BackedgeCount) { 10390 SCEVUnionPredicate BackedgePred; 10391 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10392 addPredicate(BackedgePred); 10393 } 10394 return BackedgeCount; 10395 } 10396 10397 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10398 if (Preds.implies(&Pred)) 10399 return; 10400 Preds.add(&Pred); 10401 updateGeneration(); 10402 } 10403 10404 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10405 return Preds; 10406 } 10407 10408 void PredicatedScalarEvolution::updateGeneration() { 10409 // If the generation number wrapped recompute everything. 10410 if (++Generation == 0) { 10411 for (auto &II : RewriteMap) { 10412 const SCEV *Rewritten = II.second.second; 10413 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10414 } 10415 } 10416 } 10417 10418 void PredicatedScalarEvolution::setNoOverflow( 10419 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10420 const SCEV *Expr = getSCEV(V); 10421 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10422 10423 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10424 10425 // Clear the statically implied flags. 10426 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10427 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10428 10429 auto II = FlagsMap.insert({V, Flags}); 10430 if (!II.second) 10431 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10432 } 10433 10434 bool PredicatedScalarEvolution::hasNoOverflow( 10435 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10436 const SCEV *Expr = getSCEV(V); 10437 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10438 10439 Flags = SCEVWrapPredicate::clearFlags( 10440 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10441 10442 auto II = FlagsMap.find(V); 10443 10444 if (II != FlagsMap.end()) 10445 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10446 10447 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10448 } 10449 10450 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10451 const SCEV *Expr = this->getSCEV(V); 10452 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10453 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10454 10455 if (!New) 10456 return nullptr; 10457 10458 for (auto *P : NewPreds) 10459 Preds.add(P); 10460 10461 updateGeneration(); 10462 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10463 return New; 10464 } 10465 10466 PredicatedScalarEvolution::PredicatedScalarEvolution( 10467 const PredicatedScalarEvolution &Init) 10468 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10469 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10470 for (const auto &I : Init.FlagsMap) 10471 FlagsMap.insert(I); 10472 } 10473 10474 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10475 // For each block. 10476 for (auto *BB : L.getBlocks()) 10477 for (auto &I : *BB) { 10478 if (!SE.isSCEVable(I.getType())) 10479 continue; 10480 10481 auto *Expr = SE.getSCEV(&I); 10482 auto II = RewriteMap.find(Expr); 10483 10484 if (II == RewriteMap.end()) 10485 continue; 10486 10487 // Don't print things that are not interesting. 10488 if (II->second.second == Expr) 10489 continue; 10490 10491 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10492 OS.indent(Depth + 2) << *Expr << "\n"; 10493 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10494 } 10495 } 10496