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