1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (getSCEVType()) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 default: 308 llvm_unreachable("There are no other nary expression types."); 309 } 310 OS << "("; 311 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 312 I != E; ++I) { 313 OS << **I; 314 if (std::next(I) != E) 315 OS << OpStr; 316 } 317 OS << ")"; 318 switch (NAry->getSCEVType()) { 319 case scAddExpr: 320 case scMulExpr: 321 if (NAry->hasNoUnsignedWrap()) 322 OS << "<nuw>"; 323 if (NAry->hasNoSignedWrap()) 324 OS << "<nsw>"; 325 break; 326 default: 327 // Nothing to print for other nary expressions. 328 break; 329 } 330 return; 331 } 332 case scUDivExpr: { 333 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 334 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 335 return; 336 } 337 case scUnknown: { 338 const SCEVUnknown *U = cast<SCEVUnknown>(this); 339 Type *AllocTy; 340 if (U->isSizeOf(AllocTy)) { 341 OS << "sizeof(" << *AllocTy << ")"; 342 return; 343 } 344 if (U->isAlignOf(AllocTy)) { 345 OS << "alignof(" << *AllocTy << ")"; 346 return; 347 } 348 349 Type *CTy; 350 Constant *FieldNo; 351 if (U->isOffsetOf(CTy, FieldNo)) { 352 OS << "offsetof(" << *CTy << ", "; 353 FieldNo->printAsOperand(OS, false); 354 OS << ")"; 355 return; 356 } 357 358 // Otherwise just print it normally. 359 U->getValue()->printAsOperand(OS, false); 360 return; 361 } 362 case scCouldNotCompute: 363 OS << "***COULDNOTCOMPUTE***"; 364 return; 365 } 366 llvm_unreachable("Unknown SCEV kind!"); 367 } 368 369 Type *SCEV::getType() const { 370 switch (getSCEVType()) { 371 case scConstant: 372 return cast<SCEVConstant>(this)->getType(); 373 case scTruncate: 374 case scZeroExtend: 375 case scSignExtend: 376 return cast<SCEVIntegralCastExpr>(this)->getType(); 377 case scAddRecExpr: 378 case scMulExpr: 379 case scUMaxExpr: 380 case scSMaxExpr: 381 case scUMinExpr: 382 case scSMinExpr: 383 return cast<SCEVNAryExpr>(this)->getType(); 384 case scAddExpr: 385 return cast<SCEVAddExpr>(this)->getType(); 386 case scUDivExpr: 387 return cast<SCEVUDivExpr>(this)->getType(); 388 case scUnknown: 389 return cast<SCEVUnknown>(this)->getType(); 390 case scCouldNotCompute: 391 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 392 } 393 llvm_unreachable("Unknown SCEV kind!"); 394 } 395 396 bool SCEV::isZero() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isZero(); 399 return false; 400 } 401 402 bool SCEV::isOne() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isOne(); 405 return false; 406 } 407 408 bool SCEV::isAllOnesValue() const { 409 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 410 return SC->getValue()->isMinusOne(); 411 return false; 412 } 413 414 bool SCEV::isNonConstantNegative() const { 415 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 416 if (!Mul) return false; 417 418 // If there is a constant factor, it will be first. 419 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 420 if (!SC) return false; 421 422 // Return true if the value is negative, this matches things like (-42 * V). 423 return SC->getAPInt().isNegative(); 424 } 425 426 SCEVCouldNotCompute::SCEVCouldNotCompute() : 427 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 428 429 bool SCEVCouldNotCompute::classof(const SCEV *S) { 430 return S->getSCEVType() == scCouldNotCompute; 431 } 432 433 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 434 FoldingSetNodeID ID; 435 ID.AddInteger(scConstant); 436 ID.AddPointer(V); 437 void *IP = nullptr; 438 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 439 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 440 UniqueSCEVs.InsertNode(S, IP); 441 return S; 442 } 443 444 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 445 return getConstant(ConstantInt::get(getContext(), Val)); 446 } 447 448 const SCEV * 449 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 450 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 451 return getConstant(ConstantInt::get(ITy, V, isSigned)); 452 } 453 454 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 455 SCEVTypes SCEVTy, const SCEV *op, 456 Type *ty) 457 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 458 Operands[0] = op; 459 } 460 461 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 462 Type *ty) 463 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 464 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 465 "Cannot truncate non-integer value!"); 466 } 467 468 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 469 const SCEV *op, Type *ty) 470 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 471 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 472 "Cannot zero extend non-integer value!"); 473 } 474 475 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 476 const SCEV *op, Type *ty) 477 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 478 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 479 "Cannot sign extend non-integer value!"); 480 } 481 482 void SCEVUnknown::deleted() { 483 // Clear this SCEVUnknown from various maps. 484 SE->forgetMemoizedResults(this); 485 486 // Remove this SCEVUnknown from the uniquing map. 487 SE->UniqueSCEVs.RemoveNode(this); 488 489 // Release the value. 490 setValPtr(nullptr); 491 } 492 493 void SCEVUnknown::allUsesReplacedWith(Value *New) { 494 // Remove this SCEVUnknown from the uniquing map. 495 SE->UniqueSCEVs.RemoveNode(this); 496 497 // Update this SCEVUnknown to point to the new value. This is needed 498 // because there may still be outstanding SCEVs which still point to 499 // this SCEVUnknown. 500 setValPtr(New); 501 } 502 503 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 504 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 505 if (VCE->getOpcode() == Instruction::PtrToInt) 506 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 507 if (CE->getOpcode() == Instruction::GetElementPtr && 508 CE->getOperand(0)->isNullValue() && 509 CE->getNumOperands() == 2) 510 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 511 if (CI->isOne()) { 512 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 513 ->getElementType(); 514 return true; 515 } 516 517 return false; 518 } 519 520 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 521 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 522 if (VCE->getOpcode() == Instruction::PtrToInt) 523 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 524 if (CE->getOpcode() == Instruction::GetElementPtr && 525 CE->getOperand(0)->isNullValue()) { 526 Type *Ty = 527 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 528 if (StructType *STy = dyn_cast<StructType>(Ty)) 529 if (!STy->isPacked() && 530 CE->getNumOperands() == 3 && 531 CE->getOperand(1)->isNullValue()) { 532 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 533 if (CI->isOne() && 534 STy->getNumElements() == 2 && 535 STy->getElementType(0)->isIntegerTy(1)) { 536 AllocTy = STy->getElementType(1); 537 return true; 538 } 539 } 540 } 541 542 return false; 543 } 544 545 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 546 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 547 if (VCE->getOpcode() == Instruction::PtrToInt) 548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 549 if (CE->getOpcode() == Instruction::GetElementPtr && 550 CE->getNumOperands() == 3 && 551 CE->getOperand(0)->isNullValue() && 552 CE->getOperand(1)->isNullValue()) { 553 Type *Ty = 554 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 555 // Ignore vector types here so that ScalarEvolutionExpander doesn't 556 // emit getelementptrs that index into vectors. 557 if (Ty->isStructTy() || Ty->isArrayTy()) { 558 CTy = Ty; 559 FieldNo = CE->getOperand(2); 560 return true; 561 } 562 } 563 564 return false; 565 } 566 567 //===----------------------------------------------------------------------===// 568 // SCEV Utilities 569 //===----------------------------------------------------------------------===// 570 571 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 572 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 573 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 574 /// have been previously deemed to be "equally complex" by this routine. It is 575 /// intended to avoid exponential time complexity in cases like: 576 /// 577 /// %a = f(%x, %y) 578 /// %b = f(%a, %a) 579 /// %c = f(%b, %b) 580 /// 581 /// %d = f(%x, %y) 582 /// %e = f(%d, %d) 583 /// %f = f(%e, %e) 584 /// 585 /// CompareValueComplexity(%f, %c) 586 /// 587 /// Since we do not continue running this routine on expression trees once we 588 /// have seen unequal values, there is no need to track them in the cache. 589 static int 590 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 591 const LoopInfo *const LI, Value *LV, Value *RV, 592 unsigned Depth) { 593 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 594 return 0; 595 596 // Order pointer values after integer values. This helps SCEVExpander form 597 // GEPs. 598 bool LIsPointer = LV->getType()->isPointerTy(), 599 RIsPointer = RV->getType()->isPointerTy(); 600 if (LIsPointer != RIsPointer) 601 return (int)LIsPointer - (int)RIsPointer; 602 603 // Compare getValueID values. 604 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 605 if (LID != RID) 606 return (int)LID - (int)RID; 607 608 // Sort arguments by their position. 609 if (const auto *LA = dyn_cast<Argument>(LV)) { 610 const auto *RA = cast<Argument>(RV); 611 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 612 return (int)LArgNo - (int)RArgNo; 613 } 614 615 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 616 const auto *RGV = cast<GlobalValue>(RV); 617 618 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 619 auto LT = GV->getLinkage(); 620 return !(GlobalValue::isPrivateLinkage(LT) || 621 GlobalValue::isInternalLinkage(LT)); 622 }; 623 624 // Use the names to distinguish the two values, but only if the 625 // names are semantically important. 626 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 627 return LGV->getName().compare(RGV->getName()); 628 } 629 630 // For instructions, compare their loop depth, and their operand count. This 631 // is pretty loose. 632 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 633 const auto *RInst = cast<Instruction>(RV); 634 635 // Compare loop depths. 636 const BasicBlock *LParent = LInst->getParent(), 637 *RParent = RInst->getParent(); 638 if (LParent != RParent) { 639 unsigned LDepth = LI->getLoopDepth(LParent), 640 RDepth = LI->getLoopDepth(RParent); 641 if (LDepth != RDepth) 642 return (int)LDepth - (int)RDepth; 643 } 644 645 // Compare the number of operands. 646 unsigned LNumOps = LInst->getNumOperands(), 647 RNumOps = RInst->getNumOperands(); 648 if (LNumOps != RNumOps) 649 return (int)LNumOps - (int)RNumOps; 650 651 for (unsigned Idx : seq(0u, LNumOps)) { 652 int Result = 653 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 654 RInst->getOperand(Idx), Depth + 1); 655 if (Result != 0) 656 return Result; 657 } 658 } 659 660 EqCacheValue.unionSets(LV, RV); 661 return 0; 662 } 663 664 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 665 // than RHS, respectively. A three-way result allows recursive comparisons to be 666 // more efficient. 667 static int CompareSCEVComplexity( 668 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 669 EquivalenceClasses<const Value *> &EqCacheValue, 670 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 671 DominatorTree &DT, unsigned Depth = 0) { 672 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 673 if (LHS == RHS) 674 return 0; 675 676 // Primarily, sort the SCEVs by their getSCEVType(). 677 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 678 if (LType != RType) 679 return (int)LType - (int)RType; 680 681 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 682 return 0; 683 // Aside from the getSCEVType() ordering, the particular ordering 684 // isn't very important except that it's beneficial to be consistent, 685 // so that (a + b) and (b + a) don't end up as different expressions. 686 switch (LType) { 687 case scUnknown: { 688 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 689 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 690 691 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 692 RU->getValue(), Depth + 1); 693 if (X == 0) 694 EqCacheSCEV.unionSets(LHS, RHS); 695 return X; 696 } 697 698 case scConstant: { 699 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 700 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 701 702 // Compare constant values. 703 const APInt &LA = LC->getAPInt(); 704 const APInt &RA = RC->getAPInt(); 705 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 706 if (LBitWidth != RBitWidth) 707 return (int)LBitWidth - (int)RBitWidth; 708 return LA.ult(RA) ? -1 : 1; 709 } 710 711 case scAddRecExpr: { 712 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 713 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 714 715 // There is always a dominance between two recs that are used by one SCEV, 716 // so we can safely sort recs by loop header dominance. We require such 717 // order in getAddExpr. 718 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 719 if (LLoop != RLoop) { 720 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 721 assert(LHead != RHead && "Two loops share the same header?"); 722 if (DT.dominates(LHead, RHead)) 723 return 1; 724 else 725 assert(DT.dominates(RHead, LHead) && 726 "No dominance between recurrences used by one SCEV?"); 727 return -1; 728 } 729 730 // Addrec complexity grows with operand count. 731 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 732 if (LNumOps != RNumOps) 733 return (int)LNumOps - (int)RNumOps; 734 735 // Lexicographically compare. 736 for (unsigned i = 0; i != LNumOps; ++i) { 737 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 738 LA->getOperand(i), RA->getOperand(i), DT, 739 Depth + 1); 740 if (X != 0) 741 return X; 742 } 743 EqCacheSCEV.unionSets(LHS, RHS); 744 return 0; 745 } 746 747 case scAddExpr: 748 case scMulExpr: 749 case scSMaxExpr: 750 case scUMaxExpr: 751 case scSMinExpr: 752 case scUMinExpr: { 753 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 754 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 755 756 // Lexicographically compare n-ary expressions. 757 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 758 if (LNumOps != RNumOps) 759 return (int)LNumOps - (int)RNumOps; 760 761 for (unsigned i = 0; i != LNumOps; ++i) { 762 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 763 LC->getOperand(i), RC->getOperand(i), DT, 764 Depth + 1); 765 if (X != 0) 766 return X; 767 } 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return 0; 770 } 771 772 case scUDivExpr: { 773 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 774 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 775 776 // Lexicographically compare udiv expressions. 777 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 778 RC->getLHS(), DT, Depth + 1); 779 if (X != 0) 780 return X; 781 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 782 RC->getRHS(), DT, Depth + 1); 783 if (X == 0) 784 EqCacheSCEV.unionSets(LHS, RHS); 785 return X; 786 } 787 788 case scTruncate: 789 case scZeroExtend: 790 case scSignExtend: { 791 const SCEVIntegralCastExpr *LC = cast<SCEVIntegralCastExpr>(LHS); 792 const SCEVIntegralCastExpr *RC = cast<SCEVIntegralCastExpr>(RHS); 793 794 // Compare cast expressions by operand. 795 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 796 LC->getOperand(), RC->getOperand(), DT, 797 Depth + 1); 798 if (X == 0) 799 EqCacheSCEV.unionSets(LHS, RHS); 800 return X; 801 } 802 803 case scCouldNotCompute: 804 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 805 } 806 llvm_unreachable("Unknown SCEV kind!"); 807 } 808 809 /// Given a list of SCEV objects, order them by their complexity, and group 810 /// objects of the same complexity together by value. When this routine is 811 /// finished, we know that any duplicates in the vector are consecutive and that 812 /// complexity is monotonically increasing. 813 /// 814 /// Note that we go take special precautions to ensure that we get deterministic 815 /// results from this routine. In other words, we don't want the results of 816 /// this to depend on where the addresses of various SCEV objects happened to 817 /// land in memory. 818 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 819 LoopInfo *LI, DominatorTree &DT) { 820 if (Ops.size() < 2) return; // Noop 821 822 EquivalenceClasses<const SCEV *> EqCacheSCEV; 823 EquivalenceClasses<const Value *> EqCacheValue; 824 if (Ops.size() == 2) { 825 // This is the common case, which also happens to be trivially simple. 826 // Special case it. 827 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 828 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 829 std::swap(LHS, RHS); 830 return; 831 } 832 833 // Do the rough sort by complexity. 834 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 835 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 836 0; 837 }); 838 839 // Now that we are sorted by complexity, group elements of the same 840 // complexity. Note that this is, at worst, N^2, but the vector is likely to 841 // be extremely short in practice. Note that we take this approach because we 842 // do not want to depend on the addresses of the objects we are grouping. 843 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 844 const SCEV *S = Ops[i]; 845 unsigned Complexity = S->getSCEVType(); 846 847 // If there are any objects of the same complexity and same value as this 848 // one, group them. 849 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 850 if (Ops[j] == S) { // Found a duplicate. 851 // Move it to immediately after i'th element. 852 std::swap(Ops[i+1], Ops[j]); 853 ++i; // no need to rescan it. 854 if (i == e-2) return; // Done! 855 } 856 } 857 } 858 } 859 860 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 861 /// least HugeExprThreshold nodes). 862 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 863 return any_of(Ops, [](const SCEV *S) { 864 return S->getExpressionSize() >= HugeExprThreshold; 865 }); 866 } 867 868 //===----------------------------------------------------------------------===// 869 // Simple SCEV method implementations 870 //===----------------------------------------------------------------------===// 871 872 /// Compute BC(It, K). The result has width W. Assume, K > 0. 873 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 874 ScalarEvolution &SE, 875 Type *ResultTy) { 876 // Handle the simplest case efficiently. 877 if (K == 1) 878 return SE.getTruncateOrZeroExtend(It, ResultTy); 879 880 // We are using the following formula for BC(It, K): 881 // 882 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 883 // 884 // Suppose, W is the bitwidth of the return value. We must be prepared for 885 // overflow. Hence, we must assure that the result of our computation is 886 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 887 // safe in modular arithmetic. 888 // 889 // However, this code doesn't use exactly that formula; the formula it uses 890 // is something like the following, where T is the number of factors of 2 in 891 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 892 // exponentiation: 893 // 894 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 895 // 896 // This formula is trivially equivalent to the previous formula. However, 897 // this formula can be implemented much more efficiently. The trick is that 898 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 899 // arithmetic. To do exact division in modular arithmetic, all we have 900 // to do is multiply by the inverse. Therefore, this step can be done at 901 // width W. 902 // 903 // The next issue is how to safely do the division by 2^T. The way this 904 // is done is by doing the multiplication step at a width of at least W + T 905 // bits. This way, the bottom W+T bits of the product are accurate. Then, 906 // when we perform the division by 2^T (which is equivalent to a right shift 907 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 908 // truncated out after the division by 2^T. 909 // 910 // In comparison to just directly using the first formula, this technique 911 // is much more efficient; using the first formula requires W * K bits, 912 // but this formula less than W + K bits. Also, the first formula requires 913 // a division step, whereas this formula only requires multiplies and shifts. 914 // 915 // It doesn't matter whether the subtraction step is done in the calculation 916 // width or the input iteration count's width; if the subtraction overflows, 917 // the result must be zero anyway. We prefer here to do it in the width of 918 // the induction variable because it helps a lot for certain cases; CodeGen 919 // isn't smart enough to ignore the overflow, which leads to much less 920 // efficient code if the width of the subtraction is wider than the native 921 // register width. 922 // 923 // (It's possible to not widen at all by pulling out factors of 2 before 924 // the multiplication; for example, K=2 can be calculated as 925 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 926 // extra arithmetic, so it's not an obvious win, and it gets 927 // much more complicated for K > 3.) 928 929 // Protection from insane SCEVs; this bound is conservative, 930 // but it probably doesn't matter. 931 if (K > 1000) 932 return SE.getCouldNotCompute(); 933 934 unsigned W = SE.getTypeSizeInBits(ResultTy); 935 936 // Calculate K! / 2^T and T; we divide out the factors of two before 937 // multiplying for calculating K! / 2^T to avoid overflow. 938 // Other overflow doesn't matter because we only care about the bottom 939 // W bits of the result. 940 APInt OddFactorial(W, 1); 941 unsigned T = 1; 942 for (unsigned i = 3; i <= K; ++i) { 943 APInt Mult(W, i); 944 unsigned TwoFactors = Mult.countTrailingZeros(); 945 T += TwoFactors; 946 Mult.lshrInPlace(TwoFactors); 947 OddFactorial *= Mult; 948 } 949 950 // We need at least W + T bits for the multiplication step 951 unsigned CalculationBits = W + T; 952 953 // Calculate 2^T, at width T+W. 954 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 955 956 // Calculate the multiplicative inverse of K! / 2^T; 957 // this multiplication factor will perform the exact division by 958 // K! / 2^T. 959 APInt Mod = APInt::getSignedMinValue(W+1); 960 APInt MultiplyFactor = OddFactorial.zext(W+1); 961 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 962 MultiplyFactor = MultiplyFactor.trunc(W); 963 964 // Calculate the product, at width T+W 965 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 966 CalculationBits); 967 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 968 for (unsigned i = 1; i != K; ++i) { 969 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 970 Dividend = SE.getMulExpr(Dividend, 971 SE.getTruncateOrZeroExtend(S, CalculationTy)); 972 } 973 974 // Divide by 2^T 975 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 976 977 // Truncate the result, and divide by K! / 2^T. 978 979 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 980 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 981 } 982 983 /// Return the value of this chain of recurrences at the specified iteration 984 /// number. We can evaluate this recurrence by multiplying each element in the 985 /// chain by the binomial coefficient corresponding to it. In other words, we 986 /// can evaluate {A,+,B,+,C,+,D} as: 987 /// 988 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 989 /// 990 /// where BC(It, k) stands for binomial coefficient. 991 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 992 ScalarEvolution &SE) const { 993 const SCEV *Result = getStart(); 994 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 995 // The computation is correct in the face of overflow provided that the 996 // multiplication is performed _after_ the evaluation of the binomial 997 // coefficient. 998 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 999 if (isa<SCEVCouldNotCompute>(Coeff)) 1000 return Coeff; 1001 1002 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1003 } 1004 return Result; 1005 } 1006 1007 //===----------------------------------------------------------------------===// 1008 // SCEV Expression folder implementations 1009 //===----------------------------------------------------------------------===// 1010 1011 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1012 unsigned Depth) { 1013 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1014 "This is not a truncating conversion!"); 1015 assert(isSCEVable(Ty) && 1016 "This is not a conversion to a SCEVable type!"); 1017 Ty = getEffectiveSCEVType(Ty); 1018 1019 FoldingSetNodeID ID; 1020 ID.AddInteger(scTruncate); 1021 ID.AddPointer(Op); 1022 ID.AddPointer(Ty); 1023 void *IP = nullptr; 1024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1025 1026 // Fold if the operand is constant. 1027 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1028 return getConstant( 1029 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1030 1031 // trunc(trunc(x)) --> trunc(x) 1032 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1033 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1034 1035 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1036 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1037 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1038 1039 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1040 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1041 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1042 1043 if (Depth > MaxCastDepth) { 1044 SCEV *S = 1045 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1046 UniqueSCEVs.InsertNode(S, IP); 1047 addToLoopUseLists(S); 1048 return S; 1049 } 1050 1051 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1052 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1053 // if after transforming we have at most one truncate, not counting truncates 1054 // that replace other casts. 1055 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1056 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1057 SmallVector<const SCEV *, 4> Operands; 1058 unsigned numTruncs = 0; 1059 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1060 ++i) { 1061 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1062 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1063 isa<SCEVTruncateExpr>(S)) 1064 numTruncs++; 1065 Operands.push_back(S); 1066 } 1067 if (numTruncs < 2) { 1068 if (isa<SCEVAddExpr>(Op)) 1069 return getAddExpr(Operands); 1070 else if (isa<SCEVMulExpr>(Op)) 1071 return getMulExpr(Operands); 1072 else 1073 llvm_unreachable("Unexpected SCEV type for Op."); 1074 } 1075 // Although we checked in the beginning that ID is not in the cache, it is 1076 // possible that during recursion and different modification ID was inserted 1077 // into the cache. So if we find it, just return it. 1078 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1079 return S; 1080 } 1081 1082 // If the input value is a chrec scev, truncate the chrec's operands. 1083 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1084 SmallVector<const SCEV *, 4> Operands; 1085 for (const SCEV *Op : AddRec->operands()) 1086 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1087 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1088 } 1089 1090 // The cast wasn't folded; create an explicit cast node. We can reuse 1091 // the existing insert position since if we get here, we won't have 1092 // made any changes which would invalidate it. 1093 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1094 Op, Ty); 1095 UniqueSCEVs.InsertNode(S, IP); 1096 addToLoopUseLists(S); 1097 return S; 1098 } 1099 1100 // Get the limit of a recurrence such that incrementing by Step cannot cause 1101 // signed overflow as long as the value of the recurrence within the 1102 // loop does not exceed this limit before incrementing. 1103 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1104 ICmpInst::Predicate *Pred, 1105 ScalarEvolution *SE) { 1106 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1107 if (SE->isKnownPositive(Step)) { 1108 *Pred = ICmpInst::ICMP_SLT; 1109 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1110 SE->getSignedRangeMax(Step)); 1111 } 1112 if (SE->isKnownNegative(Step)) { 1113 *Pred = ICmpInst::ICMP_SGT; 1114 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1115 SE->getSignedRangeMin(Step)); 1116 } 1117 return nullptr; 1118 } 1119 1120 // Get the limit of a recurrence such that incrementing by Step cannot cause 1121 // unsigned overflow as long as the value of the recurrence within the loop does 1122 // not exceed this limit before incrementing. 1123 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1124 ICmpInst::Predicate *Pred, 1125 ScalarEvolution *SE) { 1126 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1127 *Pred = ICmpInst::ICMP_ULT; 1128 1129 return SE->getConstant(APInt::getMinValue(BitWidth) - 1130 SE->getUnsignedRangeMax(Step)); 1131 } 1132 1133 namespace { 1134 1135 struct ExtendOpTraitsBase { 1136 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1137 unsigned); 1138 }; 1139 1140 // Used to make code generic over signed and unsigned overflow. 1141 template <typename ExtendOp> struct ExtendOpTraits { 1142 // Members present: 1143 // 1144 // static const SCEV::NoWrapFlags WrapType; 1145 // 1146 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1147 // 1148 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1149 // ICmpInst::Predicate *Pred, 1150 // ScalarEvolution *SE); 1151 }; 1152 1153 template <> 1154 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1155 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1156 1157 static const GetExtendExprTy GetExtendExpr; 1158 1159 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1160 ICmpInst::Predicate *Pred, 1161 ScalarEvolution *SE) { 1162 return getSignedOverflowLimitForStep(Step, Pred, SE); 1163 } 1164 }; 1165 1166 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1167 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1168 1169 template <> 1170 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1171 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1172 1173 static const GetExtendExprTy GetExtendExpr; 1174 1175 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1176 ICmpInst::Predicate *Pred, 1177 ScalarEvolution *SE) { 1178 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1179 } 1180 }; 1181 1182 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1183 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1184 1185 } // end anonymous namespace 1186 1187 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1188 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1189 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1190 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1191 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1192 // expression "Step + sext/zext(PreIncAR)" is congruent with 1193 // "sext/zext(PostIncAR)" 1194 template <typename ExtendOpTy> 1195 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1196 ScalarEvolution *SE, unsigned Depth) { 1197 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1198 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1199 1200 const Loop *L = AR->getLoop(); 1201 const SCEV *Start = AR->getStart(); 1202 const SCEV *Step = AR->getStepRecurrence(*SE); 1203 1204 // Check for a simple looking step prior to loop entry. 1205 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1206 if (!SA) 1207 return nullptr; 1208 1209 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1210 // subtraction is expensive. For this purpose, perform a quick and dirty 1211 // difference, by checking for Step in the operand list. 1212 SmallVector<const SCEV *, 4> DiffOps; 1213 for (const SCEV *Op : SA->operands()) 1214 if (Op != Step) 1215 DiffOps.push_back(Op); 1216 1217 if (DiffOps.size() == SA->getNumOperands()) 1218 return nullptr; 1219 1220 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1221 // `Step`: 1222 1223 // 1. NSW/NUW flags on the step increment. 1224 auto PreStartFlags = 1225 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1226 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1227 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1228 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1229 1230 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1231 // "S+X does not sign/unsign-overflow". 1232 // 1233 1234 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1235 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1236 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1237 return PreStart; 1238 1239 // 2. Direct overflow check on the step operation's expression. 1240 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1241 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1242 const SCEV *OperandExtendedStart = 1243 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1244 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1245 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1246 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1247 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1248 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1249 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1250 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1251 } 1252 return PreStart; 1253 } 1254 1255 // 3. Loop precondition. 1256 ICmpInst::Predicate Pred; 1257 const SCEV *OverflowLimit = 1258 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1259 1260 if (OverflowLimit && 1261 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1262 return PreStart; 1263 1264 return nullptr; 1265 } 1266 1267 // Get the normalized zero or sign extended expression for this AddRec's Start. 1268 template <typename ExtendOpTy> 1269 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1270 ScalarEvolution *SE, 1271 unsigned Depth) { 1272 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1273 1274 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1275 if (!PreStart) 1276 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1277 1278 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1279 Depth), 1280 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1281 } 1282 1283 // Try to prove away overflow by looking at "nearby" add recurrences. A 1284 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1285 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1286 // 1287 // Formally: 1288 // 1289 // {S,+,X} == {S-T,+,X} + T 1290 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1291 // 1292 // If ({S-T,+,X} + T) does not overflow ... (1) 1293 // 1294 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1295 // 1296 // If {S-T,+,X} does not overflow ... (2) 1297 // 1298 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1299 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1300 // 1301 // If (S-T)+T does not overflow ... (3) 1302 // 1303 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1304 // == {Ext(S),+,Ext(X)} == LHS 1305 // 1306 // Thus, if (1), (2) and (3) are true for some T, then 1307 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1308 // 1309 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1310 // does not overflow" restricted to the 0th iteration. Therefore we only need 1311 // to check for (1) and (2). 1312 // 1313 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1314 // is `Delta` (defined below). 1315 template <typename ExtendOpTy> 1316 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1317 const SCEV *Step, 1318 const Loop *L) { 1319 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1320 1321 // We restrict `Start` to a constant to prevent SCEV from spending too much 1322 // time here. It is correct (but more expensive) to continue with a 1323 // non-constant `Start` and do a general SCEV subtraction to compute 1324 // `PreStart` below. 1325 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1326 if (!StartC) 1327 return false; 1328 1329 APInt StartAI = StartC->getAPInt(); 1330 1331 for (unsigned Delta : {-2, -1, 1, 2}) { 1332 const SCEV *PreStart = getConstant(StartAI - Delta); 1333 1334 FoldingSetNodeID ID; 1335 ID.AddInteger(scAddRecExpr); 1336 ID.AddPointer(PreStart); 1337 ID.AddPointer(Step); 1338 ID.AddPointer(L); 1339 void *IP = nullptr; 1340 const auto *PreAR = 1341 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1342 1343 // Give up if we don't already have the add recurrence we need because 1344 // actually constructing an add recurrence is relatively expensive. 1345 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1346 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1347 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1348 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1349 DeltaS, &Pred, this); 1350 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1351 return true; 1352 } 1353 } 1354 1355 return false; 1356 } 1357 1358 // Finds an integer D for an expression (C + x + y + ...) such that the top 1359 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1360 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1361 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1362 // the (C + x + y + ...) expression is \p WholeAddExpr. 1363 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1364 const SCEVConstant *ConstantTerm, 1365 const SCEVAddExpr *WholeAddExpr) { 1366 const APInt &C = ConstantTerm->getAPInt(); 1367 const unsigned BitWidth = C.getBitWidth(); 1368 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1369 uint32_t TZ = BitWidth; 1370 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1371 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1372 if (TZ) { 1373 // Set D to be as many least significant bits of C as possible while still 1374 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1375 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1376 } 1377 return APInt(BitWidth, 0); 1378 } 1379 1380 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1381 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1382 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1383 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1384 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1385 const APInt &ConstantStart, 1386 const SCEV *Step) { 1387 const unsigned BitWidth = ConstantStart.getBitWidth(); 1388 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1389 if (TZ) 1390 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1391 : ConstantStart; 1392 return APInt(BitWidth, 0); 1393 } 1394 1395 const SCEV * 1396 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1397 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1398 "This is not an extending conversion!"); 1399 assert(isSCEVable(Ty) && 1400 "This is not a conversion to a SCEVable type!"); 1401 Ty = getEffectiveSCEVType(Ty); 1402 1403 // Fold if the operand is constant. 1404 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1405 return getConstant( 1406 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1407 1408 // zext(zext(x)) --> zext(x) 1409 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1410 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1411 1412 // Before doing any expensive analysis, check to see if we've already 1413 // computed a SCEV for this Op and Ty. 1414 FoldingSetNodeID ID; 1415 ID.AddInteger(scZeroExtend); 1416 ID.AddPointer(Op); 1417 ID.AddPointer(Ty); 1418 void *IP = nullptr; 1419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1420 if (Depth > MaxCastDepth) { 1421 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1422 Op, Ty); 1423 UniqueSCEVs.InsertNode(S, IP); 1424 addToLoopUseLists(S); 1425 return S; 1426 } 1427 1428 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1429 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1430 // It's possible the bits taken off by the truncate were all zero bits. If 1431 // so, we should be able to simplify this further. 1432 const SCEV *X = ST->getOperand(); 1433 ConstantRange CR = getUnsignedRange(X); 1434 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1435 unsigned NewBits = getTypeSizeInBits(Ty); 1436 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1437 CR.zextOrTrunc(NewBits))) 1438 return getTruncateOrZeroExtend(X, Ty, Depth); 1439 } 1440 1441 // If the input value is a chrec scev, and we can prove that the value 1442 // did not overflow the old, smaller, value, we can zero extend all of the 1443 // operands (often constants). This allows analysis of something like 1444 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1445 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1446 if (AR->isAffine()) { 1447 const SCEV *Start = AR->getStart(); 1448 const SCEV *Step = AR->getStepRecurrence(*this); 1449 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1450 const Loop *L = AR->getLoop(); 1451 1452 if (!AR->hasNoUnsignedWrap()) { 1453 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1454 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1455 } 1456 1457 // If we have special knowledge that this addrec won't overflow, 1458 // we don't need to do any further analysis. 1459 if (AR->hasNoUnsignedWrap()) 1460 return getAddRecExpr( 1461 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1462 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1463 1464 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1465 // Note that this serves two purposes: It filters out loops that are 1466 // simply not analyzable, and it covers the case where this code is 1467 // being called from within backedge-taken count analysis, such that 1468 // attempting to ask for the backedge-taken count would likely result 1469 // in infinite recursion. In the later case, the analysis code will 1470 // cope with a conservative value, and it will take care to purge 1471 // that value once it has finished. 1472 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1473 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1474 // Manually compute the final value for AR, checking for 1475 // overflow. 1476 1477 // Check whether the backedge-taken count can be losslessly casted to 1478 // the addrec's type. The count is always unsigned. 1479 const SCEV *CastedMaxBECount = 1480 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1481 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1482 CastedMaxBECount, MaxBECount->getType(), Depth); 1483 if (MaxBECount == RecastedMaxBECount) { 1484 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1485 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1486 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1487 SCEV::FlagAnyWrap, Depth + 1); 1488 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1489 SCEV::FlagAnyWrap, 1490 Depth + 1), 1491 WideTy, Depth + 1); 1492 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1493 const SCEV *WideMaxBECount = 1494 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1495 const SCEV *OperandExtendedAdd = 1496 getAddExpr(WideStart, 1497 getMulExpr(WideMaxBECount, 1498 getZeroExtendExpr(Step, WideTy, Depth + 1), 1499 SCEV::FlagAnyWrap, Depth + 1), 1500 SCEV::FlagAnyWrap, Depth + 1); 1501 if (ZAdd == OperandExtendedAdd) { 1502 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1503 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1504 // Return the expression with the addrec on the outside. 1505 return getAddRecExpr( 1506 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1507 Depth + 1), 1508 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1509 AR->getNoWrapFlags()); 1510 } 1511 // Similar to above, only this time treat the step value as signed. 1512 // This covers loops that count down. 1513 OperandExtendedAdd = 1514 getAddExpr(WideStart, 1515 getMulExpr(WideMaxBECount, 1516 getSignExtendExpr(Step, WideTy, Depth + 1), 1517 SCEV::FlagAnyWrap, Depth + 1), 1518 SCEV::FlagAnyWrap, Depth + 1); 1519 if (ZAdd == OperandExtendedAdd) { 1520 // Cache knowledge of AR NW, which is propagated to this AddRec. 1521 // Negative step causes unsigned wrap, but it still can't self-wrap. 1522 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1523 // Return the expression with the addrec on the outside. 1524 return getAddRecExpr( 1525 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1526 Depth + 1), 1527 getSignExtendExpr(Step, Ty, Depth + 1), L, 1528 AR->getNoWrapFlags()); 1529 } 1530 } 1531 } 1532 1533 // Normally, in the cases we can prove no-overflow via a 1534 // backedge guarding condition, we can also compute a backedge 1535 // taken count for the loop. The exceptions are assumptions and 1536 // guards present in the loop -- SCEV is not great at exploiting 1537 // these to compute max backedge taken counts, but can still use 1538 // these to prove lack of overflow. Use this fact to avoid 1539 // doing extra work that may not pay off. 1540 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1541 !AC.assumptions().empty()) { 1542 // If the backedge is guarded by a comparison with the pre-inc 1543 // value the addrec is safe. Also, if the entry is guarded by 1544 // a comparison with the start value and the backedge is 1545 // guarded by a comparison with the post-inc value, the addrec 1546 // is safe. 1547 if (isKnownPositive(Step)) { 1548 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1549 getUnsignedRangeMax(Step)); 1550 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1551 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1552 // Cache knowledge of AR NUW, which is propagated to this 1553 // AddRec. 1554 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1555 // Return the expression with the addrec on the outside. 1556 return getAddRecExpr( 1557 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1558 Depth + 1), 1559 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1560 AR->getNoWrapFlags()); 1561 } 1562 } else if (isKnownNegative(Step)) { 1563 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1564 getSignedRangeMin(Step)); 1565 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1566 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1567 // Cache knowledge of AR NW, which is propagated to this 1568 // AddRec. Negative step causes unsigned wrap, but it 1569 // still can't self-wrap. 1570 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1571 // Return the expression with the addrec on the outside. 1572 return getAddRecExpr( 1573 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1574 Depth + 1), 1575 getSignExtendExpr(Step, Ty, Depth + 1), L, 1576 AR->getNoWrapFlags()); 1577 } 1578 } 1579 } 1580 1581 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1582 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1583 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1584 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1585 const APInt &C = SC->getAPInt(); 1586 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1587 if (D != 0) { 1588 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1589 const SCEV *SResidual = 1590 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1591 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1592 return getAddExpr(SZExtD, SZExtR, 1593 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1594 Depth + 1); 1595 } 1596 } 1597 1598 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1599 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1600 return getAddRecExpr( 1601 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1602 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1603 } 1604 } 1605 1606 // zext(A % B) --> zext(A) % zext(B) 1607 { 1608 const SCEV *LHS; 1609 const SCEV *RHS; 1610 if (matchURem(Op, LHS, RHS)) 1611 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1612 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1613 } 1614 1615 // zext(A / B) --> zext(A) / zext(B). 1616 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1617 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1618 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1619 1620 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1621 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1622 if (SA->hasNoUnsignedWrap()) { 1623 // If the addition does not unsign overflow then we can, by definition, 1624 // commute the zero extension with the addition operation. 1625 SmallVector<const SCEV *, 4> Ops; 1626 for (const auto *Op : SA->operands()) 1627 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1628 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1629 } 1630 1631 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1632 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1633 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1634 // 1635 // Often address arithmetics contain expressions like 1636 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1637 // This transformation is useful while proving that such expressions are 1638 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1639 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1640 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1641 if (D != 0) { 1642 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1643 const SCEV *SResidual = 1644 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1645 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1646 return getAddExpr(SZExtD, SZExtR, 1647 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1648 Depth + 1); 1649 } 1650 } 1651 } 1652 1653 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1654 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1655 if (SM->hasNoUnsignedWrap()) { 1656 // If the multiply does not unsign overflow then we can, by definition, 1657 // commute the zero extension with the multiply operation. 1658 SmallVector<const SCEV *, 4> Ops; 1659 for (const auto *Op : SM->operands()) 1660 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1661 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1662 } 1663 1664 // zext(2^K * (trunc X to iN)) to iM -> 1665 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1666 // 1667 // Proof: 1668 // 1669 // zext(2^K * (trunc X to iN)) to iM 1670 // = zext((trunc X to iN) << K) to iM 1671 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1672 // (because shl removes the top K bits) 1673 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1674 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1675 // 1676 if (SM->getNumOperands() == 2) 1677 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1678 if (MulLHS->getAPInt().isPowerOf2()) 1679 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1680 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1681 MulLHS->getAPInt().logBase2(); 1682 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1683 return getMulExpr( 1684 getZeroExtendExpr(MulLHS, Ty), 1685 getZeroExtendExpr( 1686 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1687 SCEV::FlagNUW, Depth + 1); 1688 } 1689 } 1690 1691 // The cast wasn't folded; create an explicit cast node. 1692 // Recompute the insert position, as it may have been invalidated. 1693 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1694 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1695 Op, Ty); 1696 UniqueSCEVs.InsertNode(S, IP); 1697 addToLoopUseLists(S); 1698 return S; 1699 } 1700 1701 const SCEV * 1702 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1703 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1704 "This is not an extending conversion!"); 1705 assert(isSCEVable(Ty) && 1706 "This is not a conversion to a SCEVable type!"); 1707 Ty = getEffectiveSCEVType(Ty); 1708 1709 // Fold if the operand is constant. 1710 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1711 return getConstant( 1712 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1713 1714 // sext(sext(x)) --> sext(x) 1715 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1716 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1717 1718 // sext(zext(x)) --> zext(x) 1719 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1720 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1721 1722 // Before doing any expensive analysis, check to see if we've already 1723 // computed a SCEV for this Op and Ty. 1724 FoldingSetNodeID ID; 1725 ID.AddInteger(scSignExtend); 1726 ID.AddPointer(Op); 1727 ID.AddPointer(Ty); 1728 void *IP = nullptr; 1729 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1730 // Limit recursion depth. 1731 if (Depth > MaxCastDepth) { 1732 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1733 Op, Ty); 1734 UniqueSCEVs.InsertNode(S, IP); 1735 addToLoopUseLists(S); 1736 return S; 1737 } 1738 1739 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1740 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1741 // It's possible the bits taken off by the truncate were all sign bits. If 1742 // so, we should be able to simplify this further. 1743 const SCEV *X = ST->getOperand(); 1744 ConstantRange CR = getSignedRange(X); 1745 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1746 unsigned NewBits = getTypeSizeInBits(Ty); 1747 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1748 CR.sextOrTrunc(NewBits))) 1749 return getTruncateOrSignExtend(X, Ty, Depth); 1750 } 1751 1752 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1753 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1754 if (SA->hasNoSignedWrap()) { 1755 // If the addition does not sign overflow then we can, by definition, 1756 // commute the sign extension with the addition operation. 1757 SmallVector<const SCEV *, 4> Ops; 1758 for (const auto *Op : SA->operands()) 1759 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1760 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1761 } 1762 1763 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1764 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1765 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1766 // 1767 // For instance, this will bring two seemingly different expressions: 1768 // 1 + sext(5 + 20 * %x + 24 * %y) and 1769 // sext(6 + 20 * %x + 24 * %y) 1770 // to the same form: 1771 // 2 + sext(4 + 20 * %x + 24 * %y) 1772 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1773 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1774 if (D != 0) { 1775 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1776 const SCEV *SResidual = 1777 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1778 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1779 return getAddExpr(SSExtD, SSExtR, 1780 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1781 Depth + 1); 1782 } 1783 } 1784 } 1785 // If the input value is a chrec scev, and we can prove that the value 1786 // did not overflow the old, smaller, value, we can sign extend all of the 1787 // operands (often constants). This allows analysis of something like 1788 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1790 if (AR->isAffine()) { 1791 const SCEV *Start = AR->getStart(); 1792 const SCEV *Step = AR->getStepRecurrence(*this); 1793 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1794 const Loop *L = AR->getLoop(); 1795 1796 if (!AR->hasNoSignedWrap()) { 1797 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1798 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1799 } 1800 1801 // If we have special knowledge that this addrec won't overflow, 1802 // we don't need to do any further analysis. 1803 if (AR->hasNoSignedWrap()) 1804 return getAddRecExpr( 1805 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1806 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1807 1808 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1809 // Note that this serves two purposes: It filters out loops that are 1810 // simply not analyzable, and it covers the case where this code is 1811 // being called from within backedge-taken count analysis, such that 1812 // attempting to ask for the backedge-taken count would likely result 1813 // in infinite recursion. In the later case, the analysis code will 1814 // cope with a conservative value, and it will take care to purge 1815 // that value once it has finished. 1816 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1817 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1818 // Manually compute the final value for AR, checking for 1819 // overflow. 1820 1821 // Check whether the backedge-taken count can be losslessly casted to 1822 // the addrec's type. The count is always unsigned. 1823 const SCEV *CastedMaxBECount = 1824 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1825 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1826 CastedMaxBECount, MaxBECount->getType(), Depth); 1827 if (MaxBECount == RecastedMaxBECount) { 1828 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1829 // Check whether Start+Step*MaxBECount has no signed overflow. 1830 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1831 SCEV::FlagAnyWrap, Depth + 1); 1832 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1833 SCEV::FlagAnyWrap, 1834 Depth + 1), 1835 WideTy, Depth + 1); 1836 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1837 const SCEV *WideMaxBECount = 1838 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1839 const SCEV *OperandExtendedAdd = 1840 getAddExpr(WideStart, 1841 getMulExpr(WideMaxBECount, 1842 getSignExtendExpr(Step, WideTy, Depth + 1), 1843 SCEV::FlagAnyWrap, Depth + 1), 1844 SCEV::FlagAnyWrap, Depth + 1); 1845 if (SAdd == OperandExtendedAdd) { 1846 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1847 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1848 // Return the expression with the addrec on the outside. 1849 return getAddRecExpr( 1850 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1851 Depth + 1), 1852 getSignExtendExpr(Step, Ty, Depth + 1), L, 1853 AR->getNoWrapFlags()); 1854 } 1855 // Similar to above, only this time treat the step value as unsigned. 1856 // This covers loops that count up with an unsigned step. 1857 OperandExtendedAdd = 1858 getAddExpr(WideStart, 1859 getMulExpr(WideMaxBECount, 1860 getZeroExtendExpr(Step, WideTy, Depth + 1), 1861 SCEV::FlagAnyWrap, Depth + 1), 1862 SCEV::FlagAnyWrap, Depth + 1); 1863 if (SAdd == OperandExtendedAdd) { 1864 // If AR wraps around then 1865 // 1866 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1867 // => SAdd != OperandExtendedAdd 1868 // 1869 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1870 // (SAdd == OperandExtendedAdd => AR is NW) 1871 1872 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1873 1874 // Return the expression with the addrec on the outside. 1875 return getAddRecExpr( 1876 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1877 Depth + 1), 1878 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1879 AR->getNoWrapFlags()); 1880 } 1881 } 1882 } 1883 1884 // Normally, in the cases we can prove no-overflow via a 1885 // backedge guarding condition, we can also compute a backedge 1886 // taken count for the loop. The exceptions are assumptions and 1887 // guards present in the loop -- SCEV is not great at exploiting 1888 // these to compute max backedge taken counts, but can still use 1889 // these to prove lack of overflow. Use this fact to avoid 1890 // doing extra work that may not pay off. 1891 1892 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1893 !AC.assumptions().empty()) { 1894 // If the backedge is guarded by a comparison with the pre-inc 1895 // value the addrec is safe. Also, if the entry is guarded by 1896 // a comparison with the start value and the backedge is 1897 // guarded by a comparison with the post-inc value, the addrec 1898 // is safe. 1899 ICmpInst::Predicate Pred; 1900 const SCEV *OverflowLimit = 1901 getSignedOverflowLimitForStep(Step, &Pred, this); 1902 if (OverflowLimit && 1903 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1904 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1905 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1906 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1907 return getAddRecExpr( 1908 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1909 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1910 } 1911 } 1912 1913 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 1914 // if D + (C - D + Step * n) could be proven to not signed wrap 1915 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1916 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1917 const APInt &C = SC->getAPInt(); 1918 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1919 if (D != 0) { 1920 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1921 const SCEV *SResidual = 1922 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1923 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1924 return getAddExpr(SSExtD, SSExtR, 1925 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1926 Depth + 1); 1927 } 1928 } 1929 1930 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1931 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1932 return getAddRecExpr( 1933 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1934 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1935 } 1936 } 1937 1938 // If the input value is provably positive and we could not simplify 1939 // away the sext build a zext instead. 1940 if (isKnownNonNegative(Op)) 1941 return getZeroExtendExpr(Op, Ty, Depth + 1); 1942 1943 // The cast wasn't folded; create an explicit cast node. 1944 // Recompute the insert position, as it may have been invalidated. 1945 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1946 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1947 Op, Ty); 1948 UniqueSCEVs.InsertNode(S, IP); 1949 addToLoopUseLists(S); 1950 return S; 1951 } 1952 1953 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1954 /// unspecified bits out to the given type. 1955 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1956 Type *Ty) { 1957 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1958 "This is not an extending conversion!"); 1959 assert(isSCEVable(Ty) && 1960 "This is not a conversion to a SCEVable type!"); 1961 Ty = getEffectiveSCEVType(Ty); 1962 1963 // Sign-extend negative constants. 1964 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1965 if (SC->getAPInt().isNegative()) 1966 return getSignExtendExpr(Op, Ty); 1967 1968 // Peel off a truncate cast. 1969 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1970 const SCEV *NewOp = T->getOperand(); 1971 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1972 return getAnyExtendExpr(NewOp, Ty); 1973 return getTruncateOrNoop(NewOp, Ty); 1974 } 1975 1976 // Next try a zext cast. If the cast is folded, use it. 1977 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1978 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1979 return ZExt; 1980 1981 // Next try a sext cast. If the cast is folded, use it. 1982 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1983 if (!isa<SCEVSignExtendExpr>(SExt)) 1984 return SExt; 1985 1986 // Force the cast to be folded into the operands of an addrec. 1987 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1988 SmallVector<const SCEV *, 4> Ops; 1989 for (const SCEV *Op : AR->operands()) 1990 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1991 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1992 } 1993 1994 // If the expression is obviously signed, use the sext cast value. 1995 if (isa<SCEVSMaxExpr>(Op)) 1996 return SExt; 1997 1998 // Absent any other information, use the zext cast value. 1999 return ZExt; 2000 } 2001 2002 /// Process the given Ops list, which is a list of operands to be added under 2003 /// the given scale, update the given map. This is a helper function for 2004 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2005 /// that would form an add expression like this: 2006 /// 2007 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2008 /// 2009 /// where A and B are constants, update the map with these values: 2010 /// 2011 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2012 /// 2013 /// and add 13 + A*B*29 to AccumulatedConstant. 2014 /// This will allow getAddRecExpr to produce this: 2015 /// 2016 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2017 /// 2018 /// This form often exposes folding opportunities that are hidden in 2019 /// the original operand list. 2020 /// 2021 /// Return true iff it appears that any interesting folding opportunities 2022 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2023 /// the common case where no interesting opportunities are present, and 2024 /// is also used as a check to avoid infinite recursion. 2025 static bool 2026 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2027 SmallVectorImpl<const SCEV *> &NewOps, 2028 APInt &AccumulatedConstant, 2029 const SCEV *const *Ops, size_t NumOperands, 2030 const APInt &Scale, 2031 ScalarEvolution &SE) { 2032 bool Interesting = false; 2033 2034 // Iterate over the add operands. They are sorted, with constants first. 2035 unsigned i = 0; 2036 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2037 ++i; 2038 // Pull a buried constant out to the outside. 2039 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2040 Interesting = true; 2041 AccumulatedConstant += Scale * C->getAPInt(); 2042 } 2043 2044 // Next comes everything else. We're especially interested in multiplies 2045 // here, but they're in the middle, so just visit the rest with one loop. 2046 for (; i != NumOperands; ++i) { 2047 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2048 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2049 APInt NewScale = 2050 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2051 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2052 // A multiplication of a constant with another add; recurse. 2053 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2054 Interesting |= 2055 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2056 Add->op_begin(), Add->getNumOperands(), 2057 NewScale, SE); 2058 } else { 2059 // A multiplication of a constant with some other value. Update 2060 // the map. 2061 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2062 const SCEV *Key = SE.getMulExpr(MulOps); 2063 auto Pair = M.insert({Key, NewScale}); 2064 if (Pair.second) { 2065 NewOps.push_back(Pair.first->first); 2066 } else { 2067 Pair.first->second += NewScale; 2068 // The map already had an entry for this value, which may indicate 2069 // a folding opportunity. 2070 Interesting = true; 2071 } 2072 } 2073 } else { 2074 // An ordinary operand. Update the map. 2075 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2076 M.insert({Ops[i], Scale}); 2077 if (Pair.second) { 2078 NewOps.push_back(Pair.first->first); 2079 } else { 2080 Pair.first->second += Scale; 2081 // The map already had an entry for this value, which may indicate 2082 // a folding opportunity. 2083 Interesting = true; 2084 } 2085 } 2086 } 2087 2088 return Interesting; 2089 } 2090 2091 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2092 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2093 // can't-overflow flags for the operation if possible. 2094 static SCEV::NoWrapFlags 2095 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2096 const ArrayRef<const SCEV *> Ops, 2097 SCEV::NoWrapFlags Flags) { 2098 using namespace std::placeholders; 2099 2100 using OBO = OverflowingBinaryOperator; 2101 2102 bool CanAnalyze = 2103 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2104 (void)CanAnalyze; 2105 assert(CanAnalyze && "don't call from other places!"); 2106 2107 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2108 SCEV::NoWrapFlags SignOrUnsignWrap = 2109 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2110 2111 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2112 auto IsKnownNonNegative = [&](const SCEV *S) { 2113 return SE->isKnownNonNegative(S); 2114 }; 2115 2116 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2117 Flags = 2118 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2119 2120 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2121 2122 if (SignOrUnsignWrap != SignOrUnsignMask && 2123 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2124 isa<SCEVConstant>(Ops[0])) { 2125 2126 auto Opcode = [&] { 2127 switch (Type) { 2128 case scAddExpr: 2129 return Instruction::Add; 2130 case scMulExpr: 2131 return Instruction::Mul; 2132 default: 2133 llvm_unreachable("Unexpected SCEV op."); 2134 } 2135 }(); 2136 2137 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2138 2139 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2140 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2141 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2142 Opcode, C, OBO::NoSignedWrap); 2143 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2144 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2145 } 2146 2147 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2148 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2149 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2150 Opcode, C, OBO::NoUnsignedWrap); 2151 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2152 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2153 } 2154 } 2155 2156 return Flags; 2157 } 2158 2159 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2160 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2161 } 2162 2163 /// Get a canonical add expression, or something simpler if possible. 2164 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2165 SCEV::NoWrapFlags Flags, 2166 unsigned Depth) { 2167 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2168 "only nuw or nsw allowed"); 2169 assert(!Ops.empty() && "Cannot get empty add!"); 2170 if (Ops.size() == 1) return Ops[0]; 2171 #ifndef NDEBUG 2172 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2173 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2174 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2175 "SCEVAddExpr operand types don't match!"); 2176 #endif 2177 2178 // Sort by complexity, this groups all similar expression types together. 2179 GroupByComplexity(Ops, &LI, DT); 2180 2181 // If there are any constants, fold them together. 2182 unsigned Idx = 0; 2183 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2184 ++Idx; 2185 assert(Idx < Ops.size()); 2186 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2187 // We found two constants, fold them together! 2188 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2189 if (Ops.size() == 2) return Ops[0]; 2190 Ops.erase(Ops.begin()+1); // Erase the folded element 2191 LHSC = cast<SCEVConstant>(Ops[0]); 2192 } 2193 2194 // If we are left with a constant zero being added, strip it off. 2195 if (LHSC->getValue()->isZero()) { 2196 Ops.erase(Ops.begin()); 2197 --Idx; 2198 } 2199 2200 if (Ops.size() == 1) return Ops[0]; 2201 } 2202 2203 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2204 2205 // Limit recursion calls depth. 2206 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2207 return getOrCreateAddExpr(Ops, Flags); 2208 2209 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2210 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2211 return S; 2212 } 2213 2214 // Okay, check to see if the same value occurs in the operand list more than 2215 // once. If so, merge them together into an multiply expression. Since we 2216 // sorted the list, these values are required to be adjacent. 2217 Type *Ty = Ops[0]->getType(); 2218 bool FoundMatch = false; 2219 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2220 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2221 // Scan ahead to count how many equal operands there are. 2222 unsigned Count = 2; 2223 while (i+Count != e && Ops[i+Count] == Ops[i]) 2224 ++Count; 2225 // Merge the values into a multiply. 2226 const SCEV *Scale = getConstant(Ty, Count); 2227 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2228 if (Ops.size() == Count) 2229 return Mul; 2230 Ops[i] = Mul; 2231 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2232 --i; e -= Count - 1; 2233 FoundMatch = true; 2234 } 2235 if (FoundMatch) 2236 return getAddExpr(Ops, Flags, Depth + 1); 2237 2238 // Check for truncates. If all the operands are truncated from the same 2239 // type, see if factoring out the truncate would permit the result to be 2240 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2241 // if the contents of the resulting outer trunc fold to something simple. 2242 auto FindTruncSrcType = [&]() -> Type * { 2243 // We're ultimately looking to fold an addrec of truncs and muls of only 2244 // constants and truncs, so if we find any other types of SCEV 2245 // as operands of the addrec then we bail and return nullptr here. 2246 // Otherwise, we return the type of the operand of a trunc that we find. 2247 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2248 return T->getOperand()->getType(); 2249 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2250 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2251 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2252 return T->getOperand()->getType(); 2253 } 2254 return nullptr; 2255 }; 2256 if (auto *SrcType = FindTruncSrcType()) { 2257 SmallVector<const SCEV *, 8> LargeOps; 2258 bool Ok = true; 2259 // Check all the operands to see if they can be represented in the 2260 // source type of the truncate. 2261 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2262 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2263 if (T->getOperand()->getType() != SrcType) { 2264 Ok = false; 2265 break; 2266 } 2267 LargeOps.push_back(T->getOperand()); 2268 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2269 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2270 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2271 SmallVector<const SCEV *, 8> LargeMulOps; 2272 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2273 if (const SCEVTruncateExpr *T = 2274 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2275 if (T->getOperand()->getType() != SrcType) { 2276 Ok = false; 2277 break; 2278 } 2279 LargeMulOps.push_back(T->getOperand()); 2280 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2281 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2282 } else { 2283 Ok = false; 2284 break; 2285 } 2286 } 2287 if (Ok) 2288 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2289 } else { 2290 Ok = false; 2291 break; 2292 } 2293 } 2294 if (Ok) { 2295 // Evaluate the expression in the larger type. 2296 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2297 // If it folds to something simple, use it. Otherwise, don't. 2298 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2299 return getTruncateExpr(Fold, Ty); 2300 } 2301 } 2302 2303 // Skip past any other cast SCEVs. 2304 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2305 ++Idx; 2306 2307 // If there are add operands they would be next. 2308 if (Idx < Ops.size()) { 2309 bool DeletedAdd = false; 2310 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2311 if (Ops.size() > AddOpsInlineThreshold || 2312 Add->getNumOperands() > AddOpsInlineThreshold) 2313 break; 2314 // If we have an add, expand the add operands onto the end of the operands 2315 // list. 2316 Ops.erase(Ops.begin()+Idx); 2317 Ops.append(Add->op_begin(), Add->op_end()); 2318 DeletedAdd = true; 2319 } 2320 2321 // If we deleted at least one add, we added operands to the end of the list, 2322 // and they are not necessarily sorted. Recurse to resort and resimplify 2323 // any operands we just acquired. 2324 if (DeletedAdd) 2325 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2326 } 2327 2328 // Skip over the add expression until we get to a multiply. 2329 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2330 ++Idx; 2331 2332 // Check to see if there are any folding opportunities present with 2333 // operands multiplied by constant values. 2334 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2335 uint64_t BitWidth = getTypeSizeInBits(Ty); 2336 DenseMap<const SCEV *, APInt> M; 2337 SmallVector<const SCEV *, 8> NewOps; 2338 APInt AccumulatedConstant(BitWidth, 0); 2339 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2340 Ops.data(), Ops.size(), 2341 APInt(BitWidth, 1), *this)) { 2342 struct APIntCompare { 2343 bool operator()(const APInt &LHS, const APInt &RHS) const { 2344 return LHS.ult(RHS); 2345 } 2346 }; 2347 2348 // Some interesting folding opportunity is present, so its worthwhile to 2349 // re-generate the operands list. Group the operands by constant scale, 2350 // to avoid multiplying by the same constant scale multiple times. 2351 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2352 for (const SCEV *NewOp : NewOps) 2353 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2354 // Re-generate the operands list. 2355 Ops.clear(); 2356 if (AccumulatedConstant != 0) 2357 Ops.push_back(getConstant(AccumulatedConstant)); 2358 for (auto &MulOp : MulOpLists) 2359 if (MulOp.first != 0) 2360 Ops.push_back(getMulExpr( 2361 getConstant(MulOp.first), 2362 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2363 SCEV::FlagAnyWrap, Depth + 1)); 2364 if (Ops.empty()) 2365 return getZero(Ty); 2366 if (Ops.size() == 1) 2367 return Ops[0]; 2368 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2369 } 2370 } 2371 2372 // If we are adding something to a multiply expression, make sure the 2373 // something is not already an operand of the multiply. If so, merge it into 2374 // the multiply. 2375 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2376 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2377 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2378 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2379 if (isa<SCEVConstant>(MulOpSCEV)) 2380 continue; 2381 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2382 if (MulOpSCEV == Ops[AddOp]) { 2383 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2384 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2385 if (Mul->getNumOperands() != 2) { 2386 // If the multiply has more than two operands, we must get the 2387 // Y*Z term. 2388 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2389 Mul->op_begin()+MulOp); 2390 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2391 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2392 } 2393 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2394 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2395 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2396 SCEV::FlagAnyWrap, Depth + 1); 2397 if (Ops.size() == 2) return OuterMul; 2398 if (AddOp < Idx) { 2399 Ops.erase(Ops.begin()+AddOp); 2400 Ops.erase(Ops.begin()+Idx-1); 2401 } else { 2402 Ops.erase(Ops.begin()+Idx); 2403 Ops.erase(Ops.begin()+AddOp-1); 2404 } 2405 Ops.push_back(OuterMul); 2406 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2407 } 2408 2409 // Check this multiply against other multiplies being added together. 2410 for (unsigned OtherMulIdx = Idx+1; 2411 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2412 ++OtherMulIdx) { 2413 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2414 // If MulOp occurs in OtherMul, we can fold the two multiplies 2415 // together. 2416 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2417 OMulOp != e; ++OMulOp) 2418 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2419 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2420 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2421 if (Mul->getNumOperands() != 2) { 2422 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2423 Mul->op_begin()+MulOp); 2424 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2425 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2426 } 2427 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2428 if (OtherMul->getNumOperands() != 2) { 2429 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2430 OtherMul->op_begin()+OMulOp); 2431 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2432 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2433 } 2434 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2435 const SCEV *InnerMulSum = 2436 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2437 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2438 SCEV::FlagAnyWrap, Depth + 1); 2439 if (Ops.size() == 2) return OuterMul; 2440 Ops.erase(Ops.begin()+Idx); 2441 Ops.erase(Ops.begin()+OtherMulIdx-1); 2442 Ops.push_back(OuterMul); 2443 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2444 } 2445 } 2446 } 2447 } 2448 2449 // If there are any add recurrences in the operands list, see if any other 2450 // added values are loop invariant. If so, we can fold them into the 2451 // recurrence. 2452 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2453 ++Idx; 2454 2455 // Scan over all recurrences, trying to fold loop invariants into them. 2456 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2457 // Scan all of the other operands to this add and add them to the vector if 2458 // they are loop invariant w.r.t. the recurrence. 2459 SmallVector<const SCEV *, 8> LIOps; 2460 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2461 const Loop *AddRecLoop = AddRec->getLoop(); 2462 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2463 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2464 LIOps.push_back(Ops[i]); 2465 Ops.erase(Ops.begin()+i); 2466 --i; --e; 2467 } 2468 2469 // If we found some loop invariants, fold them into the recurrence. 2470 if (!LIOps.empty()) { 2471 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2472 LIOps.push_back(AddRec->getStart()); 2473 2474 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2475 AddRec->op_end()); 2476 // This follows from the fact that the no-wrap flags on the outer add 2477 // expression are applicable on the 0th iteration, when the add recurrence 2478 // will be equal to its start value. 2479 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2480 2481 // Build the new addrec. Propagate the NUW and NSW flags if both the 2482 // outer add and the inner addrec are guaranteed to have no overflow. 2483 // Always propagate NW. 2484 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2485 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2486 2487 // If all of the other operands were loop invariant, we are done. 2488 if (Ops.size() == 1) return NewRec; 2489 2490 // Otherwise, add the folded AddRec by the non-invariant parts. 2491 for (unsigned i = 0;; ++i) 2492 if (Ops[i] == AddRec) { 2493 Ops[i] = NewRec; 2494 break; 2495 } 2496 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2497 } 2498 2499 // Okay, if there weren't any loop invariants to be folded, check to see if 2500 // there are multiple AddRec's with the same loop induction variable being 2501 // added together. If so, we can fold them. 2502 for (unsigned OtherIdx = Idx+1; 2503 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2504 ++OtherIdx) { 2505 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2506 // so that the 1st found AddRecExpr is dominated by all others. 2507 assert(DT.dominates( 2508 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2509 AddRec->getLoop()->getHeader()) && 2510 "AddRecExprs are not sorted in reverse dominance order?"); 2511 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2512 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2513 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2514 AddRec->op_end()); 2515 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2516 ++OtherIdx) { 2517 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2518 if (OtherAddRec->getLoop() == AddRecLoop) { 2519 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2520 i != e; ++i) { 2521 if (i >= AddRecOps.size()) { 2522 AddRecOps.append(OtherAddRec->op_begin()+i, 2523 OtherAddRec->op_end()); 2524 break; 2525 } 2526 SmallVector<const SCEV *, 2> TwoOps = { 2527 AddRecOps[i], OtherAddRec->getOperand(i)}; 2528 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2529 } 2530 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2531 } 2532 } 2533 // Step size has changed, so we cannot guarantee no self-wraparound. 2534 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2535 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2536 } 2537 } 2538 2539 // Otherwise couldn't fold anything into this recurrence. Move onto the 2540 // next one. 2541 } 2542 2543 // Okay, it looks like we really DO need an add expr. Check to see if we 2544 // already have one, otherwise create a new one. 2545 return getOrCreateAddExpr(Ops, Flags); 2546 } 2547 2548 const SCEV * 2549 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2550 SCEV::NoWrapFlags Flags) { 2551 FoldingSetNodeID ID; 2552 ID.AddInteger(scAddExpr); 2553 for (const SCEV *Op : Ops) 2554 ID.AddPointer(Op); 2555 void *IP = nullptr; 2556 SCEVAddExpr *S = 2557 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2558 if (!S) { 2559 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2560 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2561 S = new (SCEVAllocator) 2562 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2563 UniqueSCEVs.InsertNode(S, IP); 2564 addToLoopUseLists(S); 2565 } 2566 S->setNoWrapFlags(Flags); 2567 return S; 2568 } 2569 2570 const SCEV * 2571 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2572 const Loop *L, SCEV::NoWrapFlags Flags) { 2573 FoldingSetNodeID ID; 2574 ID.AddInteger(scAddRecExpr); 2575 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2576 ID.AddPointer(Ops[i]); 2577 ID.AddPointer(L); 2578 void *IP = nullptr; 2579 SCEVAddRecExpr *S = 2580 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2581 if (!S) { 2582 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2583 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2584 S = new (SCEVAllocator) 2585 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2586 UniqueSCEVs.InsertNode(S, IP); 2587 addToLoopUseLists(S); 2588 } 2589 S->setNoWrapFlags(Flags); 2590 return S; 2591 } 2592 2593 const SCEV * 2594 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2595 SCEV::NoWrapFlags Flags) { 2596 FoldingSetNodeID ID; 2597 ID.AddInteger(scMulExpr); 2598 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2599 ID.AddPointer(Ops[i]); 2600 void *IP = nullptr; 2601 SCEVMulExpr *S = 2602 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2603 if (!S) { 2604 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2605 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2606 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2607 O, Ops.size()); 2608 UniqueSCEVs.InsertNode(S, IP); 2609 addToLoopUseLists(S); 2610 } 2611 S->setNoWrapFlags(Flags); 2612 return S; 2613 } 2614 2615 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2616 uint64_t k = i*j; 2617 if (j > 1 && k / j != i) Overflow = true; 2618 return k; 2619 } 2620 2621 /// Compute the result of "n choose k", the binomial coefficient. If an 2622 /// intermediate computation overflows, Overflow will be set and the return will 2623 /// be garbage. Overflow is not cleared on absence of overflow. 2624 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2625 // We use the multiplicative formula: 2626 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2627 // At each iteration, we take the n-th term of the numeral and divide by the 2628 // (k-n)th term of the denominator. This division will always produce an 2629 // integral result, and helps reduce the chance of overflow in the 2630 // intermediate computations. However, we can still overflow even when the 2631 // final result would fit. 2632 2633 if (n == 0 || n == k) return 1; 2634 if (k > n) return 0; 2635 2636 if (k > n/2) 2637 k = n-k; 2638 2639 uint64_t r = 1; 2640 for (uint64_t i = 1; i <= k; ++i) { 2641 r = umul_ov(r, n-(i-1), Overflow); 2642 r /= i; 2643 } 2644 return r; 2645 } 2646 2647 /// Determine if any of the operands in this SCEV are a constant or if 2648 /// any of the add or multiply expressions in this SCEV contain a constant. 2649 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2650 struct FindConstantInAddMulChain { 2651 bool FoundConstant = false; 2652 2653 bool follow(const SCEV *S) { 2654 FoundConstant |= isa<SCEVConstant>(S); 2655 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2656 } 2657 2658 bool isDone() const { 2659 return FoundConstant; 2660 } 2661 }; 2662 2663 FindConstantInAddMulChain F; 2664 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2665 ST.visitAll(StartExpr); 2666 return F.FoundConstant; 2667 } 2668 2669 /// Get a canonical multiply expression, or something simpler if possible. 2670 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2671 SCEV::NoWrapFlags Flags, 2672 unsigned Depth) { 2673 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2674 "only nuw or nsw allowed"); 2675 assert(!Ops.empty() && "Cannot get empty mul!"); 2676 if (Ops.size() == 1) return Ops[0]; 2677 #ifndef NDEBUG 2678 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2679 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2680 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2681 "SCEVMulExpr operand types don't match!"); 2682 #endif 2683 2684 // Sort by complexity, this groups all similar expression types together. 2685 GroupByComplexity(Ops, &LI, DT); 2686 2687 // If there are any constants, fold them together. 2688 unsigned Idx = 0; 2689 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2690 ++Idx; 2691 assert(Idx < Ops.size()); 2692 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2693 // We found two constants, fold them together! 2694 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2695 if (Ops.size() == 2) return Ops[0]; 2696 Ops.erase(Ops.begin()+1); // Erase the folded element 2697 LHSC = cast<SCEVConstant>(Ops[0]); 2698 } 2699 2700 // If we have a multiply of zero, it will always be zero. 2701 if (LHSC->getValue()->isZero()) 2702 return LHSC; 2703 2704 // If we are left with a constant one being multiplied, strip it off. 2705 if (LHSC->getValue()->isOne()) { 2706 Ops.erase(Ops.begin()); 2707 --Idx; 2708 } 2709 2710 if (Ops.size() == 1) 2711 return Ops[0]; 2712 } 2713 2714 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2715 2716 // Limit recursion calls depth. 2717 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2718 return getOrCreateMulExpr(Ops, Flags); 2719 2720 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2721 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2722 return S; 2723 } 2724 2725 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2726 if (Ops.size() == 2) { 2727 // C1*(C2+V) -> C1*C2 + C1*V 2728 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2729 // If any of Add's ops are Adds or Muls with a constant, apply this 2730 // transformation as well. 2731 // 2732 // TODO: There are some cases where this transformation is not 2733 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2734 // this transformation should be narrowed down. 2735 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2736 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2737 SCEV::FlagAnyWrap, Depth + 1), 2738 getMulExpr(LHSC, Add->getOperand(1), 2739 SCEV::FlagAnyWrap, Depth + 1), 2740 SCEV::FlagAnyWrap, Depth + 1); 2741 2742 if (Ops[0]->isAllOnesValue()) { 2743 // If we have a mul by -1 of an add, try distributing the -1 among the 2744 // add operands. 2745 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2746 SmallVector<const SCEV *, 4> NewOps; 2747 bool AnyFolded = false; 2748 for (const SCEV *AddOp : Add->operands()) { 2749 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2750 Depth + 1); 2751 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2752 NewOps.push_back(Mul); 2753 } 2754 if (AnyFolded) 2755 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2756 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2757 // Negation preserves a recurrence's no self-wrap property. 2758 SmallVector<const SCEV *, 4> Operands; 2759 for (const SCEV *AddRecOp : AddRec->operands()) 2760 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2761 Depth + 1)); 2762 2763 return getAddRecExpr(Operands, AddRec->getLoop(), 2764 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2765 } 2766 } 2767 } 2768 } 2769 2770 // Skip over the add expression until we get to a multiply. 2771 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2772 ++Idx; 2773 2774 // If there are mul operands inline them all into this expression. 2775 if (Idx < Ops.size()) { 2776 bool DeletedMul = false; 2777 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2778 if (Ops.size() > MulOpsInlineThreshold) 2779 break; 2780 // If we have an mul, expand the mul operands onto the end of the 2781 // operands list. 2782 Ops.erase(Ops.begin()+Idx); 2783 Ops.append(Mul->op_begin(), Mul->op_end()); 2784 DeletedMul = true; 2785 } 2786 2787 // If we deleted at least one mul, we added operands to the end of the 2788 // list, and they are not necessarily sorted. Recurse to resort and 2789 // resimplify any operands we just acquired. 2790 if (DeletedMul) 2791 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2792 } 2793 2794 // If there are any add recurrences in the operands list, see if any other 2795 // added values are loop invariant. If so, we can fold them into the 2796 // recurrence. 2797 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2798 ++Idx; 2799 2800 // Scan over all recurrences, trying to fold loop invariants into them. 2801 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2802 // Scan all of the other operands to this mul and add them to the vector 2803 // if they are loop invariant w.r.t. the recurrence. 2804 SmallVector<const SCEV *, 8> LIOps; 2805 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2806 const Loop *AddRecLoop = AddRec->getLoop(); 2807 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2808 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2809 LIOps.push_back(Ops[i]); 2810 Ops.erase(Ops.begin()+i); 2811 --i; --e; 2812 } 2813 2814 // If we found some loop invariants, fold them into the recurrence. 2815 if (!LIOps.empty()) { 2816 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2817 SmallVector<const SCEV *, 4> NewOps; 2818 NewOps.reserve(AddRec->getNumOperands()); 2819 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2820 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2821 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2822 SCEV::FlagAnyWrap, Depth + 1)); 2823 2824 // Build the new addrec. Propagate the NUW and NSW flags if both the 2825 // outer mul and the inner addrec are guaranteed to have no overflow. 2826 // 2827 // No self-wrap cannot be guaranteed after changing the step size, but 2828 // will be inferred if either NUW or NSW is true. 2829 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2830 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2831 2832 // If all of the other operands were loop invariant, we are done. 2833 if (Ops.size() == 1) return NewRec; 2834 2835 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2836 for (unsigned i = 0;; ++i) 2837 if (Ops[i] == AddRec) { 2838 Ops[i] = NewRec; 2839 break; 2840 } 2841 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2842 } 2843 2844 // Okay, if there weren't any loop invariants to be folded, check to see 2845 // if there are multiple AddRec's with the same loop induction variable 2846 // being multiplied together. If so, we can fold them. 2847 2848 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2849 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2850 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2851 // ]]],+,...up to x=2n}. 2852 // Note that the arguments to choose() are always integers with values 2853 // known at compile time, never SCEV objects. 2854 // 2855 // The implementation avoids pointless extra computations when the two 2856 // addrec's are of different length (mathematically, it's equivalent to 2857 // an infinite stream of zeros on the right). 2858 bool OpsModified = false; 2859 for (unsigned OtherIdx = Idx+1; 2860 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2861 ++OtherIdx) { 2862 const SCEVAddRecExpr *OtherAddRec = 2863 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2864 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2865 continue; 2866 2867 // Limit max number of arguments to avoid creation of unreasonably big 2868 // SCEVAddRecs with very complex operands. 2869 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2870 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 2871 continue; 2872 2873 bool Overflow = false; 2874 Type *Ty = AddRec->getType(); 2875 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2876 SmallVector<const SCEV*, 7> AddRecOps; 2877 for (int x = 0, xe = AddRec->getNumOperands() + 2878 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2879 SmallVector <const SCEV *, 7> SumOps; 2880 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2881 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2882 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2883 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2884 z < ze && !Overflow; ++z) { 2885 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2886 uint64_t Coeff; 2887 if (LargerThan64Bits) 2888 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2889 else 2890 Coeff = Coeff1*Coeff2; 2891 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2892 const SCEV *Term1 = AddRec->getOperand(y-z); 2893 const SCEV *Term2 = OtherAddRec->getOperand(z); 2894 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 2895 SCEV::FlagAnyWrap, Depth + 1)); 2896 } 2897 } 2898 if (SumOps.empty()) 2899 SumOps.push_back(getZero(Ty)); 2900 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 2901 } 2902 if (!Overflow) { 2903 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 2904 SCEV::FlagAnyWrap); 2905 if (Ops.size() == 2) return NewAddRec; 2906 Ops[Idx] = NewAddRec; 2907 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2908 OpsModified = true; 2909 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2910 if (!AddRec) 2911 break; 2912 } 2913 } 2914 if (OpsModified) 2915 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2916 2917 // Otherwise couldn't fold anything into this recurrence. Move onto the 2918 // next one. 2919 } 2920 2921 // Okay, it looks like we really DO need an mul expr. Check to see if we 2922 // already have one, otherwise create a new one. 2923 return getOrCreateMulExpr(Ops, Flags); 2924 } 2925 2926 /// Represents an unsigned remainder expression based on unsigned division. 2927 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2928 const SCEV *RHS) { 2929 assert(getEffectiveSCEVType(LHS->getType()) == 2930 getEffectiveSCEVType(RHS->getType()) && 2931 "SCEVURemExpr operand types don't match!"); 2932 2933 // Short-circuit easy cases 2934 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2935 // If constant is one, the result is trivial 2936 if (RHSC->getValue()->isOne()) 2937 return getZero(LHS->getType()); // X urem 1 --> 0 2938 2939 // If constant is a power of two, fold into a zext(trunc(LHS)). 2940 if (RHSC->getAPInt().isPowerOf2()) { 2941 Type *FullTy = LHS->getType(); 2942 Type *TruncTy = 2943 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2944 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2945 } 2946 } 2947 2948 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2949 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2950 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2951 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2952 } 2953 2954 /// Get a canonical unsigned division expression, or something simpler if 2955 /// possible. 2956 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2957 const SCEV *RHS) { 2958 assert(getEffectiveSCEVType(LHS->getType()) == 2959 getEffectiveSCEVType(RHS->getType()) && 2960 "SCEVUDivExpr operand types don't match!"); 2961 2962 FoldingSetNodeID ID; 2963 ID.AddInteger(scUDivExpr); 2964 ID.AddPointer(LHS); 2965 ID.AddPointer(RHS); 2966 void *IP = nullptr; 2967 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 2968 return S; 2969 2970 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2971 if (RHSC->getValue()->isOne()) 2972 return LHS; // X udiv 1 --> x 2973 // If the denominator is zero, the result of the udiv is undefined. Don't 2974 // try to analyze it, because the resolution chosen here may differ from 2975 // the resolution chosen in other parts of the compiler. 2976 if (!RHSC->getValue()->isZero()) { 2977 // Determine if the division can be folded into the operands of 2978 // its operands. 2979 // TODO: Generalize this to non-constants by using known-bits information. 2980 Type *Ty = LHS->getType(); 2981 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2982 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2983 // For non-power-of-two values, effectively round the value up to the 2984 // nearest power of two. 2985 if (!RHSC->getAPInt().isPowerOf2()) 2986 ++MaxShiftAmt; 2987 IntegerType *ExtTy = 2988 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2989 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2990 if (const SCEVConstant *Step = 2991 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2992 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2993 const APInt &StepInt = Step->getAPInt(); 2994 const APInt &DivInt = RHSC->getAPInt(); 2995 if (!StepInt.urem(DivInt) && 2996 getZeroExtendExpr(AR, ExtTy) == 2997 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2998 getZeroExtendExpr(Step, ExtTy), 2999 AR->getLoop(), SCEV::FlagAnyWrap)) { 3000 SmallVector<const SCEV *, 4> Operands; 3001 for (const SCEV *Op : AR->operands()) 3002 Operands.push_back(getUDivExpr(Op, RHS)); 3003 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3004 } 3005 /// Get a canonical UDivExpr for a recurrence. 3006 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3007 // We can currently only fold X%N if X is constant. 3008 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3009 if (StartC && !DivInt.urem(StepInt) && 3010 getZeroExtendExpr(AR, ExtTy) == 3011 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3012 getZeroExtendExpr(Step, ExtTy), 3013 AR->getLoop(), SCEV::FlagAnyWrap)) { 3014 const APInt &StartInt = StartC->getAPInt(); 3015 const APInt &StartRem = StartInt.urem(StepInt); 3016 if (StartRem != 0) { 3017 const SCEV *NewLHS = 3018 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3019 AR->getLoop(), SCEV::FlagNW); 3020 if (LHS != NewLHS) { 3021 LHS = NewLHS; 3022 3023 // Reset the ID to include the new LHS, and check if it is 3024 // already cached. 3025 ID.clear(); 3026 ID.AddInteger(scUDivExpr); 3027 ID.AddPointer(LHS); 3028 ID.AddPointer(RHS); 3029 IP = nullptr; 3030 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3031 return S; 3032 } 3033 } 3034 } 3035 } 3036 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3037 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3038 SmallVector<const SCEV *, 4> Operands; 3039 for (const SCEV *Op : M->operands()) 3040 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3041 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3042 // Find an operand that's safely divisible. 3043 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3044 const SCEV *Op = M->getOperand(i); 3045 const SCEV *Div = getUDivExpr(Op, RHSC); 3046 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3047 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3048 M->op_end()); 3049 Operands[i] = Div; 3050 return getMulExpr(Operands); 3051 } 3052 } 3053 } 3054 3055 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3056 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3057 if (auto *DivisorConstant = 3058 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3059 bool Overflow = false; 3060 APInt NewRHS = 3061 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3062 if (Overflow) { 3063 return getConstant(RHSC->getType(), 0, false); 3064 } 3065 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3066 } 3067 } 3068 3069 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3070 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3071 SmallVector<const SCEV *, 4> Operands; 3072 for (const SCEV *Op : A->operands()) 3073 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3074 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3075 Operands.clear(); 3076 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3077 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3078 if (isa<SCEVUDivExpr>(Op) || 3079 getMulExpr(Op, RHS) != A->getOperand(i)) 3080 break; 3081 Operands.push_back(Op); 3082 } 3083 if (Operands.size() == A->getNumOperands()) 3084 return getAddExpr(Operands); 3085 } 3086 } 3087 3088 // Fold if both operands are constant. 3089 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3090 Constant *LHSCV = LHSC->getValue(); 3091 Constant *RHSCV = RHSC->getValue(); 3092 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3093 RHSCV))); 3094 } 3095 } 3096 } 3097 3098 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3099 // changes). Make sure we get a new one. 3100 IP = nullptr; 3101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3102 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3103 LHS, RHS); 3104 UniqueSCEVs.InsertNode(S, IP); 3105 addToLoopUseLists(S); 3106 return S; 3107 } 3108 3109 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3110 APInt A = C1->getAPInt().abs(); 3111 APInt B = C2->getAPInt().abs(); 3112 uint32_t ABW = A.getBitWidth(); 3113 uint32_t BBW = B.getBitWidth(); 3114 3115 if (ABW > BBW) 3116 B = B.zext(ABW); 3117 else if (ABW < BBW) 3118 A = A.zext(BBW); 3119 3120 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3121 } 3122 3123 /// Get a canonical unsigned division expression, or something simpler if 3124 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3125 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3126 /// it's not exact because the udiv may be clearing bits. 3127 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3128 const SCEV *RHS) { 3129 // TODO: we could try to find factors in all sorts of things, but for now we 3130 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3131 // end of this file for inspiration. 3132 3133 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3134 if (!Mul || !Mul->hasNoUnsignedWrap()) 3135 return getUDivExpr(LHS, RHS); 3136 3137 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3138 // If the mulexpr multiplies by a constant, then that constant must be the 3139 // first element of the mulexpr. 3140 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3141 if (LHSCst == RHSCst) { 3142 SmallVector<const SCEV *, 2> Operands; 3143 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3144 return getMulExpr(Operands); 3145 } 3146 3147 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3148 // that there's a factor provided by one of the other terms. We need to 3149 // check. 3150 APInt Factor = gcd(LHSCst, RHSCst); 3151 if (!Factor.isIntN(1)) { 3152 LHSCst = 3153 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3154 RHSCst = 3155 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3156 SmallVector<const SCEV *, 2> Operands; 3157 Operands.push_back(LHSCst); 3158 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3159 LHS = getMulExpr(Operands); 3160 RHS = RHSCst; 3161 Mul = dyn_cast<SCEVMulExpr>(LHS); 3162 if (!Mul) 3163 return getUDivExactExpr(LHS, RHS); 3164 } 3165 } 3166 } 3167 3168 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3169 if (Mul->getOperand(i) == RHS) { 3170 SmallVector<const SCEV *, 2> Operands; 3171 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3172 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3173 return getMulExpr(Operands); 3174 } 3175 } 3176 3177 return getUDivExpr(LHS, RHS); 3178 } 3179 3180 /// Get an add recurrence expression for the specified loop. Simplify the 3181 /// expression as much as possible. 3182 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3183 const Loop *L, 3184 SCEV::NoWrapFlags Flags) { 3185 SmallVector<const SCEV *, 4> Operands; 3186 Operands.push_back(Start); 3187 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3188 if (StepChrec->getLoop() == L) { 3189 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3190 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3191 } 3192 3193 Operands.push_back(Step); 3194 return getAddRecExpr(Operands, L, Flags); 3195 } 3196 3197 /// Get an add recurrence expression for the specified loop. Simplify the 3198 /// expression as much as possible. 3199 const SCEV * 3200 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3201 const Loop *L, SCEV::NoWrapFlags Flags) { 3202 if (Operands.size() == 1) return Operands[0]; 3203 #ifndef NDEBUG 3204 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3205 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3206 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3207 "SCEVAddRecExpr operand types don't match!"); 3208 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3209 assert(isLoopInvariant(Operands[i], L) && 3210 "SCEVAddRecExpr operand is not loop-invariant!"); 3211 #endif 3212 3213 if (Operands.back()->isZero()) { 3214 Operands.pop_back(); 3215 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3216 } 3217 3218 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3219 // use that information to infer NUW and NSW flags. However, computing a 3220 // BE count requires calling getAddRecExpr, so we may not yet have a 3221 // meaningful BE count at this point (and if we don't, we'd be stuck 3222 // with a SCEVCouldNotCompute as the cached BE count). 3223 3224 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3225 3226 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3227 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3228 const Loop *NestedLoop = NestedAR->getLoop(); 3229 if (L->contains(NestedLoop) 3230 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3231 : (!NestedLoop->contains(L) && 3232 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3233 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3234 NestedAR->op_end()); 3235 Operands[0] = NestedAR->getStart(); 3236 // AddRecs require their operands be loop-invariant with respect to their 3237 // loops. Don't perform this transformation if it would break this 3238 // requirement. 3239 bool AllInvariant = all_of( 3240 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3241 3242 if (AllInvariant) { 3243 // Create a recurrence for the outer loop with the same step size. 3244 // 3245 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3246 // inner recurrence has the same property. 3247 SCEV::NoWrapFlags OuterFlags = 3248 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3249 3250 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3251 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3252 return isLoopInvariant(Op, NestedLoop); 3253 }); 3254 3255 if (AllInvariant) { 3256 // Ok, both add recurrences are valid after the transformation. 3257 // 3258 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3259 // the outer recurrence has the same property. 3260 SCEV::NoWrapFlags InnerFlags = 3261 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3262 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3263 } 3264 } 3265 // Reset Operands to its original state. 3266 Operands[0] = NestedAR; 3267 } 3268 } 3269 3270 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3271 // already have one, otherwise create a new one. 3272 return getOrCreateAddRecExpr(Operands, L, Flags); 3273 } 3274 3275 const SCEV * 3276 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3277 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3278 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3279 // getSCEV(Base)->getType() has the same address space as Base->getType() 3280 // because SCEV::getType() preserves the address space. 3281 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3282 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3283 // instruction to its SCEV, because the Instruction may be guarded by control 3284 // flow and the no-overflow bits may not be valid for the expression in any 3285 // context. This can be fixed similarly to how these flags are handled for 3286 // adds. 3287 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3288 : SCEV::FlagAnyWrap; 3289 3290 const SCEV *TotalOffset = getZero(IntIdxTy); 3291 Type *CurTy = GEP->getType(); 3292 bool FirstIter = true; 3293 for (const SCEV *IndexExpr : IndexExprs) { 3294 // Compute the (potentially symbolic) offset in bytes for this index. 3295 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3296 // For a struct, add the member offset. 3297 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3298 unsigned FieldNo = Index->getZExtValue(); 3299 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3300 3301 // Add the field offset to the running total offset. 3302 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3303 3304 // Update CurTy to the type of the field at Index. 3305 CurTy = STy->getTypeAtIndex(Index); 3306 } else { 3307 // Update CurTy to its element type. 3308 if (FirstIter) { 3309 assert(isa<PointerType>(CurTy) && 3310 "The first index of a GEP indexes a pointer"); 3311 CurTy = GEP->getSourceElementType(); 3312 FirstIter = false; 3313 } else { 3314 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3315 } 3316 // For an array, add the element offset, explicitly scaled. 3317 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3318 // Getelementptr indices are signed. 3319 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3320 3321 // Multiply the index by the element size to compute the element offset. 3322 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3323 3324 // Add the element offset to the running total offset. 3325 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3326 } 3327 } 3328 3329 // Add the total offset from all the GEP indices to the base. 3330 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3331 } 3332 3333 std::tuple<SCEV *, FoldingSetNodeID, void *> 3334 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3335 ArrayRef<const SCEV *> Ops) { 3336 FoldingSetNodeID ID; 3337 void *IP = nullptr; 3338 ID.AddInteger(SCEVType); 3339 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3340 ID.AddPointer(Ops[i]); 3341 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3342 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3343 } 3344 3345 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3346 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3347 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3348 } 3349 3350 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3351 Type *Ty = Op->getType(); 3352 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3353 } 3354 3355 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3356 SmallVectorImpl<const SCEV *> &Ops) { 3357 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3358 if (Ops.size() == 1) return Ops[0]; 3359 #ifndef NDEBUG 3360 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3361 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3362 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3363 "Operand types don't match!"); 3364 #endif 3365 3366 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3367 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3368 3369 // Sort by complexity, this groups all similar expression types together. 3370 GroupByComplexity(Ops, &LI, DT); 3371 3372 // Check if we have created the same expression before. 3373 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3374 return S; 3375 } 3376 3377 // If there are any constants, fold them together. 3378 unsigned Idx = 0; 3379 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3380 ++Idx; 3381 assert(Idx < Ops.size()); 3382 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3383 if (Kind == scSMaxExpr) 3384 return APIntOps::smax(LHS, RHS); 3385 else if (Kind == scSMinExpr) 3386 return APIntOps::smin(LHS, RHS); 3387 else if (Kind == scUMaxExpr) 3388 return APIntOps::umax(LHS, RHS); 3389 else if (Kind == scUMinExpr) 3390 return APIntOps::umin(LHS, RHS); 3391 llvm_unreachable("Unknown SCEV min/max opcode"); 3392 }; 3393 3394 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3395 // We found two constants, fold them together! 3396 ConstantInt *Fold = ConstantInt::get( 3397 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3398 Ops[0] = getConstant(Fold); 3399 Ops.erase(Ops.begin()+1); // Erase the folded element 3400 if (Ops.size() == 1) return Ops[0]; 3401 LHSC = cast<SCEVConstant>(Ops[0]); 3402 } 3403 3404 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3405 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3406 3407 if (IsMax ? IsMinV : IsMaxV) { 3408 // If we are left with a constant minimum(/maximum)-int, strip it off. 3409 Ops.erase(Ops.begin()); 3410 --Idx; 3411 } else if (IsMax ? IsMaxV : IsMinV) { 3412 // If we have a max(/min) with a constant maximum(/minimum)-int, 3413 // it will always be the extremum. 3414 return LHSC; 3415 } 3416 3417 if (Ops.size() == 1) return Ops[0]; 3418 } 3419 3420 // Find the first operation of the same kind 3421 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3422 ++Idx; 3423 3424 // Check to see if one of the operands is of the same kind. If so, expand its 3425 // operands onto our operand list, and recurse to simplify. 3426 if (Idx < Ops.size()) { 3427 bool DeletedAny = false; 3428 while (Ops[Idx]->getSCEVType() == Kind) { 3429 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3430 Ops.erase(Ops.begin()+Idx); 3431 Ops.append(SMME->op_begin(), SMME->op_end()); 3432 DeletedAny = true; 3433 } 3434 3435 if (DeletedAny) 3436 return getMinMaxExpr(Kind, Ops); 3437 } 3438 3439 // Okay, check to see if the same value occurs in the operand list twice. If 3440 // so, delete one. Since we sorted the list, these values are required to 3441 // be adjacent. 3442 llvm::CmpInst::Predicate GEPred = 3443 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3444 llvm::CmpInst::Predicate LEPred = 3445 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3446 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3447 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3448 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3449 if (Ops[i] == Ops[i + 1] || 3450 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3451 // X op Y op Y --> X op Y 3452 // X op Y --> X, if we know X, Y are ordered appropriately 3453 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3454 --i; 3455 --e; 3456 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3457 Ops[i + 1])) { 3458 // X op Y --> Y, if we know X, Y are ordered appropriately 3459 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3460 --i; 3461 --e; 3462 } 3463 } 3464 3465 if (Ops.size() == 1) return Ops[0]; 3466 3467 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3468 3469 // Okay, it looks like we really DO need an expr. Check to see if we 3470 // already have one, otherwise create a new one. 3471 const SCEV *ExistingSCEV; 3472 FoldingSetNodeID ID; 3473 void *IP; 3474 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3475 if (ExistingSCEV) 3476 return ExistingSCEV; 3477 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3478 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3479 SCEV *S = new (SCEVAllocator) 3480 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3481 3482 UniqueSCEVs.InsertNode(S, IP); 3483 addToLoopUseLists(S); 3484 return S; 3485 } 3486 3487 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3488 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3489 return getSMaxExpr(Ops); 3490 } 3491 3492 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3493 return getMinMaxExpr(scSMaxExpr, Ops); 3494 } 3495 3496 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3497 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3498 return getUMaxExpr(Ops); 3499 } 3500 3501 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3502 return getMinMaxExpr(scUMaxExpr, Ops); 3503 } 3504 3505 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3506 const SCEV *RHS) { 3507 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3508 return getSMinExpr(Ops); 3509 } 3510 3511 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3512 return getMinMaxExpr(scSMinExpr, Ops); 3513 } 3514 3515 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3516 const SCEV *RHS) { 3517 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3518 return getUMinExpr(Ops); 3519 } 3520 3521 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3522 return getMinMaxExpr(scUMinExpr, Ops); 3523 } 3524 3525 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3526 // We can bypass creating a target-independent 3527 // constant expression and then folding it back into a ConstantInt. 3528 // This is just a compile-time optimization. 3529 if (isa<ScalableVectorType>(AllocTy)) { 3530 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3531 Constant *One = ConstantInt::get(IntTy, 1); 3532 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3533 return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); 3534 } 3535 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3536 } 3537 3538 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3539 StructType *STy, 3540 unsigned FieldNo) { 3541 // We can bypass creating a target-independent 3542 // constant expression and then folding it back into a ConstantInt. 3543 // This is just a compile-time optimization. 3544 return getConstant( 3545 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3546 } 3547 3548 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3549 // Don't attempt to do anything other than create a SCEVUnknown object 3550 // here. createSCEV only calls getUnknown after checking for all other 3551 // interesting possibilities, and any other code that calls getUnknown 3552 // is doing so in order to hide a value from SCEV canonicalization. 3553 3554 FoldingSetNodeID ID; 3555 ID.AddInteger(scUnknown); 3556 ID.AddPointer(V); 3557 void *IP = nullptr; 3558 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3559 assert(cast<SCEVUnknown>(S)->getValue() == V && 3560 "Stale SCEVUnknown in uniquing map!"); 3561 return S; 3562 } 3563 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3564 FirstUnknown); 3565 FirstUnknown = cast<SCEVUnknown>(S); 3566 UniqueSCEVs.InsertNode(S, IP); 3567 return S; 3568 } 3569 3570 //===----------------------------------------------------------------------===// 3571 // Basic SCEV Analysis and PHI Idiom Recognition Code 3572 // 3573 3574 /// Test if values of the given type are analyzable within the SCEV 3575 /// framework. This primarily includes integer types, and it can optionally 3576 /// include pointer types if the ScalarEvolution class has access to 3577 /// target-specific information. 3578 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3579 // Integers and pointers are always SCEVable. 3580 return Ty->isIntOrPtrTy(); 3581 } 3582 3583 /// Return the size in bits of the specified type, for which isSCEVable must 3584 /// return true. 3585 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3586 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3587 if (Ty->isPointerTy()) 3588 return getDataLayout().getIndexTypeSizeInBits(Ty); 3589 return getDataLayout().getTypeSizeInBits(Ty); 3590 } 3591 3592 /// Return a type with the same bitwidth as the given type and which represents 3593 /// how SCEV will treat the given type, for which isSCEVable must return 3594 /// true. For pointer types, this is the pointer index sized integer type. 3595 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3596 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3597 3598 if (Ty->isIntegerTy()) 3599 return Ty; 3600 3601 // The only other support type is pointer. 3602 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3603 return getDataLayout().getIndexType(Ty); 3604 } 3605 3606 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3607 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3608 } 3609 3610 const SCEV *ScalarEvolution::getCouldNotCompute() { 3611 return CouldNotCompute.get(); 3612 } 3613 3614 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3615 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3616 auto *SU = dyn_cast<SCEVUnknown>(S); 3617 return SU && SU->getValue() == nullptr; 3618 }); 3619 3620 return !ContainsNulls; 3621 } 3622 3623 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3624 HasRecMapType::iterator I = HasRecMap.find(S); 3625 if (I != HasRecMap.end()) 3626 return I->second; 3627 3628 bool FoundAddRec = 3629 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3630 HasRecMap.insert({S, FoundAddRec}); 3631 return FoundAddRec; 3632 } 3633 3634 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3635 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3636 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3637 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3638 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3639 if (!Add) 3640 return {S, nullptr}; 3641 3642 if (Add->getNumOperands() != 2) 3643 return {S, nullptr}; 3644 3645 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3646 if (!ConstOp) 3647 return {S, nullptr}; 3648 3649 return {Add->getOperand(1), ConstOp->getValue()}; 3650 } 3651 3652 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3653 /// by the value and offset from any ValueOffsetPair in the set. 3654 SetVector<ScalarEvolution::ValueOffsetPair> * 3655 ScalarEvolution::getSCEVValues(const SCEV *S) { 3656 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3657 if (SI == ExprValueMap.end()) 3658 return nullptr; 3659 #ifndef NDEBUG 3660 if (VerifySCEVMap) { 3661 // Check there is no dangling Value in the set returned. 3662 for (const auto &VE : SI->second) 3663 assert(ValueExprMap.count(VE.first)); 3664 } 3665 #endif 3666 return &SI->second; 3667 } 3668 3669 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3670 /// cannot be used separately. eraseValueFromMap should be used to remove 3671 /// V from ValueExprMap and ExprValueMap at the same time. 3672 void ScalarEvolution::eraseValueFromMap(Value *V) { 3673 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3674 if (I != ValueExprMap.end()) { 3675 const SCEV *S = I->second; 3676 // Remove {V, 0} from the set of ExprValueMap[S] 3677 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3678 SV->remove({V, nullptr}); 3679 3680 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3681 const SCEV *Stripped; 3682 ConstantInt *Offset; 3683 std::tie(Stripped, Offset) = splitAddExpr(S); 3684 if (Offset != nullptr) { 3685 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3686 SV->remove({V, Offset}); 3687 } 3688 ValueExprMap.erase(V); 3689 } 3690 } 3691 3692 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3693 /// TODO: In reality it is better to check the poison recursively 3694 /// but this is better than nothing. 3695 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3696 if (auto *I = dyn_cast<Instruction>(V)) { 3697 if (isa<OverflowingBinaryOperator>(I)) { 3698 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3699 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3700 return true; 3701 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3702 return true; 3703 } 3704 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3705 return true; 3706 } 3707 return false; 3708 } 3709 3710 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3711 /// create a new one. 3712 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3713 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3714 3715 const SCEV *S = getExistingSCEV(V); 3716 if (S == nullptr) { 3717 S = createSCEV(V); 3718 // During PHI resolution, it is possible to create two SCEVs for the same 3719 // V, so it is needed to double check whether V->S is inserted into 3720 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3721 std::pair<ValueExprMapType::iterator, bool> Pair = 3722 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3723 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3724 ExprValueMap[S].insert({V, nullptr}); 3725 3726 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3727 // ExprValueMap. 3728 const SCEV *Stripped = S; 3729 ConstantInt *Offset = nullptr; 3730 std::tie(Stripped, Offset) = splitAddExpr(S); 3731 // If stripped is SCEVUnknown, don't bother to save 3732 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3733 // increase the complexity of the expansion code. 3734 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3735 // because it may generate add/sub instead of GEP in SCEV expansion. 3736 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3737 !isa<GetElementPtrInst>(V)) 3738 ExprValueMap[Stripped].insert({V, Offset}); 3739 } 3740 } 3741 return S; 3742 } 3743 3744 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3745 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3746 3747 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3748 if (I != ValueExprMap.end()) { 3749 const SCEV *S = I->second; 3750 if (checkValidity(S)) 3751 return S; 3752 eraseValueFromMap(V); 3753 forgetMemoizedResults(S); 3754 } 3755 return nullptr; 3756 } 3757 3758 /// Return a SCEV corresponding to -V = -1*V 3759 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3760 SCEV::NoWrapFlags Flags) { 3761 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3762 return getConstant( 3763 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3764 3765 Type *Ty = V->getType(); 3766 Ty = getEffectiveSCEVType(Ty); 3767 return getMulExpr(V, getMinusOne(Ty), Flags); 3768 } 3769 3770 /// If Expr computes ~A, return A else return nullptr 3771 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3772 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3773 if (!Add || Add->getNumOperands() != 2 || 3774 !Add->getOperand(0)->isAllOnesValue()) 3775 return nullptr; 3776 3777 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3778 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3779 !AddRHS->getOperand(0)->isAllOnesValue()) 3780 return nullptr; 3781 3782 return AddRHS->getOperand(1); 3783 } 3784 3785 /// Return a SCEV corresponding to ~V = -1-V 3786 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3787 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3788 return getConstant( 3789 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3790 3791 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3792 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3793 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3794 SmallVector<const SCEV *, 2> MatchedOperands; 3795 for (const SCEV *Operand : MME->operands()) { 3796 const SCEV *Matched = MatchNotExpr(Operand); 3797 if (!Matched) 3798 return (const SCEV *)nullptr; 3799 MatchedOperands.push_back(Matched); 3800 } 3801 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3802 MatchedOperands); 3803 }; 3804 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3805 return Replaced; 3806 } 3807 3808 Type *Ty = V->getType(); 3809 Ty = getEffectiveSCEVType(Ty); 3810 return getMinusSCEV(getMinusOne(Ty), V); 3811 } 3812 3813 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3814 SCEV::NoWrapFlags Flags, 3815 unsigned Depth) { 3816 // Fast path: X - X --> 0. 3817 if (LHS == RHS) 3818 return getZero(LHS->getType()); 3819 3820 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3821 // makes it so that we cannot make much use of NUW. 3822 auto AddFlags = SCEV::FlagAnyWrap; 3823 const bool RHSIsNotMinSigned = 3824 !getSignedRangeMin(RHS).isMinSignedValue(); 3825 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3826 // Let M be the minimum representable signed value. Then (-1)*RHS 3827 // signed-wraps if and only if RHS is M. That can happen even for 3828 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3829 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3830 // (-1)*RHS, we need to prove that RHS != M. 3831 // 3832 // If LHS is non-negative and we know that LHS - RHS does not 3833 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3834 // either by proving that RHS > M or that LHS >= 0. 3835 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3836 AddFlags = SCEV::FlagNSW; 3837 } 3838 } 3839 3840 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3841 // RHS is NSW and LHS >= 0. 3842 // 3843 // The difficulty here is that the NSW flag may have been proven 3844 // relative to a loop that is to be found in a recurrence in LHS and 3845 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3846 // larger scope than intended. 3847 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3848 3849 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3850 } 3851 3852 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3853 unsigned Depth) { 3854 Type *SrcTy = V->getType(); 3855 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3856 "Cannot truncate or zero extend with non-integer arguments!"); 3857 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3858 return V; // No conversion 3859 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3860 return getTruncateExpr(V, Ty, Depth); 3861 return getZeroExtendExpr(V, Ty, Depth); 3862 } 3863 3864 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 3865 unsigned Depth) { 3866 Type *SrcTy = V->getType(); 3867 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3868 "Cannot truncate or zero extend with non-integer arguments!"); 3869 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3870 return V; // No conversion 3871 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3872 return getTruncateExpr(V, Ty, Depth); 3873 return getSignExtendExpr(V, Ty, Depth); 3874 } 3875 3876 const SCEV * 3877 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3878 Type *SrcTy = V->getType(); 3879 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3880 "Cannot noop or zero extend with non-integer arguments!"); 3881 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3882 "getNoopOrZeroExtend cannot truncate!"); 3883 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3884 return V; // No conversion 3885 return getZeroExtendExpr(V, Ty); 3886 } 3887 3888 const SCEV * 3889 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3890 Type *SrcTy = V->getType(); 3891 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3892 "Cannot noop or sign extend with non-integer arguments!"); 3893 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3894 "getNoopOrSignExtend cannot truncate!"); 3895 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3896 return V; // No conversion 3897 return getSignExtendExpr(V, Ty); 3898 } 3899 3900 const SCEV * 3901 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3902 Type *SrcTy = V->getType(); 3903 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3904 "Cannot noop or any extend with non-integer arguments!"); 3905 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3906 "getNoopOrAnyExtend cannot truncate!"); 3907 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3908 return V; // No conversion 3909 return getAnyExtendExpr(V, Ty); 3910 } 3911 3912 const SCEV * 3913 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3914 Type *SrcTy = V->getType(); 3915 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3916 "Cannot truncate or noop with non-integer arguments!"); 3917 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3918 "getTruncateOrNoop cannot extend!"); 3919 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3920 return V; // No conversion 3921 return getTruncateExpr(V, Ty); 3922 } 3923 3924 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3925 const SCEV *RHS) { 3926 const SCEV *PromotedLHS = LHS; 3927 const SCEV *PromotedRHS = RHS; 3928 3929 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3930 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3931 else 3932 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3933 3934 return getUMaxExpr(PromotedLHS, PromotedRHS); 3935 } 3936 3937 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3938 const SCEV *RHS) { 3939 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3940 return getUMinFromMismatchedTypes(Ops); 3941 } 3942 3943 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 3944 SmallVectorImpl<const SCEV *> &Ops) { 3945 assert(!Ops.empty() && "At least one operand must be!"); 3946 // Trivial case. 3947 if (Ops.size() == 1) 3948 return Ops[0]; 3949 3950 // Find the max type first. 3951 Type *MaxType = nullptr; 3952 for (auto *S : Ops) 3953 if (MaxType) 3954 MaxType = getWiderType(MaxType, S->getType()); 3955 else 3956 MaxType = S->getType(); 3957 assert(MaxType && "Failed to find maximum type!"); 3958 3959 // Extend all ops to max type. 3960 SmallVector<const SCEV *, 2> PromotedOps; 3961 for (auto *S : Ops) 3962 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 3963 3964 // Generate umin. 3965 return getUMinExpr(PromotedOps); 3966 } 3967 3968 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3969 // A pointer operand may evaluate to a nonpointer expression, such as null. 3970 if (!V->getType()->isPointerTy()) 3971 return V; 3972 3973 while (true) { 3974 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 3975 V = Cast->getOperand(); 3976 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3977 const SCEV *PtrOp = nullptr; 3978 for (const SCEV *NAryOp : NAry->operands()) { 3979 if (NAryOp->getType()->isPointerTy()) { 3980 // Cannot find the base of an expression with multiple pointer ops. 3981 if (PtrOp) 3982 return V; 3983 PtrOp = NAryOp; 3984 } 3985 } 3986 if (!PtrOp) // All operands were non-pointer. 3987 return V; 3988 V = PtrOp; 3989 } else // Not something we can look further into. 3990 return V; 3991 } 3992 } 3993 3994 /// Push users of the given Instruction onto the given Worklist. 3995 static void 3996 PushDefUseChildren(Instruction *I, 3997 SmallVectorImpl<Instruction *> &Worklist) { 3998 // Push the def-use children onto the Worklist stack. 3999 for (User *U : I->users()) 4000 Worklist.push_back(cast<Instruction>(U)); 4001 } 4002 4003 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4004 SmallVector<Instruction *, 16> Worklist; 4005 PushDefUseChildren(PN, Worklist); 4006 4007 SmallPtrSet<Instruction *, 8> Visited; 4008 Visited.insert(PN); 4009 while (!Worklist.empty()) { 4010 Instruction *I = Worklist.pop_back_val(); 4011 if (!Visited.insert(I).second) 4012 continue; 4013 4014 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4015 if (It != ValueExprMap.end()) { 4016 const SCEV *Old = It->second; 4017 4018 // Short-circuit the def-use traversal if the symbolic name 4019 // ceases to appear in expressions. 4020 if (Old != SymName && !hasOperand(Old, SymName)) 4021 continue; 4022 4023 // SCEVUnknown for a PHI either means that it has an unrecognized 4024 // structure, it's a PHI that's in the progress of being computed 4025 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4026 // additional loop trip count information isn't going to change anything. 4027 // In the second case, createNodeForPHI will perform the necessary 4028 // updates on its own when it gets to that point. In the third, we do 4029 // want to forget the SCEVUnknown. 4030 if (!isa<PHINode>(I) || 4031 !isa<SCEVUnknown>(Old) || 4032 (I != PN && Old == SymName)) { 4033 eraseValueFromMap(It->first); 4034 forgetMemoizedResults(Old); 4035 } 4036 } 4037 4038 PushDefUseChildren(I, Worklist); 4039 } 4040 } 4041 4042 namespace { 4043 4044 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4045 /// expression in case its Loop is L. If it is not L then 4046 /// if IgnoreOtherLoops is true then use AddRec itself 4047 /// otherwise rewrite cannot be done. 4048 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4049 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4050 public: 4051 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4052 bool IgnoreOtherLoops = true) { 4053 SCEVInitRewriter Rewriter(L, SE); 4054 const SCEV *Result = Rewriter.visit(S); 4055 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4056 return SE.getCouldNotCompute(); 4057 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4058 ? SE.getCouldNotCompute() 4059 : Result; 4060 } 4061 4062 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4063 if (!SE.isLoopInvariant(Expr, L)) 4064 SeenLoopVariantSCEVUnknown = true; 4065 return Expr; 4066 } 4067 4068 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4069 // Only re-write AddRecExprs for this loop. 4070 if (Expr->getLoop() == L) 4071 return Expr->getStart(); 4072 SeenOtherLoops = true; 4073 return Expr; 4074 } 4075 4076 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4077 4078 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4079 4080 private: 4081 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4082 : SCEVRewriteVisitor(SE), L(L) {} 4083 4084 const Loop *L; 4085 bool SeenLoopVariantSCEVUnknown = false; 4086 bool SeenOtherLoops = false; 4087 }; 4088 4089 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4090 /// increment expression in case its Loop is L. If it is not L then 4091 /// use AddRec itself. 4092 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4093 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4094 public: 4095 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4096 SCEVPostIncRewriter Rewriter(L, SE); 4097 const SCEV *Result = Rewriter.visit(S); 4098 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4099 ? SE.getCouldNotCompute() 4100 : Result; 4101 } 4102 4103 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4104 if (!SE.isLoopInvariant(Expr, L)) 4105 SeenLoopVariantSCEVUnknown = true; 4106 return Expr; 4107 } 4108 4109 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4110 // Only re-write AddRecExprs for this loop. 4111 if (Expr->getLoop() == L) 4112 return Expr->getPostIncExpr(SE); 4113 SeenOtherLoops = true; 4114 return Expr; 4115 } 4116 4117 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4118 4119 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4120 4121 private: 4122 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4123 : SCEVRewriteVisitor(SE), L(L) {} 4124 4125 const Loop *L; 4126 bool SeenLoopVariantSCEVUnknown = false; 4127 bool SeenOtherLoops = false; 4128 }; 4129 4130 /// This class evaluates the compare condition by matching it against the 4131 /// condition of loop latch. If there is a match we assume a true value 4132 /// for the condition while building SCEV nodes. 4133 class SCEVBackedgeConditionFolder 4134 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4135 public: 4136 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4137 ScalarEvolution &SE) { 4138 bool IsPosBECond = false; 4139 Value *BECond = nullptr; 4140 if (BasicBlock *Latch = L->getLoopLatch()) { 4141 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4142 if (BI && BI->isConditional()) { 4143 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4144 "Both outgoing branches should not target same header!"); 4145 BECond = BI->getCondition(); 4146 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4147 } else { 4148 return S; 4149 } 4150 } 4151 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4152 return Rewriter.visit(S); 4153 } 4154 4155 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4156 const SCEV *Result = Expr; 4157 bool InvariantF = SE.isLoopInvariant(Expr, L); 4158 4159 if (!InvariantF) { 4160 Instruction *I = cast<Instruction>(Expr->getValue()); 4161 switch (I->getOpcode()) { 4162 case Instruction::Select: { 4163 SelectInst *SI = cast<SelectInst>(I); 4164 Optional<const SCEV *> Res = 4165 compareWithBackedgeCondition(SI->getCondition()); 4166 if (Res.hasValue()) { 4167 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4168 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4169 } 4170 break; 4171 } 4172 default: { 4173 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4174 if (Res.hasValue()) 4175 Result = Res.getValue(); 4176 break; 4177 } 4178 } 4179 } 4180 return Result; 4181 } 4182 4183 private: 4184 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4185 bool IsPosBECond, ScalarEvolution &SE) 4186 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4187 IsPositiveBECond(IsPosBECond) {} 4188 4189 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4190 4191 const Loop *L; 4192 /// Loop back condition. 4193 Value *BackedgeCond = nullptr; 4194 /// Set to true if loop back is on positive branch condition. 4195 bool IsPositiveBECond; 4196 }; 4197 4198 Optional<const SCEV *> 4199 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4200 4201 // If value matches the backedge condition for loop latch, 4202 // then return a constant evolution node based on loopback 4203 // branch taken. 4204 if (BackedgeCond == IC) 4205 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4206 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4207 return None; 4208 } 4209 4210 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4211 public: 4212 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4213 ScalarEvolution &SE) { 4214 SCEVShiftRewriter Rewriter(L, SE); 4215 const SCEV *Result = Rewriter.visit(S); 4216 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4217 } 4218 4219 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4220 // Only allow AddRecExprs for this loop. 4221 if (!SE.isLoopInvariant(Expr, L)) 4222 Valid = false; 4223 return Expr; 4224 } 4225 4226 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4227 if (Expr->getLoop() == L && Expr->isAffine()) 4228 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4229 Valid = false; 4230 return Expr; 4231 } 4232 4233 bool isValid() { return Valid; } 4234 4235 private: 4236 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4237 : SCEVRewriteVisitor(SE), L(L) {} 4238 4239 const Loop *L; 4240 bool Valid = true; 4241 }; 4242 4243 } // end anonymous namespace 4244 4245 SCEV::NoWrapFlags 4246 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4247 if (!AR->isAffine()) 4248 return SCEV::FlagAnyWrap; 4249 4250 using OBO = OverflowingBinaryOperator; 4251 4252 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4253 4254 if (!AR->hasNoSignedWrap()) { 4255 ConstantRange AddRecRange = getSignedRange(AR); 4256 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4257 4258 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4259 Instruction::Add, IncRange, OBO::NoSignedWrap); 4260 if (NSWRegion.contains(AddRecRange)) 4261 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4262 } 4263 4264 if (!AR->hasNoUnsignedWrap()) { 4265 ConstantRange AddRecRange = getUnsignedRange(AR); 4266 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4267 4268 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4269 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4270 if (NUWRegion.contains(AddRecRange)) 4271 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4272 } 4273 4274 return Result; 4275 } 4276 4277 namespace { 4278 4279 /// Represents an abstract binary operation. This may exist as a 4280 /// normal instruction or constant expression, or may have been 4281 /// derived from an expression tree. 4282 struct BinaryOp { 4283 unsigned Opcode; 4284 Value *LHS; 4285 Value *RHS; 4286 bool IsNSW = false; 4287 bool IsNUW = false; 4288 bool IsExact = false; 4289 4290 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4291 /// constant expression. 4292 Operator *Op = nullptr; 4293 4294 explicit BinaryOp(Operator *Op) 4295 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4296 Op(Op) { 4297 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4298 IsNSW = OBO->hasNoSignedWrap(); 4299 IsNUW = OBO->hasNoUnsignedWrap(); 4300 } 4301 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4302 IsExact = PEO->isExact(); 4303 } 4304 4305 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4306 bool IsNUW = false, bool IsExact = false) 4307 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4308 IsExact(IsExact) {} 4309 }; 4310 4311 } // end anonymous namespace 4312 4313 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4314 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4315 auto *Op = dyn_cast<Operator>(V); 4316 if (!Op) 4317 return None; 4318 4319 // Implementation detail: all the cleverness here should happen without 4320 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4321 // SCEV expressions when possible, and we should not break that. 4322 4323 switch (Op->getOpcode()) { 4324 case Instruction::Add: 4325 case Instruction::Sub: 4326 case Instruction::Mul: 4327 case Instruction::UDiv: 4328 case Instruction::URem: 4329 case Instruction::And: 4330 case Instruction::Or: 4331 case Instruction::AShr: 4332 case Instruction::Shl: 4333 return BinaryOp(Op); 4334 4335 case Instruction::Xor: 4336 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4337 // If the RHS of the xor is a signmask, then this is just an add. 4338 // Instcombine turns add of signmask into xor as a strength reduction step. 4339 if (RHSC->getValue().isSignMask()) 4340 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4341 return BinaryOp(Op); 4342 4343 case Instruction::LShr: 4344 // Turn logical shift right of a constant into a unsigned divide. 4345 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4346 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4347 4348 // If the shift count is not less than the bitwidth, the result of 4349 // the shift is undefined. Don't try to analyze it, because the 4350 // resolution chosen here may differ from the resolution chosen in 4351 // other parts of the compiler. 4352 if (SA->getValue().ult(BitWidth)) { 4353 Constant *X = 4354 ConstantInt::get(SA->getContext(), 4355 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4356 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4357 } 4358 } 4359 return BinaryOp(Op); 4360 4361 case Instruction::ExtractValue: { 4362 auto *EVI = cast<ExtractValueInst>(Op); 4363 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4364 break; 4365 4366 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4367 if (!WO) 4368 break; 4369 4370 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4371 bool Signed = WO->isSigned(); 4372 // TODO: Should add nuw/nsw flags for mul as well. 4373 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4374 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4375 4376 // Now that we know that all uses of the arithmetic-result component of 4377 // CI are guarded by the overflow check, we can go ahead and pretend 4378 // that the arithmetic is non-overflowing. 4379 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4380 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4381 } 4382 4383 default: 4384 break; 4385 } 4386 4387 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4388 // semantics as a Sub, return a binary sub expression. 4389 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4390 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4391 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4392 4393 return None; 4394 } 4395 4396 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4397 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4398 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4399 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4400 /// follows one of the following patterns: 4401 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4402 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4403 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4404 /// we return the type of the truncation operation, and indicate whether the 4405 /// truncated type should be treated as signed/unsigned by setting 4406 /// \p Signed to true/false, respectively. 4407 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4408 bool &Signed, ScalarEvolution &SE) { 4409 // The case where Op == SymbolicPHI (that is, with no type conversions on 4410 // the way) is handled by the regular add recurrence creating logic and 4411 // would have already been triggered in createAddRecForPHI. Reaching it here 4412 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4413 // because one of the other operands of the SCEVAddExpr updating this PHI is 4414 // not invariant). 4415 // 4416 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4417 // this case predicates that allow us to prove that Op == SymbolicPHI will 4418 // be added. 4419 if (Op == SymbolicPHI) 4420 return nullptr; 4421 4422 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4423 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4424 if (SourceBits != NewBits) 4425 return nullptr; 4426 4427 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4428 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4429 if (!SExt && !ZExt) 4430 return nullptr; 4431 const SCEVTruncateExpr *Trunc = 4432 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4433 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4434 if (!Trunc) 4435 return nullptr; 4436 const SCEV *X = Trunc->getOperand(); 4437 if (X != SymbolicPHI) 4438 return nullptr; 4439 Signed = SExt != nullptr; 4440 return Trunc->getType(); 4441 } 4442 4443 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4444 if (!PN->getType()->isIntegerTy()) 4445 return nullptr; 4446 const Loop *L = LI.getLoopFor(PN->getParent()); 4447 if (!L || L->getHeader() != PN->getParent()) 4448 return nullptr; 4449 return L; 4450 } 4451 4452 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4453 // computation that updates the phi follows the following pattern: 4454 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4455 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4456 // If so, try to see if it can be rewritten as an AddRecExpr under some 4457 // Predicates. If successful, return them as a pair. Also cache the results 4458 // of the analysis. 4459 // 4460 // Example usage scenario: 4461 // Say the Rewriter is called for the following SCEV: 4462 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4463 // where: 4464 // %X = phi i64 (%Start, %BEValue) 4465 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4466 // and call this function with %SymbolicPHI = %X. 4467 // 4468 // The analysis will find that the value coming around the backedge has 4469 // the following SCEV: 4470 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4471 // Upon concluding that this matches the desired pattern, the function 4472 // will return the pair {NewAddRec, SmallPredsVec} where: 4473 // NewAddRec = {%Start,+,%Step} 4474 // SmallPredsVec = {P1, P2, P3} as follows: 4475 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4476 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4477 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4478 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4479 // under the predicates {P1,P2,P3}. 4480 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4481 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4482 // 4483 // TODO's: 4484 // 4485 // 1) Extend the Induction descriptor to also support inductions that involve 4486 // casts: When needed (namely, when we are called in the context of the 4487 // vectorizer induction analysis), a Set of cast instructions will be 4488 // populated by this method, and provided back to isInductionPHI. This is 4489 // needed to allow the vectorizer to properly record them to be ignored by 4490 // the cost model and to avoid vectorizing them (otherwise these casts, 4491 // which are redundant under the runtime overflow checks, will be 4492 // vectorized, which can be costly). 4493 // 4494 // 2) Support additional induction/PHISCEV patterns: We also want to support 4495 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4496 // after the induction update operation (the induction increment): 4497 // 4498 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4499 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4500 // 4501 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4502 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4503 // 4504 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4505 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4506 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4507 SmallVector<const SCEVPredicate *, 3> Predicates; 4508 4509 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4510 // return an AddRec expression under some predicate. 4511 4512 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4513 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4514 assert(L && "Expecting an integer loop header phi"); 4515 4516 // The loop may have multiple entrances or multiple exits; we can analyze 4517 // this phi as an addrec if it has a unique entry value and a unique 4518 // backedge value. 4519 Value *BEValueV = nullptr, *StartValueV = nullptr; 4520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4521 Value *V = PN->getIncomingValue(i); 4522 if (L->contains(PN->getIncomingBlock(i))) { 4523 if (!BEValueV) { 4524 BEValueV = V; 4525 } else if (BEValueV != V) { 4526 BEValueV = nullptr; 4527 break; 4528 } 4529 } else if (!StartValueV) { 4530 StartValueV = V; 4531 } else if (StartValueV != V) { 4532 StartValueV = nullptr; 4533 break; 4534 } 4535 } 4536 if (!BEValueV || !StartValueV) 4537 return None; 4538 4539 const SCEV *BEValue = getSCEV(BEValueV); 4540 4541 // If the value coming around the backedge is an add with the symbolic 4542 // value we just inserted, possibly with casts that we can ignore under 4543 // an appropriate runtime guard, then we found a simple induction variable! 4544 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4545 if (!Add) 4546 return None; 4547 4548 // If there is a single occurrence of the symbolic value, possibly 4549 // casted, replace it with a recurrence. 4550 unsigned FoundIndex = Add->getNumOperands(); 4551 Type *TruncTy = nullptr; 4552 bool Signed; 4553 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4554 if ((TruncTy = 4555 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4556 if (FoundIndex == e) { 4557 FoundIndex = i; 4558 break; 4559 } 4560 4561 if (FoundIndex == Add->getNumOperands()) 4562 return None; 4563 4564 // Create an add with everything but the specified operand. 4565 SmallVector<const SCEV *, 8> Ops; 4566 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4567 if (i != FoundIndex) 4568 Ops.push_back(Add->getOperand(i)); 4569 const SCEV *Accum = getAddExpr(Ops); 4570 4571 // The runtime checks will not be valid if the step amount is 4572 // varying inside the loop. 4573 if (!isLoopInvariant(Accum, L)) 4574 return None; 4575 4576 // *** Part2: Create the predicates 4577 4578 // Analysis was successful: we have a phi-with-cast pattern for which we 4579 // can return an AddRec expression under the following predicates: 4580 // 4581 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4582 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4583 // P2: An Equal predicate that guarantees that 4584 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4585 // P3: An Equal predicate that guarantees that 4586 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4587 // 4588 // As we next prove, the above predicates guarantee that: 4589 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4590 // 4591 // 4592 // More formally, we want to prove that: 4593 // Expr(i+1) = Start + (i+1) * Accum 4594 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4595 // 4596 // Given that: 4597 // 1) Expr(0) = Start 4598 // 2) Expr(1) = Start + Accum 4599 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4600 // 3) Induction hypothesis (step i): 4601 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4602 // 4603 // Proof: 4604 // Expr(i+1) = 4605 // = Start + (i+1)*Accum 4606 // = (Start + i*Accum) + Accum 4607 // = Expr(i) + Accum 4608 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4609 // :: from step i 4610 // 4611 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4612 // 4613 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4614 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4615 // + Accum :: from P3 4616 // 4617 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4618 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4619 // 4620 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4621 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4622 // 4623 // By induction, the same applies to all iterations 1<=i<n: 4624 // 4625 4626 // Create a truncated addrec for which we will add a no overflow check (P1). 4627 const SCEV *StartVal = getSCEV(StartValueV); 4628 const SCEV *PHISCEV = 4629 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4630 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4631 4632 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4633 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4634 // will be constant. 4635 // 4636 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4637 // add P1. 4638 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4639 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4640 Signed ? SCEVWrapPredicate::IncrementNSSW 4641 : SCEVWrapPredicate::IncrementNUSW; 4642 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4643 Predicates.push_back(AddRecPred); 4644 } 4645 4646 // Create the Equal Predicates P2,P3: 4647 4648 // It is possible that the predicates P2 and/or P3 are computable at 4649 // compile time due to StartVal and/or Accum being constants. 4650 // If either one is, then we can check that now and escape if either P2 4651 // or P3 is false. 4652 4653 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4654 // for each of StartVal and Accum 4655 auto getExtendedExpr = [&](const SCEV *Expr, 4656 bool CreateSignExtend) -> const SCEV * { 4657 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4658 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4659 const SCEV *ExtendedExpr = 4660 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4661 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4662 return ExtendedExpr; 4663 }; 4664 4665 // Given: 4666 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4667 // = getExtendedExpr(Expr) 4668 // Determine whether the predicate P: Expr == ExtendedExpr 4669 // is known to be false at compile time 4670 auto PredIsKnownFalse = [&](const SCEV *Expr, 4671 const SCEV *ExtendedExpr) -> bool { 4672 return Expr != ExtendedExpr && 4673 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4674 }; 4675 4676 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4677 if (PredIsKnownFalse(StartVal, StartExtended)) { 4678 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4679 return None; 4680 } 4681 4682 // The Step is always Signed (because the overflow checks are either 4683 // NSSW or NUSW) 4684 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4685 if (PredIsKnownFalse(Accum, AccumExtended)) { 4686 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4687 return None; 4688 } 4689 4690 auto AppendPredicate = [&](const SCEV *Expr, 4691 const SCEV *ExtendedExpr) -> void { 4692 if (Expr != ExtendedExpr && 4693 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4694 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4695 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4696 Predicates.push_back(Pred); 4697 } 4698 }; 4699 4700 AppendPredicate(StartVal, StartExtended); 4701 AppendPredicate(Accum, AccumExtended); 4702 4703 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4704 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4705 // into NewAR if it will also add the runtime overflow checks specified in 4706 // Predicates. 4707 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4708 4709 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4710 std::make_pair(NewAR, Predicates); 4711 // Remember the result of the analysis for this SCEV at this locayyytion. 4712 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4713 return PredRewrite; 4714 } 4715 4716 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4717 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4718 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4719 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4720 if (!L) 4721 return None; 4722 4723 // Check to see if we already analyzed this PHI. 4724 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4725 if (I != PredicatedSCEVRewrites.end()) { 4726 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4727 I->second; 4728 // Analysis was done before and failed to create an AddRec: 4729 if (Rewrite.first == SymbolicPHI) 4730 return None; 4731 // Analysis was done before and succeeded to create an AddRec under 4732 // a predicate: 4733 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4734 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4735 return Rewrite; 4736 } 4737 4738 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4739 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4740 4741 // Record in the cache that the analysis failed 4742 if (!Rewrite) { 4743 SmallVector<const SCEVPredicate *, 3> Predicates; 4744 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4745 return None; 4746 } 4747 4748 return Rewrite; 4749 } 4750 4751 // FIXME: This utility is currently required because the Rewriter currently 4752 // does not rewrite this expression: 4753 // {0, +, (sext ix (trunc iy to ix) to iy)} 4754 // into {0, +, %step}, 4755 // even when the following Equal predicate exists: 4756 // "%step == (sext ix (trunc iy to ix) to iy)". 4757 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4758 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4759 if (AR1 == AR2) 4760 return true; 4761 4762 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4763 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4764 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4765 return false; 4766 return true; 4767 }; 4768 4769 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4770 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4771 return false; 4772 return true; 4773 } 4774 4775 /// A helper function for createAddRecFromPHI to handle simple cases. 4776 /// 4777 /// This function tries to find an AddRec expression for the simplest (yet most 4778 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4779 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4780 /// technique for finding the AddRec expression. 4781 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4782 Value *BEValueV, 4783 Value *StartValueV) { 4784 const Loop *L = LI.getLoopFor(PN->getParent()); 4785 assert(L && L->getHeader() == PN->getParent()); 4786 assert(BEValueV && StartValueV); 4787 4788 auto BO = MatchBinaryOp(BEValueV, DT); 4789 if (!BO) 4790 return nullptr; 4791 4792 if (BO->Opcode != Instruction::Add) 4793 return nullptr; 4794 4795 const SCEV *Accum = nullptr; 4796 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4797 Accum = getSCEV(BO->RHS); 4798 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4799 Accum = getSCEV(BO->LHS); 4800 4801 if (!Accum) 4802 return nullptr; 4803 4804 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4805 if (BO->IsNUW) 4806 Flags = setFlags(Flags, SCEV::FlagNUW); 4807 if (BO->IsNSW) 4808 Flags = setFlags(Flags, SCEV::FlagNSW); 4809 4810 const SCEV *StartVal = getSCEV(StartValueV); 4811 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4812 4813 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4814 4815 // We can add Flags to the post-inc expression only if we 4816 // know that it is *undefined behavior* for BEValueV to 4817 // overflow. 4818 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4819 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4820 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4821 4822 return PHISCEV; 4823 } 4824 4825 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4826 const Loop *L = LI.getLoopFor(PN->getParent()); 4827 if (!L || L->getHeader() != PN->getParent()) 4828 return nullptr; 4829 4830 // The loop may have multiple entrances or multiple exits; we can analyze 4831 // this phi as an addrec if it has a unique entry value and a unique 4832 // backedge value. 4833 Value *BEValueV = nullptr, *StartValueV = nullptr; 4834 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4835 Value *V = PN->getIncomingValue(i); 4836 if (L->contains(PN->getIncomingBlock(i))) { 4837 if (!BEValueV) { 4838 BEValueV = V; 4839 } else if (BEValueV != V) { 4840 BEValueV = nullptr; 4841 break; 4842 } 4843 } else if (!StartValueV) { 4844 StartValueV = V; 4845 } else if (StartValueV != V) { 4846 StartValueV = nullptr; 4847 break; 4848 } 4849 } 4850 if (!BEValueV || !StartValueV) 4851 return nullptr; 4852 4853 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4854 "PHI node already processed?"); 4855 4856 // First, try to find AddRec expression without creating a fictituos symbolic 4857 // value for PN. 4858 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4859 return S; 4860 4861 // Handle PHI node value symbolically. 4862 const SCEV *SymbolicName = getUnknown(PN); 4863 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4864 4865 // Using this symbolic name for the PHI, analyze the value coming around 4866 // the back-edge. 4867 const SCEV *BEValue = getSCEV(BEValueV); 4868 4869 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4870 // has a special value for the first iteration of the loop. 4871 4872 // If the value coming around the backedge is an add with the symbolic 4873 // value we just inserted, then we found a simple induction variable! 4874 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4875 // If there is a single occurrence of the symbolic value, replace it 4876 // with a recurrence. 4877 unsigned FoundIndex = Add->getNumOperands(); 4878 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4879 if (Add->getOperand(i) == SymbolicName) 4880 if (FoundIndex == e) { 4881 FoundIndex = i; 4882 break; 4883 } 4884 4885 if (FoundIndex != Add->getNumOperands()) { 4886 // Create an add with everything but the specified operand. 4887 SmallVector<const SCEV *, 8> Ops; 4888 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4889 if (i != FoundIndex) 4890 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4891 L, *this)); 4892 const SCEV *Accum = getAddExpr(Ops); 4893 4894 // This is not a valid addrec if the step amount is varying each 4895 // loop iteration, but is not itself an addrec in this loop. 4896 if (isLoopInvariant(Accum, L) || 4897 (isa<SCEVAddRecExpr>(Accum) && 4898 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4899 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4900 4901 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4902 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4903 if (BO->IsNUW) 4904 Flags = setFlags(Flags, SCEV::FlagNUW); 4905 if (BO->IsNSW) 4906 Flags = setFlags(Flags, SCEV::FlagNSW); 4907 } 4908 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4909 // If the increment is an inbounds GEP, then we know the address 4910 // space cannot be wrapped around. We cannot make any guarantee 4911 // about signed or unsigned overflow because pointers are 4912 // unsigned but we may have a negative index from the base 4913 // pointer. We can guarantee that no unsigned wrap occurs if the 4914 // indices form a positive value. 4915 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4916 Flags = setFlags(Flags, SCEV::FlagNW); 4917 4918 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4919 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4920 Flags = setFlags(Flags, SCEV::FlagNUW); 4921 } 4922 4923 // We cannot transfer nuw and nsw flags from subtraction 4924 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4925 // for instance. 4926 } 4927 4928 const SCEV *StartVal = getSCEV(StartValueV); 4929 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4930 4931 // Okay, for the entire analysis of this edge we assumed the PHI 4932 // to be symbolic. We now need to go back and purge all of the 4933 // entries for the scalars that use the symbolic expression. 4934 forgetSymbolicName(PN, SymbolicName); 4935 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4936 4937 // We can add Flags to the post-inc expression only if we 4938 // know that it is *undefined behavior* for BEValueV to 4939 // overflow. 4940 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4941 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4942 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4943 4944 return PHISCEV; 4945 } 4946 } 4947 } else { 4948 // Otherwise, this could be a loop like this: 4949 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4950 // In this case, j = {1,+,1} and BEValue is j. 4951 // Because the other in-value of i (0) fits the evolution of BEValue 4952 // i really is an addrec evolution. 4953 // 4954 // We can generalize this saying that i is the shifted value of BEValue 4955 // by one iteration: 4956 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4957 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4958 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4959 if (Shifted != getCouldNotCompute() && 4960 Start != getCouldNotCompute()) { 4961 const SCEV *StartVal = getSCEV(StartValueV); 4962 if (Start == StartVal) { 4963 // Okay, for the entire analysis of this edge we assumed the PHI 4964 // to be symbolic. We now need to go back and purge all of the 4965 // entries for the scalars that use the symbolic expression. 4966 forgetSymbolicName(PN, SymbolicName); 4967 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4968 return Shifted; 4969 } 4970 } 4971 } 4972 4973 // Remove the temporary PHI node SCEV that has been inserted while intending 4974 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4975 // as it will prevent later (possibly simpler) SCEV expressions to be added 4976 // to the ValueExprMap. 4977 eraseValueFromMap(PN); 4978 4979 return nullptr; 4980 } 4981 4982 // Checks if the SCEV S is available at BB. S is considered available at BB 4983 // if S can be materialized at BB without introducing a fault. 4984 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4985 BasicBlock *BB) { 4986 struct CheckAvailable { 4987 bool TraversalDone = false; 4988 bool Available = true; 4989 4990 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4991 BasicBlock *BB = nullptr; 4992 DominatorTree &DT; 4993 4994 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4995 : L(L), BB(BB), DT(DT) {} 4996 4997 bool setUnavailable() { 4998 TraversalDone = true; 4999 Available = false; 5000 return false; 5001 } 5002 5003 bool follow(const SCEV *S) { 5004 switch (S->getSCEVType()) { 5005 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5006 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5007 case scUMinExpr: 5008 case scSMinExpr: 5009 // These expressions are available if their operand(s) is/are. 5010 return true; 5011 5012 case scAddRecExpr: { 5013 // We allow add recurrences that are on the loop BB is in, or some 5014 // outer loop. This guarantees availability because the value of the 5015 // add recurrence at BB is simply the "current" value of the induction 5016 // variable. We can relax this in the future; for instance an add 5017 // recurrence on a sibling dominating loop is also available at BB. 5018 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5019 if (L && (ARLoop == L || ARLoop->contains(L))) 5020 return true; 5021 5022 return setUnavailable(); 5023 } 5024 5025 case scUnknown: { 5026 // For SCEVUnknown, we check for simple dominance. 5027 const auto *SU = cast<SCEVUnknown>(S); 5028 Value *V = SU->getValue(); 5029 5030 if (isa<Argument>(V)) 5031 return false; 5032 5033 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5034 return false; 5035 5036 return setUnavailable(); 5037 } 5038 5039 case scUDivExpr: 5040 case scCouldNotCompute: 5041 // We do not try to smart about these at all. 5042 return setUnavailable(); 5043 } 5044 llvm_unreachable("Unknown SCEV kind!"); 5045 } 5046 5047 bool isDone() { return TraversalDone; } 5048 }; 5049 5050 CheckAvailable CA(L, BB, DT); 5051 SCEVTraversal<CheckAvailable> ST(CA); 5052 5053 ST.visitAll(S); 5054 return CA.Available; 5055 } 5056 5057 // Try to match a control flow sequence that branches out at BI and merges back 5058 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5059 // match. 5060 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5061 Value *&C, Value *&LHS, Value *&RHS) { 5062 C = BI->getCondition(); 5063 5064 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5065 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5066 5067 if (!LeftEdge.isSingleEdge()) 5068 return false; 5069 5070 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5071 5072 Use &LeftUse = Merge->getOperandUse(0); 5073 Use &RightUse = Merge->getOperandUse(1); 5074 5075 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5076 LHS = LeftUse; 5077 RHS = RightUse; 5078 return true; 5079 } 5080 5081 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5082 LHS = RightUse; 5083 RHS = LeftUse; 5084 return true; 5085 } 5086 5087 return false; 5088 } 5089 5090 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5091 auto IsReachable = 5092 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5093 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5094 const Loop *L = LI.getLoopFor(PN->getParent()); 5095 5096 // We don't want to break LCSSA, even in a SCEV expression tree. 5097 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5098 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5099 return nullptr; 5100 5101 // Try to match 5102 // 5103 // br %cond, label %left, label %right 5104 // left: 5105 // br label %merge 5106 // right: 5107 // br label %merge 5108 // merge: 5109 // V = phi [ %x, %left ], [ %y, %right ] 5110 // 5111 // as "select %cond, %x, %y" 5112 5113 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5114 assert(IDom && "At least the entry block should dominate PN"); 5115 5116 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5117 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5118 5119 if (BI && BI->isConditional() && 5120 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5121 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5122 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5123 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5124 } 5125 5126 return nullptr; 5127 } 5128 5129 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5130 if (const SCEV *S = createAddRecFromPHI(PN)) 5131 return S; 5132 5133 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5134 return S; 5135 5136 // If the PHI has a single incoming value, follow that value, unless the 5137 // PHI's incoming blocks are in a different loop, in which case doing so 5138 // risks breaking LCSSA form. Instcombine would normally zap these, but 5139 // it doesn't have DominatorTree information, so it may miss cases. 5140 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5141 if (LI.replacementPreservesLCSSAForm(PN, V)) 5142 return getSCEV(V); 5143 5144 // If it's not a loop phi, we can't handle it yet. 5145 return getUnknown(PN); 5146 } 5147 5148 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5149 Value *Cond, 5150 Value *TrueVal, 5151 Value *FalseVal) { 5152 // Handle "constant" branch or select. This can occur for instance when a 5153 // loop pass transforms an inner loop and moves on to process the outer loop. 5154 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5155 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5156 5157 // Try to match some simple smax or umax patterns. 5158 auto *ICI = dyn_cast<ICmpInst>(Cond); 5159 if (!ICI) 5160 return getUnknown(I); 5161 5162 Value *LHS = ICI->getOperand(0); 5163 Value *RHS = ICI->getOperand(1); 5164 5165 switch (ICI->getPredicate()) { 5166 case ICmpInst::ICMP_SLT: 5167 case ICmpInst::ICMP_SLE: 5168 std::swap(LHS, RHS); 5169 LLVM_FALLTHROUGH; 5170 case ICmpInst::ICMP_SGT: 5171 case ICmpInst::ICMP_SGE: 5172 // a >s b ? a+x : b+x -> smax(a, b)+x 5173 // a >s b ? b+x : a+x -> smin(a, b)+x 5174 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5175 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5176 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5177 const SCEV *LA = getSCEV(TrueVal); 5178 const SCEV *RA = getSCEV(FalseVal); 5179 const SCEV *LDiff = getMinusSCEV(LA, LS); 5180 const SCEV *RDiff = getMinusSCEV(RA, RS); 5181 if (LDiff == RDiff) 5182 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5183 LDiff = getMinusSCEV(LA, RS); 5184 RDiff = getMinusSCEV(RA, LS); 5185 if (LDiff == RDiff) 5186 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5187 } 5188 break; 5189 case ICmpInst::ICMP_ULT: 5190 case ICmpInst::ICMP_ULE: 5191 std::swap(LHS, RHS); 5192 LLVM_FALLTHROUGH; 5193 case ICmpInst::ICMP_UGT: 5194 case ICmpInst::ICMP_UGE: 5195 // a >u b ? a+x : b+x -> umax(a, b)+x 5196 // a >u b ? b+x : a+x -> umin(a, b)+x 5197 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5198 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5199 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5200 const SCEV *LA = getSCEV(TrueVal); 5201 const SCEV *RA = getSCEV(FalseVal); 5202 const SCEV *LDiff = getMinusSCEV(LA, LS); 5203 const SCEV *RDiff = getMinusSCEV(RA, RS); 5204 if (LDiff == RDiff) 5205 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5206 LDiff = getMinusSCEV(LA, RS); 5207 RDiff = getMinusSCEV(RA, LS); 5208 if (LDiff == RDiff) 5209 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5210 } 5211 break; 5212 case ICmpInst::ICMP_NE: 5213 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5214 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5215 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5216 const SCEV *One = getOne(I->getType()); 5217 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5218 const SCEV *LA = getSCEV(TrueVal); 5219 const SCEV *RA = getSCEV(FalseVal); 5220 const SCEV *LDiff = getMinusSCEV(LA, LS); 5221 const SCEV *RDiff = getMinusSCEV(RA, One); 5222 if (LDiff == RDiff) 5223 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5224 } 5225 break; 5226 case ICmpInst::ICMP_EQ: 5227 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5228 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5229 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5230 const SCEV *One = getOne(I->getType()); 5231 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5232 const SCEV *LA = getSCEV(TrueVal); 5233 const SCEV *RA = getSCEV(FalseVal); 5234 const SCEV *LDiff = getMinusSCEV(LA, One); 5235 const SCEV *RDiff = getMinusSCEV(RA, LS); 5236 if (LDiff == RDiff) 5237 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5238 } 5239 break; 5240 default: 5241 break; 5242 } 5243 5244 return getUnknown(I); 5245 } 5246 5247 /// Expand GEP instructions into add and multiply operations. This allows them 5248 /// to be analyzed by regular SCEV code. 5249 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5250 // Don't attempt to analyze GEPs over unsized objects. 5251 if (!GEP->getSourceElementType()->isSized()) 5252 return getUnknown(GEP); 5253 5254 SmallVector<const SCEV *, 4> IndexExprs; 5255 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5256 IndexExprs.push_back(getSCEV(*Index)); 5257 return getGEPExpr(GEP, IndexExprs); 5258 } 5259 5260 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5261 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5262 return C->getAPInt().countTrailingZeros(); 5263 5264 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5265 return std::min(GetMinTrailingZeros(T->getOperand()), 5266 (uint32_t)getTypeSizeInBits(T->getType())); 5267 5268 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5269 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5270 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5271 ? getTypeSizeInBits(E->getType()) 5272 : OpRes; 5273 } 5274 5275 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5276 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5277 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5278 ? getTypeSizeInBits(E->getType()) 5279 : OpRes; 5280 } 5281 5282 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5283 // The result is the min of all operands results. 5284 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5285 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5286 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5287 return MinOpRes; 5288 } 5289 5290 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5291 // The result is the sum of all operands results. 5292 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5293 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5294 for (unsigned i = 1, e = M->getNumOperands(); 5295 SumOpRes != BitWidth && i != e; ++i) 5296 SumOpRes = 5297 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5298 return SumOpRes; 5299 } 5300 5301 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5302 // The result is the min of all operands results. 5303 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5304 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5305 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5306 return MinOpRes; 5307 } 5308 5309 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5310 // The result is the min of all operands results. 5311 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5312 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5313 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5314 return MinOpRes; 5315 } 5316 5317 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5318 // The result is the min of all operands results. 5319 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5320 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5321 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5322 return MinOpRes; 5323 } 5324 5325 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5326 // For a SCEVUnknown, ask ValueTracking. 5327 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5328 return Known.countMinTrailingZeros(); 5329 } 5330 5331 // SCEVUDivExpr 5332 return 0; 5333 } 5334 5335 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5336 auto I = MinTrailingZerosCache.find(S); 5337 if (I != MinTrailingZerosCache.end()) 5338 return I->second; 5339 5340 uint32_t Result = GetMinTrailingZerosImpl(S); 5341 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5342 assert(InsertPair.second && "Should insert a new key"); 5343 return InsertPair.first->second; 5344 } 5345 5346 /// Helper method to assign a range to V from metadata present in the IR. 5347 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5348 if (Instruction *I = dyn_cast<Instruction>(V)) 5349 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5350 return getConstantRangeFromMetadata(*MD); 5351 5352 return None; 5353 } 5354 5355 /// Determine the range for a particular SCEV. If SignHint is 5356 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5357 /// with a "cleaner" unsigned (resp. signed) representation. 5358 const ConstantRange & 5359 ScalarEvolution::getRangeRef(const SCEV *S, 5360 ScalarEvolution::RangeSignHint SignHint) { 5361 DenseMap<const SCEV *, ConstantRange> &Cache = 5362 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5363 : SignedRanges; 5364 ConstantRange::PreferredRangeType RangeType = 5365 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5366 ? ConstantRange::Unsigned : ConstantRange::Signed; 5367 5368 // See if we've computed this range already. 5369 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5370 if (I != Cache.end()) 5371 return I->second; 5372 5373 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5374 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5375 5376 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5377 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5378 using OBO = OverflowingBinaryOperator; 5379 5380 // If the value has known zeros, the maximum value will have those known zeros 5381 // as well. 5382 uint32_t TZ = GetMinTrailingZeros(S); 5383 if (TZ != 0) { 5384 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5385 ConservativeResult = 5386 ConstantRange(APInt::getMinValue(BitWidth), 5387 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5388 else 5389 ConservativeResult = ConstantRange( 5390 APInt::getSignedMinValue(BitWidth), 5391 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5392 } 5393 5394 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5395 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5396 unsigned WrapType = OBO::AnyWrap; 5397 if (Add->hasNoSignedWrap()) 5398 WrapType |= OBO::NoSignedWrap; 5399 if (Add->hasNoUnsignedWrap()) 5400 WrapType |= OBO::NoUnsignedWrap; 5401 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5402 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5403 WrapType, RangeType); 5404 return setRange(Add, SignHint, 5405 ConservativeResult.intersectWith(X, RangeType)); 5406 } 5407 5408 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5409 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5410 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5411 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5412 return setRange(Mul, SignHint, 5413 ConservativeResult.intersectWith(X, RangeType)); 5414 } 5415 5416 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5417 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5418 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5419 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5420 return setRange(SMax, SignHint, 5421 ConservativeResult.intersectWith(X, RangeType)); 5422 } 5423 5424 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5425 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5426 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5427 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5428 return setRange(UMax, SignHint, 5429 ConservativeResult.intersectWith(X, RangeType)); 5430 } 5431 5432 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5433 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5434 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5435 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5436 return setRange(SMin, SignHint, 5437 ConservativeResult.intersectWith(X, RangeType)); 5438 } 5439 5440 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5441 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5442 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5443 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5444 return setRange(UMin, SignHint, 5445 ConservativeResult.intersectWith(X, RangeType)); 5446 } 5447 5448 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5449 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5450 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5451 return setRange(UDiv, SignHint, 5452 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5453 } 5454 5455 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5456 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5457 return setRange(ZExt, SignHint, 5458 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5459 RangeType)); 5460 } 5461 5462 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5463 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5464 return setRange(SExt, SignHint, 5465 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5466 RangeType)); 5467 } 5468 5469 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5470 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5471 return setRange(Trunc, SignHint, 5472 ConservativeResult.intersectWith(X.truncate(BitWidth), 5473 RangeType)); 5474 } 5475 5476 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5477 // If there's no unsigned wrap, the value will never be less than its 5478 // initial value. 5479 if (AddRec->hasNoUnsignedWrap()) { 5480 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5481 if (!UnsignedMinValue.isNullValue()) 5482 ConservativeResult = ConservativeResult.intersectWith( 5483 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5484 } 5485 5486 // If there's no signed wrap, and all the operands except initial value have 5487 // the same sign or zero, the value won't ever be: 5488 // 1: smaller than initial value if operands are non negative, 5489 // 2: bigger than initial value if operands are non positive. 5490 // For both cases, value can not cross signed min/max boundary. 5491 if (AddRec->hasNoSignedWrap()) { 5492 bool AllNonNeg = true; 5493 bool AllNonPos = true; 5494 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5495 if (!isKnownNonNegative(AddRec->getOperand(i))) 5496 AllNonNeg = false; 5497 if (!isKnownNonPositive(AddRec->getOperand(i))) 5498 AllNonPos = false; 5499 } 5500 if (AllNonNeg) 5501 ConservativeResult = ConservativeResult.intersectWith( 5502 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5503 APInt::getSignedMinValue(BitWidth)), 5504 RangeType); 5505 else if (AllNonPos) 5506 ConservativeResult = ConservativeResult.intersectWith( 5507 ConstantRange::getNonEmpty( 5508 APInt::getSignedMinValue(BitWidth), 5509 getSignedRangeMax(AddRec->getStart()) + 1), 5510 RangeType); 5511 } 5512 5513 // TODO: non-affine addrec 5514 if (AddRec->isAffine()) { 5515 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5516 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5517 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5518 auto RangeFromAffine = getRangeForAffineAR( 5519 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5520 BitWidth); 5521 ConservativeResult = 5522 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5523 5524 auto RangeFromFactoring = getRangeViaFactoring( 5525 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5526 BitWidth); 5527 ConservativeResult = 5528 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5529 } 5530 } 5531 5532 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5533 } 5534 5535 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5536 // Check if the IR explicitly contains !range metadata. 5537 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5538 if (MDRange.hasValue()) 5539 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5540 RangeType); 5541 5542 // Split here to avoid paying the compile-time cost of calling both 5543 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5544 // if needed. 5545 const DataLayout &DL = getDataLayout(); 5546 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5547 // For a SCEVUnknown, ask ValueTracking. 5548 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5549 if (Known.getBitWidth() != BitWidth) 5550 Known = Known.zextOrTrunc(BitWidth); 5551 // If Known does not result in full-set, intersect with it. 5552 if (Known.getMinValue() != Known.getMaxValue() + 1) 5553 ConservativeResult = ConservativeResult.intersectWith( 5554 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5555 RangeType); 5556 } else { 5557 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5558 "generalize as needed!"); 5559 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5560 // If the pointer size is larger than the index size type, this can cause 5561 // NS to be larger than BitWidth. So compensate for this. 5562 if (U->getType()->isPointerTy()) { 5563 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5564 int ptrIdxDiff = ptrSize - BitWidth; 5565 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5566 NS -= ptrIdxDiff; 5567 } 5568 5569 if (NS > 1) 5570 ConservativeResult = ConservativeResult.intersectWith( 5571 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5572 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5573 RangeType); 5574 } 5575 5576 // A range of Phi is a subset of union of all ranges of its input. 5577 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5578 // Make sure that we do not run over cycled Phis. 5579 if (PendingPhiRanges.insert(Phi).second) { 5580 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5581 for (auto &Op : Phi->operands()) { 5582 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5583 RangeFromOps = RangeFromOps.unionWith(OpRange); 5584 // No point to continue if we already have a full set. 5585 if (RangeFromOps.isFullSet()) 5586 break; 5587 } 5588 ConservativeResult = 5589 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5590 bool Erased = PendingPhiRanges.erase(Phi); 5591 assert(Erased && "Failed to erase Phi properly?"); 5592 (void) Erased; 5593 } 5594 } 5595 5596 return setRange(U, SignHint, std::move(ConservativeResult)); 5597 } 5598 5599 return setRange(S, SignHint, std::move(ConservativeResult)); 5600 } 5601 5602 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5603 // values that the expression can take. Initially, the expression has a value 5604 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5605 // argument defines if we treat Step as signed or unsigned. 5606 static ConstantRange getRangeForAffineARHelper(APInt Step, 5607 const ConstantRange &StartRange, 5608 const APInt &MaxBECount, 5609 unsigned BitWidth, bool Signed) { 5610 // If either Step or MaxBECount is 0, then the expression won't change, and we 5611 // just need to return the initial range. 5612 if (Step == 0 || MaxBECount == 0) 5613 return StartRange; 5614 5615 // If we don't know anything about the initial value (i.e. StartRange is 5616 // FullRange), then we don't know anything about the final range either. 5617 // Return FullRange. 5618 if (StartRange.isFullSet()) 5619 return ConstantRange::getFull(BitWidth); 5620 5621 // If Step is signed and negative, then we use its absolute value, but we also 5622 // note that we're moving in the opposite direction. 5623 bool Descending = Signed && Step.isNegative(); 5624 5625 if (Signed) 5626 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5627 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5628 // This equations hold true due to the well-defined wrap-around behavior of 5629 // APInt. 5630 Step = Step.abs(); 5631 5632 // Check if Offset is more than full span of BitWidth. If it is, the 5633 // expression is guaranteed to overflow. 5634 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5635 return ConstantRange::getFull(BitWidth); 5636 5637 // Offset is by how much the expression can change. Checks above guarantee no 5638 // overflow here. 5639 APInt Offset = Step * MaxBECount; 5640 5641 // Minimum value of the final range will match the minimal value of StartRange 5642 // if the expression is increasing and will be decreased by Offset otherwise. 5643 // Maximum value of the final range will match the maximal value of StartRange 5644 // if the expression is decreasing and will be increased by Offset otherwise. 5645 APInt StartLower = StartRange.getLower(); 5646 APInt StartUpper = StartRange.getUpper() - 1; 5647 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5648 : (StartUpper + std::move(Offset)); 5649 5650 // It's possible that the new minimum/maximum value will fall into the initial 5651 // range (due to wrap around). This means that the expression can take any 5652 // value in this bitwidth, and we have to return full range. 5653 if (StartRange.contains(MovedBoundary)) 5654 return ConstantRange::getFull(BitWidth); 5655 5656 APInt NewLower = 5657 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5658 APInt NewUpper = 5659 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5660 NewUpper += 1; 5661 5662 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5663 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5664 } 5665 5666 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5667 const SCEV *Step, 5668 const SCEV *MaxBECount, 5669 unsigned BitWidth) { 5670 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5671 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5672 "Precondition!"); 5673 5674 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5675 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5676 5677 // First, consider step signed. 5678 ConstantRange StartSRange = getSignedRange(Start); 5679 ConstantRange StepSRange = getSignedRange(Step); 5680 5681 // If Step can be both positive and negative, we need to find ranges for the 5682 // maximum absolute step values in both directions and union them. 5683 ConstantRange SR = 5684 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5685 MaxBECountValue, BitWidth, /* Signed = */ true); 5686 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5687 StartSRange, MaxBECountValue, 5688 BitWidth, /* Signed = */ true)); 5689 5690 // Next, consider step unsigned. 5691 ConstantRange UR = getRangeForAffineARHelper( 5692 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5693 MaxBECountValue, BitWidth, /* Signed = */ false); 5694 5695 // Finally, intersect signed and unsigned ranges. 5696 return SR.intersectWith(UR, ConstantRange::Smallest); 5697 } 5698 5699 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5700 const SCEV *Step, 5701 const SCEV *MaxBECount, 5702 unsigned BitWidth) { 5703 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5704 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5705 5706 struct SelectPattern { 5707 Value *Condition = nullptr; 5708 APInt TrueValue; 5709 APInt FalseValue; 5710 5711 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5712 const SCEV *S) { 5713 Optional<unsigned> CastOp; 5714 APInt Offset(BitWidth, 0); 5715 5716 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5717 "Should be!"); 5718 5719 // Peel off a constant offset: 5720 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5721 // In the future we could consider being smarter here and handle 5722 // {Start+Step,+,Step} too. 5723 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5724 return; 5725 5726 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5727 S = SA->getOperand(1); 5728 } 5729 5730 // Peel off a cast operation 5731 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 5732 CastOp = SCast->getSCEVType(); 5733 S = SCast->getOperand(); 5734 } 5735 5736 using namespace llvm::PatternMatch; 5737 5738 auto *SU = dyn_cast<SCEVUnknown>(S); 5739 const APInt *TrueVal, *FalseVal; 5740 if (!SU || 5741 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5742 m_APInt(FalseVal)))) { 5743 Condition = nullptr; 5744 return; 5745 } 5746 5747 TrueValue = *TrueVal; 5748 FalseValue = *FalseVal; 5749 5750 // Re-apply the cast we peeled off earlier 5751 if (CastOp.hasValue()) 5752 switch (*CastOp) { 5753 default: 5754 llvm_unreachable("Unknown SCEV cast type!"); 5755 5756 case scTruncate: 5757 TrueValue = TrueValue.trunc(BitWidth); 5758 FalseValue = FalseValue.trunc(BitWidth); 5759 break; 5760 case scZeroExtend: 5761 TrueValue = TrueValue.zext(BitWidth); 5762 FalseValue = FalseValue.zext(BitWidth); 5763 break; 5764 case scSignExtend: 5765 TrueValue = TrueValue.sext(BitWidth); 5766 FalseValue = FalseValue.sext(BitWidth); 5767 break; 5768 } 5769 5770 // Re-apply the constant offset we peeled off earlier 5771 TrueValue += Offset; 5772 FalseValue += Offset; 5773 } 5774 5775 bool isRecognized() { return Condition != nullptr; } 5776 }; 5777 5778 SelectPattern StartPattern(*this, BitWidth, Start); 5779 if (!StartPattern.isRecognized()) 5780 return ConstantRange::getFull(BitWidth); 5781 5782 SelectPattern StepPattern(*this, BitWidth, Step); 5783 if (!StepPattern.isRecognized()) 5784 return ConstantRange::getFull(BitWidth); 5785 5786 if (StartPattern.Condition != StepPattern.Condition) { 5787 // We don't handle this case today; but we could, by considering four 5788 // possibilities below instead of two. I'm not sure if there are cases where 5789 // that will help over what getRange already does, though. 5790 return ConstantRange::getFull(BitWidth); 5791 } 5792 5793 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5794 // construct arbitrary general SCEV expressions here. This function is called 5795 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5796 // say) can end up caching a suboptimal value. 5797 5798 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5799 // C2352 and C2512 (otherwise it isn't needed). 5800 5801 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5802 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5803 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5804 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5805 5806 ConstantRange TrueRange = 5807 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5808 ConstantRange FalseRange = 5809 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5810 5811 return TrueRange.unionWith(FalseRange); 5812 } 5813 5814 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5815 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5816 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5817 5818 // Return early if there are no flags to propagate to the SCEV. 5819 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5820 if (BinOp->hasNoUnsignedWrap()) 5821 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5822 if (BinOp->hasNoSignedWrap()) 5823 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5824 if (Flags == SCEV::FlagAnyWrap) 5825 return SCEV::FlagAnyWrap; 5826 5827 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5828 } 5829 5830 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5831 // Here we check that I is in the header of the innermost loop containing I, 5832 // since we only deal with instructions in the loop header. The actual loop we 5833 // need to check later will come from an add recurrence, but getting that 5834 // requires computing the SCEV of the operands, which can be expensive. This 5835 // check we can do cheaply to rule out some cases early. 5836 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5837 if (InnermostContainingLoop == nullptr || 5838 InnermostContainingLoop->getHeader() != I->getParent()) 5839 return false; 5840 5841 // Only proceed if we can prove that I does not yield poison. 5842 if (!programUndefinedIfPoison(I)) 5843 return false; 5844 5845 // At this point we know that if I is executed, then it does not wrap 5846 // according to at least one of NSW or NUW. If I is not executed, then we do 5847 // not know if the calculation that I represents would wrap. Multiple 5848 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5849 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5850 // derived from other instructions that map to the same SCEV. We cannot make 5851 // that guarantee for cases where I is not executed. So we need to find the 5852 // loop that I is considered in relation to and prove that I is executed for 5853 // every iteration of that loop. That implies that the value that I 5854 // calculates does not wrap anywhere in the loop, so then we can apply the 5855 // flags to the SCEV. 5856 // 5857 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5858 // from different loops, so that we know which loop to prove that I is 5859 // executed in. 5860 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5861 // I could be an extractvalue from a call to an overflow intrinsic. 5862 // TODO: We can do better here in some cases. 5863 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5864 return false; 5865 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5866 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5867 bool AllOtherOpsLoopInvariant = true; 5868 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5869 ++OtherOpIndex) { 5870 if (OtherOpIndex != OpIndex) { 5871 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5872 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5873 AllOtherOpsLoopInvariant = false; 5874 break; 5875 } 5876 } 5877 } 5878 if (AllOtherOpsLoopInvariant && 5879 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5880 return true; 5881 } 5882 } 5883 return false; 5884 } 5885 5886 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5887 // If we know that \c I can never be poison period, then that's enough. 5888 if (isSCEVExprNeverPoison(I)) 5889 return true; 5890 5891 // For an add recurrence specifically, we assume that infinite loops without 5892 // side effects are undefined behavior, and then reason as follows: 5893 // 5894 // If the add recurrence is poison in any iteration, it is poison on all 5895 // future iterations (since incrementing poison yields poison). If the result 5896 // of the add recurrence is fed into the loop latch condition and the loop 5897 // does not contain any throws or exiting blocks other than the latch, we now 5898 // have the ability to "choose" whether the backedge is taken or not (by 5899 // choosing a sufficiently evil value for the poison feeding into the branch) 5900 // for every iteration including and after the one in which \p I first became 5901 // poison. There are two possibilities (let's call the iteration in which \p 5902 // I first became poison as K): 5903 // 5904 // 1. In the set of iterations including and after K, the loop body executes 5905 // no side effects. In this case executing the backege an infinte number 5906 // of times will yield undefined behavior. 5907 // 5908 // 2. In the set of iterations including and after K, the loop body executes 5909 // at least one side effect. In this case, that specific instance of side 5910 // effect is control dependent on poison, which also yields undefined 5911 // behavior. 5912 5913 auto *ExitingBB = L->getExitingBlock(); 5914 auto *LatchBB = L->getLoopLatch(); 5915 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5916 return false; 5917 5918 SmallPtrSet<const Instruction *, 16> Pushed; 5919 SmallVector<const Instruction *, 8> PoisonStack; 5920 5921 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5922 // things that are known to be poison under that assumption go on the 5923 // PoisonStack. 5924 Pushed.insert(I); 5925 PoisonStack.push_back(I); 5926 5927 bool LatchControlDependentOnPoison = false; 5928 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5929 const Instruction *Poison = PoisonStack.pop_back_val(); 5930 5931 for (auto *PoisonUser : Poison->users()) { 5932 if (propagatesPoison(cast<Operator>(PoisonUser))) { 5933 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5934 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5935 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5936 assert(BI->isConditional() && "Only possibility!"); 5937 if (BI->getParent() == LatchBB) { 5938 LatchControlDependentOnPoison = true; 5939 break; 5940 } 5941 } 5942 } 5943 } 5944 5945 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5946 } 5947 5948 ScalarEvolution::LoopProperties 5949 ScalarEvolution::getLoopProperties(const Loop *L) { 5950 using LoopProperties = ScalarEvolution::LoopProperties; 5951 5952 auto Itr = LoopPropertiesCache.find(L); 5953 if (Itr == LoopPropertiesCache.end()) { 5954 auto HasSideEffects = [](Instruction *I) { 5955 if (auto *SI = dyn_cast<StoreInst>(I)) 5956 return !SI->isSimple(); 5957 5958 return I->mayHaveSideEffects(); 5959 }; 5960 5961 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5962 /*HasNoSideEffects*/ true}; 5963 5964 for (auto *BB : L->getBlocks()) 5965 for (auto &I : *BB) { 5966 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5967 LP.HasNoAbnormalExits = false; 5968 if (HasSideEffects(&I)) 5969 LP.HasNoSideEffects = false; 5970 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5971 break; // We're already as pessimistic as we can get. 5972 } 5973 5974 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5975 assert(InsertPair.second && "We just checked!"); 5976 Itr = InsertPair.first; 5977 } 5978 5979 return Itr->second; 5980 } 5981 5982 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5983 if (!isSCEVable(V->getType())) 5984 return getUnknown(V); 5985 5986 if (Instruction *I = dyn_cast<Instruction>(V)) { 5987 // Don't attempt to analyze instructions in blocks that aren't 5988 // reachable. Such instructions don't matter, and they aren't required 5989 // to obey basic rules for definitions dominating uses which this 5990 // analysis depends on. 5991 if (!DT.isReachableFromEntry(I->getParent())) 5992 return getUnknown(UndefValue::get(V->getType())); 5993 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5994 return getConstant(CI); 5995 else if (isa<ConstantPointerNull>(V)) 5996 return getZero(V->getType()); 5997 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5998 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5999 else if (!isa<ConstantExpr>(V)) 6000 return getUnknown(V); 6001 6002 Operator *U = cast<Operator>(V); 6003 if (auto BO = MatchBinaryOp(U, DT)) { 6004 switch (BO->Opcode) { 6005 case Instruction::Add: { 6006 // The simple thing to do would be to just call getSCEV on both operands 6007 // and call getAddExpr with the result. However if we're looking at a 6008 // bunch of things all added together, this can be quite inefficient, 6009 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6010 // Instead, gather up all the operands and make a single getAddExpr call. 6011 // LLVM IR canonical form means we need only traverse the left operands. 6012 SmallVector<const SCEV *, 4> AddOps; 6013 do { 6014 if (BO->Op) { 6015 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6016 AddOps.push_back(OpSCEV); 6017 break; 6018 } 6019 6020 // If a NUW or NSW flag can be applied to the SCEV for this 6021 // addition, then compute the SCEV for this addition by itself 6022 // with a separate call to getAddExpr. We need to do that 6023 // instead of pushing the operands of the addition onto AddOps, 6024 // since the flags are only known to apply to this particular 6025 // addition - they may not apply to other additions that can be 6026 // formed with operands from AddOps. 6027 const SCEV *RHS = getSCEV(BO->RHS); 6028 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6029 if (Flags != SCEV::FlagAnyWrap) { 6030 const SCEV *LHS = getSCEV(BO->LHS); 6031 if (BO->Opcode == Instruction::Sub) 6032 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6033 else 6034 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6035 break; 6036 } 6037 } 6038 6039 if (BO->Opcode == Instruction::Sub) 6040 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6041 else 6042 AddOps.push_back(getSCEV(BO->RHS)); 6043 6044 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6045 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6046 NewBO->Opcode != Instruction::Sub)) { 6047 AddOps.push_back(getSCEV(BO->LHS)); 6048 break; 6049 } 6050 BO = NewBO; 6051 } while (true); 6052 6053 return getAddExpr(AddOps); 6054 } 6055 6056 case Instruction::Mul: { 6057 SmallVector<const SCEV *, 4> MulOps; 6058 do { 6059 if (BO->Op) { 6060 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6061 MulOps.push_back(OpSCEV); 6062 break; 6063 } 6064 6065 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6066 if (Flags != SCEV::FlagAnyWrap) { 6067 MulOps.push_back( 6068 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6069 break; 6070 } 6071 } 6072 6073 MulOps.push_back(getSCEV(BO->RHS)); 6074 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6075 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6076 MulOps.push_back(getSCEV(BO->LHS)); 6077 break; 6078 } 6079 BO = NewBO; 6080 } while (true); 6081 6082 return getMulExpr(MulOps); 6083 } 6084 case Instruction::UDiv: 6085 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6086 case Instruction::URem: 6087 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6088 case Instruction::Sub: { 6089 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6090 if (BO->Op) 6091 Flags = getNoWrapFlagsFromUB(BO->Op); 6092 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6093 } 6094 case Instruction::And: 6095 // For an expression like x&255 that merely masks off the high bits, 6096 // use zext(trunc(x)) as the SCEV expression. 6097 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6098 if (CI->isZero()) 6099 return getSCEV(BO->RHS); 6100 if (CI->isMinusOne()) 6101 return getSCEV(BO->LHS); 6102 const APInt &A = CI->getValue(); 6103 6104 // Instcombine's ShrinkDemandedConstant may strip bits out of 6105 // constants, obscuring what would otherwise be a low-bits mask. 6106 // Use computeKnownBits to compute what ShrinkDemandedConstant 6107 // knew about to reconstruct a low-bits mask value. 6108 unsigned LZ = A.countLeadingZeros(); 6109 unsigned TZ = A.countTrailingZeros(); 6110 unsigned BitWidth = A.getBitWidth(); 6111 KnownBits Known(BitWidth); 6112 computeKnownBits(BO->LHS, Known, getDataLayout(), 6113 0, &AC, nullptr, &DT); 6114 6115 APInt EffectiveMask = 6116 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6117 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6118 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6119 const SCEV *LHS = getSCEV(BO->LHS); 6120 const SCEV *ShiftedLHS = nullptr; 6121 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6122 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6123 // For an expression like (x * 8) & 8, simplify the multiply. 6124 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6125 unsigned GCD = std::min(MulZeros, TZ); 6126 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6127 SmallVector<const SCEV*, 4> MulOps; 6128 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6129 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6130 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6131 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6132 } 6133 } 6134 if (!ShiftedLHS) 6135 ShiftedLHS = getUDivExpr(LHS, MulCount); 6136 return getMulExpr( 6137 getZeroExtendExpr( 6138 getTruncateExpr(ShiftedLHS, 6139 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6140 BO->LHS->getType()), 6141 MulCount); 6142 } 6143 } 6144 break; 6145 6146 case Instruction::Or: 6147 // If the RHS of the Or is a constant, we may have something like: 6148 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6149 // optimizations will transparently handle this case. 6150 // 6151 // In order for this transformation to be safe, the LHS must be of the 6152 // form X*(2^n) and the Or constant must be less than 2^n. 6153 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6154 const SCEV *LHS = getSCEV(BO->LHS); 6155 const APInt &CIVal = CI->getValue(); 6156 if (GetMinTrailingZeros(LHS) >= 6157 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6158 // Build a plain add SCEV. 6159 return getAddExpr(LHS, getSCEV(CI), 6160 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6161 } 6162 } 6163 break; 6164 6165 case Instruction::Xor: 6166 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6167 // If the RHS of xor is -1, then this is a not operation. 6168 if (CI->isMinusOne()) 6169 return getNotSCEV(getSCEV(BO->LHS)); 6170 6171 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6172 // This is a variant of the check for xor with -1, and it handles 6173 // the case where instcombine has trimmed non-demanded bits out 6174 // of an xor with -1. 6175 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6176 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6177 if (LBO->getOpcode() == Instruction::And && 6178 LCI->getValue() == CI->getValue()) 6179 if (const SCEVZeroExtendExpr *Z = 6180 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6181 Type *UTy = BO->LHS->getType(); 6182 const SCEV *Z0 = Z->getOperand(); 6183 Type *Z0Ty = Z0->getType(); 6184 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6185 6186 // If C is a low-bits mask, the zero extend is serving to 6187 // mask off the high bits. Complement the operand and 6188 // re-apply the zext. 6189 if (CI->getValue().isMask(Z0TySize)) 6190 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6191 6192 // If C is a single bit, it may be in the sign-bit position 6193 // before the zero-extend. In this case, represent the xor 6194 // using an add, which is equivalent, and re-apply the zext. 6195 APInt Trunc = CI->getValue().trunc(Z0TySize); 6196 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6197 Trunc.isSignMask()) 6198 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6199 UTy); 6200 } 6201 } 6202 break; 6203 6204 case Instruction::Shl: 6205 // Turn shift left of a constant amount into a multiply. 6206 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6207 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6208 6209 // If the shift count is not less than the bitwidth, the result of 6210 // the shift is undefined. Don't try to analyze it, because the 6211 // resolution chosen here may differ from the resolution chosen in 6212 // other parts of the compiler. 6213 if (SA->getValue().uge(BitWidth)) 6214 break; 6215 6216 // We can safely preserve the nuw flag in all cases. It's also safe to 6217 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6218 // requires special handling. It can be preserved as long as we're not 6219 // left shifting by bitwidth - 1. 6220 auto Flags = SCEV::FlagAnyWrap; 6221 if (BO->Op) { 6222 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6223 if ((MulFlags & SCEV::FlagNSW) && 6224 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6225 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6226 if (MulFlags & SCEV::FlagNUW) 6227 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6228 } 6229 6230 Constant *X = ConstantInt::get( 6231 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6232 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6233 } 6234 break; 6235 6236 case Instruction::AShr: { 6237 // AShr X, C, where C is a constant. 6238 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6239 if (!CI) 6240 break; 6241 6242 Type *OuterTy = BO->LHS->getType(); 6243 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6244 // If the shift count is not less than the bitwidth, the result of 6245 // the shift is undefined. Don't try to analyze it, because the 6246 // resolution chosen here may differ from the resolution chosen in 6247 // other parts of the compiler. 6248 if (CI->getValue().uge(BitWidth)) 6249 break; 6250 6251 if (CI->isZero()) 6252 return getSCEV(BO->LHS); // shift by zero --> noop 6253 6254 uint64_t AShrAmt = CI->getZExtValue(); 6255 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6256 6257 Operator *L = dyn_cast<Operator>(BO->LHS); 6258 if (L && L->getOpcode() == Instruction::Shl) { 6259 // X = Shl A, n 6260 // Y = AShr X, m 6261 // Both n and m are constant. 6262 6263 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6264 if (L->getOperand(1) == BO->RHS) 6265 // For a two-shift sext-inreg, i.e. n = m, 6266 // use sext(trunc(x)) as the SCEV expression. 6267 return getSignExtendExpr( 6268 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6269 6270 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6271 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6272 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6273 if (ShlAmt > AShrAmt) { 6274 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6275 // expression. We already checked that ShlAmt < BitWidth, so 6276 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6277 // ShlAmt - AShrAmt < Amt. 6278 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6279 ShlAmt - AShrAmt); 6280 return getSignExtendExpr( 6281 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6282 getConstant(Mul)), OuterTy); 6283 } 6284 } 6285 } 6286 if (BO->IsExact) { 6287 // Given exact arithmetic in-bounds right-shift by a constant, 6288 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6289 const SCEV *X = getSCEV(BO->LHS); 6290 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6291 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6292 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6293 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6294 } 6295 break; 6296 } 6297 } 6298 } 6299 6300 switch (U->getOpcode()) { 6301 case Instruction::Trunc: 6302 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6303 6304 case Instruction::ZExt: 6305 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6306 6307 case Instruction::SExt: 6308 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6309 // The NSW flag of a subtract does not always survive the conversion to 6310 // A + (-1)*B. By pushing sign extension onto its operands we are much 6311 // more likely to preserve NSW and allow later AddRec optimisations. 6312 // 6313 // NOTE: This is effectively duplicating this logic from getSignExtend: 6314 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6315 // but by that point the NSW information has potentially been lost. 6316 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6317 Type *Ty = U->getType(); 6318 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6319 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6320 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6321 } 6322 } 6323 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6324 6325 case Instruction::BitCast: 6326 // BitCasts are no-op casts so we just eliminate the cast. 6327 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6328 return getSCEV(U->getOperand(0)); 6329 break; 6330 6331 case Instruction::SDiv: 6332 // If both operands are non-negative, this is just an udiv. 6333 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6334 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6335 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6336 break; 6337 6338 case Instruction::SRem: 6339 // If both operands are non-negative, this is just an urem. 6340 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6341 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6342 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6343 break; 6344 6345 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6346 // lead to pointer expressions which cannot safely be expanded to GEPs, 6347 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6348 // simplifying integer expressions. 6349 6350 case Instruction::GetElementPtr: 6351 return createNodeForGEP(cast<GEPOperator>(U)); 6352 6353 case Instruction::PHI: 6354 return createNodeForPHI(cast<PHINode>(U)); 6355 6356 case Instruction::Select: 6357 // U can also be a select constant expr, which let fall through. Since 6358 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6359 // constant expressions cannot have instructions as operands, we'd have 6360 // returned getUnknown for a select constant expressions anyway. 6361 if (isa<Instruction>(U)) 6362 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6363 U->getOperand(1), U->getOperand(2)); 6364 break; 6365 6366 case Instruction::Call: 6367 case Instruction::Invoke: 6368 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6369 return getSCEV(RV); 6370 6371 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6372 switch (II->getIntrinsicID()) { 6373 case Intrinsic::abs: 6374 return getAbsExpr( 6375 getSCEV(II->getArgOperand(0)), 6376 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6377 case Intrinsic::umax: 6378 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6379 getSCEV(II->getArgOperand(1))); 6380 case Intrinsic::umin: 6381 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6382 getSCEV(II->getArgOperand(1))); 6383 case Intrinsic::smax: 6384 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6385 getSCEV(II->getArgOperand(1))); 6386 case Intrinsic::smin: 6387 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6388 getSCEV(II->getArgOperand(1))); 6389 case Intrinsic::usub_sat: { 6390 const SCEV *X = getSCEV(II->getArgOperand(0)); 6391 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6392 const SCEV *ClampedY = getUMinExpr(X, Y); 6393 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6394 } 6395 case Intrinsic::uadd_sat: { 6396 const SCEV *X = getSCEV(II->getArgOperand(0)); 6397 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6398 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6399 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6400 } 6401 default: 6402 break; 6403 } 6404 } 6405 break; 6406 } 6407 6408 return getUnknown(V); 6409 } 6410 6411 //===----------------------------------------------------------------------===// 6412 // Iteration Count Computation Code 6413 // 6414 6415 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6416 if (!ExitCount) 6417 return 0; 6418 6419 ConstantInt *ExitConst = ExitCount->getValue(); 6420 6421 // Guard against huge trip counts. 6422 if (ExitConst->getValue().getActiveBits() > 32) 6423 return 0; 6424 6425 // In case of integer overflow, this returns 0, which is correct. 6426 return ((unsigned)ExitConst->getZExtValue()) + 1; 6427 } 6428 6429 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6430 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6431 return getSmallConstantTripCount(L, ExitingBB); 6432 6433 // No trip count information for multiple exits. 6434 return 0; 6435 } 6436 6437 unsigned 6438 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6439 const BasicBlock *ExitingBlock) { 6440 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6441 assert(L->isLoopExiting(ExitingBlock) && 6442 "Exiting block must actually branch out of the loop!"); 6443 const SCEVConstant *ExitCount = 6444 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6445 return getConstantTripCount(ExitCount); 6446 } 6447 6448 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6449 const auto *MaxExitCount = 6450 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6451 return getConstantTripCount(MaxExitCount); 6452 } 6453 6454 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6455 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6456 return getSmallConstantTripMultiple(L, ExitingBB); 6457 6458 // No trip multiple information for multiple exits. 6459 return 0; 6460 } 6461 6462 /// Returns the largest constant divisor of the trip count of this loop as a 6463 /// normal unsigned value, if possible. This means that the actual trip count is 6464 /// always a multiple of the returned value (don't forget the trip count could 6465 /// very well be zero as well!). 6466 /// 6467 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6468 /// multiple of a constant (which is also the case if the trip count is simply 6469 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6470 /// if the trip count is very large (>= 2^32). 6471 /// 6472 /// As explained in the comments for getSmallConstantTripCount, this assumes 6473 /// that control exits the loop via ExitingBlock. 6474 unsigned 6475 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6476 const BasicBlock *ExitingBlock) { 6477 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6478 assert(L->isLoopExiting(ExitingBlock) && 6479 "Exiting block must actually branch out of the loop!"); 6480 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6481 if (ExitCount == getCouldNotCompute()) 6482 return 1; 6483 6484 // Get the trip count from the BE count by adding 1. 6485 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6486 6487 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6488 if (!TC) 6489 // Attempt to factor more general cases. Returns the greatest power of 6490 // two divisor. If overflow happens, the trip count expression is still 6491 // divisible by the greatest power of 2 divisor returned. 6492 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6493 6494 ConstantInt *Result = TC->getValue(); 6495 6496 // Guard against huge trip counts (this requires checking 6497 // for zero to handle the case where the trip count == -1 and the 6498 // addition wraps). 6499 if (!Result || Result->getValue().getActiveBits() > 32 || 6500 Result->getValue().getActiveBits() == 0) 6501 return 1; 6502 6503 return (unsigned)Result->getZExtValue(); 6504 } 6505 6506 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6507 const BasicBlock *ExitingBlock, 6508 ExitCountKind Kind) { 6509 switch (Kind) { 6510 case Exact: 6511 case SymbolicMaximum: 6512 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6513 case ConstantMaximum: 6514 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 6515 }; 6516 llvm_unreachable("Invalid ExitCountKind!"); 6517 } 6518 6519 const SCEV * 6520 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6521 SCEVUnionPredicate &Preds) { 6522 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6523 } 6524 6525 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6526 ExitCountKind Kind) { 6527 switch (Kind) { 6528 case Exact: 6529 return getBackedgeTakenInfo(L).getExact(L, this); 6530 case ConstantMaximum: 6531 return getBackedgeTakenInfo(L).getConstantMax(this); 6532 case SymbolicMaximum: 6533 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 6534 }; 6535 llvm_unreachable("Invalid ExitCountKind!"); 6536 } 6537 6538 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6539 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 6540 } 6541 6542 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6543 static void 6544 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6545 BasicBlock *Header = L->getHeader(); 6546 6547 // Push all Loop-header PHIs onto the Worklist stack. 6548 for (PHINode &PN : Header->phis()) 6549 Worklist.push_back(&PN); 6550 } 6551 6552 const ScalarEvolution::BackedgeTakenInfo & 6553 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6554 auto &BTI = getBackedgeTakenInfo(L); 6555 if (BTI.hasFullInfo()) 6556 return BTI; 6557 6558 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6559 6560 if (!Pair.second) 6561 return Pair.first->second; 6562 6563 BackedgeTakenInfo Result = 6564 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6565 6566 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6567 } 6568 6569 ScalarEvolution::BackedgeTakenInfo & 6570 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6571 // Initially insert an invalid entry for this loop. If the insertion 6572 // succeeds, proceed to actually compute a backedge-taken count and 6573 // update the value. The temporary CouldNotCompute value tells SCEV 6574 // code elsewhere that it shouldn't attempt to request a new 6575 // backedge-taken count, which could result in infinite recursion. 6576 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6577 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6578 if (!Pair.second) 6579 return Pair.first->second; 6580 6581 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6582 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6583 // must be cleared in this scope. 6584 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6585 6586 // In product build, there are no usage of statistic. 6587 (void)NumTripCountsComputed; 6588 (void)NumTripCountsNotComputed; 6589 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6590 const SCEV *BEExact = Result.getExact(L, this); 6591 if (BEExact != getCouldNotCompute()) { 6592 assert(isLoopInvariant(BEExact, L) && 6593 isLoopInvariant(Result.getConstantMax(this), L) && 6594 "Computed backedge-taken count isn't loop invariant for loop!"); 6595 ++NumTripCountsComputed; 6596 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 6597 isa<PHINode>(L->getHeader()->begin())) { 6598 // Only count loops that have phi nodes as not being computable. 6599 ++NumTripCountsNotComputed; 6600 } 6601 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6602 6603 // Now that we know more about the trip count for this loop, forget any 6604 // existing SCEV values for PHI nodes in this loop since they are only 6605 // conservative estimates made without the benefit of trip count 6606 // information. This is similar to the code in forgetLoop, except that 6607 // it handles SCEVUnknown PHI nodes specially. 6608 if (Result.hasAnyInfo()) { 6609 SmallVector<Instruction *, 16> Worklist; 6610 PushLoopPHIs(L, Worklist); 6611 6612 SmallPtrSet<Instruction *, 8> Discovered; 6613 while (!Worklist.empty()) { 6614 Instruction *I = Worklist.pop_back_val(); 6615 6616 ValueExprMapType::iterator It = 6617 ValueExprMap.find_as(static_cast<Value *>(I)); 6618 if (It != ValueExprMap.end()) { 6619 const SCEV *Old = It->second; 6620 6621 // SCEVUnknown for a PHI either means that it has an unrecognized 6622 // structure, or it's a PHI that's in the progress of being computed 6623 // by createNodeForPHI. In the former case, additional loop trip 6624 // count information isn't going to change anything. In the later 6625 // case, createNodeForPHI will perform the necessary updates on its 6626 // own when it gets to that point. 6627 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6628 eraseValueFromMap(It->first); 6629 forgetMemoizedResults(Old); 6630 } 6631 if (PHINode *PN = dyn_cast<PHINode>(I)) 6632 ConstantEvolutionLoopExitValue.erase(PN); 6633 } 6634 6635 // Since we don't need to invalidate anything for correctness and we're 6636 // only invalidating to make SCEV's results more precise, we get to stop 6637 // early to avoid invalidating too much. This is especially important in 6638 // cases like: 6639 // 6640 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6641 // loop0: 6642 // %pn0 = phi 6643 // ... 6644 // loop1: 6645 // %pn1 = phi 6646 // ... 6647 // 6648 // where both loop0 and loop1's backedge taken count uses the SCEV 6649 // expression for %v. If we don't have the early stop below then in cases 6650 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6651 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6652 // count for loop1, effectively nullifying SCEV's trip count cache. 6653 for (auto *U : I->users()) 6654 if (auto *I = dyn_cast<Instruction>(U)) { 6655 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6656 if (LoopForUser && L->contains(LoopForUser) && 6657 Discovered.insert(I).second) 6658 Worklist.push_back(I); 6659 } 6660 } 6661 } 6662 6663 // Re-lookup the insert position, since the call to 6664 // computeBackedgeTakenCount above could result in a 6665 // recusive call to getBackedgeTakenInfo (on a different 6666 // loop), which would invalidate the iterator computed 6667 // earlier. 6668 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6669 } 6670 6671 void ScalarEvolution::forgetAllLoops() { 6672 // This method is intended to forget all info about loops. It should 6673 // invalidate caches as if the following happened: 6674 // - The trip counts of all loops have changed arbitrarily 6675 // - Every llvm::Value has been updated in place to produce a different 6676 // result. 6677 BackedgeTakenCounts.clear(); 6678 PredicatedBackedgeTakenCounts.clear(); 6679 LoopPropertiesCache.clear(); 6680 ConstantEvolutionLoopExitValue.clear(); 6681 ValueExprMap.clear(); 6682 ValuesAtScopes.clear(); 6683 LoopDispositions.clear(); 6684 BlockDispositions.clear(); 6685 UnsignedRanges.clear(); 6686 SignedRanges.clear(); 6687 ExprValueMap.clear(); 6688 HasRecMap.clear(); 6689 MinTrailingZerosCache.clear(); 6690 PredicatedSCEVRewrites.clear(); 6691 } 6692 6693 void ScalarEvolution::forgetLoop(const Loop *L) { 6694 // Drop any stored trip count value. 6695 auto RemoveLoopFromBackedgeMap = 6696 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6697 auto BTCPos = Map.find(L); 6698 if (BTCPos != Map.end()) { 6699 BTCPos->second.clear(); 6700 Map.erase(BTCPos); 6701 } 6702 }; 6703 6704 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6705 SmallVector<Instruction *, 32> Worklist; 6706 SmallPtrSet<Instruction *, 16> Visited; 6707 6708 // Iterate over all the loops and sub-loops to drop SCEV information. 6709 while (!LoopWorklist.empty()) { 6710 auto *CurrL = LoopWorklist.pop_back_val(); 6711 6712 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6713 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6714 6715 // Drop information about predicated SCEV rewrites for this loop. 6716 for (auto I = PredicatedSCEVRewrites.begin(); 6717 I != PredicatedSCEVRewrites.end();) { 6718 std::pair<const SCEV *, const Loop *> Entry = I->first; 6719 if (Entry.second == CurrL) 6720 PredicatedSCEVRewrites.erase(I++); 6721 else 6722 ++I; 6723 } 6724 6725 auto LoopUsersItr = LoopUsers.find(CurrL); 6726 if (LoopUsersItr != LoopUsers.end()) { 6727 for (auto *S : LoopUsersItr->second) 6728 forgetMemoizedResults(S); 6729 LoopUsers.erase(LoopUsersItr); 6730 } 6731 6732 // Drop information about expressions based on loop-header PHIs. 6733 PushLoopPHIs(CurrL, Worklist); 6734 6735 while (!Worklist.empty()) { 6736 Instruction *I = Worklist.pop_back_val(); 6737 if (!Visited.insert(I).second) 6738 continue; 6739 6740 ValueExprMapType::iterator It = 6741 ValueExprMap.find_as(static_cast<Value *>(I)); 6742 if (It != ValueExprMap.end()) { 6743 eraseValueFromMap(It->first); 6744 forgetMemoizedResults(It->second); 6745 if (PHINode *PN = dyn_cast<PHINode>(I)) 6746 ConstantEvolutionLoopExitValue.erase(PN); 6747 } 6748 6749 PushDefUseChildren(I, Worklist); 6750 } 6751 6752 LoopPropertiesCache.erase(CurrL); 6753 // Forget all contained loops too, to avoid dangling entries in the 6754 // ValuesAtScopes map. 6755 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6756 } 6757 } 6758 6759 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6760 while (Loop *Parent = L->getParentLoop()) 6761 L = Parent; 6762 forgetLoop(L); 6763 } 6764 6765 void ScalarEvolution::forgetValue(Value *V) { 6766 Instruction *I = dyn_cast<Instruction>(V); 6767 if (!I) return; 6768 6769 // Drop information about expressions based on loop-header PHIs. 6770 SmallVector<Instruction *, 16> Worklist; 6771 Worklist.push_back(I); 6772 6773 SmallPtrSet<Instruction *, 8> Visited; 6774 while (!Worklist.empty()) { 6775 I = Worklist.pop_back_val(); 6776 if (!Visited.insert(I).second) 6777 continue; 6778 6779 ValueExprMapType::iterator It = 6780 ValueExprMap.find_as(static_cast<Value *>(I)); 6781 if (It != ValueExprMap.end()) { 6782 eraseValueFromMap(It->first); 6783 forgetMemoizedResults(It->second); 6784 if (PHINode *PN = dyn_cast<PHINode>(I)) 6785 ConstantEvolutionLoopExitValue.erase(PN); 6786 } 6787 6788 PushDefUseChildren(I, Worklist); 6789 } 6790 } 6791 6792 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 6793 LoopDispositions.clear(); 6794 } 6795 6796 /// Get the exact loop backedge taken count considering all loop exits. A 6797 /// computable result can only be returned for loops with all exiting blocks 6798 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6799 /// is never skipped. This is a valid assumption as long as the loop exits via 6800 /// that test. For precise results, it is the caller's responsibility to specify 6801 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6802 const SCEV * 6803 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6804 SCEVUnionPredicate *Preds) const { 6805 // If any exits were not computable, the loop is not computable. 6806 if (!isComplete() || ExitNotTaken.empty()) 6807 return SE->getCouldNotCompute(); 6808 6809 const BasicBlock *Latch = L->getLoopLatch(); 6810 // All exiting blocks we have collected must dominate the only backedge. 6811 if (!Latch) 6812 return SE->getCouldNotCompute(); 6813 6814 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6815 // count is simply a minimum out of all these calculated exit counts. 6816 SmallVector<const SCEV *, 2> Ops; 6817 for (auto &ENT : ExitNotTaken) { 6818 const SCEV *BECount = ENT.ExactNotTaken; 6819 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6820 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6821 "We should only have known counts for exiting blocks that dominate " 6822 "latch!"); 6823 6824 Ops.push_back(BECount); 6825 6826 if (Preds && !ENT.hasAlwaysTruePredicate()) 6827 Preds->add(ENT.Predicate.get()); 6828 6829 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6830 "Predicate should be always true!"); 6831 } 6832 6833 return SE->getUMinFromMismatchedTypes(Ops); 6834 } 6835 6836 /// Get the exact not taken count for this loop exit. 6837 const SCEV * 6838 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 6839 ScalarEvolution *SE) const { 6840 for (auto &ENT : ExitNotTaken) 6841 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6842 return ENT.ExactNotTaken; 6843 6844 return SE->getCouldNotCompute(); 6845 } 6846 6847 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 6848 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 6849 for (auto &ENT : ExitNotTaken) 6850 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6851 return ENT.MaxNotTaken; 6852 6853 return SE->getCouldNotCompute(); 6854 } 6855 6856 /// getConstantMax - Get the constant max backedge taken count for the loop. 6857 const SCEV * 6858 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 6859 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6860 return !ENT.hasAlwaysTruePredicate(); 6861 }; 6862 6863 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 6864 return SE->getCouldNotCompute(); 6865 6866 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 6867 isa<SCEVConstant>(getConstantMax())) && 6868 "No point in having a non-constant max backedge taken count!"); 6869 return getConstantMax(); 6870 } 6871 6872 const SCEV * 6873 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 6874 ScalarEvolution *SE) { 6875 if (!SymbolicMax) 6876 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 6877 return SymbolicMax; 6878 } 6879 6880 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 6881 ScalarEvolution *SE) const { 6882 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6883 return !ENT.hasAlwaysTruePredicate(); 6884 }; 6885 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6886 } 6887 6888 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6889 ScalarEvolution *SE) const { 6890 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() && 6891 SE->hasOperand(getConstantMax(), S)) 6892 return true; 6893 6894 for (auto &ENT : ExitNotTaken) 6895 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6896 SE->hasOperand(ENT.ExactNotTaken, S)) 6897 return true; 6898 6899 return false; 6900 } 6901 6902 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6903 : ExactNotTaken(E), MaxNotTaken(E) { 6904 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6905 isa<SCEVConstant>(MaxNotTaken)) && 6906 "No point in having a non-constant max backedge taken count!"); 6907 } 6908 6909 ScalarEvolution::ExitLimit::ExitLimit( 6910 const SCEV *E, const SCEV *M, bool MaxOrZero, 6911 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6912 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6913 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6914 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6915 "Exact is not allowed to be less precise than Max"); 6916 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6917 isa<SCEVConstant>(MaxNotTaken)) && 6918 "No point in having a non-constant max backedge taken count!"); 6919 for (auto *PredSet : PredSetList) 6920 for (auto *P : *PredSet) 6921 addPredicate(P); 6922 } 6923 6924 ScalarEvolution::ExitLimit::ExitLimit( 6925 const SCEV *E, const SCEV *M, bool MaxOrZero, 6926 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6927 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6928 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6929 isa<SCEVConstant>(MaxNotTaken)) && 6930 "No point in having a non-constant max backedge taken count!"); 6931 } 6932 6933 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6934 bool MaxOrZero) 6935 : ExitLimit(E, M, MaxOrZero, None) { 6936 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6937 isa<SCEVConstant>(MaxNotTaken)) && 6938 "No point in having a non-constant max backedge taken count!"); 6939 } 6940 6941 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6942 /// computable exit into a persistent ExitNotTakenInfo array. 6943 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6944 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 6945 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 6946 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 6947 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6948 6949 ExitNotTaken.reserve(ExitCounts.size()); 6950 std::transform( 6951 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6952 [&](const EdgeExitInfo &EEI) { 6953 BasicBlock *ExitBB = EEI.first; 6954 const ExitLimit &EL = EEI.second; 6955 if (EL.Predicates.empty()) 6956 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6957 nullptr); 6958 6959 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6960 for (auto *Pred : EL.Predicates) 6961 Predicate->add(Pred); 6962 6963 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6964 std::move(Predicate)); 6965 }); 6966 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 6967 isa<SCEVConstant>(ConstantMax)) && 6968 "No point in having a non-constant max backedge taken count!"); 6969 } 6970 6971 /// Invalidate this result and free the ExitNotTakenInfo array. 6972 void ScalarEvolution::BackedgeTakenInfo::clear() { 6973 ExitNotTaken.clear(); 6974 } 6975 6976 /// Compute the number of times the backedge of the specified loop will execute. 6977 ScalarEvolution::BackedgeTakenInfo 6978 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6979 bool AllowPredicates) { 6980 SmallVector<BasicBlock *, 8> ExitingBlocks; 6981 L->getExitingBlocks(ExitingBlocks); 6982 6983 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6984 6985 SmallVector<EdgeExitInfo, 4> ExitCounts; 6986 bool CouldComputeBECount = true; 6987 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6988 const SCEV *MustExitMaxBECount = nullptr; 6989 const SCEV *MayExitMaxBECount = nullptr; 6990 bool MustExitMaxOrZero = false; 6991 6992 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6993 // and compute maxBECount. 6994 // Do a union of all the predicates here. 6995 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6996 BasicBlock *ExitBB = ExitingBlocks[i]; 6997 6998 // We canonicalize untaken exits to br (constant), ignore them so that 6999 // proving an exit untaken doesn't negatively impact our ability to reason 7000 // about the loop as whole. 7001 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7002 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7003 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7004 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7005 continue; 7006 } 7007 7008 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7009 7010 assert((AllowPredicates || EL.Predicates.empty()) && 7011 "Predicated exit limit when predicates are not allowed!"); 7012 7013 // 1. For each exit that can be computed, add an entry to ExitCounts. 7014 // CouldComputeBECount is true only if all exits can be computed. 7015 if (EL.ExactNotTaken == getCouldNotCompute()) 7016 // We couldn't compute an exact value for this exit, so 7017 // we won't be able to compute an exact value for the loop. 7018 CouldComputeBECount = false; 7019 else 7020 ExitCounts.emplace_back(ExitBB, EL); 7021 7022 // 2. Derive the loop's MaxBECount from each exit's max number of 7023 // non-exiting iterations. Partition the loop exits into two kinds: 7024 // LoopMustExits and LoopMayExits. 7025 // 7026 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7027 // is a LoopMayExit. If any computable LoopMustExit is found, then 7028 // MaxBECount is the minimum EL.MaxNotTaken of computable 7029 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7030 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7031 // computable EL.MaxNotTaken. 7032 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7033 DT.dominates(ExitBB, Latch)) { 7034 if (!MustExitMaxBECount) { 7035 MustExitMaxBECount = EL.MaxNotTaken; 7036 MustExitMaxOrZero = EL.MaxOrZero; 7037 } else { 7038 MustExitMaxBECount = 7039 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7040 } 7041 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7042 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7043 MayExitMaxBECount = EL.MaxNotTaken; 7044 else { 7045 MayExitMaxBECount = 7046 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7047 } 7048 } 7049 } 7050 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7051 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7052 // The loop backedge will be taken the maximum or zero times if there's 7053 // a single exit that must be taken the maximum or zero times. 7054 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7055 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7056 MaxBECount, MaxOrZero); 7057 } 7058 7059 ScalarEvolution::ExitLimit 7060 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7061 bool AllowPredicates) { 7062 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7063 // If our exiting block does not dominate the latch, then its connection with 7064 // loop's exit limit may be far from trivial. 7065 const BasicBlock *Latch = L->getLoopLatch(); 7066 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7067 return getCouldNotCompute(); 7068 7069 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7070 Instruction *Term = ExitingBlock->getTerminator(); 7071 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7072 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7073 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7074 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7075 "It should have one successor in loop and one exit block!"); 7076 // Proceed to the next level to examine the exit condition expression. 7077 return computeExitLimitFromCond( 7078 L, BI->getCondition(), ExitIfTrue, 7079 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7080 } 7081 7082 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7083 // For switch, make sure that there is a single exit from the loop. 7084 BasicBlock *Exit = nullptr; 7085 for (auto *SBB : successors(ExitingBlock)) 7086 if (!L->contains(SBB)) { 7087 if (Exit) // Multiple exit successors. 7088 return getCouldNotCompute(); 7089 Exit = SBB; 7090 } 7091 assert(Exit && "Exiting block must have at least one exit"); 7092 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7093 /*ControlsExit=*/IsOnlyExit); 7094 } 7095 7096 return getCouldNotCompute(); 7097 } 7098 7099 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7100 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7101 bool ControlsExit, bool AllowPredicates) { 7102 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7103 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7104 ControlsExit, AllowPredicates); 7105 } 7106 7107 Optional<ScalarEvolution::ExitLimit> 7108 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7109 bool ExitIfTrue, bool ControlsExit, 7110 bool AllowPredicates) { 7111 (void)this->L; 7112 (void)this->ExitIfTrue; 7113 (void)this->AllowPredicates; 7114 7115 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7116 this->AllowPredicates == AllowPredicates && 7117 "Variance in assumed invariant key components!"); 7118 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7119 if (Itr == TripCountMap.end()) 7120 return None; 7121 return Itr->second; 7122 } 7123 7124 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7125 bool ExitIfTrue, 7126 bool ControlsExit, 7127 bool AllowPredicates, 7128 const ExitLimit &EL) { 7129 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7130 this->AllowPredicates == AllowPredicates && 7131 "Variance in assumed invariant key components!"); 7132 7133 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7134 assert(InsertResult.second && "Expected successful insertion!"); 7135 (void)InsertResult; 7136 (void)ExitIfTrue; 7137 } 7138 7139 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7140 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7141 bool ControlsExit, bool AllowPredicates) { 7142 7143 if (auto MaybeEL = 7144 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7145 return *MaybeEL; 7146 7147 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7148 ControlsExit, AllowPredicates); 7149 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7150 return EL; 7151 } 7152 7153 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7154 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7155 bool ControlsExit, bool AllowPredicates) { 7156 // Check if the controlling expression for this loop is an And or Or. 7157 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7158 if (BO->getOpcode() == Instruction::And) { 7159 // Recurse on the operands of the and. 7160 bool EitherMayExit = !ExitIfTrue; 7161 ExitLimit EL0 = computeExitLimitFromCondCached( 7162 Cache, L, BO->getOperand(0), ExitIfTrue, 7163 ControlsExit && !EitherMayExit, AllowPredicates); 7164 ExitLimit EL1 = computeExitLimitFromCondCached( 7165 Cache, L, BO->getOperand(1), ExitIfTrue, 7166 ControlsExit && !EitherMayExit, AllowPredicates); 7167 // Be robust against unsimplified IR for the form "and i1 X, true" 7168 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7169 return CI->isOne() ? EL0 : EL1; 7170 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7171 return CI->isOne() ? EL1 : EL0; 7172 const SCEV *BECount = getCouldNotCompute(); 7173 const SCEV *MaxBECount = getCouldNotCompute(); 7174 if (EitherMayExit) { 7175 // Both conditions must be true for the loop to continue executing. 7176 // Choose the less conservative count. 7177 if (EL0.ExactNotTaken == getCouldNotCompute() || 7178 EL1.ExactNotTaken == getCouldNotCompute()) 7179 BECount = getCouldNotCompute(); 7180 else 7181 BECount = 7182 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7183 if (EL0.MaxNotTaken == getCouldNotCompute()) 7184 MaxBECount = EL1.MaxNotTaken; 7185 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7186 MaxBECount = EL0.MaxNotTaken; 7187 else 7188 MaxBECount = 7189 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7190 } else { 7191 // Both conditions must be true at the same time for the loop to exit. 7192 // For now, be conservative. 7193 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7194 MaxBECount = EL0.MaxNotTaken; 7195 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7196 BECount = EL0.ExactNotTaken; 7197 } 7198 7199 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7200 // to be more aggressive when computing BECount than when computing 7201 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7202 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7203 // to not. 7204 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7205 !isa<SCEVCouldNotCompute>(BECount)) 7206 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7207 7208 return ExitLimit(BECount, MaxBECount, false, 7209 {&EL0.Predicates, &EL1.Predicates}); 7210 } 7211 if (BO->getOpcode() == Instruction::Or) { 7212 // Recurse on the operands of the or. 7213 bool EitherMayExit = ExitIfTrue; 7214 ExitLimit EL0 = computeExitLimitFromCondCached( 7215 Cache, L, BO->getOperand(0), ExitIfTrue, 7216 ControlsExit && !EitherMayExit, AllowPredicates); 7217 ExitLimit EL1 = computeExitLimitFromCondCached( 7218 Cache, L, BO->getOperand(1), ExitIfTrue, 7219 ControlsExit && !EitherMayExit, AllowPredicates); 7220 // Be robust against unsimplified IR for the form "or i1 X, true" 7221 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7222 return CI->isZero() ? EL0 : EL1; 7223 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7224 return CI->isZero() ? EL1 : EL0; 7225 const SCEV *BECount = getCouldNotCompute(); 7226 const SCEV *MaxBECount = getCouldNotCompute(); 7227 if (EitherMayExit) { 7228 // Both conditions must be false for the loop to continue executing. 7229 // Choose the less conservative count. 7230 if (EL0.ExactNotTaken == getCouldNotCompute() || 7231 EL1.ExactNotTaken == getCouldNotCompute()) 7232 BECount = getCouldNotCompute(); 7233 else 7234 BECount = 7235 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7236 if (EL0.MaxNotTaken == getCouldNotCompute()) 7237 MaxBECount = EL1.MaxNotTaken; 7238 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7239 MaxBECount = EL0.MaxNotTaken; 7240 else 7241 MaxBECount = 7242 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7243 } else { 7244 // Both conditions must be false at the same time for the loop to exit. 7245 // For now, be conservative. 7246 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7247 MaxBECount = EL0.MaxNotTaken; 7248 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7249 BECount = EL0.ExactNotTaken; 7250 } 7251 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7252 // to be more aggressive when computing BECount than when computing 7253 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7254 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7255 // to not. 7256 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7257 !isa<SCEVCouldNotCompute>(BECount)) 7258 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7259 7260 return ExitLimit(BECount, MaxBECount, false, 7261 {&EL0.Predicates, &EL1.Predicates}); 7262 } 7263 } 7264 7265 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7266 // Proceed to the next level to examine the icmp. 7267 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7268 ExitLimit EL = 7269 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7270 if (EL.hasFullInfo() || !AllowPredicates) 7271 return EL; 7272 7273 // Try again, but use SCEV predicates this time. 7274 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7275 /*AllowPredicates=*/true); 7276 } 7277 7278 // Check for a constant condition. These are normally stripped out by 7279 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7280 // preserve the CFG and is temporarily leaving constant conditions 7281 // in place. 7282 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7283 if (ExitIfTrue == !CI->getZExtValue()) 7284 // The backedge is always taken. 7285 return getCouldNotCompute(); 7286 else 7287 // The backedge is never taken. 7288 return getZero(CI->getType()); 7289 } 7290 7291 // If it's not an integer or pointer comparison then compute it the hard way. 7292 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7293 } 7294 7295 ScalarEvolution::ExitLimit 7296 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7297 ICmpInst *ExitCond, 7298 bool ExitIfTrue, 7299 bool ControlsExit, 7300 bool AllowPredicates) { 7301 // If the condition was exit on true, convert the condition to exit on false 7302 ICmpInst::Predicate Pred; 7303 if (!ExitIfTrue) 7304 Pred = ExitCond->getPredicate(); 7305 else 7306 Pred = ExitCond->getInversePredicate(); 7307 const ICmpInst::Predicate OriginalPred = Pred; 7308 7309 // Handle common loops like: for (X = "string"; *X; ++X) 7310 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7311 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7312 ExitLimit ItCnt = 7313 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7314 if (ItCnt.hasAnyInfo()) 7315 return ItCnt; 7316 } 7317 7318 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7319 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7320 7321 // Try to evaluate any dependencies out of the loop. 7322 LHS = getSCEVAtScope(LHS, L); 7323 RHS = getSCEVAtScope(RHS, L); 7324 7325 // At this point, we would like to compute how many iterations of the 7326 // loop the predicate will return true for these inputs. 7327 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7328 // If there is a loop-invariant, force it into the RHS. 7329 std::swap(LHS, RHS); 7330 Pred = ICmpInst::getSwappedPredicate(Pred); 7331 } 7332 7333 // Simplify the operands before analyzing them. 7334 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7335 7336 // If we have a comparison of a chrec against a constant, try to use value 7337 // ranges to answer this query. 7338 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7339 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7340 if (AddRec->getLoop() == L) { 7341 // Form the constant range. 7342 ConstantRange CompRange = 7343 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7344 7345 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7346 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7347 } 7348 7349 switch (Pred) { 7350 case ICmpInst::ICMP_NE: { // while (X != Y) 7351 // Convert to: while (X-Y != 0) 7352 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7353 AllowPredicates); 7354 if (EL.hasAnyInfo()) return EL; 7355 break; 7356 } 7357 case ICmpInst::ICMP_EQ: { // while (X == Y) 7358 // Convert to: while (X-Y == 0) 7359 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7360 if (EL.hasAnyInfo()) return EL; 7361 break; 7362 } 7363 case ICmpInst::ICMP_SLT: 7364 case ICmpInst::ICMP_ULT: { // while (X < Y) 7365 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7366 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7367 AllowPredicates); 7368 if (EL.hasAnyInfo()) return EL; 7369 break; 7370 } 7371 case ICmpInst::ICMP_SGT: 7372 case ICmpInst::ICMP_UGT: { // while (X > Y) 7373 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7374 ExitLimit EL = 7375 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7376 AllowPredicates); 7377 if (EL.hasAnyInfo()) return EL; 7378 break; 7379 } 7380 default: 7381 break; 7382 } 7383 7384 auto *ExhaustiveCount = 7385 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7386 7387 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7388 return ExhaustiveCount; 7389 7390 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7391 ExitCond->getOperand(1), L, OriginalPred); 7392 } 7393 7394 ScalarEvolution::ExitLimit 7395 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7396 SwitchInst *Switch, 7397 BasicBlock *ExitingBlock, 7398 bool ControlsExit) { 7399 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7400 7401 // Give up if the exit is the default dest of a switch. 7402 if (Switch->getDefaultDest() == ExitingBlock) 7403 return getCouldNotCompute(); 7404 7405 assert(L->contains(Switch->getDefaultDest()) && 7406 "Default case must not exit the loop!"); 7407 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7408 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7409 7410 // while (X != Y) --> while (X-Y != 0) 7411 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7412 if (EL.hasAnyInfo()) 7413 return EL; 7414 7415 return getCouldNotCompute(); 7416 } 7417 7418 static ConstantInt * 7419 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7420 ScalarEvolution &SE) { 7421 const SCEV *InVal = SE.getConstant(C); 7422 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7423 assert(isa<SCEVConstant>(Val) && 7424 "Evaluation of SCEV at constant didn't fold correctly?"); 7425 return cast<SCEVConstant>(Val)->getValue(); 7426 } 7427 7428 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7429 /// compute the backedge execution count. 7430 ScalarEvolution::ExitLimit 7431 ScalarEvolution::computeLoadConstantCompareExitLimit( 7432 LoadInst *LI, 7433 Constant *RHS, 7434 const Loop *L, 7435 ICmpInst::Predicate predicate) { 7436 if (LI->isVolatile()) return getCouldNotCompute(); 7437 7438 // Check to see if the loaded pointer is a getelementptr of a global. 7439 // TODO: Use SCEV instead of manually grubbing with GEPs. 7440 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7441 if (!GEP) return getCouldNotCompute(); 7442 7443 // Make sure that it is really a constant global we are gepping, with an 7444 // initializer, and make sure the first IDX is really 0. 7445 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7446 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7447 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7448 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7449 return getCouldNotCompute(); 7450 7451 // Okay, we allow one non-constant index into the GEP instruction. 7452 Value *VarIdx = nullptr; 7453 std::vector<Constant*> Indexes; 7454 unsigned VarIdxNum = 0; 7455 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7456 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7457 Indexes.push_back(CI); 7458 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7459 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7460 VarIdx = GEP->getOperand(i); 7461 VarIdxNum = i-2; 7462 Indexes.push_back(nullptr); 7463 } 7464 7465 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7466 if (!VarIdx) 7467 return getCouldNotCompute(); 7468 7469 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7470 // Check to see if X is a loop variant variable value now. 7471 const SCEV *Idx = getSCEV(VarIdx); 7472 Idx = getSCEVAtScope(Idx, L); 7473 7474 // We can only recognize very limited forms of loop index expressions, in 7475 // particular, only affine AddRec's like {C1,+,C2}. 7476 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7477 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7478 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7479 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7480 return getCouldNotCompute(); 7481 7482 unsigned MaxSteps = MaxBruteForceIterations; 7483 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7484 ConstantInt *ItCst = ConstantInt::get( 7485 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7486 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7487 7488 // Form the GEP offset. 7489 Indexes[VarIdxNum] = Val; 7490 7491 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7492 Indexes); 7493 if (!Result) break; // Cannot compute! 7494 7495 // Evaluate the condition for this iteration. 7496 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7497 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7498 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7499 ++NumArrayLenItCounts; 7500 return getConstant(ItCst); // Found terminating iteration! 7501 } 7502 } 7503 return getCouldNotCompute(); 7504 } 7505 7506 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7507 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7508 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7509 if (!RHS) 7510 return getCouldNotCompute(); 7511 7512 const BasicBlock *Latch = L->getLoopLatch(); 7513 if (!Latch) 7514 return getCouldNotCompute(); 7515 7516 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7517 if (!Predecessor) 7518 return getCouldNotCompute(); 7519 7520 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7521 // Return LHS in OutLHS and shift_opt in OutOpCode. 7522 auto MatchPositiveShift = 7523 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7524 7525 using namespace PatternMatch; 7526 7527 ConstantInt *ShiftAmt; 7528 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7529 OutOpCode = Instruction::LShr; 7530 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7531 OutOpCode = Instruction::AShr; 7532 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7533 OutOpCode = Instruction::Shl; 7534 else 7535 return false; 7536 7537 return ShiftAmt->getValue().isStrictlyPositive(); 7538 }; 7539 7540 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7541 // 7542 // loop: 7543 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7544 // %iv.shifted = lshr i32 %iv, <positive constant> 7545 // 7546 // Return true on a successful match. Return the corresponding PHI node (%iv 7547 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7548 auto MatchShiftRecurrence = 7549 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7550 Optional<Instruction::BinaryOps> PostShiftOpCode; 7551 7552 { 7553 Instruction::BinaryOps OpC; 7554 Value *V; 7555 7556 // If we encounter a shift instruction, "peel off" the shift operation, 7557 // and remember that we did so. Later when we inspect %iv's backedge 7558 // value, we will make sure that the backedge value uses the same 7559 // operation. 7560 // 7561 // Note: the peeled shift operation does not have to be the same 7562 // instruction as the one feeding into the PHI's backedge value. We only 7563 // really care about it being the same *kind* of shift instruction -- 7564 // that's all that is required for our later inferences to hold. 7565 if (MatchPositiveShift(LHS, V, OpC)) { 7566 PostShiftOpCode = OpC; 7567 LHS = V; 7568 } 7569 } 7570 7571 PNOut = dyn_cast<PHINode>(LHS); 7572 if (!PNOut || PNOut->getParent() != L->getHeader()) 7573 return false; 7574 7575 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7576 Value *OpLHS; 7577 7578 return 7579 // The backedge value for the PHI node must be a shift by a positive 7580 // amount 7581 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7582 7583 // of the PHI node itself 7584 OpLHS == PNOut && 7585 7586 // and the kind of shift should be match the kind of shift we peeled 7587 // off, if any. 7588 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7589 }; 7590 7591 PHINode *PN; 7592 Instruction::BinaryOps OpCode; 7593 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7594 return getCouldNotCompute(); 7595 7596 const DataLayout &DL = getDataLayout(); 7597 7598 // The key rationale for this optimization is that for some kinds of shift 7599 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7600 // within a finite number of iterations. If the condition guarding the 7601 // backedge (in the sense that the backedge is taken if the condition is true) 7602 // is false for the value the shift recurrence stabilizes to, then we know 7603 // that the backedge is taken only a finite number of times. 7604 7605 ConstantInt *StableValue = nullptr; 7606 switch (OpCode) { 7607 default: 7608 llvm_unreachable("Impossible case!"); 7609 7610 case Instruction::AShr: { 7611 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7612 // bitwidth(K) iterations. 7613 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7614 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7615 Predecessor->getTerminator(), &DT); 7616 auto *Ty = cast<IntegerType>(RHS->getType()); 7617 if (Known.isNonNegative()) 7618 StableValue = ConstantInt::get(Ty, 0); 7619 else if (Known.isNegative()) 7620 StableValue = ConstantInt::get(Ty, -1, true); 7621 else 7622 return getCouldNotCompute(); 7623 7624 break; 7625 } 7626 case Instruction::LShr: 7627 case Instruction::Shl: 7628 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7629 // stabilize to 0 in at most bitwidth(K) iterations. 7630 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7631 break; 7632 } 7633 7634 auto *Result = 7635 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7636 assert(Result->getType()->isIntegerTy(1) && 7637 "Otherwise cannot be an operand to a branch instruction"); 7638 7639 if (Result->isZeroValue()) { 7640 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7641 const SCEV *UpperBound = 7642 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7643 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7644 } 7645 7646 return getCouldNotCompute(); 7647 } 7648 7649 /// Return true if we can constant fold an instruction of the specified type, 7650 /// assuming that all operands were constants. 7651 static bool CanConstantFold(const Instruction *I) { 7652 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7653 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7654 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7655 return true; 7656 7657 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7658 if (const Function *F = CI->getCalledFunction()) 7659 return canConstantFoldCallTo(CI, F); 7660 return false; 7661 } 7662 7663 /// Determine whether this instruction can constant evolve within this loop 7664 /// assuming its operands can all constant evolve. 7665 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7666 // An instruction outside of the loop can't be derived from a loop PHI. 7667 if (!L->contains(I)) return false; 7668 7669 if (isa<PHINode>(I)) { 7670 // We don't currently keep track of the control flow needed to evaluate 7671 // PHIs, so we cannot handle PHIs inside of loops. 7672 return L->getHeader() == I->getParent(); 7673 } 7674 7675 // If we won't be able to constant fold this expression even if the operands 7676 // are constants, bail early. 7677 return CanConstantFold(I); 7678 } 7679 7680 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7681 /// recursing through each instruction operand until reaching a loop header phi. 7682 static PHINode * 7683 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7684 DenseMap<Instruction *, PHINode *> &PHIMap, 7685 unsigned Depth) { 7686 if (Depth > MaxConstantEvolvingDepth) 7687 return nullptr; 7688 7689 // Otherwise, we can evaluate this instruction if all of its operands are 7690 // constant or derived from a PHI node themselves. 7691 PHINode *PHI = nullptr; 7692 for (Value *Op : UseInst->operands()) { 7693 if (isa<Constant>(Op)) continue; 7694 7695 Instruction *OpInst = dyn_cast<Instruction>(Op); 7696 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7697 7698 PHINode *P = dyn_cast<PHINode>(OpInst); 7699 if (!P) 7700 // If this operand is already visited, reuse the prior result. 7701 // We may have P != PHI if this is the deepest point at which the 7702 // inconsistent paths meet. 7703 P = PHIMap.lookup(OpInst); 7704 if (!P) { 7705 // Recurse and memoize the results, whether a phi is found or not. 7706 // This recursive call invalidates pointers into PHIMap. 7707 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7708 PHIMap[OpInst] = P; 7709 } 7710 if (!P) 7711 return nullptr; // Not evolving from PHI 7712 if (PHI && PHI != P) 7713 return nullptr; // Evolving from multiple different PHIs. 7714 PHI = P; 7715 } 7716 // This is a expression evolving from a constant PHI! 7717 return PHI; 7718 } 7719 7720 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7721 /// in the loop that V is derived from. We allow arbitrary operations along the 7722 /// way, but the operands of an operation must either be constants or a value 7723 /// derived from a constant PHI. If this expression does not fit with these 7724 /// constraints, return null. 7725 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7726 Instruction *I = dyn_cast<Instruction>(V); 7727 if (!I || !canConstantEvolve(I, L)) return nullptr; 7728 7729 if (PHINode *PN = dyn_cast<PHINode>(I)) 7730 return PN; 7731 7732 // Record non-constant instructions contained by the loop. 7733 DenseMap<Instruction *, PHINode *> PHIMap; 7734 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7735 } 7736 7737 /// EvaluateExpression - Given an expression that passes the 7738 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7739 /// in the loop has the value PHIVal. If we can't fold this expression for some 7740 /// reason, return null. 7741 static Constant *EvaluateExpression(Value *V, const Loop *L, 7742 DenseMap<Instruction *, Constant *> &Vals, 7743 const DataLayout &DL, 7744 const TargetLibraryInfo *TLI) { 7745 // Convenient constant check, but redundant for recursive calls. 7746 if (Constant *C = dyn_cast<Constant>(V)) return C; 7747 Instruction *I = dyn_cast<Instruction>(V); 7748 if (!I) return nullptr; 7749 7750 if (Constant *C = Vals.lookup(I)) return C; 7751 7752 // An instruction inside the loop depends on a value outside the loop that we 7753 // weren't given a mapping for, or a value such as a call inside the loop. 7754 if (!canConstantEvolve(I, L)) return nullptr; 7755 7756 // An unmapped PHI can be due to a branch or another loop inside this loop, 7757 // or due to this not being the initial iteration through a loop where we 7758 // couldn't compute the evolution of this particular PHI last time. 7759 if (isa<PHINode>(I)) return nullptr; 7760 7761 std::vector<Constant*> Operands(I->getNumOperands()); 7762 7763 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7764 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7765 if (!Operand) { 7766 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7767 if (!Operands[i]) return nullptr; 7768 continue; 7769 } 7770 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7771 Vals[Operand] = C; 7772 if (!C) return nullptr; 7773 Operands[i] = C; 7774 } 7775 7776 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7777 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7778 Operands[1], DL, TLI); 7779 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7780 if (!LI->isVolatile()) 7781 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7782 } 7783 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7784 } 7785 7786 7787 // If every incoming value to PN except the one for BB is a specific Constant, 7788 // return that, else return nullptr. 7789 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7790 Constant *IncomingVal = nullptr; 7791 7792 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7793 if (PN->getIncomingBlock(i) == BB) 7794 continue; 7795 7796 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7797 if (!CurrentVal) 7798 return nullptr; 7799 7800 if (IncomingVal != CurrentVal) { 7801 if (IncomingVal) 7802 return nullptr; 7803 IncomingVal = CurrentVal; 7804 } 7805 } 7806 7807 return IncomingVal; 7808 } 7809 7810 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7811 /// in the header of its containing loop, we know the loop executes a 7812 /// constant number of times, and the PHI node is just a recurrence 7813 /// involving constants, fold it. 7814 Constant * 7815 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7816 const APInt &BEs, 7817 const Loop *L) { 7818 auto I = ConstantEvolutionLoopExitValue.find(PN); 7819 if (I != ConstantEvolutionLoopExitValue.end()) 7820 return I->second; 7821 7822 if (BEs.ugt(MaxBruteForceIterations)) 7823 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7824 7825 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7826 7827 DenseMap<Instruction *, Constant *> CurrentIterVals; 7828 BasicBlock *Header = L->getHeader(); 7829 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7830 7831 BasicBlock *Latch = L->getLoopLatch(); 7832 if (!Latch) 7833 return nullptr; 7834 7835 for (PHINode &PHI : Header->phis()) { 7836 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7837 CurrentIterVals[&PHI] = StartCST; 7838 } 7839 if (!CurrentIterVals.count(PN)) 7840 return RetVal = nullptr; 7841 7842 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7843 7844 // Execute the loop symbolically to determine the exit value. 7845 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7846 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7847 7848 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7849 unsigned IterationNum = 0; 7850 const DataLayout &DL = getDataLayout(); 7851 for (; ; ++IterationNum) { 7852 if (IterationNum == NumIterations) 7853 return RetVal = CurrentIterVals[PN]; // Got exit value! 7854 7855 // Compute the value of the PHIs for the next iteration. 7856 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7857 DenseMap<Instruction *, Constant *> NextIterVals; 7858 Constant *NextPHI = 7859 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7860 if (!NextPHI) 7861 return nullptr; // Couldn't evaluate! 7862 NextIterVals[PN] = NextPHI; 7863 7864 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7865 7866 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7867 // cease to be able to evaluate one of them or if they stop evolving, 7868 // because that doesn't necessarily prevent us from computing PN. 7869 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7870 for (const auto &I : CurrentIterVals) { 7871 PHINode *PHI = dyn_cast<PHINode>(I.first); 7872 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7873 PHIsToCompute.emplace_back(PHI, I.second); 7874 } 7875 // We use two distinct loops because EvaluateExpression may invalidate any 7876 // iterators into CurrentIterVals. 7877 for (const auto &I : PHIsToCompute) { 7878 PHINode *PHI = I.first; 7879 Constant *&NextPHI = NextIterVals[PHI]; 7880 if (!NextPHI) { // Not already computed. 7881 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7882 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7883 } 7884 if (NextPHI != I.second) 7885 StoppedEvolving = false; 7886 } 7887 7888 // If all entries in CurrentIterVals == NextIterVals then we can stop 7889 // iterating, the loop can't continue to change. 7890 if (StoppedEvolving) 7891 return RetVal = CurrentIterVals[PN]; 7892 7893 CurrentIterVals.swap(NextIterVals); 7894 } 7895 } 7896 7897 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7898 Value *Cond, 7899 bool ExitWhen) { 7900 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7901 if (!PN) return getCouldNotCompute(); 7902 7903 // If the loop is canonicalized, the PHI will have exactly two entries. 7904 // That's the only form we support here. 7905 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7906 7907 DenseMap<Instruction *, Constant *> CurrentIterVals; 7908 BasicBlock *Header = L->getHeader(); 7909 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7910 7911 BasicBlock *Latch = L->getLoopLatch(); 7912 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7913 7914 for (PHINode &PHI : Header->phis()) { 7915 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7916 CurrentIterVals[&PHI] = StartCST; 7917 } 7918 if (!CurrentIterVals.count(PN)) 7919 return getCouldNotCompute(); 7920 7921 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7922 // the loop symbolically to determine when the condition gets a value of 7923 // "ExitWhen". 7924 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7925 const DataLayout &DL = getDataLayout(); 7926 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7927 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7928 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7929 7930 // Couldn't symbolically evaluate. 7931 if (!CondVal) return getCouldNotCompute(); 7932 7933 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7934 ++NumBruteForceTripCountsComputed; 7935 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7936 } 7937 7938 // Update all the PHI nodes for the next iteration. 7939 DenseMap<Instruction *, Constant *> NextIterVals; 7940 7941 // Create a list of which PHIs we need to compute. We want to do this before 7942 // calling EvaluateExpression on them because that may invalidate iterators 7943 // into CurrentIterVals. 7944 SmallVector<PHINode *, 8> PHIsToCompute; 7945 for (const auto &I : CurrentIterVals) { 7946 PHINode *PHI = dyn_cast<PHINode>(I.first); 7947 if (!PHI || PHI->getParent() != Header) continue; 7948 PHIsToCompute.push_back(PHI); 7949 } 7950 for (PHINode *PHI : PHIsToCompute) { 7951 Constant *&NextPHI = NextIterVals[PHI]; 7952 if (NextPHI) continue; // Already computed! 7953 7954 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7955 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7956 } 7957 CurrentIterVals.swap(NextIterVals); 7958 } 7959 7960 // Too many iterations were needed to evaluate. 7961 return getCouldNotCompute(); 7962 } 7963 7964 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7965 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7966 ValuesAtScopes[V]; 7967 // Check to see if we've folded this expression at this loop before. 7968 for (auto &LS : Values) 7969 if (LS.first == L) 7970 return LS.second ? LS.second : V; 7971 7972 Values.emplace_back(L, nullptr); 7973 7974 // Otherwise compute it. 7975 const SCEV *C = computeSCEVAtScope(V, L); 7976 for (auto &LS : reverse(ValuesAtScopes[V])) 7977 if (LS.first == L) { 7978 LS.second = C; 7979 break; 7980 } 7981 return C; 7982 } 7983 7984 /// This builds up a Constant using the ConstantExpr interface. That way, we 7985 /// will return Constants for objects which aren't represented by a 7986 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7987 /// Returns NULL if the SCEV isn't representable as a Constant. 7988 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7989 switch (V->getSCEVType()) { 7990 case scCouldNotCompute: 7991 case scAddRecExpr: 7992 return nullptr; 7993 case scConstant: 7994 return cast<SCEVConstant>(V)->getValue(); 7995 case scUnknown: 7996 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7997 case scSignExtend: { 7998 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7999 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8000 return ConstantExpr::getSExt(CastOp, SS->getType()); 8001 return nullptr; 8002 } 8003 case scZeroExtend: { 8004 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8005 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8006 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8007 return nullptr; 8008 } 8009 case scTruncate: { 8010 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8011 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8012 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8013 return nullptr; 8014 } 8015 case scAddExpr: { 8016 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8017 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8018 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8019 unsigned AS = PTy->getAddressSpace(); 8020 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8021 C = ConstantExpr::getBitCast(C, DestPtrTy); 8022 } 8023 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8024 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8025 if (!C2) 8026 return nullptr; 8027 8028 // First pointer! 8029 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8030 unsigned AS = C2->getType()->getPointerAddressSpace(); 8031 std::swap(C, C2); 8032 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8033 // The offsets have been converted to bytes. We can add bytes to an 8034 // i8* by GEP with the byte count in the first index. 8035 C = ConstantExpr::getBitCast(C, DestPtrTy); 8036 } 8037 8038 // Don't bother trying to sum two pointers. We probably can't 8039 // statically compute a load that results from it anyway. 8040 if (C2->getType()->isPointerTy()) 8041 return nullptr; 8042 8043 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8044 if (PTy->getElementType()->isStructTy()) 8045 C2 = ConstantExpr::getIntegerCast( 8046 C2, Type::getInt32Ty(C->getContext()), true); 8047 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8048 } else 8049 C = ConstantExpr::getAdd(C, C2); 8050 } 8051 return C; 8052 } 8053 return nullptr; 8054 } 8055 case scMulExpr: { 8056 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8057 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8058 // Don't bother with pointers at all. 8059 if (C->getType()->isPointerTy()) 8060 return nullptr; 8061 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8062 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8063 if (!C2 || C2->getType()->isPointerTy()) 8064 return nullptr; 8065 C = ConstantExpr::getMul(C, C2); 8066 } 8067 return C; 8068 } 8069 return nullptr; 8070 } 8071 case scUDivExpr: { 8072 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8073 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8074 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8075 if (LHS->getType() == RHS->getType()) 8076 return ConstantExpr::getUDiv(LHS, RHS); 8077 return nullptr; 8078 } 8079 case scSMaxExpr: 8080 case scUMaxExpr: 8081 case scSMinExpr: 8082 case scUMinExpr: 8083 return nullptr; // TODO: smax, umax, smin, umax. 8084 } 8085 llvm_unreachable("Unknown SCEV kind!"); 8086 } 8087 8088 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8089 if (isa<SCEVConstant>(V)) return V; 8090 8091 // If this instruction is evolved from a constant-evolving PHI, compute the 8092 // exit value from the loop without using SCEVs. 8093 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8094 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8095 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8096 const Loop *CurrLoop = this->LI[I->getParent()]; 8097 // Looking for loop exit value. 8098 if (CurrLoop && CurrLoop->getParentLoop() == L && 8099 PN->getParent() == CurrLoop->getHeader()) { 8100 // Okay, there is no closed form solution for the PHI node. Check 8101 // to see if the loop that contains it has a known backedge-taken 8102 // count. If so, we may be able to force computation of the exit 8103 // value. 8104 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8105 // This trivial case can show up in some degenerate cases where 8106 // the incoming IR has not yet been fully simplified. 8107 if (BackedgeTakenCount->isZero()) { 8108 Value *InitValue = nullptr; 8109 bool MultipleInitValues = false; 8110 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8111 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8112 if (!InitValue) 8113 InitValue = PN->getIncomingValue(i); 8114 else if (InitValue != PN->getIncomingValue(i)) { 8115 MultipleInitValues = true; 8116 break; 8117 } 8118 } 8119 } 8120 if (!MultipleInitValues && InitValue) 8121 return getSCEV(InitValue); 8122 } 8123 // Do we have a loop invariant value flowing around the backedge 8124 // for a loop which must execute the backedge? 8125 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8126 isKnownPositive(BackedgeTakenCount) && 8127 PN->getNumIncomingValues() == 2) { 8128 8129 unsigned InLoopPred = 8130 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8131 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8132 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8133 return getSCEV(BackedgeVal); 8134 } 8135 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8136 // Okay, we know how many times the containing loop executes. If 8137 // this is a constant evolving PHI node, get the final value at 8138 // the specified iteration number. 8139 Constant *RV = getConstantEvolutionLoopExitValue( 8140 PN, BTCC->getAPInt(), CurrLoop); 8141 if (RV) return getSCEV(RV); 8142 } 8143 } 8144 8145 // If there is a single-input Phi, evaluate it at our scope. If we can 8146 // prove that this replacement does not break LCSSA form, use new value. 8147 if (PN->getNumOperands() == 1) { 8148 const SCEV *Input = getSCEV(PN->getOperand(0)); 8149 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8150 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8151 // for the simplest case just support constants. 8152 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8153 } 8154 } 8155 8156 // Okay, this is an expression that we cannot symbolically evaluate 8157 // into a SCEV. Check to see if it's possible to symbolically evaluate 8158 // the arguments into constants, and if so, try to constant propagate the 8159 // result. This is particularly useful for computing loop exit values. 8160 if (CanConstantFold(I)) { 8161 SmallVector<Constant *, 4> Operands; 8162 bool MadeImprovement = false; 8163 for (Value *Op : I->operands()) { 8164 if (Constant *C = dyn_cast<Constant>(Op)) { 8165 Operands.push_back(C); 8166 continue; 8167 } 8168 8169 // If any of the operands is non-constant and if they are 8170 // non-integer and non-pointer, don't even try to analyze them 8171 // with scev techniques. 8172 if (!isSCEVable(Op->getType())) 8173 return V; 8174 8175 const SCEV *OrigV = getSCEV(Op); 8176 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8177 MadeImprovement |= OrigV != OpV; 8178 8179 Constant *C = BuildConstantFromSCEV(OpV); 8180 if (!C) return V; 8181 if (C->getType() != Op->getType()) 8182 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8183 Op->getType(), 8184 false), 8185 C, Op->getType()); 8186 Operands.push_back(C); 8187 } 8188 8189 // Check to see if getSCEVAtScope actually made an improvement. 8190 if (MadeImprovement) { 8191 Constant *C = nullptr; 8192 const DataLayout &DL = getDataLayout(); 8193 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8194 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8195 Operands[1], DL, &TLI); 8196 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8197 if (!Load->isVolatile()) 8198 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8199 DL); 8200 } else 8201 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8202 if (!C) return V; 8203 return getSCEV(C); 8204 } 8205 } 8206 } 8207 8208 // This is some other type of SCEVUnknown, just return it. 8209 return V; 8210 } 8211 8212 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8213 // Avoid performing the look-up in the common case where the specified 8214 // expression has no loop-variant portions. 8215 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8216 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8217 if (OpAtScope != Comm->getOperand(i)) { 8218 // Okay, at least one of these operands is loop variant but might be 8219 // foldable. Build a new instance of the folded commutative expression. 8220 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8221 Comm->op_begin()+i); 8222 NewOps.push_back(OpAtScope); 8223 8224 for (++i; i != e; ++i) { 8225 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8226 NewOps.push_back(OpAtScope); 8227 } 8228 if (isa<SCEVAddExpr>(Comm)) 8229 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8230 if (isa<SCEVMulExpr>(Comm)) 8231 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8232 if (isa<SCEVMinMaxExpr>(Comm)) 8233 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8234 llvm_unreachable("Unknown commutative SCEV type!"); 8235 } 8236 } 8237 // If we got here, all operands are loop invariant. 8238 return Comm; 8239 } 8240 8241 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8242 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8243 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8244 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8245 return Div; // must be loop invariant 8246 return getUDivExpr(LHS, RHS); 8247 } 8248 8249 // If this is a loop recurrence for a loop that does not contain L, then we 8250 // are dealing with the final value computed by the loop. 8251 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8252 // First, attempt to evaluate each operand. 8253 // Avoid performing the look-up in the common case where the specified 8254 // expression has no loop-variant portions. 8255 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8256 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8257 if (OpAtScope == AddRec->getOperand(i)) 8258 continue; 8259 8260 // Okay, at least one of these operands is loop variant but might be 8261 // foldable. Build a new instance of the folded commutative expression. 8262 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8263 AddRec->op_begin()+i); 8264 NewOps.push_back(OpAtScope); 8265 for (++i; i != e; ++i) 8266 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8267 8268 const SCEV *FoldedRec = 8269 getAddRecExpr(NewOps, AddRec->getLoop(), 8270 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8271 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8272 // The addrec may be folded to a nonrecurrence, for example, if the 8273 // induction variable is multiplied by zero after constant folding. Go 8274 // ahead and return the folded value. 8275 if (!AddRec) 8276 return FoldedRec; 8277 break; 8278 } 8279 8280 // If the scope is outside the addrec's loop, evaluate it by using the 8281 // loop exit value of the addrec. 8282 if (!AddRec->getLoop()->contains(L)) { 8283 // To evaluate this recurrence, we need to know how many times the AddRec 8284 // loop iterates. Compute this now. 8285 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8286 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8287 8288 // Then, evaluate the AddRec. 8289 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8290 } 8291 8292 return AddRec; 8293 } 8294 8295 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8296 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8297 if (Op == Cast->getOperand()) 8298 return Cast; // must be loop invariant 8299 return getZeroExtendExpr(Op, Cast->getType()); 8300 } 8301 8302 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8303 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8304 if (Op == Cast->getOperand()) 8305 return Cast; // must be loop invariant 8306 return getSignExtendExpr(Op, Cast->getType()); 8307 } 8308 8309 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8310 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8311 if (Op == Cast->getOperand()) 8312 return Cast; // must be loop invariant 8313 return getTruncateExpr(Op, Cast->getType()); 8314 } 8315 8316 llvm_unreachable("Unknown SCEV type!"); 8317 } 8318 8319 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8320 return getSCEVAtScope(getSCEV(V), L); 8321 } 8322 8323 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8324 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8325 return stripInjectiveFunctions(ZExt->getOperand()); 8326 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8327 return stripInjectiveFunctions(SExt->getOperand()); 8328 return S; 8329 } 8330 8331 /// Finds the minimum unsigned root of the following equation: 8332 /// 8333 /// A * X = B (mod N) 8334 /// 8335 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8336 /// A and B isn't important. 8337 /// 8338 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8339 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8340 ScalarEvolution &SE) { 8341 uint32_t BW = A.getBitWidth(); 8342 assert(BW == SE.getTypeSizeInBits(B->getType())); 8343 assert(A != 0 && "A must be non-zero."); 8344 8345 // 1. D = gcd(A, N) 8346 // 8347 // The gcd of A and N may have only one prime factor: 2. The number of 8348 // trailing zeros in A is its multiplicity 8349 uint32_t Mult2 = A.countTrailingZeros(); 8350 // D = 2^Mult2 8351 8352 // 2. Check if B is divisible by D. 8353 // 8354 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8355 // is not less than multiplicity of this prime factor for D. 8356 if (SE.GetMinTrailingZeros(B) < Mult2) 8357 return SE.getCouldNotCompute(); 8358 8359 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8360 // modulo (N / D). 8361 // 8362 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8363 // (N / D) in general. The inverse itself always fits into BW bits, though, 8364 // so we immediately truncate it. 8365 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8366 APInt Mod(BW + 1, 0); 8367 Mod.setBit(BW - Mult2); // Mod = N / D 8368 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8369 8370 // 4. Compute the minimum unsigned root of the equation: 8371 // I * (B / D) mod (N / D) 8372 // To simplify the computation, we factor out the divide by D: 8373 // (I * B mod N) / D 8374 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8375 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8376 } 8377 8378 /// For a given quadratic addrec, generate coefficients of the corresponding 8379 /// quadratic equation, multiplied by a common value to ensure that they are 8380 /// integers. 8381 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8382 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8383 /// were multiplied by, and BitWidth is the bit width of the original addrec 8384 /// coefficients. 8385 /// This function returns None if the addrec coefficients are not compile- 8386 /// time constants. 8387 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8388 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8389 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8390 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8391 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8392 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8393 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8394 << *AddRec << '\n'); 8395 8396 // We currently can only solve this if the coefficients are constants. 8397 if (!LC || !MC || !NC) { 8398 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8399 return None; 8400 } 8401 8402 APInt L = LC->getAPInt(); 8403 APInt M = MC->getAPInt(); 8404 APInt N = NC->getAPInt(); 8405 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8406 8407 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8408 unsigned NewWidth = BitWidth + 1; 8409 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8410 << BitWidth << '\n'); 8411 // The sign-extension (as opposed to a zero-extension) here matches the 8412 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8413 N = N.sext(NewWidth); 8414 M = M.sext(NewWidth); 8415 L = L.sext(NewWidth); 8416 8417 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8418 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8419 // L+M, L+2M+N, L+3M+3N, ... 8420 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8421 // 8422 // The equation Acc = 0 is then 8423 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8424 // In a quadratic form it becomes: 8425 // N n^2 + (2M-N) n + 2L = 0. 8426 8427 APInt A = N; 8428 APInt B = 2 * M - A; 8429 APInt C = 2 * L; 8430 APInt T = APInt(NewWidth, 2); 8431 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8432 << "x + " << C << ", coeff bw: " << NewWidth 8433 << ", multiplied by " << T << '\n'); 8434 return std::make_tuple(A, B, C, T, BitWidth); 8435 } 8436 8437 /// Helper function to compare optional APInts: 8438 /// (a) if X and Y both exist, return min(X, Y), 8439 /// (b) if neither X nor Y exist, return None, 8440 /// (c) if exactly one of X and Y exists, return that value. 8441 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8442 if (X.hasValue() && Y.hasValue()) { 8443 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8444 APInt XW = X->sextOrSelf(W); 8445 APInt YW = Y->sextOrSelf(W); 8446 return XW.slt(YW) ? *X : *Y; 8447 } 8448 if (!X.hasValue() && !Y.hasValue()) 8449 return None; 8450 return X.hasValue() ? *X : *Y; 8451 } 8452 8453 /// Helper function to truncate an optional APInt to a given BitWidth. 8454 /// When solving addrec-related equations, it is preferable to return a value 8455 /// that has the same bit width as the original addrec's coefficients. If the 8456 /// solution fits in the original bit width, truncate it (except for i1). 8457 /// Returning a value of a different bit width may inhibit some optimizations. 8458 /// 8459 /// In general, a solution to a quadratic equation generated from an addrec 8460 /// may require BW+1 bits, where BW is the bit width of the addrec's 8461 /// coefficients. The reason is that the coefficients of the quadratic 8462 /// equation are BW+1 bits wide (to avoid truncation when converting from 8463 /// the addrec to the equation). 8464 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8465 if (!X.hasValue()) 8466 return None; 8467 unsigned W = X->getBitWidth(); 8468 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8469 return X->trunc(BitWidth); 8470 return X; 8471 } 8472 8473 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8474 /// iterations. The values L, M, N are assumed to be signed, and they 8475 /// should all have the same bit widths. 8476 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8477 /// where BW is the bit width of the addrec's coefficients. 8478 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8479 /// returned as such, otherwise the bit width of the returned value may 8480 /// be greater than BW. 8481 /// 8482 /// This function returns None if 8483 /// (a) the addrec coefficients are not constant, or 8484 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8485 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8486 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8487 static Optional<APInt> 8488 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8489 APInt A, B, C, M; 8490 unsigned BitWidth; 8491 auto T = GetQuadraticEquation(AddRec); 8492 if (!T.hasValue()) 8493 return None; 8494 8495 std::tie(A, B, C, M, BitWidth) = *T; 8496 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8497 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8498 if (!X.hasValue()) 8499 return None; 8500 8501 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8502 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8503 if (!V->isZero()) 8504 return None; 8505 8506 return TruncIfPossible(X, BitWidth); 8507 } 8508 8509 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8510 /// iterations. The values M, N are assumed to be signed, and they 8511 /// should all have the same bit widths. 8512 /// Find the least n such that c(n) does not belong to the given range, 8513 /// while c(n-1) does. 8514 /// 8515 /// This function returns None if 8516 /// (a) the addrec coefficients are not constant, or 8517 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8518 /// bounds of the range. 8519 static Optional<APInt> 8520 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8521 const ConstantRange &Range, ScalarEvolution &SE) { 8522 assert(AddRec->getOperand(0)->isZero() && 8523 "Starting value of addrec should be 0"); 8524 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8525 << Range << ", addrec " << *AddRec << '\n'); 8526 // This case is handled in getNumIterationsInRange. Here we can assume that 8527 // we start in the range. 8528 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8529 "Addrec's initial value should be in range"); 8530 8531 APInt A, B, C, M; 8532 unsigned BitWidth; 8533 auto T = GetQuadraticEquation(AddRec); 8534 if (!T.hasValue()) 8535 return None; 8536 8537 // Be careful about the return value: there can be two reasons for not 8538 // returning an actual number. First, if no solutions to the equations 8539 // were found, and second, if the solutions don't leave the given range. 8540 // The first case means that the actual solution is "unknown", the second 8541 // means that it's known, but not valid. If the solution is unknown, we 8542 // cannot make any conclusions. 8543 // Return a pair: the optional solution and a flag indicating if the 8544 // solution was found. 8545 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8546 // Solve for signed overflow and unsigned overflow, pick the lower 8547 // solution. 8548 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8549 << Bound << " (before multiplying by " << M << ")\n"); 8550 Bound *= M; // The quadratic equation multiplier. 8551 8552 Optional<APInt> SO = None; 8553 if (BitWidth > 1) { 8554 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8555 "signed overflow\n"); 8556 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8557 } 8558 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8559 "unsigned overflow\n"); 8560 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8561 BitWidth+1); 8562 8563 auto LeavesRange = [&] (const APInt &X) { 8564 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8565 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8566 if (Range.contains(V0->getValue())) 8567 return false; 8568 // X should be at least 1, so X-1 is non-negative. 8569 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8570 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8571 if (Range.contains(V1->getValue())) 8572 return true; 8573 return false; 8574 }; 8575 8576 // If SolveQuadraticEquationWrap returns None, it means that there can 8577 // be a solution, but the function failed to find it. We cannot treat it 8578 // as "no solution". 8579 if (!SO.hasValue() || !UO.hasValue()) 8580 return { None, false }; 8581 8582 // Check the smaller value first to see if it leaves the range. 8583 // At this point, both SO and UO must have values. 8584 Optional<APInt> Min = MinOptional(SO, UO); 8585 if (LeavesRange(*Min)) 8586 return { Min, true }; 8587 Optional<APInt> Max = Min == SO ? UO : SO; 8588 if (LeavesRange(*Max)) 8589 return { Max, true }; 8590 8591 // Solutions were found, but were eliminated, hence the "true". 8592 return { None, true }; 8593 }; 8594 8595 std::tie(A, B, C, M, BitWidth) = *T; 8596 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8597 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8598 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8599 auto SL = SolveForBoundary(Lower); 8600 auto SU = SolveForBoundary(Upper); 8601 // If any of the solutions was unknown, no meaninigful conclusions can 8602 // be made. 8603 if (!SL.second || !SU.second) 8604 return None; 8605 8606 // Claim: The correct solution is not some value between Min and Max. 8607 // 8608 // Justification: Assuming that Min and Max are different values, one of 8609 // them is when the first signed overflow happens, the other is when the 8610 // first unsigned overflow happens. Crossing the range boundary is only 8611 // possible via an overflow (treating 0 as a special case of it, modeling 8612 // an overflow as crossing k*2^W for some k). 8613 // 8614 // The interesting case here is when Min was eliminated as an invalid 8615 // solution, but Max was not. The argument is that if there was another 8616 // overflow between Min and Max, it would also have been eliminated if 8617 // it was considered. 8618 // 8619 // For a given boundary, it is possible to have two overflows of the same 8620 // type (signed/unsigned) without having the other type in between: this 8621 // can happen when the vertex of the parabola is between the iterations 8622 // corresponding to the overflows. This is only possible when the two 8623 // overflows cross k*2^W for the same k. In such case, if the second one 8624 // left the range (and was the first one to do so), the first overflow 8625 // would have to enter the range, which would mean that either we had left 8626 // the range before or that we started outside of it. Both of these cases 8627 // are contradictions. 8628 // 8629 // Claim: In the case where SolveForBoundary returns None, the correct 8630 // solution is not some value between the Max for this boundary and the 8631 // Min of the other boundary. 8632 // 8633 // Justification: Assume that we had such Max_A and Min_B corresponding 8634 // to range boundaries A and B and such that Max_A < Min_B. If there was 8635 // a solution between Max_A and Min_B, it would have to be caused by an 8636 // overflow corresponding to either A or B. It cannot correspond to B, 8637 // since Min_B is the first occurrence of such an overflow. If it 8638 // corresponded to A, it would have to be either a signed or an unsigned 8639 // overflow that is larger than both eliminated overflows for A. But 8640 // between the eliminated overflows and this overflow, the values would 8641 // cover the entire value space, thus crossing the other boundary, which 8642 // is a contradiction. 8643 8644 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8645 } 8646 8647 ScalarEvolution::ExitLimit 8648 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8649 bool AllowPredicates) { 8650 8651 // This is only used for loops with a "x != y" exit test. The exit condition 8652 // is now expressed as a single expression, V = x-y. So the exit test is 8653 // effectively V != 0. We know and take advantage of the fact that this 8654 // expression only being used in a comparison by zero context. 8655 8656 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8657 // If the value is a constant 8658 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8659 // If the value is already zero, the branch will execute zero times. 8660 if (C->getValue()->isZero()) return C; 8661 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8662 } 8663 8664 const SCEVAddRecExpr *AddRec = 8665 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8666 8667 if (!AddRec && AllowPredicates) 8668 // Try to make this an AddRec using runtime tests, in the first X 8669 // iterations of this loop, where X is the SCEV expression found by the 8670 // algorithm below. 8671 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8672 8673 if (!AddRec || AddRec->getLoop() != L) 8674 return getCouldNotCompute(); 8675 8676 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8677 // the quadratic equation to solve it. 8678 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8679 // We can only use this value if the chrec ends up with an exact zero 8680 // value at this index. When solving for "X*X != 5", for example, we 8681 // should not accept a root of 2. 8682 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8683 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8684 return ExitLimit(R, R, false, Predicates); 8685 } 8686 return getCouldNotCompute(); 8687 } 8688 8689 // Otherwise we can only handle this if it is affine. 8690 if (!AddRec->isAffine()) 8691 return getCouldNotCompute(); 8692 8693 // If this is an affine expression, the execution count of this branch is 8694 // the minimum unsigned root of the following equation: 8695 // 8696 // Start + Step*N = 0 (mod 2^BW) 8697 // 8698 // equivalent to: 8699 // 8700 // Step*N = -Start (mod 2^BW) 8701 // 8702 // where BW is the common bit width of Start and Step. 8703 8704 // Get the initial value for the loop. 8705 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8706 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8707 8708 // For now we handle only constant steps. 8709 // 8710 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8711 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8712 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8713 // We have not yet seen any such cases. 8714 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8715 if (!StepC || StepC->getValue()->isZero()) 8716 return getCouldNotCompute(); 8717 8718 // For positive steps (counting up until unsigned overflow): 8719 // N = -Start/Step (as unsigned) 8720 // For negative steps (counting down to zero): 8721 // N = Start/-Step 8722 // First compute the unsigned distance from zero in the direction of Step. 8723 bool CountDown = StepC->getAPInt().isNegative(); 8724 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8725 8726 // Handle unitary steps, which cannot wraparound. 8727 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8728 // N = Distance (as unsigned) 8729 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8730 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 8731 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 8732 if (MaxBECountBase.ult(MaxBECount)) 8733 MaxBECount = MaxBECountBase; 8734 8735 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8736 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8737 // case, and see if we can improve the bound. 8738 // 8739 // Explicitly handling this here is necessary because getUnsignedRange 8740 // isn't context-sensitive; it doesn't know that we only care about the 8741 // range inside the loop. 8742 const SCEV *Zero = getZero(Distance->getType()); 8743 const SCEV *One = getOne(Distance->getType()); 8744 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8745 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8746 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8747 // as "unsigned_max(Distance + 1) - 1". 8748 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8749 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8750 } 8751 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8752 } 8753 8754 // If the condition controls loop exit (the loop exits only if the expression 8755 // is true) and the addition is no-wrap we can use unsigned divide to 8756 // compute the backedge count. In this case, the step may not divide the 8757 // distance, but we don't care because if the condition is "missed" the loop 8758 // will have undefined behavior due to wrapping. 8759 if (ControlsExit && AddRec->hasNoSelfWrap() && 8760 loopHasNoAbnormalExits(AddRec->getLoop())) { 8761 const SCEV *Exact = 8762 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8763 const SCEV *Max = 8764 Exact == getCouldNotCompute() 8765 ? Exact 8766 : getConstant(getUnsignedRangeMax(Exact)); 8767 return ExitLimit(Exact, Max, false, Predicates); 8768 } 8769 8770 // Solve the general equation. 8771 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8772 getNegativeSCEV(Start), *this); 8773 const SCEV *M = E == getCouldNotCompute() 8774 ? E 8775 : getConstant(getUnsignedRangeMax(E)); 8776 return ExitLimit(E, M, false, Predicates); 8777 } 8778 8779 ScalarEvolution::ExitLimit 8780 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8781 // Loops that look like: while (X == 0) are very strange indeed. We don't 8782 // handle them yet except for the trivial case. This could be expanded in the 8783 // future as needed. 8784 8785 // If the value is a constant, check to see if it is known to be non-zero 8786 // already. If so, the backedge will execute zero times. 8787 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8788 if (!C->getValue()->isZero()) 8789 return getZero(C->getType()); 8790 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8791 } 8792 8793 // We could implement others, but I really doubt anyone writes loops like 8794 // this, and if they did, they would already be constant folded. 8795 return getCouldNotCompute(); 8796 } 8797 8798 std::pair<const BasicBlock *, const BasicBlock *> 8799 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 8800 const { 8801 // If the block has a unique predecessor, then there is no path from the 8802 // predecessor to the block that does not go through the direct edge 8803 // from the predecessor to the block. 8804 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 8805 return {Pred, BB}; 8806 8807 // A loop's header is defined to be a block that dominates the loop. 8808 // If the header has a unique predecessor outside the loop, it must be 8809 // a block that has exactly one successor that can reach the loop. 8810 if (const Loop *L = LI.getLoopFor(BB)) 8811 return {L->getLoopPredecessor(), L->getHeader()}; 8812 8813 return {nullptr, nullptr}; 8814 } 8815 8816 /// SCEV structural equivalence is usually sufficient for testing whether two 8817 /// expressions are equal, however for the purposes of looking for a condition 8818 /// guarding a loop, it can be useful to be a little more general, since a 8819 /// front-end may have replicated the controlling expression. 8820 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8821 // Quick check to see if they are the same SCEV. 8822 if (A == B) return true; 8823 8824 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8825 // Not all instructions that are "identical" compute the same value. For 8826 // instance, two distinct alloca instructions allocating the same type are 8827 // identical and do not read memory; but compute distinct values. 8828 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8829 }; 8830 8831 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8832 // two different instructions with the same value. Check for this case. 8833 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8834 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8835 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8836 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8837 if (ComputesEqualValues(AI, BI)) 8838 return true; 8839 8840 // Otherwise assume they may have a different value. 8841 return false; 8842 } 8843 8844 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8845 const SCEV *&LHS, const SCEV *&RHS, 8846 unsigned Depth) { 8847 bool Changed = false; 8848 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8849 // '0 != 0'. 8850 auto TrivialCase = [&](bool TriviallyTrue) { 8851 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8852 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8853 return true; 8854 }; 8855 // If we hit the max recursion limit bail out. 8856 if (Depth >= 3) 8857 return false; 8858 8859 // Canonicalize a constant to the right side. 8860 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8861 // Check for both operands constant. 8862 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8863 if (ConstantExpr::getICmp(Pred, 8864 LHSC->getValue(), 8865 RHSC->getValue())->isNullValue()) 8866 return TrivialCase(false); 8867 else 8868 return TrivialCase(true); 8869 } 8870 // Otherwise swap the operands to put the constant on the right. 8871 std::swap(LHS, RHS); 8872 Pred = ICmpInst::getSwappedPredicate(Pred); 8873 Changed = true; 8874 } 8875 8876 // If we're comparing an addrec with a value which is loop-invariant in the 8877 // addrec's loop, put the addrec on the left. Also make a dominance check, 8878 // as both operands could be addrecs loop-invariant in each other's loop. 8879 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8880 const Loop *L = AR->getLoop(); 8881 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8882 std::swap(LHS, RHS); 8883 Pred = ICmpInst::getSwappedPredicate(Pred); 8884 Changed = true; 8885 } 8886 } 8887 8888 // If there's a constant operand, canonicalize comparisons with boundary 8889 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8890 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8891 const APInt &RA = RC->getAPInt(); 8892 8893 bool SimplifiedByConstantRange = false; 8894 8895 if (!ICmpInst::isEquality(Pred)) { 8896 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8897 if (ExactCR.isFullSet()) 8898 return TrivialCase(true); 8899 else if (ExactCR.isEmptySet()) 8900 return TrivialCase(false); 8901 8902 APInt NewRHS; 8903 CmpInst::Predicate NewPred; 8904 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8905 ICmpInst::isEquality(NewPred)) { 8906 // We were able to convert an inequality to an equality. 8907 Pred = NewPred; 8908 RHS = getConstant(NewRHS); 8909 Changed = SimplifiedByConstantRange = true; 8910 } 8911 } 8912 8913 if (!SimplifiedByConstantRange) { 8914 switch (Pred) { 8915 default: 8916 break; 8917 case ICmpInst::ICMP_EQ: 8918 case ICmpInst::ICMP_NE: 8919 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8920 if (!RA) 8921 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8922 if (const SCEVMulExpr *ME = 8923 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8924 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8925 ME->getOperand(0)->isAllOnesValue()) { 8926 RHS = AE->getOperand(1); 8927 LHS = ME->getOperand(1); 8928 Changed = true; 8929 } 8930 break; 8931 8932 8933 // The "Should have been caught earlier!" messages refer to the fact 8934 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8935 // should have fired on the corresponding cases, and canonicalized the 8936 // check to trivial case. 8937 8938 case ICmpInst::ICMP_UGE: 8939 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8940 Pred = ICmpInst::ICMP_UGT; 8941 RHS = getConstant(RA - 1); 8942 Changed = true; 8943 break; 8944 case ICmpInst::ICMP_ULE: 8945 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8946 Pred = ICmpInst::ICMP_ULT; 8947 RHS = getConstant(RA + 1); 8948 Changed = true; 8949 break; 8950 case ICmpInst::ICMP_SGE: 8951 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8952 Pred = ICmpInst::ICMP_SGT; 8953 RHS = getConstant(RA - 1); 8954 Changed = true; 8955 break; 8956 case ICmpInst::ICMP_SLE: 8957 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8958 Pred = ICmpInst::ICMP_SLT; 8959 RHS = getConstant(RA + 1); 8960 Changed = true; 8961 break; 8962 } 8963 } 8964 } 8965 8966 // Check for obvious equality. 8967 if (HasSameValue(LHS, RHS)) { 8968 if (ICmpInst::isTrueWhenEqual(Pred)) 8969 return TrivialCase(true); 8970 if (ICmpInst::isFalseWhenEqual(Pred)) 8971 return TrivialCase(false); 8972 } 8973 8974 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8975 // adding or subtracting 1 from one of the operands. 8976 switch (Pred) { 8977 case ICmpInst::ICMP_SLE: 8978 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8979 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8980 SCEV::FlagNSW); 8981 Pred = ICmpInst::ICMP_SLT; 8982 Changed = true; 8983 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8984 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8985 SCEV::FlagNSW); 8986 Pred = ICmpInst::ICMP_SLT; 8987 Changed = true; 8988 } 8989 break; 8990 case ICmpInst::ICMP_SGE: 8991 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8992 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8993 SCEV::FlagNSW); 8994 Pred = ICmpInst::ICMP_SGT; 8995 Changed = true; 8996 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8997 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8998 SCEV::FlagNSW); 8999 Pred = ICmpInst::ICMP_SGT; 9000 Changed = true; 9001 } 9002 break; 9003 case ICmpInst::ICMP_ULE: 9004 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9005 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9006 SCEV::FlagNUW); 9007 Pred = ICmpInst::ICMP_ULT; 9008 Changed = true; 9009 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9010 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9011 Pred = ICmpInst::ICMP_ULT; 9012 Changed = true; 9013 } 9014 break; 9015 case ICmpInst::ICMP_UGE: 9016 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9017 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9018 Pred = ICmpInst::ICMP_UGT; 9019 Changed = true; 9020 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9021 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9022 SCEV::FlagNUW); 9023 Pred = ICmpInst::ICMP_UGT; 9024 Changed = true; 9025 } 9026 break; 9027 default: 9028 break; 9029 } 9030 9031 // TODO: More simplifications are possible here. 9032 9033 // Recursively simplify until we either hit a recursion limit or nothing 9034 // changes. 9035 if (Changed) 9036 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9037 9038 return Changed; 9039 } 9040 9041 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9042 return getSignedRangeMax(S).isNegative(); 9043 } 9044 9045 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9046 return getSignedRangeMin(S).isStrictlyPositive(); 9047 } 9048 9049 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9050 return !getSignedRangeMin(S).isNegative(); 9051 } 9052 9053 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9054 return !getSignedRangeMax(S).isStrictlyPositive(); 9055 } 9056 9057 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9058 return isKnownNegative(S) || isKnownPositive(S); 9059 } 9060 9061 std::pair<const SCEV *, const SCEV *> 9062 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9063 // Compute SCEV on entry of loop L. 9064 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9065 if (Start == getCouldNotCompute()) 9066 return { Start, Start }; 9067 // Compute post increment SCEV for loop L. 9068 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9069 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9070 return { Start, PostInc }; 9071 } 9072 9073 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9074 const SCEV *LHS, const SCEV *RHS) { 9075 // First collect all loops. 9076 SmallPtrSet<const Loop *, 8> LoopsUsed; 9077 getUsedLoops(LHS, LoopsUsed); 9078 getUsedLoops(RHS, LoopsUsed); 9079 9080 if (LoopsUsed.empty()) 9081 return false; 9082 9083 // Domination relationship must be a linear order on collected loops. 9084 #ifndef NDEBUG 9085 for (auto *L1 : LoopsUsed) 9086 for (auto *L2 : LoopsUsed) 9087 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9088 DT.dominates(L2->getHeader(), L1->getHeader())) && 9089 "Domination relationship is not a linear order"); 9090 #endif 9091 9092 const Loop *MDL = 9093 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9094 [&](const Loop *L1, const Loop *L2) { 9095 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9096 }); 9097 9098 // Get init and post increment value for LHS. 9099 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9100 // if LHS contains unknown non-invariant SCEV then bail out. 9101 if (SplitLHS.first == getCouldNotCompute()) 9102 return false; 9103 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9104 // Get init and post increment value for RHS. 9105 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9106 // if RHS contains unknown non-invariant SCEV then bail out. 9107 if (SplitRHS.first == getCouldNotCompute()) 9108 return false; 9109 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9110 // It is possible that init SCEV contains an invariant load but it does 9111 // not dominate MDL and is not available at MDL loop entry, so we should 9112 // check it here. 9113 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9114 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9115 return false; 9116 9117 // It seems backedge guard check is faster than entry one so in some cases 9118 // it can speed up whole estimation by short circuit 9119 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9120 SplitRHS.second) && 9121 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9122 } 9123 9124 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9125 const SCEV *LHS, const SCEV *RHS) { 9126 // Canonicalize the inputs first. 9127 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9128 9129 if (isKnownViaInduction(Pred, LHS, RHS)) 9130 return true; 9131 9132 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9133 return true; 9134 9135 // Otherwise see what can be done with some simple reasoning. 9136 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9137 } 9138 9139 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9140 const SCEV *LHS, const SCEV *RHS, 9141 const Instruction *Context) { 9142 // TODO: Analyze guards and assumes from Context's block. 9143 return isKnownPredicate(Pred, LHS, RHS) || 9144 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9145 } 9146 9147 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9148 const SCEVAddRecExpr *LHS, 9149 const SCEV *RHS) { 9150 const Loop *L = LHS->getLoop(); 9151 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9152 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9153 } 9154 9155 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9156 ICmpInst::Predicate Pred, 9157 bool &Increasing) { 9158 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9159 9160 #ifndef NDEBUG 9161 // Verify an invariant: inverting the predicate should turn a monotonically 9162 // increasing change to a monotonically decreasing one, and vice versa. 9163 bool IncreasingSwapped; 9164 bool ResultSwapped = isMonotonicPredicateImpl( 9165 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9166 9167 assert(Result == ResultSwapped && "should be able to analyze both!"); 9168 if (ResultSwapped) 9169 assert(Increasing == !IncreasingSwapped && 9170 "monotonicity should flip as we flip the predicate"); 9171 #endif 9172 9173 return Result; 9174 } 9175 9176 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9177 ICmpInst::Predicate Pred, 9178 bool &Increasing) { 9179 9180 // A zero step value for LHS means the induction variable is essentially a 9181 // loop invariant value. We don't really depend on the predicate actually 9182 // flipping from false to true (for increasing predicates, and the other way 9183 // around for decreasing predicates), all we care about is that *if* the 9184 // predicate changes then it only changes from false to true. 9185 // 9186 // A zero step value in itself is not very useful, but there may be places 9187 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9188 // as general as possible. 9189 9190 switch (Pred) { 9191 default: 9192 return false; // Conservative answer 9193 9194 case ICmpInst::ICMP_UGT: 9195 case ICmpInst::ICMP_UGE: 9196 case ICmpInst::ICMP_ULT: 9197 case ICmpInst::ICMP_ULE: 9198 if (!LHS->hasNoUnsignedWrap()) 9199 return false; 9200 9201 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9202 return true; 9203 9204 case ICmpInst::ICMP_SGT: 9205 case ICmpInst::ICMP_SGE: 9206 case ICmpInst::ICMP_SLT: 9207 case ICmpInst::ICMP_SLE: { 9208 if (!LHS->hasNoSignedWrap()) 9209 return false; 9210 9211 const SCEV *Step = LHS->getStepRecurrence(*this); 9212 9213 if (isKnownNonNegative(Step)) { 9214 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9215 return true; 9216 } 9217 9218 if (isKnownNonPositive(Step)) { 9219 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9220 return true; 9221 } 9222 9223 return false; 9224 } 9225 9226 } 9227 9228 llvm_unreachable("switch has default clause!"); 9229 } 9230 9231 bool ScalarEvolution::isLoopInvariantPredicate( 9232 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9233 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9234 const SCEV *&InvariantRHS) { 9235 9236 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9237 if (!isLoopInvariant(RHS, L)) { 9238 if (!isLoopInvariant(LHS, L)) 9239 return false; 9240 9241 std::swap(LHS, RHS); 9242 Pred = ICmpInst::getSwappedPredicate(Pred); 9243 } 9244 9245 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9246 if (!ArLHS || ArLHS->getLoop() != L) 9247 return false; 9248 9249 bool Increasing; 9250 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9251 return false; 9252 9253 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9254 // true as the loop iterates, and the backedge is control dependent on 9255 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9256 // 9257 // * if the predicate was false in the first iteration then the predicate 9258 // is never evaluated again, since the loop exits without taking the 9259 // backedge. 9260 // * if the predicate was true in the first iteration then it will 9261 // continue to be true for all future iterations since it is 9262 // monotonically increasing. 9263 // 9264 // For both the above possibilities, we can replace the loop varying 9265 // predicate with its value on the first iteration of the loop (which is 9266 // loop invariant). 9267 // 9268 // A similar reasoning applies for a monotonically decreasing predicate, by 9269 // replacing true with false and false with true in the above two bullets. 9270 9271 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9272 9273 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9274 return false; 9275 9276 InvariantPred = Pred; 9277 InvariantLHS = ArLHS->getStart(); 9278 InvariantRHS = RHS; 9279 return true; 9280 } 9281 9282 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9283 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9284 if (HasSameValue(LHS, RHS)) 9285 return ICmpInst::isTrueWhenEqual(Pred); 9286 9287 // This code is split out from isKnownPredicate because it is called from 9288 // within isLoopEntryGuardedByCond. 9289 9290 auto CheckRanges = 9291 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9292 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9293 .contains(RangeLHS); 9294 }; 9295 9296 // The check at the top of the function catches the case where the values are 9297 // known to be equal. 9298 if (Pred == CmpInst::ICMP_EQ) 9299 return false; 9300 9301 if (Pred == CmpInst::ICMP_NE) 9302 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9303 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9304 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9305 9306 if (CmpInst::isSigned(Pred)) 9307 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9308 9309 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9310 } 9311 9312 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9313 const SCEV *LHS, 9314 const SCEV *RHS) { 9315 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9316 // Return Y via OutY. 9317 auto MatchBinaryAddToConst = 9318 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9319 SCEV::NoWrapFlags ExpectedFlags) { 9320 const SCEV *NonConstOp, *ConstOp; 9321 SCEV::NoWrapFlags FlagsPresent; 9322 9323 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9324 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9325 return false; 9326 9327 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9328 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9329 }; 9330 9331 APInt C; 9332 9333 switch (Pred) { 9334 default: 9335 break; 9336 9337 case ICmpInst::ICMP_SGE: 9338 std::swap(LHS, RHS); 9339 LLVM_FALLTHROUGH; 9340 case ICmpInst::ICMP_SLE: 9341 // X s<= (X + C)<nsw> if C >= 0 9342 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9343 return true; 9344 9345 // (X + C)<nsw> s<= X if C <= 0 9346 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9347 !C.isStrictlyPositive()) 9348 return true; 9349 break; 9350 9351 case ICmpInst::ICMP_SGT: 9352 std::swap(LHS, RHS); 9353 LLVM_FALLTHROUGH; 9354 case ICmpInst::ICMP_SLT: 9355 // X s< (X + C)<nsw> if C > 0 9356 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9357 C.isStrictlyPositive()) 9358 return true; 9359 9360 // (X + C)<nsw> s< X if C < 0 9361 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9362 return true; 9363 break; 9364 9365 case ICmpInst::ICMP_UGE: 9366 std::swap(LHS, RHS); 9367 LLVM_FALLTHROUGH; 9368 case ICmpInst::ICMP_ULE: 9369 // X u<= (X + C)<nuw> for any C 9370 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9371 return true; 9372 break; 9373 9374 case ICmpInst::ICMP_UGT: 9375 std::swap(LHS, RHS); 9376 LLVM_FALLTHROUGH; 9377 case ICmpInst::ICMP_ULT: 9378 // X u< (X + C)<nuw> if C != 0 9379 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9380 return true; 9381 break; 9382 } 9383 9384 return false; 9385 } 9386 9387 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9388 const SCEV *LHS, 9389 const SCEV *RHS) { 9390 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9391 return false; 9392 9393 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9394 // the stack can result in exponential time complexity. 9395 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9396 9397 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9398 // 9399 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9400 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9401 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9402 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9403 // use isKnownPredicate later if needed. 9404 return isKnownNonNegative(RHS) && 9405 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9406 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9407 } 9408 9409 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9410 ICmpInst::Predicate Pred, 9411 const SCEV *LHS, const SCEV *RHS) { 9412 // No need to even try if we know the module has no guards. 9413 if (!HasGuards) 9414 return false; 9415 9416 return any_of(*BB, [&](const Instruction &I) { 9417 using namespace llvm::PatternMatch; 9418 9419 Value *Condition; 9420 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9421 m_Value(Condition))) && 9422 isImpliedCond(Pred, LHS, RHS, Condition, false); 9423 }); 9424 } 9425 9426 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9427 /// protected by a conditional between LHS and RHS. This is used to 9428 /// to eliminate casts. 9429 bool 9430 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9431 ICmpInst::Predicate Pred, 9432 const SCEV *LHS, const SCEV *RHS) { 9433 // Interpret a null as meaning no loop, where there is obviously no guard 9434 // (interprocedural conditions notwithstanding). 9435 if (!L) return true; 9436 9437 if (VerifyIR) 9438 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9439 "This cannot be done on broken IR!"); 9440 9441 9442 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9443 return true; 9444 9445 BasicBlock *Latch = L->getLoopLatch(); 9446 if (!Latch) 9447 return false; 9448 9449 BranchInst *LoopContinuePredicate = 9450 dyn_cast<BranchInst>(Latch->getTerminator()); 9451 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9452 isImpliedCond(Pred, LHS, RHS, 9453 LoopContinuePredicate->getCondition(), 9454 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9455 return true; 9456 9457 // We don't want more than one activation of the following loops on the stack 9458 // -- that can lead to O(n!) time complexity. 9459 if (WalkingBEDominatingConds) 9460 return false; 9461 9462 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9463 9464 // See if we can exploit a trip count to prove the predicate. 9465 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9466 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9467 if (LatchBECount != getCouldNotCompute()) { 9468 // We know that Latch branches back to the loop header exactly 9469 // LatchBECount times. This means the backdege condition at Latch is 9470 // equivalent to "{0,+,1} u< LatchBECount". 9471 Type *Ty = LatchBECount->getType(); 9472 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9473 const SCEV *LoopCounter = 9474 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9475 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9476 LatchBECount)) 9477 return true; 9478 } 9479 9480 // Check conditions due to any @llvm.assume intrinsics. 9481 for (auto &AssumeVH : AC.assumptions()) { 9482 if (!AssumeVH) 9483 continue; 9484 auto *CI = cast<CallInst>(AssumeVH); 9485 if (!DT.dominates(CI, Latch->getTerminator())) 9486 continue; 9487 9488 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9489 return true; 9490 } 9491 9492 // If the loop is not reachable from the entry block, we risk running into an 9493 // infinite loop as we walk up into the dom tree. These loops do not matter 9494 // anyway, so we just return a conservative answer when we see them. 9495 if (!DT.isReachableFromEntry(L->getHeader())) 9496 return false; 9497 9498 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9499 return true; 9500 9501 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9502 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9503 assert(DTN && "should reach the loop header before reaching the root!"); 9504 9505 BasicBlock *BB = DTN->getBlock(); 9506 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9507 return true; 9508 9509 BasicBlock *PBB = BB->getSinglePredecessor(); 9510 if (!PBB) 9511 continue; 9512 9513 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9514 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9515 continue; 9516 9517 Value *Condition = ContinuePredicate->getCondition(); 9518 9519 // If we have an edge `E` within the loop body that dominates the only 9520 // latch, the condition guarding `E` also guards the backedge. This 9521 // reasoning works only for loops with a single latch. 9522 9523 BasicBlockEdge DominatingEdge(PBB, BB); 9524 if (DominatingEdge.isSingleEdge()) { 9525 // We're constructively (and conservatively) enumerating edges within the 9526 // loop body that dominate the latch. The dominator tree better agree 9527 // with us on this: 9528 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9529 9530 if (isImpliedCond(Pred, LHS, RHS, Condition, 9531 BB != ContinuePredicate->getSuccessor(0))) 9532 return true; 9533 } 9534 } 9535 9536 return false; 9537 } 9538 9539 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9540 ICmpInst::Predicate Pred, 9541 const SCEV *LHS, 9542 const SCEV *RHS) { 9543 if (VerifyIR) 9544 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9545 "This cannot be done on broken IR!"); 9546 9547 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9548 return true; 9549 9550 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9551 // the facts (a >= b && a != b) separately. A typical situation is when the 9552 // non-strict comparison is known from ranges and non-equality is known from 9553 // dominating predicates. If we are proving strict comparison, we always try 9554 // to prove non-equality and non-strict comparison separately. 9555 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9556 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9557 bool ProvedNonStrictComparison = false; 9558 bool ProvedNonEquality = false; 9559 9560 if (ProvingStrictComparison) { 9561 ProvedNonStrictComparison = 9562 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9563 ProvedNonEquality = 9564 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9565 if (ProvedNonStrictComparison && ProvedNonEquality) 9566 return true; 9567 } 9568 9569 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9570 auto ProveViaGuard = [&](const BasicBlock *Block) { 9571 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9572 return true; 9573 if (ProvingStrictComparison) { 9574 if (!ProvedNonStrictComparison) 9575 ProvedNonStrictComparison = 9576 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9577 if (!ProvedNonEquality) 9578 ProvedNonEquality = 9579 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9580 if (ProvedNonStrictComparison && ProvedNonEquality) 9581 return true; 9582 } 9583 return false; 9584 }; 9585 9586 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9587 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9588 const Instruction *Context = &BB->front(); 9589 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9590 return true; 9591 if (ProvingStrictComparison) { 9592 if (!ProvedNonStrictComparison) 9593 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9594 Condition, Inverse, Context); 9595 if (!ProvedNonEquality) 9596 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9597 Condition, Inverse, Context); 9598 if (ProvedNonStrictComparison && ProvedNonEquality) 9599 return true; 9600 } 9601 return false; 9602 }; 9603 9604 // Starting at the block's predecessor, climb up the predecessor chain, as long 9605 // as there are predecessors that can be found that have unique successors 9606 // leading to the original block. 9607 const Loop *ContainingLoop = LI.getLoopFor(BB); 9608 const BasicBlock *PredBB; 9609 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9610 PredBB = ContainingLoop->getLoopPredecessor(); 9611 else 9612 PredBB = BB->getSinglePredecessor(); 9613 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9614 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9615 if (ProveViaGuard(Pair.first)) 9616 return true; 9617 9618 const BranchInst *LoopEntryPredicate = 9619 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9620 if (!LoopEntryPredicate || 9621 LoopEntryPredicate->isUnconditional()) 9622 continue; 9623 9624 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9625 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9626 return true; 9627 } 9628 9629 // Check conditions due to any @llvm.assume intrinsics. 9630 for (auto &AssumeVH : AC.assumptions()) { 9631 if (!AssumeVH) 9632 continue; 9633 auto *CI = cast<CallInst>(AssumeVH); 9634 if (!DT.dominates(CI, BB)) 9635 continue; 9636 9637 if (ProveViaCond(CI->getArgOperand(0), false)) 9638 return true; 9639 } 9640 9641 return false; 9642 } 9643 9644 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9645 ICmpInst::Predicate Pred, 9646 const SCEV *LHS, 9647 const SCEV *RHS) { 9648 // Interpret a null as meaning no loop, where there is obviously no guard 9649 // (interprocedural conditions notwithstanding). 9650 if (!L) 9651 return false; 9652 9653 // Both LHS and RHS must be available at loop entry. 9654 assert(isAvailableAtLoopEntry(LHS, L) && 9655 "LHS is not available at Loop Entry"); 9656 assert(isAvailableAtLoopEntry(RHS, L) && 9657 "RHS is not available at Loop Entry"); 9658 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 9659 } 9660 9661 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9662 const SCEV *RHS, 9663 const Value *FoundCondValue, bool Inverse, 9664 const Instruction *Context) { 9665 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9666 return false; 9667 9668 auto ClearOnExit = 9669 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9670 9671 // Recursively handle And and Or conditions. 9672 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9673 if (BO->getOpcode() == Instruction::And) { 9674 if (!Inverse) 9675 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9676 Context) || 9677 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9678 Context); 9679 } else if (BO->getOpcode() == Instruction::Or) { 9680 if (Inverse) 9681 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9682 Context) || 9683 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9684 Context); 9685 } 9686 } 9687 9688 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9689 if (!ICI) return false; 9690 9691 // Now that we found a conditional branch that dominates the loop or controls 9692 // the loop latch. Check to see if it is the comparison we are looking for. 9693 ICmpInst::Predicate FoundPred; 9694 if (Inverse) 9695 FoundPred = ICI->getInversePredicate(); 9696 else 9697 FoundPred = ICI->getPredicate(); 9698 9699 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9700 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9701 9702 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 9703 } 9704 9705 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9706 const SCEV *RHS, 9707 ICmpInst::Predicate FoundPred, 9708 const SCEV *FoundLHS, const SCEV *FoundRHS, 9709 const Instruction *Context) { 9710 // Balance the types. 9711 if (getTypeSizeInBits(LHS->getType()) < 9712 getTypeSizeInBits(FoundLHS->getType())) { 9713 if (CmpInst::isSigned(Pred)) { 9714 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9715 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9716 } else { 9717 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9718 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9719 } 9720 } else if (getTypeSizeInBits(LHS->getType()) > 9721 getTypeSizeInBits(FoundLHS->getType())) { 9722 if (CmpInst::isSigned(FoundPred)) { 9723 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9724 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9725 } else { 9726 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9727 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9728 } 9729 } 9730 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 9731 FoundRHS, Context); 9732 } 9733 9734 bool ScalarEvolution::isImpliedCondBalancedTypes( 9735 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9736 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 9737 const Instruction *Context) { 9738 assert(getTypeSizeInBits(LHS->getType()) == 9739 getTypeSizeInBits(FoundLHS->getType()) && 9740 "Types should be balanced!"); 9741 // Canonicalize the query to match the way instcombine will have 9742 // canonicalized the comparison. 9743 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9744 if (LHS == RHS) 9745 return CmpInst::isTrueWhenEqual(Pred); 9746 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9747 if (FoundLHS == FoundRHS) 9748 return CmpInst::isFalseWhenEqual(FoundPred); 9749 9750 // Check to see if we can make the LHS or RHS match. 9751 if (LHS == FoundRHS || RHS == FoundLHS) { 9752 if (isa<SCEVConstant>(RHS)) { 9753 std::swap(FoundLHS, FoundRHS); 9754 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9755 } else { 9756 std::swap(LHS, RHS); 9757 Pred = ICmpInst::getSwappedPredicate(Pred); 9758 } 9759 } 9760 9761 // Check whether the found predicate is the same as the desired predicate. 9762 if (FoundPred == Pred) 9763 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9764 9765 // Check whether swapping the found predicate makes it the same as the 9766 // desired predicate. 9767 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9768 if (isa<SCEVConstant>(RHS)) 9769 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 9770 else 9771 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 9772 LHS, FoundLHS, FoundRHS, Context); 9773 } 9774 9775 // Unsigned comparison is the same as signed comparison when both the operands 9776 // are non-negative. 9777 if (CmpInst::isUnsigned(FoundPred) && 9778 CmpInst::getSignedPredicate(FoundPred) == Pred && 9779 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9780 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 9781 9782 // Check if we can make progress by sharpening ranges. 9783 if (FoundPred == ICmpInst::ICMP_NE && 9784 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9785 9786 const SCEVConstant *C = nullptr; 9787 const SCEV *V = nullptr; 9788 9789 if (isa<SCEVConstant>(FoundLHS)) { 9790 C = cast<SCEVConstant>(FoundLHS); 9791 V = FoundRHS; 9792 } else { 9793 C = cast<SCEVConstant>(FoundRHS); 9794 V = FoundLHS; 9795 } 9796 9797 // The guarding predicate tells us that C != V. If the known range 9798 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9799 // range we consider has to correspond to same signedness as the 9800 // predicate we're interested in folding. 9801 9802 APInt Min = ICmpInst::isSigned(Pred) ? 9803 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9804 9805 if (Min == C->getAPInt()) { 9806 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9807 // This is true even if (Min + 1) wraps around -- in case of 9808 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9809 9810 APInt SharperMin = Min + 1; 9811 9812 switch (Pred) { 9813 case ICmpInst::ICMP_SGE: 9814 case ICmpInst::ICMP_UGE: 9815 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9816 // RHS, we're done. 9817 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 9818 Context)) 9819 return true; 9820 LLVM_FALLTHROUGH; 9821 9822 case ICmpInst::ICMP_SGT: 9823 case ICmpInst::ICMP_UGT: 9824 // We know from the range information that (V `Pred` Min || 9825 // V == Min). We know from the guarding condition that !(V 9826 // == Min). This gives us 9827 // 9828 // V `Pred` Min || V == Min && !(V == Min) 9829 // => V `Pred` Min 9830 // 9831 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9832 9833 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 9834 Context)) 9835 return true; 9836 break; 9837 9838 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 9839 case ICmpInst::ICMP_SLE: 9840 case ICmpInst::ICMP_ULE: 9841 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9842 LHS, V, getConstant(SharperMin), Context)) 9843 return true; 9844 LLVM_FALLTHROUGH; 9845 9846 case ICmpInst::ICMP_SLT: 9847 case ICmpInst::ICMP_ULT: 9848 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 9849 LHS, V, getConstant(Min), Context)) 9850 return true; 9851 break; 9852 9853 default: 9854 // No change 9855 break; 9856 } 9857 } 9858 } 9859 9860 // Check whether the actual condition is beyond sufficient. 9861 if (FoundPred == ICmpInst::ICMP_EQ) 9862 if (ICmpInst::isTrueWhenEqual(Pred)) 9863 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 9864 return true; 9865 if (Pred == ICmpInst::ICMP_NE) 9866 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9867 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 9868 Context)) 9869 return true; 9870 9871 // Otherwise assume the worst. 9872 return false; 9873 } 9874 9875 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9876 const SCEV *&L, const SCEV *&R, 9877 SCEV::NoWrapFlags &Flags) { 9878 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9879 if (!AE || AE->getNumOperands() != 2) 9880 return false; 9881 9882 L = AE->getOperand(0); 9883 R = AE->getOperand(1); 9884 Flags = AE->getNoWrapFlags(); 9885 return true; 9886 } 9887 9888 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9889 const SCEV *Less) { 9890 // We avoid subtracting expressions here because this function is usually 9891 // fairly deep in the call stack (i.e. is called many times). 9892 9893 // X - X = 0. 9894 if (More == Less) 9895 return APInt(getTypeSizeInBits(More->getType()), 0); 9896 9897 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9898 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9899 const auto *MAR = cast<SCEVAddRecExpr>(More); 9900 9901 if (LAR->getLoop() != MAR->getLoop()) 9902 return None; 9903 9904 // We look at affine expressions only; not for correctness but to keep 9905 // getStepRecurrence cheap. 9906 if (!LAR->isAffine() || !MAR->isAffine()) 9907 return None; 9908 9909 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9910 return None; 9911 9912 Less = LAR->getStart(); 9913 More = MAR->getStart(); 9914 9915 // fall through 9916 } 9917 9918 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9919 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9920 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9921 return M - L; 9922 } 9923 9924 SCEV::NoWrapFlags Flags; 9925 const SCEV *LLess = nullptr, *RLess = nullptr; 9926 const SCEV *LMore = nullptr, *RMore = nullptr; 9927 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9928 // Compare (X + C1) vs X. 9929 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9930 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9931 if (RLess == More) 9932 return -(C1->getAPInt()); 9933 9934 // Compare X vs (X + C2). 9935 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9936 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9937 if (RMore == Less) 9938 return C2->getAPInt(); 9939 9940 // Compare (X + C1) vs (X + C2). 9941 if (C1 && C2 && RLess == RMore) 9942 return C2->getAPInt() - C1->getAPInt(); 9943 9944 return None; 9945 } 9946 9947 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 9948 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9949 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 9950 // Try to recognize the following pattern: 9951 // 9952 // FoundRHS = ... 9953 // ... 9954 // loop: 9955 // FoundLHS = {Start,+,W} 9956 // context_bb: // Basic block from the same loop 9957 // known(Pred, FoundLHS, FoundRHS) 9958 // 9959 // If some predicate is known in the context of a loop, it is also known on 9960 // each iteration of this loop, including the first iteration. Therefore, in 9961 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 9962 // prove the original pred using this fact. 9963 if (!Context) 9964 return false; 9965 const BasicBlock *ContextBB = Context->getParent(); 9966 // Make sure AR varies in the context block. 9967 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 9968 const Loop *L = AR->getLoop(); 9969 // Make sure that context belongs to the loop and executes on 1st iteration 9970 // (if it ever executes at all). 9971 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9972 return false; 9973 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 9974 return false; 9975 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 9976 } 9977 9978 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 9979 const Loop *L = AR->getLoop(); 9980 // Make sure that context belongs to the loop and executes on 1st iteration 9981 // (if it ever executes at all). 9982 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 9983 return false; 9984 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 9985 return false; 9986 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 9987 } 9988 9989 return false; 9990 } 9991 9992 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9993 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9994 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9995 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9996 return false; 9997 9998 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9999 if (!AddRecLHS) 10000 return false; 10001 10002 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10003 if (!AddRecFoundLHS) 10004 return false; 10005 10006 // We'd like to let SCEV reason about control dependencies, so we constrain 10007 // both the inequalities to be about add recurrences on the same loop. This 10008 // way we can use isLoopEntryGuardedByCond later. 10009 10010 const Loop *L = AddRecFoundLHS->getLoop(); 10011 if (L != AddRecLHS->getLoop()) 10012 return false; 10013 10014 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10015 // 10016 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10017 // ... (2) 10018 // 10019 // Informal proof for (2), assuming (1) [*]: 10020 // 10021 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10022 // 10023 // Then 10024 // 10025 // FoundLHS s< FoundRHS s< INT_MIN - C 10026 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10027 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10028 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10029 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10030 // <=> FoundLHS + C s< FoundRHS + C 10031 // 10032 // [*]: (1) can be proved by ruling out overflow. 10033 // 10034 // [**]: This can be proved by analyzing all the four possibilities: 10035 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10036 // (A s>= 0, B s>= 0). 10037 // 10038 // Note: 10039 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10040 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10041 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10042 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10043 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10044 // C)". 10045 10046 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10047 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10048 if (!LDiff || !RDiff || *LDiff != *RDiff) 10049 return false; 10050 10051 if (LDiff->isMinValue()) 10052 return true; 10053 10054 APInt FoundRHSLimit; 10055 10056 if (Pred == CmpInst::ICMP_ULT) { 10057 FoundRHSLimit = -(*RDiff); 10058 } else { 10059 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10060 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10061 } 10062 10063 // Try to prove (1) or (2), as needed. 10064 return isAvailableAtLoopEntry(FoundRHS, L) && 10065 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10066 getConstant(FoundRHSLimit)); 10067 } 10068 10069 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10070 const SCEV *LHS, const SCEV *RHS, 10071 const SCEV *FoundLHS, 10072 const SCEV *FoundRHS, unsigned Depth) { 10073 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10074 10075 auto ClearOnExit = make_scope_exit([&]() { 10076 if (LPhi) { 10077 bool Erased = PendingMerges.erase(LPhi); 10078 assert(Erased && "Failed to erase LPhi!"); 10079 (void)Erased; 10080 } 10081 if (RPhi) { 10082 bool Erased = PendingMerges.erase(RPhi); 10083 assert(Erased && "Failed to erase RPhi!"); 10084 (void)Erased; 10085 } 10086 }); 10087 10088 // Find respective Phis and check that they are not being pending. 10089 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10090 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10091 if (!PendingMerges.insert(Phi).second) 10092 return false; 10093 LPhi = Phi; 10094 } 10095 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10096 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10097 // If we detect a loop of Phi nodes being processed by this method, for 10098 // example: 10099 // 10100 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10101 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10102 // 10103 // we don't want to deal with a case that complex, so return conservative 10104 // answer false. 10105 if (!PendingMerges.insert(Phi).second) 10106 return false; 10107 RPhi = Phi; 10108 } 10109 10110 // If none of LHS, RHS is a Phi, nothing to do here. 10111 if (!LPhi && !RPhi) 10112 return false; 10113 10114 // If there is a SCEVUnknown Phi we are interested in, make it left. 10115 if (!LPhi) { 10116 std::swap(LHS, RHS); 10117 std::swap(FoundLHS, FoundRHS); 10118 std::swap(LPhi, RPhi); 10119 Pred = ICmpInst::getSwappedPredicate(Pred); 10120 } 10121 10122 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10123 const BasicBlock *LBB = LPhi->getParent(); 10124 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10125 10126 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10127 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10128 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10129 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10130 }; 10131 10132 if (RPhi && RPhi->getParent() == LBB) { 10133 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10134 // If we compare two Phis from the same block, and for each entry block 10135 // the predicate is true for incoming values from this block, then the 10136 // predicate is also true for the Phis. 10137 for (const BasicBlock *IncBB : predecessors(LBB)) { 10138 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10139 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10140 if (!ProvedEasily(L, R)) 10141 return false; 10142 } 10143 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10144 // Case two: RHS is also a Phi from the same basic block, and it is an 10145 // AddRec. It means that there is a loop which has both AddRec and Unknown 10146 // PHIs, for it we can compare incoming values of AddRec from above the loop 10147 // and latch with their respective incoming values of LPhi. 10148 // TODO: Generalize to handle loops with many inputs in a header. 10149 if (LPhi->getNumIncomingValues() != 2) return false; 10150 10151 auto *RLoop = RAR->getLoop(); 10152 auto *Predecessor = RLoop->getLoopPredecessor(); 10153 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10154 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10155 if (!ProvedEasily(L1, RAR->getStart())) 10156 return false; 10157 auto *Latch = RLoop->getLoopLatch(); 10158 assert(Latch && "Loop with AddRec with no latch?"); 10159 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10160 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10161 return false; 10162 } else { 10163 // In all other cases go over inputs of LHS and compare each of them to RHS, 10164 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10165 // At this point RHS is either a non-Phi, or it is a Phi from some block 10166 // different from LBB. 10167 for (const BasicBlock *IncBB : predecessors(LBB)) { 10168 // Check that RHS is available in this block. 10169 if (!dominates(RHS, IncBB)) 10170 return false; 10171 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10172 if (!ProvedEasily(L, RHS)) 10173 return false; 10174 } 10175 } 10176 return true; 10177 } 10178 10179 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10180 const SCEV *LHS, const SCEV *RHS, 10181 const SCEV *FoundLHS, 10182 const SCEV *FoundRHS, 10183 const Instruction *Context) { 10184 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10185 return true; 10186 10187 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10188 return true; 10189 10190 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10191 Context)) 10192 return true; 10193 10194 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10195 FoundLHS, FoundRHS) || 10196 // ~x < ~y --> x > y 10197 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10198 getNotSCEV(FoundRHS), 10199 getNotSCEV(FoundLHS)); 10200 } 10201 10202 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10203 template <typename MinMaxExprType> 10204 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10205 const SCEV *Candidate) { 10206 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10207 if (!MinMaxExpr) 10208 return false; 10209 10210 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10211 } 10212 10213 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10214 ICmpInst::Predicate Pred, 10215 const SCEV *LHS, const SCEV *RHS) { 10216 // If both sides are affine addrecs for the same loop, with equal 10217 // steps, and we know the recurrences don't wrap, then we only 10218 // need to check the predicate on the starting values. 10219 10220 if (!ICmpInst::isRelational(Pred)) 10221 return false; 10222 10223 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10224 if (!LAR) 10225 return false; 10226 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10227 if (!RAR) 10228 return false; 10229 if (LAR->getLoop() != RAR->getLoop()) 10230 return false; 10231 if (!LAR->isAffine() || !RAR->isAffine()) 10232 return false; 10233 10234 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10235 return false; 10236 10237 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10238 SCEV::FlagNSW : SCEV::FlagNUW; 10239 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10240 return false; 10241 10242 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10243 } 10244 10245 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10246 /// expression? 10247 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10248 ICmpInst::Predicate Pred, 10249 const SCEV *LHS, const SCEV *RHS) { 10250 switch (Pred) { 10251 default: 10252 return false; 10253 10254 case ICmpInst::ICMP_SGE: 10255 std::swap(LHS, RHS); 10256 LLVM_FALLTHROUGH; 10257 case ICmpInst::ICMP_SLE: 10258 return 10259 // min(A, ...) <= A 10260 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10261 // A <= max(A, ...) 10262 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10263 10264 case ICmpInst::ICMP_UGE: 10265 std::swap(LHS, RHS); 10266 LLVM_FALLTHROUGH; 10267 case ICmpInst::ICMP_ULE: 10268 return 10269 // min(A, ...) <= A 10270 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10271 // A <= max(A, ...) 10272 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10273 } 10274 10275 llvm_unreachable("covered switch fell through?!"); 10276 } 10277 10278 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10279 const SCEV *LHS, const SCEV *RHS, 10280 const SCEV *FoundLHS, 10281 const SCEV *FoundRHS, 10282 unsigned Depth) { 10283 assert(getTypeSizeInBits(LHS->getType()) == 10284 getTypeSizeInBits(RHS->getType()) && 10285 "LHS and RHS have different sizes?"); 10286 assert(getTypeSizeInBits(FoundLHS->getType()) == 10287 getTypeSizeInBits(FoundRHS->getType()) && 10288 "FoundLHS and FoundRHS have different sizes?"); 10289 // We want to avoid hurting the compile time with analysis of too big trees. 10290 if (Depth > MaxSCEVOperationsImplicationDepth) 10291 return false; 10292 10293 // We only want to work with GT comparison so far. 10294 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10295 Pred = CmpInst::getSwappedPredicate(Pred); 10296 std::swap(LHS, RHS); 10297 std::swap(FoundLHS, FoundRHS); 10298 } 10299 10300 // For unsigned, try to reduce it to corresponding signed comparison. 10301 if (Pred == ICmpInst::ICMP_UGT) 10302 // We can replace unsigned predicate with its signed counterpart if all 10303 // involved values are non-negative. 10304 // TODO: We could have better support for unsigned. 10305 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10306 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10307 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10308 // use this fact to prove that LHS and RHS are non-negative. 10309 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10310 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10311 FoundRHS) && 10312 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10313 FoundRHS)) 10314 Pred = ICmpInst::ICMP_SGT; 10315 } 10316 10317 if (Pred != ICmpInst::ICMP_SGT) 10318 return false; 10319 10320 auto GetOpFromSExt = [&](const SCEV *S) { 10321 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10322 return Ext->getOperand(); 10323 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10324 // the constant in some cases. 10325 return S; 10326 }; 10327 10328 // Acquire values from extensions. 10329 auto *OrigLHS = LHS; 10330 auto *OrigFoundLHS = FoundLHS; 10331 LHS = GetOpFromSExt(LHS); 10332 FoundLHS = GetOpFromSExt(FoundLHS); 10333 10334 // Is the SGT predicate can be proved trivially or using the found context. 10335 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10336 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10337 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10338 FoundRHS, Depth + 1); 10339 }; 10340 10341 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10342 // We want to avoid creation of any new non-constant SCEV. Since we are 10343 // going to compare the operands to RHS, we should be certain that we don't 10344 // need any size extensions for this. So let's decline all cases when the 10345 // sizes of types of LHS and RHS do not match. 10346 // TODO: Maybe try to get RHS from sext to catch more cases? 10347 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10348 return false; 10349 10350 // Should not overflow. 10351 if (!LHSAddExpr->hasNoSignedWrap()) 10352 return false; 10353 10354 auto *LL = LHSAddExpr->getOperand(0); 10355 auto *LR = LHSAddExpr->getOperand(1); 10356 auto *MinusOne = getMinusOne(RHS->getType()); 10357 10358 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10359 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10360 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10361 }; 10362 // Try to prove the following rule: 10363 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10364 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10365 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10366 return true; 10367 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10368 Value *LL, *LR; 10369 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10370 10371 using namespace llvm::PatternMatch; 10372 10373 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10374 // Rules for division. 10375 // We are going to perform some comparisons with Denominator and its 10376 // derivative expressions. In general case, creating a SCEV for it may 10377 // lead to a complex analysis of the entire graph, and in particular it 10378 // can request trip count recalculation for the same loop. This would 10379 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10380 // this, we only want to create SCEVs that are constants in this section. 10381 // So we bail if Denominator is not a constant. 10382 if (!isa<ConstantInt>(LR)) 10383 return false; 10384 10385 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10386 10387 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10388 // then a SCEV for the numerator already exists and matches with FoundLHS. 10389 auto *Numerator = getExistingSCEV(LL); 10390 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10391 return false; 10392 10393 // Make sure that the numerator matches with FoundLHS and the denominator 10394 // is positive. 10395 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10396 return false; 10397 10398 auto *DTy = Denominator->getType(); 10399 auto *FRHSTy = FoundRHS->getType(); 10400 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10401 // One of types is a pointer and another one is not. We cannot extend 10402 // them properly to a wider type, so let us just reject this case. 10403 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10404 // to avoid this check. 10405 return false; 10406 10407 // Given that: 10408 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10409 auto *WTy = getWiderType(DTy, FRHSTy); 10410 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10411 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10412 10413 // Try to prove the following rule: 10414 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10415 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10416 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10417 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10418 if (isKnownNonPositive(RHS) && 10419 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10420 return true; 10421 10422 // Try to prove the following rule: 10423 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10424 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10425 // If we divide it by Denominator > 2, then: 10426 // 1. If FoundLHS is negative, then the result is 0. 10427 // 2. If FoundLHS is non-negative, then the result is non-negative. 10428 // Anyways, the result is non-negative. 10429 auto *MinusOne = getMinusOne(WTy); 10430 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10431 if (isKnownNegative(RHS) && 10432 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10433 return true; 10434 } 10435 } 10436 10437 // If our expression contained SCEVUnknown Phis, and we split it down and now 10438 // need to prove something for them, try to prove the predicate for every 10439 // possible incoming values of those Phis. 10440 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10441 return true; 10442 10443 return false; 10444 } 10445 10446 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10447 const SCEV *LHS, const SCEV *RHS) { 10448 // zext x u<= sext x, sext x s<= zext x 10449 switch (Pred) { 10450 case ICmpInst::ICMP_SGE: 10451 std::swap(LHS, RHS); 10452 LLVM_FALLTHROUGH; 10453 case ICmpInst::ICMP_SLE: { 10454 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10455 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10456 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10457 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10458 return true; 10459 break; 10460 } 10461 case ICmpInst::ICMP_UGE: 10462 std::swap(LHS, RHS); 10463 LLVM_FALLTHROUGH; 10464 case ICmpInst::ICMP_ULE: { 10465 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10466 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10467 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10468 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10469 return true; 10470 break; 10471 } 10472 default: 10473 break; 10474 }; 10475 return false; 10476 } 10477 10478 bool 10479 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10480 const SCEV *LHS, const SCEV *RHS) { 10481 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10482 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10483 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10484 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10485 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10486 } 10487 10488 bool 10489 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10490 const SCEV *LHS, const SCEV *RHS, 10491 const SCEV *FoundLHS, 10492 const SCEV *FoundRHS) { 10493 switch (Pred) { 10494 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10495 case ICmpInst::ICMP_EQ: 10496 case ICmpInst::ICMP_NE: 10497 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10498 return true; 10499 break; 10500 case ICmpInst::ICMP_SLT: 10501 case ICmpInst::ICMP_SLE: 10502 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10503 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10504 return true; 10505 break; 10506 case ICmpInst::ICMP_SGT: 10507 case ICmpInst::ICMP_SGE: 10508 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10509 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10510 return true; 10511 break; 10512 case ICmpInst::ICMP_ULT: 10513 case ICmpInst::ICMP_ULE: 10514 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10515 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10516 return true; 10517 break; 10518 case ICmpInst::ICMP_UGT: 10519 case ICmpInst::ICMP_UGE: 10520 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10521 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10522 return true; 10523 break; 10524 } 10525 10526 // Maybe it can be proved via operations? 10527 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10528 return true; 10529 10530 return false; 10531 } 10532 10533 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10534 const SCEV *LHS, 10535 const SCEV *RHS, 10536 const SCEV *FoundLHS, 10537 const SCEV *FoundRHS) { 10538 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10539 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10540 // reduce the compile time impact of this optimization. 10541 return false; 10542 10543 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10544 if (!Addend) 10545 return false; 10546 10547 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10548 10549 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10550 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10551 ConstantRange FoundLHSRange = 10552 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10553 10554 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10555 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10556 10557 // We can also compute the range of values for `LHS` that satisfy the 10558 // consequent, "`LHS` `Pred` `RHS`": 10559 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10560 ConstantRange SatisfyingLHSRange = 10561 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10562 10563 // The antecedent implies the consequent if every value of `LHS` that 10564 // satisfies the antecedent also satisfies the consequent. 10565 return SatisfyingLHSRange.contains(LHSRange); 10566 } 10567 10568 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10569 bool IsSigned, bool NoWrap) { 10570 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10571 10572 if (NoWrap) return false; 10573 10574 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10575 const SCEV *One = getOne(Stride->getType()); 10576 10577 if (IsSigned) { 10578 APInt MaxRHS = getSignedRangeMax(RHS); 10579 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10580 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10581 10582 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10583 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10584 } 10585 10586 APInt MaxRHS = getUnsignedRangeMax(RHS); 10587 APInt MaxValue = APInt::getMaxValue(BitWidth); 10588 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10589 10590 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10591 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10592 } 10593 10594 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10595 bool IsSigned, bool NoWrap) { 10596 if (NoWrap) return false; 10597 10598 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10599 const SCEV *One = getOne(Stride->getType()); 10600 10601 if (IsSigned) { 10602 APInt MinRHS = getSignedRangeMin(RHS); 10603 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10604 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10605 10606 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10607 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10608 } 10609 10610 APInt MinRHS = getUnsignedRangeMin(RHS); 10611 APInt MinValue = APInt::getMinValue(BitWidth); 10612 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10613 10614 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10615 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10616 } 10617 10618 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10619 bool Equality) { 10620 const SCEV *One = getOne(Step->getType()); 10621 Delta = Equality ? getAddExpr(Delta, Step) 10622 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10623 return getUDivExpr(Delta, Step); 10624 } 10625 10626 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10627 const SCEV *Stride, 10628 const SCEV *End, 10629 unsigned BitWidth, 10630 bool IsSigned) { 10631 10632 assert(!isKnownNonPositive(Stride) && 10633 "Stride is expected strictly positive!"); 10634 // Calculate the maximum backedge count based on the range of values 10635 // permitted by Start, End, and Stride. 10636 const SCEV *MaxBECount; 10637 APInt MinStart = 10638 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10639 10640 APInt StrideForMaxBECount = 10641 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10642 10643 // We already know that the stride is positive, so we paper over conservatism 10644 // in our range computation by forcing StrideForMaxBECount to be at least one. 10645 // In theory this is unnecessary, but we expect MaxBECount to be a 10646 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10647 // is nothing to constant fold it to). 10648 APInt One(BitWidth, 1, IsSigned); 10649 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10650 10651 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10652 : APInt::getMaxValue(BitWidth); 10653 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10654 10655 // Although End can be a MAX expression we estimate MaxEnd considering only 10656 // the case End = RHS of the loop termination condition. This is safe because 10657 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10658 // taken count. 10659 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10660 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10661 10662 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10663 getConstant(StrideForMaxBECount) /* Step */, 10664 false /* Equality */); 10665 10666 return MaxBECount; 10667 } 10668 10669 ScalarEvolution::ExitLimit 10670 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10671 const Loop *L, bool IsSigned, 10672 bool ControlsExit, bool AllowPredicates) { 10673 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10674 10675 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10676 bool PredicatedIV = false; 10677 10678 if (!IV && AllowPredicates) { 10679 // Try to make this an AddRec using runtime tests, in the first X 10680 // iterations of this loop, where X is the SCEV expression found by the 10681 // algorithm below. 10682 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10683 PredicatedIV = true; 10684 } 10685 10686 // Avoid weird loops 10687 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10688 return getCouldNotCompute(); 10689 10690 bool NoWrap = ControlsExit && 10691 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10692 10693 const SCEV *Stride = IV->getStepRecurrence(*this); 10694 10695 bool PositiveStride = isKnownPositive(Stride); 10696 10697 // Avoid negative or zero stride values. 10698 if (!PositiveStride) { 10699 // We can compute the correct backedge taken count for loops with unknown 10700 // strides if we can prove that the loop is not an infinite loop with side 10701 // effects. Here's the loop structure we are trying to handle - 10702 // 10703 // i = start 10704 // do { 10705 // A[i] = i; 10706 // i += s; 10707 // } while (i < end); 10708 // 10709 // The backedge taken count for such loops is evaluated as - 10710 // (max(end, start + stride) - start - 1) /u stride 10711 // 10712 // The additional preconditions that we need to check to prove correctness 10713 // of the above formula is as follows - 10714 // 10715 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10716 // NoWrap flag). 10717 // b) loop is single exit with no side effects. 10718 // 10719 // 10720 // Precondition a) implies that if the stride is negative, this is a single 10721 // trip loop. The backedge taken count formula reduces to zero in this case. 10722 // 10723 // Precondition b) implies that the unknown stride cannot be zero otherwise 10724 // we have UB. 10725 // 10726 // The positive stride case is the same as isKnownPositive(Stride) returning 10727 // true (original behavior of the function). 10728 // 10729 // We want to make sure that the stride is truly unknown as there are edge 10730 // cases where ScalarEvolution propagates no wrap flags to the 10731 // post-increment/decrement IV even though the increment/decrement operation 10732 // itself is wrapping. The computed backedge taken count may be wrong in 10733 // such cases. This is prevented by checking that the stride is not known to 10734 // be either positive or non-positive. For example, no wrap flags are 10735 // propagated to the post-increment IV of this loop with a trip count of 2 - 10736 // 10737 // unsigned char i; 10738 // for(i=127; i<128; i+=129) 10739 // A[i] = i; 10740 // 10741 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10742 !loopHasNoSideEffects(L)) 10743 return getCouldNotCompute(); 10744 } else if (!Stride->isOne() && 10745 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10746 // Avoid proven overflow cases: this will ensure that the backedge taken 10747 // count will not generate any unsigned overflow. Relaxed no-overflow 10748 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10749 // undefined behaviors like the case of C language. 10750 return getCouldNotCompute(); 10751 10752 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10753 : ICmpInst::ICMP_ULT; 10754 const SCEV *Start = IV->getStart(); 10755 const SCEV *End = RHS; 10756 // When the RHS is not invariant, we do not know the end bound of the loop and 10757 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10758 // calculate the MaxBECount, given the start, stride and max value for the end 10759 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10760 // checked above). 10761 if (!isLoopInvariant(RHS, L)) { 10762 const SCEV *MaxBECount = computeMaxBECountForLT( 10763 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10764 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10765 false /*MaxOrZero*/, Predicates); 10766 } 10767 // If the backedge is taken at least once, then it will be taken 10768 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10769 // is the LHS value of the less-than comparison the first time it is evaluated 10770 // and End is the RHS. 10771 const SCEV *BECountIfBackedgeTaken = 10772 computeBECount(getMinusSCEV(End, Start), Stride, false); 10773 // If the loop entry is guarded by the result of the backedge test of the 10774 // first loop iteration, then we know the backedge will be taken at least 10775 // once and so the backedge taken count is as above. If not then we use the 10776 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10777 // as if the backedge is taken at least once max(End,Start) is End and so the 10778 // result is as above, and if not max(End,Start) is Start so we get a backedge 10779 // count of zero. 10780 const SCEV *BECount; 10781 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10782 BECount = BECountIfBackedgeTaken; 10783 else { 10784 // If we know that RHS >= Start in the context of loop, then we know that 10785 // max(RHS, Start) = RHS at this point. 10786 if (isLoopEntryGuardedByCond( 10787 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 10788 End = RHS; 10789 else 10790 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10791 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10792 } 10793 10794 const SCEV *MaxBECount; 10795 bool MaxOrZero = false; 10796 if (isa<SCEVConstant>(BECount)) 10797 MaxBECount = BECount; 10798 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10799 // If we know exactly how many times the backedge will be taken if it's 10800 // taken at least once, then the backedge count will either be that or 10801 // zero. 10802 MaxBECount = BECountIfBackedgeTaken; 10803 MaxOrZero = true; 10804 } else { 10805 MaxBECount = computeMaxBECountForLT( 10806 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10807 } 10808 10809 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10810 !isa<SCEVCouldNotCompute>(BECount)) 10811 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10812 10813 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10814 } 10815 10816 ScalarEvolution::ExitLimit 10817 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10818 const Loop *L, bool IsSigned, 10819 bool ControlsExit, bool AllowPredicates) { 10820 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10821 // We handle only IV > Invariant 10822 if (!isLoopInvariant(RHS, L)) 10823 return getCouldNotCompute(); 10824 10825 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10826 if (!IV && AllowPredicates) 10827 // Try to make this an AddRec using runtime tests, in the first X 10828 // iterations of this loop, where X is the SCEV expression found by the 10829 // algorithm below. 10830 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10831 10832 // Avoid weird loops 10833 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10834 return getCouldNotCompute(); 10835 10836 bool NoWrap = ControlsExit && 10837 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10838 10839 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10840 10841 // Avoid negative or zero stride values 10842 if (!isKnownPositive(Stride)) 10843 return getCouldNotCompute(); 10844 10845 // Avoid proven overflow cases: this will ensure that the backedge taken count 10846 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10847 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10848 // behaviors like the case of C language. 10849 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10850 return getCouldNotCompute(); 10851 10852 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10853 : ICmpInst::ICMP_UGT; 10854 10855 const SCEV *Start = IV->getStart(); 10856 const SCEV *End = RHS; 10857 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 10858 // If we know that Start >= RHS in the context of loop, then we know that 10859 // min(RHS, Start) = RHS at this point. 10860 if (isLoopEntryGuardedByCond( 10861 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 10862 End = RHS; 10863 else 10864 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10865 } 10866 10867 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10868 10869 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10870 : getUnsignedRangeMax(Start); 10871 10872 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10873 : getUnsignedRangeMin(Stride); 10874 10875 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10876 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10877 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10878 10879 // Although End can be a MIN expression we estimate MinEnd considering only 10880 // the case End = RHS. This is safe because in the other case (Start - End) 10881 // is zero, leading to a zero maximum backedge taken count. 10882 APInt MinEnd = 10883 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10884 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10885 10886 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10887 ? BECount 10888 : computeBECount(getConstant(MaxStart - MinEnd), 10889 getConstant(MinStride), false); 10890 10891 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10892 MaxBECount = BECount; 10893 10894 return ExitLimit(BECount, MaxBECount, false, Predicates); 10895 } 10896 10897 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10898 ScalarEvolution &SE) const { 10899 if (Range.isFullSet()) // Infinite loop. 10900 return SE.getCouldNotCompute(); 10901 10902 // If the start is a non-zero constant, shift the range to simplify things. 10903 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10904 if (!SC->getValue()->isZero()) { 10905 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10906 Operands[0] = SE.getZero(SC->getType()); 10907 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10908 getNoWrapFlags(FlagNW)); 10909 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10910 return ShiftedAddRec->getNumIterationsInRange( 10911 Range.subtract(SC->getAPInt()), SE); 10912 // This is strange and shouldn't happen. 10913 return SE.getCouldNotCompute(); 10914 } 10915 10916 // The only time we can solve this is when we have all constant indices. 10917 // Otherwise, we cannot determine the overflow conditions. 10918 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10919 return SE.getCouldNotCompute(); 10920 10921 // Okay at this point we know that all elements of the chrec are constants and 10922 // that the start element is zero. 10923 10924 // First check to see if the range contains zero. If not, the first 10925 // iteration exits. 10926 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10927 if (!Range.contains(APInt(BitWidth, 0))) 10928 return SE.getZero(getType()); 10929 10930 if (isAffine()) { 10931 // If this is an affine expression then we have this situation: 10932 // Solve {0,+,A} in Range === Ax in Range 10933 10934 // We know that zero is in the range. If A is positive then we know that 10935 // the upper value of the range must be the first possible exit value. 10936 // If A is negative then the lower of the range is the last possible loop 10937 // value. Also note that we already checked for a full range. 10938 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10939 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10940 10941 // The exit value should be (End+A)/A. 10942 APInt ExitVal = (End + A).udiv(A); 10943 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10944 10945 // Evaluate at the exit value. If we really did fall out of the valid 10946 // range, then we computed our trip count, otherwise wrap around or other 10947 // things must have happened. 10948 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10949 if (Range.contains(Val->getValue())) 10950 return SE.getCouldNotCompute(); // Something strange happened 10951 10952 // Ensure that the previous value is in the range. This is a sanity check. 10953 assert(Range.contains( 10954 EvaluateConstantChrecAtConstant(this, 10955 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10956 "Linear scev computation is off in a bad way!"); 10957 return SE.getConstant(ExitValue); 10958 } 10959 10960 if (isQuadratic()) { 10961 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10962 return SE.getConstant(S.getValue()); 10963 } 10964 10965 return SE.getCouldNotCompute(); 10966 } 10967 10968 const SCEVAddRecExpr * 10969 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10970 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10971 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10972 // but in this case we cannot guarantee that the value returned will be an 10973 // AddRec because SCEV does not have a fixed point where it stops 10974 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10975 // may happen if we reach arithmetic depth limit while simplifying. So we 10976 // construct the returned value explicitly. 10977 SmallVector<const SCEV *, 3> Ops; 10978 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10979 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10980 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10981 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10982 // We know that the last operand is not a constant zero (otherwise it would 10983 // have been popped out earlier). This guarantees us that if the result has 10984 // the same last operand, then it will also not be popped out, meaning that 10985 // the returned value will be an AddRec. 10986 const SCEV *Last = getOperand(getNumOperands() - 1); 10987 assert(!Last->isZero() && "Recurrency with zero step?"); 10988 Ops.push_back(Last); 10989 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10990 SCEV::FlagAnyWrap)); 10991 } 10992 10993 // Return true when S contains at least an undef value. 10994 static inline bool containsUndefs(const SCEV *S) { 10995 return SCEVExprContains(S, [](const SCEV *S) { 10996 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10997 return isa<UndefValue>(SU->getValue()); 10998 return false; 10999 }); 11000 } 11001 11002 namespace { 11003 11004 // Collect all steps of SCEV expressions. 11005 struct SCEVCollectStrides { 11006 ScalarEvolution &SE; 11007 SmallVectorImpl<const SCEV *> &Strides; 11008 11009 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11010 : SE(SE), Strides(S) {} 11011 11012 bool follow(const SCEV *S) { 11013 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11014 Strides.push_back(AR->getStepRecurrence(SE)); 11015 return true; 11016 } 11017 11018 bool isDone() const { return false; } 11019 }; 11020 11021 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11022 struct SCEVCollectTerms { 11023 SmallVectorImpl<const SCEV *> &Terms; 11024 11025 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11026 11027 bool follow(const SCEV *S) { 11028 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11029 isa<SCEVSignExtendExpr>(S)) { 11030 if (!containsUndefs(S)) 11031 Terms.push_back(S); 11032 11033 // Stop recursion: once we collected a term, do not walk its operands. 11034 return false; 11035 } 11036 11037 // Keep looking. 11038 return true; 11039 } 11040 11041 bool isDone() const { return false; } 11042 }; 11043 11044 // Check if a SCEV contains an AddRecExpr. 11045 struct SCEVHasAddRec { 11046 bool &ContainsAddRec; 11047 11048 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11049 ContainsAddRec = false; 11050 } 11051 11052 bool follow(const SCEV *S) { 11053 if (isa<SCEVAddRecExpr>(S)) { 11054 ContainsAddRec = true; 11055 11056 // Stop recursion: once we collected a term, do not walk its operands. 11057 return false; 11058 } 11059 11060 // Keep looking. 11061 return true; 11062 } 11063 11064 bool isDone() const { return false; } 11065 }; 11066 11067 // Find factors that are multiplied with an expression that (possibly as a 11068 // subexpression) contains an AddRecExpr. In the expression: 11069 // 11070 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11071 // 11072 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11073 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11074 // parameters as they form a product with an induction variable. 11075 // 11076 // This collector expects all array size parameters to be in the same MulExpr. 11077 // It might be necessary to later add support for collecting parameters that are 11078 // spread over different nested MulExpr. 11079 struct SCEVCollectAddRecMultiplies { 11080 SmallVectorImpl<const SCEV *> &Terms; 11081 ScalarEvolution &SE; 11082 11083 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11084 : Terms(T), SE(SE) {} 11085 11086 bool follow(const SCEV *S) { 11087 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11088 bool HasAddRec = false; 11089 SmallVector<const SCEV *, 0> Operands; 11090 for (auto Op : Mul->operands()) { 11091 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11092 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11093 Operands.push_back(Op); 11094 } else if (Unknown) { 11095 HasAddRec = true; 11096 } else { 11097 bool ContainsAddRec = false; 11098 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11099 visitAll(Op, ContiansAddRec); 11100 HasAddRec |= ContainsAddRec; 11101 } 11102 } 11103 if (Operands.size() == 0) 11104 return true; 11105 11106 if (!HasAddRec) 11107 return false; 11108 11109 Terms.push_back(SE.getMulExpr(Operands)); 11110 // Stop recursion: once we collected a term, do not walk its operands. 11111 return false; 11112 } 11113 11114 // Keep looking. 11115 return true; 11116 } 11117 11118 bool isDone() const { return false; } 11119 }; 11120 11121 } // end anonymous namespace 11122 11123 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11124 /// two places: 11125 /// 1) The strides of AddRec expressions. 11126 /// 2) Unknowns that are multiplied with AddRec expressions. 11127 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11128 SmallVectorImpl<const SCEV *> &Terms) { 11129 SmallVector<const SCEV *, 4> Strides; 11130 SCEVCollectStrides StrideCollector(*this, Strides); 11131 visitAll(Expr, StrideCollector); 11132 11133 LLVM_DEBUG({ 11134 dbgs() << "Strides:\n"; 11135 for (const SCEV *S : Strides) 11136 dbgs() << *S << "\n"; 11137 }); 11138 11139 for (const SCEV *S : Strides) { 11140 SCEVCollectTerms TermCollector(Terms); 11141 visitAll(S, TermCollector); 11142 } 11143 11144 LLVM_DEBUG({ 11145 dbgs() << "Terms:\n"; 11146 for (const SCEV *T : Terms) 11147 dbgs() << *T << "\n"; 11148 }); 11149 11150 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11151 visitAll(Expr, MulCollector); 11152 } 11153 11154 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11155 SmallVectorImpl<const SCEV *> &Terms, 11156 SmallVectorImpl<const SCEV *> &Sizes) { 11157 int Last = Terms.size() - 1; 11158 const SCEV *Step = Terms[Last]; 11159 11160 // End of recursion. 11161 if (Last == 0) { 11162 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11163 SmallVector<const SCEV *, 2> Qs; 11164 for (const SCEV *Op : M->operands()) 11165 if (!isa<SCEVConstant>(Op)) 11166 Qs.push_back(Op); 11167 11168 Step = SE.getMulExpr(Qs); 11169 } 11170 11171 Sizes.push_back(Step); 11172 return true; 11173 } 11174 11175 for (const SCEV *&Term : Terms) { 11176 // Normalize the terms before the next call to findArrayDimensionsRec. 11177 const SCEV *Q, *R; 11178 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11179 11180 // Bail out when GCD does not evenly divide one of the terms. 11181 if (!R->isZero()) 11182 return false; 11183 11184 Term = Q; 11185 } 11186 11187 // Remove all SCEVConstants. 11188 Terms.erase( 11189 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11190 Terms.end()); 11191 11192 if (Terms.size() > 0) 11193 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11194 return false; 11195 11196 Sizes.push_back(Step); 11197 return true; 11198 } 11199 11200 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11201 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11202 for (const SCEV *T : Terms) 11203 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11204 return true; 11205 11206 return false; 11207 } 11208 11209 // Return the number of product terms in S. 11210 static inline int numberOfTerms(const SCEV *S) { 11211 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11212 return Expr->getNumOperands(); 11213 return 1; 11214 } 11215 11216 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11217 if (isa<SCEVConstant>(T)) 11218 return nullptr; 11219 11220 if (isa<SCEVUnknown>(T)) 11221 return T; 11222 11223 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11224 SmallVector<const SCEV *, 2> Factors; 11225 for (const SCEV *Op : M->operands()) 11226 if (!isa<SCEVConstant>(Op)) 11227 Factors.push_back(Op); 11228 11229 return SE.getMulExpr(Factors); 11230 } 11231 11232 return T; 11233 } 11234 11235 /// Return the size of an element read or written by Inst. 11236 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11237 Type *Ty; 11238 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11239 Ty = Store->getValueOperand()->getType(); 11240 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11241 Ty = Load->getType(); 11242 else 11243 return nullptr; 11244 11245 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11246 return getSizeOfExpr(ETy, Ty); 11247 } 11248 11249 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11250 SmallVectorImpl<const SCEV *> &Sizes, 11251 const SCEV *ElementSize) { 11252 if (Terms.size() < 1 || !ElementSize) 11253 return; 11254 11255 // Early return when Terms do not contain parameters: we do not delinearize 11256 // non parametric SCEVs. 11257 if (!containsParameters(Terms)) 11258 return; 11259 11260 LLVM_DEBUG({ 11261 dbgs() << "Terms:\n"; 11262 for (const SCEV *T : Terms) 11263 dbgs() << *T << "\n"; 11264 }); 11265 11266 // Remove duplicates. 11267 array_pod_sort(Terms.begin(), Terms.end()); 11268 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11269 11270 // Put larger terms first. 11271 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11272 return numberOfTerms(LHS) > numberOfTerms(RHS); 11273 }); 11274 11275 // Try to divide all terms by the element size. If term is not divisible by 11276 // element size, proceed with the original term. 11277 for (const SCEV *&Term : Terms) { 11278 const SCEV *Q, *R; 11279 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11280 if (!Q->isZero()) 11281 Term = Q; 11282 } 11283 11284 SmallVector<const SCEV *, 4> NewTerms; 11285 11286 // Remove constant factors. 11287 for (const SCEV *T : Terms) 11288 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11289 NewTerms.push_back(NewT); 11290 11291 LLVM_DEBUG({ 11292 dbgs() << "Terms after sorting:\n"; 11293 for (const SCEV *T : NewTerms) 11294 dbgs() << *T << "\n"; 11295 }); 11296 11297 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11298 Sizes.clear(); 11299 return; 11300 } 11301 11302 // The last element to be pushed into Sizes is the size of an element. 11303 Sizes.push_back(ElementSize); 11304 11305 LLVM_DEBUG({ 11306 dbgs() << "Sizes:\n"; 11307 for (const SCEV *S : Sizes) 11308 dbgs() << *S << "\n"; 11309 }); 11310 } 11311 11312 void ScalarEvolution::computeAccessFunctions( 11313 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11314 SmallVectorImpl<const SCEV *> &Sizes) { 11315 // Early exit in case this SCEV is not an affine multivariate function. 11316 if (Sizes.empty()) 11317 return; 11318 11319 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11320 if (!AR->isAffine()) 11321 return; 11322 11323 const SCEV *Res = Expr; 11324 int Last = Sizes.size() - 1; 11325 for (int i = Last; i >= 0; i--) { 11326 const SCEV *Q, *R; 11327 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11328 11329 LLVM_DEBUG({ 11330 dbgs() << "Res: " << *Res << "\n"; 11331 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11332 dbgs() << "Res divided by Sizes[i]:\n"; 11333 dbgs() << "Quotient: " << *Q << "\n"; 11334 dbgs() << "Remainder: " << *R << "\n"; 11335 }); 11336 11337 Res = Q; 11338 11339 // Do not record the last subscript corresponding to the size of elements in 11340 // the array. 11341 if (i == Last) { 11342 11343 // Bail out if the remainder is too complex. 11344 if (isa<SCEVAddRecExpr>(R)) { 11345 Subscripts.clear(); 11346 Sizes.clear(); 11347 return; 11348 } 11349 11350 continue; 11351 } 11352 11353 // Record the access function for the current subscript. 11354 Subscripts.push_back(R); 11355 } 11356 11357 // Also push in last position the remainder of the last division: it will be 11358 // the access function of the innermost dimension. 11359 Subscripts.push_back(Res); 11360 11361 std::reverse(Subscripts.begin(), Subscripts.end()); 11362 11363 LLVM_DEBUG({ 11364 dbgs() << "Subscripts:\n"; 11365 for (const SCEV *S : Subscripts) 11366 dbgs() << *S << "\n"; 11367 }); 11368 } 11369 11370 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11371 /// sizes of an array access. Returns the remainder of the delinearization that 11372 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11373 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11374 /// expressions in the stride and base of a SCEV corresponding to the 11375 /// computation of a GCD (greatest common divisor) of base and stride. When 11376 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11377 /// 11378 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11379 /// 11380 /// void foo(long n, long m, long o, double A[n][m][o]) { 11381 /// 11382 /// for (long i = 0; i < n; i++) 11383 /// for (long j = 0; j < m; j++) 11384 /// for (long k = 0; k < o; k++) 11385 /// A[i][j][k] = 1.0; 11386 /// } 11387 /// 11388 /// the delinearization input is the following AddRec SCEV: 11389 /// 11390 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11391 /// 11392 /// From this SCEV, we are able to say that the base offset of the access is %A 11393 /// because it appears as an offset that does not divide any of the strides in 11394 /// the loops: 11395 /// 11396 /// CHECK: Base offset: %A 11397 /// 11398 /// and then SCEV->delinearize determines the size of some of the dimensions of 11399 /// the array as these are the multiples by which the strides are happening: 11400 /// 11401 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11402 /// 11403 /// Note that the outermost dimension remains of UnknownSize because there are 11404 /// no strides that would help identifying the size of the last dimension: when 11405 /// the array has been statically allocated, one could compute the size of that 11406 /// dimension by dividing the overall size of the array by the size of the known 11407 /// dimensions: %m * %o * 8. 11408 /// 11409 /// Finally delinearize provides the access functions for the array reference 11410 /// that does correspond to A[i][j][k] of the above C testcase: 11411 /// 11412 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11413 /// 11414 /// The testcases are checking the output of a function pass: 11415 /// DelinearizationPass that walks through all loads and stores of a function 11416 /// asking for the SCEV of the memory access with respect to all enclosing 11417 /// loops, calling SCEV->delinearize on that and printing the results. 11418 void ScalarEvolution::delinearize(const SCEV *Expr, 11419 SmallVectorImpl<const SCEV *> &Subscripts, 11420 SmallVectorImpl<const SCEV *> &Sizes, 11421 const SCEV *ElementSize) { 11422 // First step: collect parametric terms. 11423 SmallVector<const SCEV *, 4> Terms; 11424 collectParametricTerms(Expr, Terms); 11425 11426 if (Terms.empty()) 11427 return; 11428 11429 // Second step: find subscript sizes. 11430 findArrayDimensions(Terms, Sizes, ElementSize); 11431 11432 if (Sizes.empty()) 11433 return; 11434 11435 // Third step: compute the access functions for each subscript. 11436 computeAccessFunctions(Expr, Subscripts, Sizes); 11437 11438 if (Subscripts.empty()) 11439 return; 11440 11441 LLVM_DEBUG({ 11442 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11443 dbgs() << "ArrayDecl[UnknownSize]"; 11444 for (const SCEV *S : Sizes) 11445 dbgs() << "[" << *S << "]"; 11446 11447 dbgs() << "\nArrayRef"; 11448 for (const SCEV *S : Subscripts) 11449 dbgs() << "[" << *S << "]"; 11450 dbgs() << "\n"; 11451 }); 11452 } 11453 11454 bool ScalarEvolution::getIndexExpressionsFromGEP( 11455 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11456 SmallVectorImpl<int> &Sizes) { 11457 assert(Subscripts.empty() && Sizes.empty() && 11458 "Expected output lists to be empty on entry to this function."); 11459 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11460 Type *Ty = GEP->getPointerOperandType(); 11461 bool DroppedFirstDim = false; 11462 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11463 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11464 if (i == 1) { 11465 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11466 Ty = PtrTy->getElementType(); 11467 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11468 Ty = ArrayTy->getElementType(); 11469 } else { 11470 Subscripts.clear(); 11471 Sizes.clear(); 11472 return false; 11473 } 11474 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11475 if (Const->getValue()->isZero()) { 11476 DroppedFirstDim = true; 11477 continue; 11478 } 11479 Subscripts.push_back(Expr); 11480 continue; 11481 } 11482 11483 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11484 if (!ArrayTy) { 11485 Subscripts.clear(); 11486 Sizes.clear(); 11487 return false; 11488 } 11489 11490 Subscripts.push_back(Expr); 11491 if (!(DroppedFirstDim && i == 2)) 11492 Sizes.push_back(ArrayTy->getNumElements()); 11493 11494 Ty = ArrayTy->getElementType(); 11495 } 11496 return !Subscripts.empty(); 11497 } 11498 11499 //===----------------------------------------------------------------------===// 11500 // SCEVCallbackVH Class Implementation 11501 //===----------------------------------------------------------------------===// 11502 11503 void ScalarEvolution::SCEVCallbackVH::deleted() { 11504 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11505 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11506 SE->ConstantEvolutionLoopExitValue.erase(PN); 11507 SE->eraseValueFromMap(getValPtr()); 11508 // this now dangles! 11509 } 11510 11511 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11512 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11513 11514 // Forget all the expressions associated with users of the old value, 11515 // so that future queries will recompute the expressions using the new 11516 // value. 11517 Value *Old = getValPtr(); 11518 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11519 SmallPtrSet<User *, 8> Visited; 11520 while (!Worklist.empty()) { 11521 User *U = Worklist.pop_back_val(); 11522 // Deleting the Old value will cause this to dangle. Postpone 11523 // that until everything else is done. 11524 if (U == Old) 11525 continue; 11526 if (!Visited.insert(U).second) 11527 continue; 11528 if (PHINode *PN = dyn_cast<PHINode>(U)) 11529 SE->ConstantEvolutionLoopExitValue.erase(PN); 11530 SE->eraseValueFromMap(U); 11531 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11532 } 11533 // Delete the Old value. 11534 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11535 SE->ConstantEvolutionLoopExitValue.erase(PN); 11536 SE->eraseValueFromMap(Old); 11537 // this now dangles! 11538 } 11539 11540 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11541 : CallbackVH(V), SE(se) {} 11542 11543 //===----------------------------------------------------------------------===// 11544 // ScalarEvolution Class Implementation 11545 //===----------------------------------------------------------------------===// 11546 11547 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11548 AssumptionCache &AC, DominatorTree &DT, 11549 LoopInfo &LI) 11550 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11551 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11552 LoopDispositions(64), BlockDispositions(64) { 11553 // To use guards for proving predicates, we need to scan every instruction in 11554 // relevant basic blocks, and not just terminators. Doing this is a waste of 11555 // time if the IR does not actually contain any calls to 11556 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11557 // 11558 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11559 // to _add_ guards to the module when there weren't any before, and wants 11560 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11561 // efficient in lieu of being smart in that rather obscure case. 11562 11563 auto *GuardDecl = F.getParent()->getFunction( 11564 Intrinsic::getName(Intrinsic::experimental_guard)); 11565 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11566 } 11567 11568 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11569 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11570 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11571 ValueExprMap(std::move(Arg.ValueExprMap)), 11572 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11573 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11574 PendingMerges(std::move(Arg.PendingMerges)), 11575 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11576 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11577 PredicatedBackedgeTakenCounts( 11578 std::move(Arg.PredicatedBackedgeTakenCounts)), 11579 ConstantEvolutionLoopExitValue( 11580 std::move(Arg.ConstantEvolutionLoopExitValue)), 11581 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11582 LoopDispositions(std::move(Arg.LoopDispositions)), 11583 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11584 BlockDispositions(std::move(Arg.BlockDispositions)), 11585 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11586 SignedRanges(std::move(Arg.SignedRanges)), 11587 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11588 UniquePreds(std::move(Arg.UniquePreds)), 11589 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11590 LoopUsers(std::move(Arg.LoopUsers)), 11591 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11592 FirstUnknown(Arg.FirstUnknown) { 11593 Arg.FirstUnknown = nullptr; 11594 } 11595 11596 ScalarEvolution::~ScalarEvolution() { 11597 // Iterate through all the SCEVUnknown instances and call their 11598 // destructors, so that they release their references to their values. 11599 for (SCEVUnknown *U = FirstUnknown; U;) { 11600 SCEVUnknown *Tmp = U; 11601 U = U->Next; 11602 Tmp->~SCEVUnknown(); 11603 } 11604 FirstUnknown = nullptr; 11605 11606 ExprValueMap.clear(); 11607 ValueExprMap.clear(); 11608 HasRecMap.clear(); 11609 11610 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11611 // that a loop had multiple computable exits. 11612 for (auto &BTCI : BackedgeTakenCounts) 11613 BTCI.second.clear(); 11614 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11615 BTCI.second.clear(); 11616 11617 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11618 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11619 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11620 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11621 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11622 } 11623 11624 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11625 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11626 } 11627 11628 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11629 const Loop *L) { 11630 // Print all inner loops first 11631 for (Loop *I : *L) 11632 PrintLoopInfo(OS, SE, I); 11633 11634 OS << "Loop "; 11635 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11636 OS << ": "; 11637 11638 SmallVector<BasicBlock *, 8> ExitingBlocks; 11639 L->getExitingBlocks(ExitingBlocks); 11640 if (ExitingBlocks.size() != 1) 11641 OS << "<multiple exits> "; 11642 11643 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11644 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11645 else 11646 OS << "Unpredictable backedge-taken count.\n"; 11647 11648 if (ExitingBlocks.size() > 1) 11649 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11650 OS << " exit count for " << ExitingBlock->getName() << ": " 11651 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11652 } 11653 11654 OS << "Loop "; 11655 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11656 OS << ": "; 11657 11658 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11659 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11660 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11661 OS << ", actual taken count either this or zero."; 11662 } else { 11663 OS << "Unpredictable max backedge-taken count. "; 11664 } 11665 11666 OS << "\n" 11667 "Loop "; 11668 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11669 OS << ": "; 11670 11671 SCEVUnionPredicate Pred; 11672 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11673 if (!isa<SCEVCouldNotCompute>(PBT)) { 11674 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11675 OS << " Predicates:\n"; 11676 Pred.print(OS, 4); 11677 } else { 11678 OS << "Unpredictable predicated backedge-taken count. "; 11679 } 11680 OS << "\n"; 11681 11682 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11683 OS << "Loop "; 11684 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11685 OS << ": "; 11686 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11687 } 11688 } 11689 11690 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11691 switch (LD) { 11692 case ScalarEvolution::LoopVariant: 11693 return "Variant"; 11694 case ScalarEvolution::LoopInvariant: 11695 return "Invariant"; 11696 case ScalarEvolution::LoopComputable: 11697 return "Computable"; 11698 } 11699 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11700 } 11701 11702 void ScalarEvolution::print(raw_ostream &OS) const { 11703 // ScalarEvolution's implementation of the print method is to print 11704 // out SCEV values of all instructions that are interesting. Doing 11705 // this potentially causes it to create new SCEV objects though, 11706 // which technically conflicts with the const qualifier. This isn't 11707 // observable from outside the class though, so casting away the 11708 // const isn't dangerous. 11709 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11710 11711 if (ClassifyExpressions) { 11712 OS << "Classifying expressions for: "; 11713 F.printAsOperand(OS, /*PrintType=*/false); 11714 OS << "\n"; 11715 for (Instruction &I : instructions(F)) 11716 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11717 OS << I << '\n'; 11718 OS << " --> "; 11719 const SCEV *SV = SE.getSCEV(&I); 11720 SV->print(OS); 11721 if (!isa<SCEVCouldNotCompute>(SV)) { 11722 OS << " U: "; 11723 SE.getUnsignedRange(SV).print(OS); 11724 OS << " S: "; 11725 SE.getSignedRange(SV).print(OS); 11726 } 11727 11728 const Loop *L = LI.getLoopFor(I.getParent()); 11729 11730 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11731 if (AtUse != SV) { 11732 OS << " --> "; 11733 AtUse->print(OS); 11734 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11735 OS << " U: "; 11736 SE.getUnsignedRange(AtUse).print(OS); 11737 OS << " S: "; 11738 SE.getSignedRange(AtUse).print(OS); 11739 } 11740 } 11741 11742 if (L) { 11743 OS << "\t\t" "Exits: "; 11744 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11745 if (!SE.isLoopInvariant(ExitValue, L)) { 11746 OS << "<<Unknown>>"; 11747 } else { 11748 OS << *ExitValue; 11749 } 11750 11751 bool First = true; 11752 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11753 if (First) { 11754 OS << "\t\t" "LoopDispositions: { "; 11755 First = false; 11756 } else { 11757 OS << ", "; 11758 } 11759 11760 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11761 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11762 } 11763 11764 for (auto *InnerL : depth_first(L)) { 11765 if (InnerL == L) 11766 continue; 11767 if (First) { 11768 OS << "\t\t" "LoopDispositions: { "; 11769 First = false; 11770 } else { 11771 OS << ", "; 11772 } 11773 11774 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11775 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11776 } 11777 11778 OS << " }"; 11779 } 11780 11781 OS << "\n"; 11782 } 11783 } 11784 11785 OS << "Determining loop execution counts for: "; 11786 F.printAsOperand(OS, /*PrintType=*/false); 11787 OS << "\n"; 11788 for (Loop *I : LI) 11789 PrintLoopInfo(OS, &SE, I); 11790 } 11791 11792 ScalarEvolution::LoopDisposition 11793 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11794 auto &Values = LoopDispositions[S]; 11795 for (auto &V : Values) { 11796 if (V.getPointer() == L) 11797 return V.getInt(); 11798 } 11799 Values.emplace_back(L, LoopVariant); 11800 LoopDisposition D = computeLoopDisposition(S, L); 11801 auto &Values2 = LoopDispositions[S]; 11802 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11803 if (V.getPointer() == L) { 11804 V.setInt(D); 11805 break; 11806 } 11807 } 11808 return D; 11809 } 11810 11811 ScalarEvolution::LoopDisposition 11812 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11813 switch (S->getSCEVType()) { 11814 case scConstant: 11815 return LoopInvariant; 11816 case scTruncate: 11817 case scZeroExtend: 11818 case scSignExtend: 11819 return getLoopDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), L); 11820 case scAddRecExpr: { 11821 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11822 11823 // If L is the addrec's loop, it's computable. 11824 if (AR->getLoop() == L) 11825 return LoopComputable; 11826 11827 // Add recurrences are never invariant in the function-body (null loop). 11828 if (!L) 11829 return LoopVariant; 11830 11831 // Everything that is not defined at loop entry is variant. 11832 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11833 return LoopVariant; 11834 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11835 " dominate the contained loop's header?"); 11836 11837 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11838 if (AR->getLoop()->contains(L)) 11839 return LoopInvariant; 11840 11841 // This recurrence is variant w.r.t. L if any of its operands 11842 // are variant. 11843 for (auto *Op : AR->operands()) 11844 if (!isLoopInvariant(Op, L)) 11845 return LoopVariant; 11846 11847 // Otherwise it's loop-invariant. 11848 return LoopInvariant; 11849 } 11850 case scAddExpr: 11851 case scMulExpr: 11852 case scUMaxExpr: 11853 case scSMaxExpr: 11854 case scUMinExpr: 11855 case scSMinExpr: { 11856 bool HasVarying = false; 11857 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11858 LoopDisposition D = getLoopDisposition(Op, L); 11859 if (D == LoopVariant) 11860 return LoopVariant; 11861 if (D == LoopComputable) 11862 HasVarying = true; 11863 } 11864 return HasVarying ? LoopComputable : LoopInvariant; 11865 } 11866 case scUDivExpr: { 11867 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11868 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11869 if (LD == LoopVariant) 11870 return LoopVariant; 11871 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11872 if (RD == LoopVariant) 11873 return LoopVariant; 11874 return (LD == LoopInvariant && RD == LoopInvariant) ? 11875 LoopInvariant : LoopComputable; 11876 } 11877 case scUnknown: 11878 // All non-instruction values are loop invariant. All instructions are loop 11879 // invariant if they are not contained in the specified loop. 11880 // Instructions are never considered invariant in the function body 11881 // (null loop) because they are defined within the "loop". 11882 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11883 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11884 return LoopInvariant; 11885 case scCouldNotCompute: 11886 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11887 } 11888 llvm_unreachable("Unknown SCEV kind!"); 11889 } 11890 11891 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11892 return getLoopDisposition(S, L) == LoopInvariant; 11893 } 11894 11895 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11896 return getLoopDisposition(S, L) == LoopComputable; 11897 } 11898 11899 ScalarEvolution::BlockDisposition 11900 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11901 auto &Values = BlockDispositions[S]; 11902 for (auto &V : Values) { 11903 if (V.getPointer() == BB) 11904 return V.getInt(); 11905 } 11906 Values.emplace_back(BB, DoesNotDominateBlock); 11907 BlockDisposition D = computeBlockDisposition(S, BB); 11908 auto &Values2 = BlockDispositions[S]; 11909 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11910 if (V.getPointer() == BB) { 11911 V.setInt(D); 11912 break; 11913 } 11914 } 11915 return D; 11916 } 11917 11918 ScalarEvolution::BlockDisposition 11919 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11920 switch (S->getSCEVType()) { 11921 case scConstant: 11922 return ProperlyDominatesBlock; 11923 case scTruncate: 11924 case scZeroExtend: 11925 case scSignExtend: 11926 return getBlockDisposition(cast<SCEVIntegralCastExpr>(S)->getOperand(), BB); 11927 case scAddRecExpr: { 11928 // This uses a "dominates" query instead of "properly dominates" query 11929 // to test for proper dominance too, because the instruction which 11930 // produces the addrec's value is a PHI, and a PHI effectively properly 11931 // dominates its entire containing block. 11932 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11933 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11934 return DoesNotDominateBlock; 11935 11936 // Fall through into SCEVNAryExpr handling. 11937 LLVM_FALLTHROUGH; 11938 } 11939 case scAddExpr: 11940 case scMulExpr: 11941 case scUMaxExpr: 11942 case scSMaxExpr: 11943 case scUMinExpr: 11944 case scSMinExpr: { 11945 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11946 bool Proper = true; 11947 for (const SCEV *NAryOp : NAry->operands()) { 11948 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11949 if (D == DoesNotDominateBlock) 11950 return DoesNotDominateBlock; 11951 if (D == DominatesBlock) 11952 Proper = false; 11953 } 11954 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11955 } 11956 case scUDivExpr: { 11957 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11958 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11959 BlockDisposition LD = getBlockDisposition(LHS, BB); 11960 if (LD == DoesNotDominateBlock) 11961 return DoesNotDominateBlock; 11962 BlockDisposition RD = getBlockDisposition(RHS, BB); 11963 if (RD == DoesNotDominateBlock) 11964 return DoesNotDominateBlock; 11965 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11966 ProperlyDominatesBlock : DominatesBlock; 11967 } 11968 case scUnknown: 11969 if (Instruction *I = 11970 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11971 if (I->getParent() == BB) 11972 return DominatesBlock; 11973 if (DT.properlyDominates(I->getParent(), BB)) 11974 return ProperlyDominatesBlock; 11975 return DoesNotDominateBlock; 11976 } 11977 return ProperlyDominatesBlock; 11978 case scCouldNotCompute: 11979 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11980 } 11981 llvm_unreachable("Unknown SCEV kind!"); 11982 } 11983 11984 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11985 return getBlockDisposition(S, BB) >= DominatesBlock; 11986 } 11987 11988 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11989 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11990 } 11991 11992 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11993 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11994 } 11995 11996 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11997 auto IsS = [&](const SCEV *X) { return S == X; }; 11998 auto ContainsS = [&](const SCEV *X) { 11999 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12000 }; 12001 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12002 } 12003 12004 void 12005 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12006 ValuesAtScopes.erase(S); 12007 LoopDispositions.erase(S); 12008 BlockDispositions.erase(S); 12009 UnsignedRanges.erase(S); 12010 SignedRanges.erase(S); 12011 ExprValueMap.erase(S); 12012 HasRecMap.erase(S); 12013 MinTrailingZerosCache.erase(S); 12014 12015 for (auto I = PredicatedSCEVRewrites.begin(); 12016 I != PredicatedSCEVRewrites.end();) { 12017 std::pair<const SCEV *, const Loop *> Entry = I->first; 12018 if (Entry.first == S) 12019 PredicatedSCEVRewrites.erase(I++); 12020 else 12021 ++I; 12022 } 12023 12024 auto RemoveSCEVFromBackedgeMap = 12025 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12026 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12027 BackedgeTakenInfo &BEInfo = I->second; 12028 if (BEInfo.hasOperand(S, this)) { 12029 BEInfo.clear(); 12030 Map.erase(I++); 12031 } else 12032 ++I; 12033 } 12034 }; 12035 12036 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12037 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12038 } 12039 12040 void 12041 ScalarEvolution::getUsedLoops(const SCEV *S, 12042 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12043 struct FindUsedLoops { 12044 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12045 : LoopsUsed(LoopsUsed) {} 12046 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12047 bool follow(const SCEV *S) { 12048 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12049 LoopsUsed.insert(AR->getLoop()); 12050 return true; 12051 } 12052 12053 bool isDone() const { return false; } 12054 }; 12055 12056 FindUsedLoops F(LoopsUsed); 12057 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12058 } 12059 12060 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12061 SmallPtrSet<const Loop *, 8> LoopsUsed; 12062 getUsedLoops(S, LoopsUsed); 12063 for (auto *L : LoopsUsed) 12064 LoopUsers[L].push_back(S); 12065 } 12066 12067 void ScalarEvolution::verify() const { 12068 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12069 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12070 12071 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12072 12073 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12074 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12075 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12076 12077 const SCEV *visitConstant(const SCEVConstant *Constant) { 12078 return SE.getConstant(Constant->getAPInt()); 12079 } 12080 12081 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12082 return SE.getUnknown(Expr->getValue()); 12083 } 12084 12085 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12086 return SE.getCouldNotCompute(); 12087 } 12088 }; 12089 12090 SCEVMapper SCM(SE2); 12091 12092 while (!LoopStack.empty()) { 12093 auto *L = LoopStack.pop_back_val(); 12094 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12095 12096 auto *CurBECount = SCM.visit( 12097 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12098 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12099 12100 if (CurBECount == SE2.getCouldNotCompute() || 12101 NewBECount == SE2.getCouldNotCompute()) { 12102 // NB! This situation is legal, but is very suspicious -- whatever pass 12103 // change the loop to make a trip count go from could not compute to 12104 // computable or vice-versa *should have* invalidated SCEV. However, we 12105 // choose not to assert here (for now) since we don't want false 12106 // positives. 12107 continue; 12108 } 12109 12110 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12111 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12112 // not propagate undef aggressively). This means we can (and do) fail 12113 // verification in cases where a transform makes the trip count of a loop 12114 // go from "undef" to "undef+1" (say). The transform is fine, since in 12115 // both cases the loop iterates "undef" times, but SCEV thinks we 12116 // increased the trip count of the loop by 1 incorrectly. 12117 continue; 12118 } 12119 12120 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12121 SE.getTypeSizeInBits(NewBECount->getType())) 12122 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12123 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12124 SE.getTypeSizeInBits(NewBECount->getType())) 12125 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12126 12127 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12128 12129 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12130 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12131 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12132 dbgs() << "Old: " << *CurBECount << "\n"; 12133 dbgs() << "New: " << *NewBECount << "\n"; 12134 dbgs() << "Delta: " << *Delta << "\n"; 12135 std::abort(); 12136 } 12137 } 12138 12139 // Collect all valid loops currently in LoopInfo. 12140 SmallPtrSet<Loop *, 32> ValidLoops; 12141 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12142 while (!Worklist.empty()) { 12143 Loop *L = Worklist.pop_back_val(); 12144 if (ValidLoops.contains(L)) 12145 continue; 12146 ValidLoops.insert(L); 12147 Worklist.append(L->begin(), L->end()); 12148 } 12149 // Check for SCEV expressions referencing invalid/deleted loops. 12150 for (auto &KV : ValueExprMap) { 12151 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12152 if (!AR) 12153 continue; 12154 assert(ValidLoops.contains(AR->getLoop()) && 12155 "AddRec references invalid loop"); 12156 } 12157 } 12158 12159 bool ScalarEvolution::invalidate( 12160 Function &F, const PreservedAnalyses &PA, 12161 FunctionAnalysisManager::Invalidator &Inv) { 12162 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12163 // of its dependencies is invalidated. 12164 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12165 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12166 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12167 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12168 Inv.invalidate<LoopAnalysis>(F, PA); 12169 } 12170 12171 AnalysisKey ScalarEvolutionAnalysis::Key; 12172 12173 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12174 FunctionAnalysisManager &AM) { 12175 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12176 AM.getResult<AssumptionAnalysis>(F), 12177 AM.getResult<DominatorTreeAnalysis>(F), 12178 AM.getResult<LoopAnalysis>(F)); 12179 } 12180 12181 PreservedAnalyses 12182 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12183 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12184 return PreservedAnalyses::all(); 12185 } 12186 12187 PreservedAnalyses 12188 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12189 // For compatibility with opt's -analyze feature under legacy pass manager 12190 // which was not ported to NPM. This keeps tests using 12191 // update_analyze_test_checks.py working. 12192 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12193 << F.getName() << "':\n"; 12194 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12195 return PreservedAnalyses::all(); 12196 } 12197 12198 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12199 "Scalar Evolution Analysis", false, true) 12200 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12201 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12203 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12204 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12205 "Scalar Evolution Analysis", false, true) 12206 12207 char ScalarEvolutionWrapperPass::ID = 0; 12208 12209 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12210 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12211 } 12212 12213 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12214 SE.reset(new ScalarEvolution( 12215 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12216 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12217 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12218 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12219 return false; 12220 } 12221 12222 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12223 12224 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12225 SE->print(OS); 12226 } 12227 12228 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12229 if (!VerifySCEV) 12230 return; 12231 12232 SE->verify(); 12233 } 12234 12235 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12236 AU.setPreservesAll(); 12237 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12238 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12239 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12240 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12241 } 12242 12243 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12244 const SCEV *RHS) { 12245 FoldingSetNodeID ID; 12246 assert(LHS->getType() == RHS->getType() && 12247 "Type mismatch between LHS and RHS"); 12248 // Unique this node based on the arguments 12249 ID.AddInteger(SCEVPredicate::P_Equal); 12250 ID.AddPointer(LHS); 12251 ID.AddPointer(RHS); 12252 void *IP = nullptr; 12253 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12254 return S; 12255 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12256 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12257 UniquePreds.InsertNode(Eq, IP); 12258 return Eq; 12259 } 12260 12261 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12262 const SCEVAddRecExpr *AR, 12263 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12264 FoldingSetNodeID ID; 12265 // Unique this node based on the arguments 12266 ID.AddInteger(SCEVPredicate::P_Wrap); 12267 ID.AddPointer(AR); 12268 ID.AddInteger(AddedFlags); 12269 void *IP = nullptr; 12270 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12271 return S; 12272 auto *OF = new (SCEVAllocator) 12273 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12274 UniquePreds.InsertNode(OF, IP); 12275 return OF; 12276 } 12277 12278 namespace { 12279 12280 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12281 public: 12282 12283 /// Rewrites \p S in the context of a loop L and the SCEV predication 12284 /// infrastructure. 12285 /// 12286 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12287 /// equivalences present in \p Pred. 12288 /// 12289 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12290 /// \p NewPreds such that the result will be an AddRecExpr. 12291 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12292 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12293 SCEVUnionPredicate *Pred) { 12294 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12295 return Rewriter.visit(S); 12296 } 12297 12298 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12299 if (Pred) { 12300 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12301 for (auto *Pred : ExprPreds) 12302 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12303 if (IPred->getLHS() == Expr) 12304 return IPred->getRHS(); 12305 } 12306 return convertToAddRecWithPreds(Expr); 12307 } 12308 12309 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12310 const SCEV *Operand = visit(Expr->getOperand()); 12311 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12312 if (AR && AR->getLoop() == L && AR->isAffine()) { 12313 // This couldn't be folded because the operand didn't have the nuw 12314 // flag. Add the nusw flag as an assumption that we could make. 12315 const SCEV *Step = AR->getStepRecurrence(SE); 12316 Type *Ty = Expr->getType(); 12317 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12318 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12319 SE.getSignExtendExpr(Step, Ty), L, 12320 AR->getNoWrapFlags()); 12321 } 12322 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12323 } 12324 12325 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12326 const SCEV *Operand = visit(Expr->getOperand()); 12327 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12328 if (AR && AR->getLoop() == L && AR->isAffine()) { 12329 // This couldn't be folded because the operand didn't have the nsw 12330 // flag. Add the nssw flag as an assumption that we could make. 12331 const SCEV *Step = AR->getStepRecurrence(SE); 12332 Type *Ty = Expr->getType(); 12333 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12334 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12335 SE.getSignExtendExpr(Step, Ty), L, 12336 AR->getNoWrapFlags()); 12337 } 12338 return SE.getSignExtendExpr(Operand, Expr->getType()); 12339 } 12340 12341 private: 12342 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12343 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12344 SCEVUnionPredicate *Pred) 12345 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12346 12347 bool addOverflowAssumption(const SCEVPredicate *P) { 12348 if (!NewPreds) { 12349 // Check if we've already made this assumption. 12350 return Pred && Pred->implies(P); 12351 } 12352 NewPreds->insert(P); 12353 return true; 12354 } 12355 12356 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12357 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12358 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12359 return addOverflowAssumption(A); 12360 } 12361 12362 // If \p Expr represents a PHINode, we try to see if it can be represented 12363 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12364 // to add this predicate as a runtime overflow check, we return the AddRec. 12365 // If \p Expr does not meet these conditions (is not a PHI node, or we 12366 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12367 // return \p Expr. 12368 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12369 if (!isa<PHINode>(Expr->getValue())) 12370 return Expr; 12371 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12372 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12373 if (!PredicatedRewrite) 12374 return Expr; 12375 for (auto *P : PredicatedRewrite->second){ 12376 // Wrap predicates from outer loops are not supported. 12377 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12378 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12379 if (L != AR->getLoop()) 12380 return Expr; 12381 } 12382 if (!addOverflowAssumption(P)) 12383 return Expr; 12384 } 12385 return PredicatedRewrite->first; 12386 } 12387 12388 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12389 SCEVUnionPredicate *Pred; 12390 const Loop *L; 12391 }; 12392 12393 } // end anonymous namespace 12394 12395 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12396 SCEVUnionPredicate &Preds) { 12397 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12398 } 12399 12400 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12401 const SCEV *S, const Loop *L, 12402 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12403 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12404 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12405 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12406 12407 if (!AddRec) 12408 return nullptr; 12409 12410 // Since the transformation was successful, we can now transfer the SCEV 12411 // predicates. 12412 for (auto *P : TransformPreds) 12413 Preds.insert(P); 12414 12415 return AddRec; 12416 } 12417 12418 /// SCEV predicates 12419 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12420 SCEVPredicateKind Kind) 12421 : FastID(ID), Kind(Kind) {} 12422 12423 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12424 const SCEV *LHS, const SCEV *RHS) 12425 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12426 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12427 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12428 } 12429 12430 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12431 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12432 12433 if (!Op) 12434 return false; 12435 12436 return Op->LHS == LHS && Op->RHS == RHS; 12437 } 12438 12439 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12440 12441 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12442 12443 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12444 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12445 } 12446 12447 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12448 const SCEVAddRecExpr *AR, 12449 IncrementWrapFlags Flags) 12450 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12451 12452 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12453 12454 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12455 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12456 12457 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12458 } 12459 12460 bool SCEVWrapPredicate::isAlwaysTrue() const { 12461 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12462 IncrementWrapFlags IFlags = Flags; 12463 12464 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12465 IFlags = clearFlags(IFlags, IncrementNSSW); 12466 12467 return IFlags == IncrementAnyWrap; 12468 } 12469 12470 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12471 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12472 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12473 OS << "<nusw>"; 12474 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12475 OS << "<nssw>"; 12476 OS << "\n"; 12477 } 12478 12479 SCEVWrapPredicate::IncrementWrapFlags 12480 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12481 ScalarEvolution &SE) { 12482 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12483 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12484 12485 // We can safely transfer the NSW flag as NSSW. 12486 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12487 ImpliedFlags = IncrementNSSW; 12488 12489 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12490 // If the increment is positive, the SCEV NUW flag will also imply the 12491 // WrapPredicate NUSW flag. 12492 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12493 if (Step->getValue()->getValue().isNonNegative()) 12494 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12495 } 12496 12497 return ImpliedFlags; 12498 } 12499 12500 /// Union predicates don't get cached so create a dummy set ID for it. 12501 SCEVUnionPredicate::SCEVUnionPredicate() 12502 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12503 12504 bool SCEVUnionPredicate::isAlwaysTrue() const { 12505 return all_of(Preds, 12506 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12507 } 12508 12509 ArrayRef<const SCEVPredicate *> 12510 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12511 auto I = SCEVToPreds.find(Expr); 12512 if (I == SCEVToPreds.end()) 12513 return ArrayRef<const SCEVPredicate *>(); 12514 return I->second; 12515 } 12516 12517 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12518 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12519 return all_of(Set->Preds, 12520 [this](const SCEVPredicate *I) { return this->implies(I); }); 12521 12522 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12523 if (ScevPredsIt == SCEVToPreds.end()) 12524 return false; 12525 auto &SCEVPreds = ScevPredsIt->second; 12526 12527 return any_of(SCEVPreds, 12528 [N](const SCEVPredicate *I) { return I->implies(N); }); 12529 } 12530 12531 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12532 12533 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12534 for (auto Pred : Preds) 12535 Pred->print(OS, Depth); 12536 } 12537 12538 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12539 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12540 for (auto Pred : Set->Preds) 12541 add(Pred); 12542 return; 12543 } 12544 12545 if (implies(N)) 12546 return; 12547 12548 const SCEV *Key = N->getExpr(); 12549 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12550 " associated expression!"); 12551 12552 SCEVToPreds[Key].push_back(N); 12553 Preds.push_back(N); 12554 } 12555 12556 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12557 Loop &L) 12558 : SE(SE), L(L) {} 12559 12560 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12561 const SCEV *Expr = SE.getSCEV(V); 12562 RewriteEntry &Entry = RewriteMap[Expr]; 12563 12564 // If we already have an entry and the version matches, return it. 12565 if (Entry.second && Generation == Entry.first) 12566 return Entry.second; 12567 12568 // We found an entry but it's stale. Rewrite the stale entry 12569 // according to the current predicate. 12570 if (Entry.second) 12571 Expr = Entry.second; 12572 12573 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12574 Entry = {Generation, NewSCEV}; 12575 12576 return NewSCEV; 12577 } 12578 12579 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12580 if (!BackedgeCount) { 12581 SCEVUnionPredicate BackedgePred; 12582 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12583 addPredicate(BackedgePred); 12584 } 12585 return BackedgeCount; 12586 } 12587 12588 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12589 if (Preds.implies(&Pred)) 12590 return; 12591 Preds.add(&Pred); 12592 updateGeneration(); 12593 } 12594 12595 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12596 return Preds; 12597 } 12598 12599 void PredicatedScalarEvolution::updateGeneration() { 12600 // If the generation number wrapped recompute everything. 12601 if (++Generation == 0) { 12602 for (auto &II : RewriteMap) { 12603 const SCEV *Rewritten = II.second.second; 12604 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12605 } 12606 } 12607 } 12608 12609 void PredicatedScalarEvolution::setNoOverflow( 12610 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12611 const SCEV *Expr = getSCEV(V); 12612 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12613 12614 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12615 12616 // Clear the statically implied flags. 12617 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12618 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12619 12620 auto II = FlagsMap.insert({V, Flags}); 12621 if (!II.second) 12622 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12623 } 12624 12625 bool PredicatedScalarEvolution::hasNoOverflow( 12626 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12627 const SCEV *Expr = getSCEV(V); 12628 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12629 12630 Flags = SCEVWrapPredicate::clearFlags( 12631 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12632 12633 auto II = FlagsMap.find(V); 12634 12635 if (II != FlagsMap.end()) 12636 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12637 12638 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12639 } 12640 12641 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12642 const SCEV *Expr = this->getSCEV(V); 12643 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12644 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12645 12646 if (!New) 12647 return nullptr; 12648 12649 for (auto *P : NewPreds) 12650 Preds.add(P); 12651 12652 updateGeneration(); 12653 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12654 return New; 12655 } 12656 12657 PredicatedScalarEvolution::PredicatedScalarEvolution( 12658 const PredicatedScalarEvolution &Init) 12659 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12660 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12661 for (auto I : Init.FlagsMap) 12662 FlagsMap.insert(I); 12663 } 12664 12665 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12666 // For each block. 12667 for (auto *BB : L.getBlocks()) 12668 for (auto &I : *BB) { 12669 if (!SE.isSCEVable(I.getType())) 12670 continue; 12671 12672 auto *Expr = SE.getSCEV(&I); 12673 auto II = RewriteMap.find(Expr); 12674 12675 if (II == RewriteMap.end()) 12676 continue; 12677 12678 // Don't print things that are not interesting. 12679 if (II->second.second == Expr) 12680 continue; 12681 12682 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12683 OS.indent(Depth + 2) << *Expr << "\n"; 12684 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12685 } 12686 } 12687 12688 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12689 // arbitrary expressions. 12690 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12691 // 4, A / B becomes X / 8). 12692 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12693 const SCEV *&RHS) { 12694 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12695 if (Add == nullptr || Add->getNumOperands() != 2) 12696 return false; 12697 12698 const SCEV *A = Add->getOperand(1); 12699 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12700 12701 if (Mul == nullptr) 12702 return false; 12703 12704 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12705 // (SomeExpr + (-(SomeExpr / B) * B)). 12706 if (Expr == getURemExpr(A, B)) { 12707 LHS = A; 12708 RHS = B; 12709 return true; 12710 } 12711 return false; 12712 }; 12713 12714 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12715 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12716 return MatchURemWithDivisor(Mul->getOperand(1)) || 12717 MatchURemWithDivisor(Mul->getOperand(2)); 12718 12719 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12720 if (Mul->getNumOperands() == 2) 12721 return MatchURemWithDivisor(Mul->getOperand(1)) || 12722 MatchURemWithDivisor(Mul->getOperand(0)) || 12723 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12724 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12725 return false; 12726 } 12727 12728 const SCEV * 12729 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 12730 SmallVector<BasicBlock*, 16> ExitingBlocks; 12731 L->getExitingBlocks(ExitingBlocks); 12732 12733 // Form an expression for the maximum exit count possible for this loop. We 12734 // merge the max and exact information to approximate a version of 12735 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 12736 SmallVector<const SCEV*, 4> ExitCounts; 12737 for (BasicBlock *ExitingBB : ExitingBlocks) { 12738 const SCEV *ExitCount = getExitCount(L, ExitingBB); 12739 if (isa<SCEVCouldNotCompute>(ExitCount)) 12740 ExitCount = getExitCount(L, ExitingBB, 12741 ScalarEvolution::ConstantMaximum); 12742 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 12743 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 12744 "We should only have known counts for exiting blocks that " 12745 "dominate latch!"); 12746 ExitCounts.push_back(ExitCount); 12747 } 12748 } 12749 if (ExitCounts.empty()) 12750 return getCouldNotCompute(); 12751 return getUMinFromMismatchedTypes(ExitCounts); 12752 } 12753 12754 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 12755 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 12756 /// we cannot guarantee that the replacement is loop invariant in the loop of 12757 /// the AddRec. 12758 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 12759 ValueToSCEVMapTy ⤅ 12760 12761 public: 12762 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 12763 : SCEVRewriteVisitor(SE), Map(M) {} 12764 12765 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 12766 12767 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12768 auto I = Map.find(Expr->getValue()); 12769 if (I == Map.end()) 12770 return Expr; 12771 return I->second; 12772 } 12773 }; 12774 12775 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 12776 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 12777 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 12778 if (!isa<SCEVUnknown>(LHS)) { 12779 std::swap(LHS, RHS); 12780 Predicate = CmpInst::getSwappedPredicate(Predicate); 12781 } 12782 12783 // For now, limit to conditions that provide information about unknown 12784 // expressions. 12785 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 12786 if (!LHSUnknown) 12787 return; 12788 12789 // TODO: use information from more predicates. 12790 switch (Predicate) { 12791 case CmpInst::ICMP_ULT: { 12792 if (!containsAddRecurrence(RHS)) { 12793 const SCEV *Base = LHS; 12794 auto I = RewriteMap.find(LHSUnknown->getValue()); 12795 if (I != RewriteMap.end()) 12796 Base = I->second; 12797 12798 RewriteMap[LHSUnknown->getValue()] = 12799 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 12800 } 12801 break; 12802 } 12803 case CmpInst::ICMP_ULE: { 12804 if (!containsAddRecurrence(RHS)) { 12805 const SCEV *Base = LHS; 12806 auto I = RewriteMap.find(LHSUnknown->getValue()); 12807 if (I != RewriteMap.end()) 12808 Base = I->second; 12809 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 12810 } 12811 break; 12812 } 12813 case CmpInst::ICMP_EQ: 12814 if (isa<SCEVConstant>(RHS)) 12815 RewriteMap[LHSUnknown->getValue()] = RHS; 12816 break; 12817 case CmpInst::ICMP_NE: 12818 if (isa<SCEVConstant>(RHS) && 12819 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 12820 RewriteMap[LHSUnknown->getValue()] = 12821 getUMaxExpr(LHS, getOne(RHS->getType())); 12822 break; 12823 default: 12824 break; 12825 } 12826 }; 12827 // Starting at the loop predecessor, climb up the predecessor chain, as long 12828 // as there are predecessors that can be found that have unique successors 12829 // leading to the original header. 12830 // TODO: share this logic with isLoopEntryGuardedByCond. 12831 ValueToSCEVMapTy RewriteMap; 12832 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 12833 L->getLoopPredecessor(), L->getHeader()); 12834 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 12835 12836 const BranchInst *LoopEntryPredicate = 12837 dyn_cast<BranchInst>(Pair.first->getTerminator()); 12838 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 12839 continue; 12840 12841 // TODO: use information from more complex conditions, e.g. AND expressions. 12842 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 12843 if (!Cmp) 12844 continue; 12845 12846 auto Predicate = Cmp->getPredicate(); 12847 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 12848 Predicate = CmpInst::getInversePredicate(Predicate); 12849 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 12850 getSCEV(Cmp->getOperand(1)), RewriteMap); 12851 } 12852 12853 // Also collect information from assumptions dominating the loop. 12854 for (auto &AssumeVH : AC.assumptions()) { 12855 if (!AssumeVH) 12856 continue; 12857 auto *AssumeI = cast<CallInst>(AssumeVH); 12858 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 12859 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 12860 continue; 12861 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 12862 getSCEV(Cmp->getOperand(1)), RewriteMap); 12863 } 12864 12865 if (RewriteMap.empty()) 12866 return Expr; 12867 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 12868 return Rewriter.visit(Expr); 12869 } 12870