1 //===- InductiveRangeCheckElimination.cpp - -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The InductiveRangeCheckElimination pass splits a loop's iteration space into 11 // three disjoint ranges. It does that in a way such that the loop running in 12 // the middle loop provably does not need range checks. As an example, it will 13 // convert 14 // 15 // len = < known positive > 16 // for (i = 0; i < n; i++) { 17 // if (0 <= i && i < len) { 18 // do_something(); 19 // } else { 20 // throw_out_of_bounds(); 21 // } 22 // } 23 // 24 // to 25 // 26 // len = < known positive > 27 // limit = smin(n, len) 28 // // no first segment 29 // for (i = 0; i < limit; i++) { 30 // if (0 <= i && i < len) { // this check is fully redundant 31 // do_something(); 32 // } else { 33 // throw_out_of_bounds(); 34 // } 35 // } 36 // for (i = limit; i < n; i++) { 37 // if (0 <= i && i < len) { 38 // do_something(); 39 // } else { 40 // throw_out_of_bounds(); 41 // } 42 // } 43 // 44 //===----------------------------------------------------------------------===// 45 46 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" 47 #include "llvm/ADT/APInt.h" 48 #include "llvm/ADT/ArrayRef.h" 49 #include "llvm/ADT/None.h" 50 #include "llvm/ADT/Optional.h" 51 #include "llvm/ADT/SmallPtrSet.h" 52 #include "llvm/ADT/SmallVector.h" 53 #include "llvm/ADT/StringRef.h" 54 #include "llvm/ADT/Twine.h" 55 #include "llvm/Analysis/BranchProbabilityInfo.h" 56 #include "llvm/Analysis/LoopAnalysisManager.h" 57 #include "llvm/Analysis/LoopInfo.h" 58 #include "llvm/Analysis/LoopPass.h" 59 #include "llvm/Analysis/ScalarEvolution.h" 60 #include "llvm/Analysis/ScalarEvolutionExpander.h" 61 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 62 #include "llvm/IR/BasicBlock.h" 63 #include "llvm/IR/CFG.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DerivedTypes.h" 66 #include "llvm/IR/Dominators.h" 67 #include "llvm/IR/Function.h" 68 #include "llvm/IR/IRBuilder.h" 69 #include "llvm/IR/InstrTypes.h" 70 #include "llvm/IR/Instructions.h" 71 #include "llvm/IR/Metadata.h" 72 #include "llvm/IR/Module.h" 73 #include "llvm/IR/PatternMatch.h" 74 #include "llvm/IR/Type.h" 75 #include "llvm/IR/Use.h" 76 #include "llvm/IR/User.h" 77 #include "llvm/IR/Value.h" 78 #include "llvm/Pass.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/raw_ostream.h" 86 #include "llvm/Transforms/Scalar.h" 87 #include "llvm/Transforms/Utils/Cloning.h" 88 #include "llvm/Transforms/Utils/LoopSimplify.h" 89 #include "llvm/Transforms/Utils/LoopUtils.h" 90 #include "llvm/Transforms/Utils/ValueMapper.h" 91 #include <algorithm> 92 #include <cassert> 93 #include <iterator> 94 #include <limits> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 using namespace llvm::PatternMatch; 100 101 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, 102 cl::init(64)); 103 104 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, 105 cl::init(false)); 106 107 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, 108 cl::init(false)); 109 110 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", 111 cl::Hidden, cl::init(10)); 112 113 static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks", 114 cl::Hidden, cl::init(false)); 115 116 static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch", 117 cl::Hidden, cl::init(true)); 118 119 static const char *ClonedLoopTag = "irce.loop.clone"; 120 121 #define DEBUG_TYPE "irce" 122 123 namespace { 124 125 /// An inductive range check is conditional branch in a loop with 126 /// 127 /// 1. a very cold successor (i.e. the branch jumps to that successor very 128 /// rarely) 129 /// 130 /// and 131 /// 132 /// 2. a condition that is provably true for some contiguous range of values 133 /// taken by the containing loop's induction variable. 134 /// 135 class InductiveRangeCheck { 136 // Classifies a range check 137 enum RangeCheckKind : unsigned { 138 // Range check of the form "0 <= I". 139 RANGE_CHECK_LOWER = 1, 140 141 // Range check of the form "I < L" where L is known positive. 142 RANGE_CHECK_UPPER = 2, 143 144 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER 145 // conditions. 146 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, 147 148 // Unrecognized range check condition. 149 RANGE_CHECK_UNKNOWN = (unsigned)-1 150 }; 151 152 static StringRef rangeCheckKindToStr(RangeCheckKind); 153 154 const SCEV *Begin = nullptr; 155 const SCEV *Step = nullptr; 156 const SCEV *End = nullptr; 157 Use *CheckUse = nullptr; 158 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN; 159 bool IsSigned = true; 160 161 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 162 ScalarEvolution &SE, Value *&Index, 163 Value *&Length, bool &IsSigned); 164 165 static void 166 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, 167 SmallVectorImpl<InductiveRangeCheck> &Checks, 168 SmallPtrSetImpl<Value *> &Visited); 169 170 public: 171 const SCEV *getBegin() const { return Begin; } 172 const SCEV *getStep() const { return Step; } 173 const SCEV *getEnd() const { return End; } 174 bool isSigned() const { return IsSigned; } 175 176 void print(raw_ostream &OS) const { 177 OS << "InductiveRangeCheck:\n"; 178 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; 179 OS << " Begin: "; 180 Begin->print(OS); 181 OS << " Step: "; 182 Step->print(OS); 183 OS << " End: "; 184 End->print(OS); 185 OS << "\n CheckUse: "; 186 getCheckUse()->getUser()->print(OS); 187 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; 188 } 189 190 LLVM_DUMP_METHOD 191 void dump() { 192 print(dbgs()); 193 } 194 195 Use *getCheckUse() const { return CheckUse; } 196 197 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If 198 /// R.getEnd() le R.getBegin(), then R denotes the empty range. 199 200 class Range { 201 const SCEV *Begin; 202 const SCEV *End; 203 204 public: 205 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { 206 assert(Begin->getType() == End->getType() && "ill-typed range!"); 207 } 208 209 Type *getType() const { return Begin->getType(); } 210 const SCEV *getBegin() const { return Begin; } 211 const SCEV *getEnd() const { return End; } 212 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const { 213 if (Begin == End) 214 return true; 215 if (IsSigned) 216 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End); 217 else 218 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End); 219 } 220 }; 221 222 /// This is the value the condition of the branch needs to evaluate to for the 223 /// branch to take the hot successor (see (1) above). 224 bool getPassingDirection() { return true; } 225 226 /// Computes a range for the induction variable (IndVar) in which the range 227 /// check is redundant and can be constant-folded away. The induction 228 /// variable is not required to be the canonical {0,+,1} induction variable. 229 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, 230 const SCEVAddRecExpr *IndVar, 231 bool IsLatchSigned) const; 232 233 /// Parse out a set of inductive range checks from \p BI and append them to \p 234 /// Checks. 235 /// 236 /// NB! There may be conditions feeding into \p BI that aren't inductive range 237 /// checks, and hence don't end up in \p Checks. 238 static void 239 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, 240 BranchProbabilityInfo *BPI, 241 SmallVectorImpl<InductiveRangeCheck> &Checks); 242 }; 243 244 class InductiveRangeCheckElimination { 245 ScalarEvolution &SE; 246 BranchProbabilityInfo *BPI; 247 DominatorTree &DT; 248 LoopInfo &LI; 249 250 public: 251 InductiveRangeCheckElimination(ScalarEvolution &SE, 252 BranchProbabilityInfo *BPI, DominatorTree &DT, 253 LoopInfo &LI) 254 : SE(SE), BPI(BPI), DT(DT), LI(LI) {} 255 256 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop); 257 }; 258 259 class IRCELegacyPass : public LoopPass { 260 public: 261 static char ID; 262 263 IRCELegacyPass() : LoopPass(ID) { 264 initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry()); 265 } 266 267 void getAnalysisUsage(AnalysisUsage &AU) const override { 268 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 269 getLoopAnalysisUsage(AU); 270 } 271 272 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 273 }; 274 275 } // end anonymous namespace 276 277 char IRCELegacyPass::ID = 0; 278 279 INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce", 280 "Inductive range check elimination", false, false) 281 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 282 INITIALIZE_PASS_DEPENDENCY(LoopPass) 283 INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination", 284 false, false) 285 286 StringRef InductiveRangeCheck::rangeCheckKindToStr( 287 InductiveRangeCheck::RangeCheckKind RCK) { 288 switch (RCK) { 289 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: 290 return "RANGE_CHECK_UNKNOWN"; 291 292 case InductiveRangeCheck::RANGE_CHECK_UPPER: 293 return "RANGE_CHECK_UPPER"; 294 295 case InductiveRangeCheck::RANGE_CHECK_LOWER: 296 return "RANGE_CHECK_LOWER"; 297 298 case InductiveRangeCheck::RANGE_CHECK_BOTH: 299 return "RANGE_CHECK_BOTH"; 300 } 301 302 llvm_unreachable("unknown range check type!"); 303 } 304 305 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot 306 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set 307 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being 308 /// range checked, and set `Length` to the upper limit `Index` is being range 309 /// checked with if (and only if) the range check type is stronger or equal to 310 /// RANGE_CHECK_UPPER. 311 InductiveRangeCheck::RangeCheckKind 312 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 313 ScalarEvolution &SE, Value *&Index, 314 Value *&Length, bool &IsSigned) { 315 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) { 316 const SCEV *S = SE.getSCEV(V); 317 if (isa<SCEVCouldNotCompute>(S)) 318 return false; 319 320 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant && 321 SE.isKnownNonNegative(S); 322 }; 323 324 ICmpInst::Predicate Pred = ICI->getPredicate(); 325 Value *LHS = ICI->getOperand(0); 326 Value *RHS = ICI->getOperand(1); 327 328 switch (Pred) { 329 default: 330 return RANGE_CHECK_UNKNOWN; 331 332 case ICmpInst::ICMP_SLE: 333 std::swap(LHS, RHS); 334 LLVM_FALLTHROUGH; 335 case ICmpInst::ICMP_SGE: 336 IsSigned = true; 337 if (match(RHS, m_ConstantInt<0>())) { 338 Index = LHS; 339 return RANGE_CHECK_LOWER; 340 } 341 return RANGE_CHECK_UNKNOWN; 342 343 case ICmpInst::ICMP_SLT: 344 std::swap(LHS, RHS); 345 LLVM_FALLTHROUGH; 346 case ICmpInst::ICMP_SGT: 347 IsSigned = true; 348 if (match(RHS, m_ConstantInt<-1>())) { 349 Index = LHS; 350 return RANGE_CHECK_LOWER; 351 } 352 353 if (IsNonNegativeAndNotLoopVarying(LHS)) { 354 Index = RHS; 355 Length = LHS; 356 return RANGE_CHECK_UPPER; 357 } 358 return RANGE_CHECK_UNKNOWN; 359 360 case ICmpInst::ICMP_ULT: 361 std::swap(LHS, RHS); 362 LLVM_FALLTHROUGH; 363 case ICmpInst::ICMP_UGT: 364 IsSigned = false; 365 if (IsNonNegativeAndNotLoopVarying(LHS)) { 366 Index = RHS; 367 Length = LHS; 368 return RANGE_CHECK_BOTH; 369 } 370 return RANGE_CHECK_UNKNOWN; 371 } 372 373 llvm_unreachable("default clause returns!"); 374 } 375 376 void InductiveRangeCheck::extractRangeChecksFromCond( 377 Loop *L, ScalarEvolution &SE, Use &ConditionUse, 378 SmallVectorImpl<InductiveRangeCheck> &Checks, 379 SmallPtrSetImpl<Value *> &Visited) { 380 Value *Condition = ConditionUse.get(); 381 if (!Visited.insert(Condition).second) 382 return; 383 384 // TODO: Do the same for OR, XOR, NOT etc? 385 if (match(Condition, m_And(m_Value(), m_Value()))) { 386 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), 387 Checks, Visited); 388 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), 389 Checks, Visited); 390 return; 391 } 392 393 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); 394 if (!ICI) 395 return; 396 397 Value *Length = nullptr, *Index; 398 bool IsSigned; 399 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned); 400 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) 401 return; 402 403 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); 404 bool IsAffineIndex = 405 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); 406 407 if (!IsAffineIndex) 408 return; 409 410 const SCEV *End = nullptr; 411 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". 412 // We can potentially do much better here. 413 if (Length) 414 End = SE.getSCEV(Length); 415 else { 416 assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); 417 // So far we can only reach this point for Signed range check. This may 418 // change in future. In this case we will need to pick Unsigned max for the 419 // unsigned range check. 420 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth(); 421 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 422 End = SIntMax; 423 } 424 425 InductiveRangeCheck IRC; 426 IRC.End = End; 427 IRC.Begin = IndexAddRec->getStart(); 428 IRC.Step = IndexAddRec->getStepRecurrence(SE); 429 IRC.CheckUse = &ConditionUse; 430 IRC.Kind = RCKind; 431 IRC.IsSigned = IsSigned; 432 Checks.push_back(IRC); 433 } 434 435 void InductiveRangeCheck::extractRangeChecksFromBranch( 436 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI, 437 SmallVectorImpl<InductiveRangeCheck> &Checks) { 438 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) 439 return; 440 441 BranchProbability LikelyTaken(15, 16); 442 443 if (!SkipProfitabilityChecks && BPI && 444 BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) 445 return; 446 447 SmallPtrSet<Value *, 8> Visited; 448 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), 449 Checks, Visited); 450 } 451 452 // Add metadata to the loop L to disable loop optimizations. Callers need to 453 // confirm that optimizing loop L is not beneficial. 454 static void DisableAllLoopOptsOnLoop(Loop &L) { 455 // We do not care about any existing loopID related metadata for L, since we 456 // are setting all loop metadata to false. 457 LLVMContext &Context = L.getHeader()->getContext(); 458 // Reserve first location for self reference to the LoopID metadata node. 459 MDNode *Dummy = MDNode::get(Context, {}); 460 MDNode *DisableUnroll = MDNode::get( 461 Context, {MDString::get(Context, "llvm.loop.unroll.disable")}); 462 Metadata *FalseVal = 463 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0)); 464 MDNode *DisableVectorize = MDNode::get( 465 Context, 466 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal}); 467 MDNode *DisableLICMVersioning = MDNode::get( 468 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")}); 469 MDNode *DisableDistribution= MDNode::get( 470 Context, 471 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal}); 472 MDNode *NewLoopID = 473 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize, 474 DisableLICMVersioning, DisableDistribution}); 475 // Set operand 0 to refer to the loop id itself. 476 NewLoopID->replaceOperandWith(0, NewLoopID); 477 L.setLoopID(NewLoopID); 478 } 479 480 namespace { 481 482 // Keeps track of the structure of a loop. This is similar to llvm::Loop, 483 // except that it is more lightweight and can track the state of a loop through 484 // changing and potentially invalid IR. This structure also formalizes the 485 // kinds of loops we can deal with -- ones that have a single latch that is also 486 // an exiting block *and* have a canonical induction variable. 487 struct LoopStructure { 488 const char *Tag = ""; 489 490 BasicBlock *Header = nullptr; 491 BasicBlock *Latch = nullptr; 492 493 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th 494 // successor is `LatchExit', the exit block of the loop. 495 BranchInst *LatchBr = nullptr; 496 BasicBlock *LatchExit = nullptr; 497 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max(); 498 499 // The loop represented by this instance of LoopStructure is semantically 500 // equivalent to: 501 // 502 // intN_ty inc = IndVarIncreasing ? 1 : -1; 503 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT; 504 // 505 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase) 506 // ... body ... 507 508 Value *IndVarBase = nullptr; 509 Value *IndVarStart = nullptr; 510 Value *IndVarStep = nullptr; 511 Value *LoopExitAt = nullptr; 512 bool IndVarIncreasing = false; 513 bool IsSignedPredicate = true; 514 515 LoopStructure() = default; 516 517 template <typename M> LoopStructure map(M Map) const { 518 LoopStructure Result; 519 Result.Tag = Tag; 520 Result.Header = cast<BasicBlock>(Map(Header)); 521 Result.Latch = cast<BasicBlock>(Map(Latch)); 522 Result.LatchBr = cast<BranchInst>(Map(LatchBr)); 523 Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); 524 Result.LatchBrExitIdx = LatchBrExitIdx; 525 Result.IndVarBase = Map(IndVarBase); 526 Result.IndVarStart = Map(IndVarStart); 527 Result.IndVarStep = Map(IndVarStep); 528 Result.LoopExitAt = Map(LoopExitAt); 529 Result.IndVarIncreasing = IndVarIncreasing; 530 Result.IsSignedPredicate = IsSignedPredicate; 531 return Result; 532 } 533 534 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, 535 BranchProbabilityInfo *BPI, 536 Loop &, const char *&); 537 }; 538 539 /// This class is used to constrain loops to run within a given iteration space. 540 /// The algorithm this class implements is given a Loop and a range [Begin, 541 /// End). The algorithm then tries to break out a "main loop" out of the loop 542 /// it is given in a way that the "main loop" runs with the induction variable 543 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post 544 /// loops to run any remaining iterations. The pre loop runs any iterations in 545 /// which the induction variable is < Begin, and the post loop runs any 546 /// iterations in which the induction variable is >= End. 547 class LoopConstrainer { 548 // The representation of a clone of the original loop we started out with. 549 struct ClonedLoop { 550 // The cloned blocks 551 std::vector<BasicBlock *> Blocks; 552 553 // `Map` maps values in the clonee into values in the cloned version 554 ValueToValueMapTy Map; 555 556 // An instance of `LoopStructure` for the cloned loop 557 LoopStructure Structure; 558 }; 559 560 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for 561 // more details on what these fields mean. 562 struct RewrittenRangeInfo { 563 BasicBlock *PseudoExit = nullptr; 564 BasicBlock *ExitSelector = nullptr; 565 std::vector<PHINode *> PHIValuesAtPseudoExit; 566 PHINode *IndVarEnd = nullptr; 567 568 RewrittenRangeInfo() = default; 569 }; 570 571 // Calculated subranges we restrict the iteration space of the main loop to. 572 // See the implementation of `calculateSubRanges' for more details on how 573 // these fields are computed. `LowLimit` is None if there is no restriction 574 // on low end of the restricted iteration space of the main loop. `HighLimit` 575 // is None if there is no restriction on high end of the restricted iteration 576 // space of the main loop. 577 578 struct SubRanges { 579 Optional<const SCEV *> LowLimit; 580 Optional<const SCEV *> HighLimit; 581 }; 582 583 // A utility function that does a `replaceUsesOfWith' on the incoming block 584 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's 585 // incoming block list with `ReplaceBy'. 586 static void replacePHIBlock(PHINode *PN, BasicBlock *Block, 587 BasicBlock *ReplaceBy); 588 589 // Compute a safe set of limits for the main loop to run in -- effectively the 590 // intersection of `Range' and the iteration space of the original loop. 591 // Return None if unable to compute the set of subranges. 592 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const; 593 594 // Clone `OriginalLoop' and return the result in CLResult. The IR after 595 // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- 596 // the PHI nodes say that there is an incoming edge from `OriginalPreheader` 597 // but there is no such edge. 598 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; 599 600 // Create the appropriate loop structure needed to describe a cloned copy of 601 // `Original`. The clone is described by `VM`. 602 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent, 603 ValueToValueMapTy &VM, bool IsSubloop); 604 605 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The 606 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the 607 // iteration space is not changed. `ExitLoopAt' is assumed to be slt 608 // `OriginalHeaderCount'. 609 // 610 // If there are iterations left to execute, control is made to jump to 611 // `ContinuationBlock', otherwise they take the normal loop exit. The 612 // returned `RewrittenRangeInfo' object is populated as follows: 613 // 614 // .PseudoExit is a basic block that unconditionally branches to 615 // `ContinuationBlock'. 616 // 617 // .ExitSelector is a basic block that decides, on exit from the loop, 618 // whether to branch to the "true" exit or to `PseudoExit'. 619 // 620 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value 621 // for each PHINode in the loop header on taking the pseudo exit. 622 // 623 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate 624 // preheader because it is made to branch to the loop header only 625 // conditionally. 626 RewrittenRangeInfo 627 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, 628 Value *ExitLoopAt, 629 BasicBlock *ContinuationBlock) const; 630 631 // The loop denoted by `LS' has `OldPreheader' as its preheader. This 632 // function creates a new preheader for `LS' and returns it. 633 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, 634 const char *Tag) const; 635 636 // `ContinuationBlockAndPreheader' was the continuation block for some call to 637 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. 638 // This function rewrites the PHI nodes in `LS.Header' to start with the 639 // correct value. 640 void rewriteIncomingValuesForPHIs( 641 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, 642 const LoopConstrainer::RewrittenRangeInfo &RRI) const; 643 644 // Even though we do not preserve any passes at this time, we at least need to 645 // keep the parent loop structure consistent. The `LPPassManager' seems to 646 // verify this after running a loop pass. This function adds the list of 647 // blocks denoted by BBs to this loops parent loop if required. 648 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); 649 650 // Some global state. 651 Function &F; 652 LLVMContext &Ctx; 653 ScalarEvolution &SE; 654 DominatorTree &DT; 655 LoopInfo &LI; 656 function_ref<void(Loop *, bool)> LPMAddNewLoop; 657 658 // Information about the original loop we started out with. 659 Loop &OriginalLoop; 660 661 const SCEV *LatchTakenCount = nullptr; 662 BasicBlock *OriginalPreheader = nullptr; 663 664 // The preheader of the main loop. This may or may not be different from 665 // `OriginalPreheader'. 666 BasicBlock *MainLoopPreheader = nullptr; 667 668 // The range we need to run the main loop in. 669 InductiveRangeCheck::Range Range; 670 671 // The structure of the main loop (see comment at the beginning of this class 672 // for a definition) 673 LoopStructure MainLoopStructure; 674 675 public: 676 LoopConstrainer(Loop &L, LoopInfo &LI, 677 function_ref<void(Loop *, bool)> LPMAddNewLoop, 678 const LoopStructure &LS, ScalarEvolution &SE, 679 DominatorTree &DT, InductiveRangeCheck::Range R) 680 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), 681 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), 682 Range(R), MainLoopStructure(LS) {} 683 684 // Entry point for the algorithm. Returns true on success. 685 bool run(); 686 }; 687 688 } // end anonymous namespace 689 690 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, 691 BasicBlock *ReplaceBy) { 692 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 693 if (PN->getIncomingBlock(i) == Block) 694 PN->setIncomingBlock(i, ReplaceBy); 695 } 696 697 static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) { 698 APInt Max = Signed ? 699 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) : 700 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); 701 return SE.getSignedRange(S).contains(Max) && 702 SE.getUnsignedRange(S).contains(Max); 703 } 704 705 static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2, 706 bool Signed) { 707 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX. 708 assert(SE.isKnownNonNegative(S2) && 709 "We expected the 2nd arg to be non-negative!"); 710 const SCEV *Max = SE.getConstant( 711 Signed ? APInt::getSignedMaxValue( 712 cast<IntegerType>(S1->getType())->getBitWidth()) 713 : APInt::getMaxValue( 714 cast<IntegerType>(S1->getType())->getBitWidth())); 715 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2); 716 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 717 S1, CapForS1); 718 } 719 720 static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) { 721 APInt Min = Signed ? 722 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) : 723 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth()); 724 return SE.getSignedRange(S).contains(Min) && 725 SE.getUnsignedRange(S).contains(Min); 726 } 727 728 static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2, 729 bool Signed) { 730 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN. 731 assert(SE.isKnownNonPositive(S2) && 732 "We expected the 2nd arg to be non-positive!"); 733 const SCEV *Max = SE.getConstant( 734 Signed ? APInt::getSignedMinValue( 735 cast<IntegerType>(S1->getType())->getBitWidth()) 736 : APInt::getMinValue( 737 cast<IntegerType>(S1->getType())->getBitWidth())); 738 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2); 739 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, 740 S1, CapForS1); 741 } 742 743 Optional<LoopStructure> 744 LoopStructure::parseLoopStructure(ScalarEvolution &SE, 745 BranchProbabilityInfo *BPI, Loop &L, 746 const char *&FailureReason) { 747 if (!L.isLoopSimplifyForm()) { 748 FailureReason = "loop not in LoopSimplify form"; 749 return None; 750 } 751 752 BasicBlock *Latch = L.getLoopLatch(); 753 assert(Latch && "Simplified loops only have one latch!"); 754 755 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) { 756 FailureReason = "loop has already been cloned"; 757 return None; 758 } 759 760 if (!L.isLoopExiting(Latch)) { 761 FailureReason = "no loop latch"; 762 return None; 763 } 764 765 BasicBlock *Header = L.getHeader(); 766 BasicBlock *Preheader = L.getLoopPreheader(); 767 if (!Preheader) { 768 FailureReason = "no preheader"; 769 return None; 770 } 771 772 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); 773 if (!LatchBr || LatchBr->isUnconditional()) { 774 FailureReason = "latch terminator not conditional branch"; 775 return None; 776 } 777 778 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; 779 780 BranchProbability ExitProbability = 781 BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx) 782 : BranchProbability::getZero(); 783 784 if (!SkipProfitabilityChecks && 785 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { 786 FailureReason = "short running loop, not profitable"; 787 return None; 788 } 789 790 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); 791 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { 792 FailureReason = "latch terminator branch not conditional on integral icmp"; 793 return None; 794 } 795 796 const SCEV *LatchCount = SE.getExitCount(&L, Latch); 797 if (isa<SCEVCouldNotCompute>(LatchCount)) { 798 FailureReason = "could not compute latch count"; 799 return None; 800 } 801 802 ICmpInst::Predicate Pred = ICI->getPredicate(); 803 Value *LeftValue = ICI->getOperand(0); 804 const SCEV *LeftSCEV = SE.getSCEV(LeftValue); 805 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); 806 807 Value *RightValue = ICI->getOperand(1); 808 const SCEV *RightSCEV = SE.getSCEV(RightValue); 809 810 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. 811 if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 812 if (isa<SCEVAddRecExpr>(RightSCEV)) { 813 std::swap(LeftSCEV, RightSCEV); 814 std::swap(LeftValue, RightValue); 815 Pred = ICmpInst::getSwappedPredicate(Pred); 816 } else { 817 FailureReason = "no add recurrences in the icmp"; 818 return None; 819 } 820 } 821 822 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { 823 if (AR->getNoWrapFlags(SCEV::FlagNSW)) 824 return true; 825 826 IntegerType *Ty = cast<IntegerType>(AR->getType()); 827 IntegerType *WideTy = 828 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); 829 830 const SCEVAddRecExpr *ExtendAfterOp = 831 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 832 if (ExtendAfterOp) { 833 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); 834 const SCEV *ExtendedStep = 835 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); 836 837 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && 838 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; 839 840 if (NoSignedWrap) 841 return true; 842 } 843 844 // We may have proved this when computing the sign extension above. 845 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; 846 }; 847 848 // Here we check whether the suggested AddRec is an induction variable that 849 // can be handled (i.e. with known constant step), and if yes, calculate its 850 // step and identify whether it is increasing or decreasing. 851 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing, 852 ConstantInt *&StepCI) { 853 if (!AR->isAffine()) 854 return false; 855 856 // Currently we only work with induction variables that have been proved to 857 // not wrap. This restriction can potentially be lifted in the future. 858 859 if (!HasNoSignedWrap(AR)) 860 return false; 861 862 if (const SCEVConstant *StepExpr = 863 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { 864 StepCI = StepExpr->getValue(); 865 assert(!StepCI->isZero() && "Zero step?"); 866 IsIncreasing = !StepCI->isNegative(); 867 return true; 868 } 869 870 return false; 871 }; 872 873 // `ICI` is interpreted as taking the backedge if the *next* value of the 874 // induction variable satisfies some constraint. 875 876 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV); 877 bool IsIncreasing = false; 878 bool IsSignedPredicate = true; 879 ConstantInt *StepCI; 880 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) { 881 FailureReason = "LHS in icmp not induction variable"; 882 return None; 883 } 884 885 const SCEV *StartNext = IndVarBase->getStart(); 886 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE)); 887 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); 888 const SCEV *Step = SE.getSCEV(StepCI); 889 890 ConstantInt *One = ConstantInt::get(IndVarTy, 1); 891 if (IsIncreasing) { 892 bool DecreasedRightValueByOne = false; 893 if (StepCI->isOne()) { 894 // Try to turn eq/ne predicates to those we can work with. 895 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) 896 // while (++i != len) { while (++i < len) { 897 // ... ---> ... 898 // } } 899 // If both parts are known non-negative, it is profitable to use 900 // unsigned comparison in increasing loop. This allows us to make the 901 // comparison check against "RightSCEV + 1" more optimistic. 902 if (SE.isKnownNonNegative(IndVarStart) && 903 SE.isKnownNonNegative(RightSCEV)) 904 Pred = ICmpInst::ICMP_ULT; 905 else 906 Pred = ICmpInst::ICMP_SLT; 907 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 && 908 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) { 909 // while (true) { while (true) { 910 // if (++i == len) ---> if (++i > len - 1) 911 // break; break; 912 // ... ... 913 // } } 914 // TODO: Insert ICMP_UGT if both are non-negative? 915 Pred = ICmpInst::ICMP_SGT; 916 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())); 917 DecreasedRightValueByOne = true; 918 } 919 } 920 921 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); 922 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); 923 bool FoundExpectedPred = 924 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0); 925 926 if (!FoundExpectedPred) { 927 FailureReason = "expected icmp slt semantically, found something else"; 928 return None; 929 } 930 931 IsSignedPredicate = 932 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; 933 934 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { 935 FailureReason = "unsigned latch conditions are explicitly prohibited"; 936 return None; 937 } 938 939 // The predicate that we need to check that the induction variable lies 940 // within bounds. 941 ICmpInst::Predicate BoundPred = 942 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; 943 944 if (LatchBrExitIdx == 0) { 945 const SCEV *StepMinusOne = SE.getMinusSCEV(Step, 946 SE.getOne(Step->getType())); 947 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) { 948 // TODO: this restriction is easily removable -- we just have to 949 // remember that the icmp was an slt and not an sle. 950 FailureReason = "limit may overflow when coercing le to lt"; 951 return None; 952 } 953 954 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 955 !SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, 956 SE.getAddExpr(RightSCEV, Step))) { 957 FailureReason = "Induction variable start not bounded by upper limit"; 958 return None; 959 } 960 961 // We need to increase the right value unless we have already decreased 962 // it virtually when we replaced EQ with SGT. 963 if (!DecreasedRightValueByOne) { 964 IRBuilder<> B(Preheader->getTerminator()); 965 RightValue = B.CreateAdd(RightValue, One); 966 } 967 } else { 968 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 969 !SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) { 970 FailureReason = "Induction variable start not bounded by upper limit"; 971 return None; 972 } 973 assert(!DecreasedRightValueByOne && 974 "Right value can be decreased only for LatchBrExitIdx == 0!"); 975 } 976 } else { 977 bool IncreasedRightValueByOne = false; 978 if (StepCI->isMinusOne()) { 979 // Try to turn eq/ne predicates to those we can work with. 980 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) 981 // while (--i != len) { while (--i > len) { 982 // ... ---> ... 983 // } } 984 // We intentionally don't turn the predicate into UGT even if we know 985 // that both operands are non-negative, because it will only pessimize 986 // our check against "RightSCEV - 1". 987 Pred = ICmpInst::ICMP_SGT; 988 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 && 989 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) { 990 // while (true) { while (true) { 991 // if (--i == len) ---> if (--i < len + 1) 992 // break; break; 993 // ... ... 994 // } } 995 // TODO: Insert ICMP_ULT if both are non-negative? 996 Pred = ICmpInst::ICMP_SLT; 997 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())); 998 IncreasedRightValueByOne = true; 999 } 1000 } 1001 1002 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); 1003 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); 1004 1005 bool FoundExpectedPred = 1006 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0); 1007 1008 if (!FoundExpectedPred) { 1009 FailureReason = "expected icmp sgt semantically, found something else"; 1010 return None; 1011 } 1012 1013 IsSignedPredicate = 1014 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; 1015 1016 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { 1017 FailureReason = "unsigned latch conditions are explicitly prohibited"; 1018 return None; 1019 } 1020 1021 // The predicate that we need to check that the induction variable lies 1022 // within bounds. 1023 ICmpInst::Predicate BoundPred = 1024 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT; 1025 1026 if (LatchBrExitIdx == 0) { 1027 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType())); 1028 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) { 1029 // TODO: this restriction is easily removable -- we just have to 1030 // remember that the icmp was an sgt and not an sge. 1031 FailureReason = "limit may overflow when coercing ge to gt"; 1032 return None; 1033 } 1034 1035 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 1036 !SE.isLoopEntryGuardedByCond( 1037 &L, BoundPred, IndVarStart, 1038 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) { 1039 FailureReason = "Induction variable start not bounded by lower limit"; 1040 return None; 1041 } 1042 1043 // We need to decrease the right value unless we have already increased 1044 // it virtually when we replaced EQ with SLT. 1045 if (!IncreasedRightValueByOne) { 1046 IRBuilder<> B(Preheader->getTerminator()); 1047 RightValue = B.CreateSub(RightValue, One); 1048 } 1049 } else { 1050 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 1051 !SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) { 1052 FailureReason = "Induction variable start not bounded by lower limit"; 1053 return None; 1054 } 1055 assert(!IncreasedRightValueByOne && 1056 "Right value can be increased only for LatchBrExitIdx == 0!"); 1057 } 1058 } 1059 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); 1060 1061 assert(SE.getLoopDisposition(LatchCount, &L) == 1062 ScalarEvolution::LoopInvariant && 1063 "loop variant exit count doesn't make sense!"); 1064 1065 assert(!L.contains(LatchExit) && "expected an exit block!"); 1066 const DataLayout &DL = Preheader->getModule()->getDataLayout(); 1067 Value *IndVarStartV = 1068 SCEVExpander(SE, DL, "irce") 1069 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator()); 1070 IndVarStartV->setName("indvar.start"); 1071 1072 LoopStructure Result; 1073 1074 Result.Tag = "main"; 1075 Result.Header = Header; 1076 Result.Latch = Latch; 1077 Result.LatchBr = LatchBr; 1078 Result.LatchExit = LatchExit; 1079 Result.LatchBrExitIdx = LatchBrExitIdx; 1080 Result.IndVarStart = IndVarStartV; 1081 Result.IndVarStep = StepCI; 1082 Result.IndVarBase = LeftValue; 1083 Result.IndVarIncreasing = IsIncreasing; 1084 Result.LoopExitAt = RightValue; 1085 Result.IsSignedPredicate = IsSignedPredicate; 1086 1087 FailureReason = nullptr; 1088 1089 return Result; 1090 } 1091 1092 Optional<LoopConstrainer::SubRanges> 1093 LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const { 1094 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); 1095 1096 if (Range.getType() != Ty) 1097 return None; 1098 1099 LoopConstrainer::SubRanges Result; 1100 1101 // I think we can be more aggressive here and make this nuw / nsw if the 1102 // addition that feeds into the icmp for the latch's terminating branch is nuw 1103 // / nsw. In any case, a wrapping 2's complement addition is safe. 1104 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); 1105 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); 1106 1107 bool Increasing = MainLoopStructure.IndVarIncreasing; 1108 1109 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or 1110 // [Smallest, GreatestSeen] is the range of values the induction variable 1111 // takes. 1112 1113 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr; 1114 1115 const SCEV *One = SE.getOne(Ty); 1116 if (Increasing) { 1117 Smallest = Start; 1118 Greatest = End; 1119 // No overflow, because the range [Smallest, GreatestSeen] is not empty. 1120 GreatestSeen = SE.getMinusSCEV(End, One); 1121 } else { 1122 // These two computations may sign-overflow. Here is why that is okay: 1123 // 1124 // We know that the induction variable does not sign-overflow on any 1125 // iteration except the last one, and it starts at `Start` and ends at 1126 // `End`, decrementing by one every time. 1127 // 1128 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the 1129 // induction variable is decreasing we know that that the smallest value 1130 // the loop body is actually executed with is `INT_SMIN` == `Smallest`. 1131 // 1132 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In 1133 // that case, `Clamp` will always return `Smallest` and 1134 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) 1135 // will be an empty range. Returning an empty range is always safe. 1136 1137 Smallest = SE.getAddExpr(End, One); 1138 Greatest = SE.getAddExpr(Start, One); 1139 GreatestSeen = Start; 1140 } 1141 1142 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) { 1143 return IsSignedPredicate 1144 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)) 1145 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S)); 1146 }; 1147 1148 // In some cases we can prove that we don't need a pre or post loop. 1149 ICmpInst::Predicate PredLE = 1150 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1151 ICmpInst::Predicate PredLT = 1152 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1153 1154 bool ProvablyNoPreloop = 1155 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest); 1156 if (!ProvablyNoPreloop) 1157 Result.LowLimit = Clamp(Range.getBegin()); 1158 1159 bool ProvablyNoPostLoop = 1160 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd()); 1161 if (!ProvablyNoPostLoop) 1162 Result.HighLimit = Clamp(Range.getEnd()); 1163 1164 return Result; 1165 } 1166 1167 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, 1168 const char *Tag) const { 1169 for (BasicBlock *BB : OriginalLoop.getBlocks()) { 1170 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); 1171 Result.Blocks.push_back(Clone); 1172 Result.Map[BB] = Clone; 1173 } 1174 1175 auto GetClonedValue = [&Result](Value *V) { 1176 assert(V && "null values not in domain!"); 1177 auto It = Result.Map.find(V); 1178 if (It == Result.Map.end()) 1179 return V; 1180 return static_cast<Value *>(It->second); 1181 }; 1182 1183 auto *ClonedLatch = 1184 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch())); 1185 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag, 1186 MDNode::get(Ctx, {})); 1187 1188 Result.Structure = MainLoopStructure.map(GetClonedValue); 1189 Result.Structure.Tag = Tag; 1190 1191 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { 1192 BasicBlock *ClonedBB = Result.Blocks[i]; 1193 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; 1194 1195 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); 1196 1197 for (Instruction &I : *ClonedBB) 1198 RemapInstruction(&I, Result.Map, 1199 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1200 1201 // Exit blocks will now have one more predecessor and their PHI nodes need 1202 // to be edited to reflect that. No phi nodes need to be introduced because 1203 // the loop is in LCSSA. 1204 1205 for (auto *SBB : successors(OriginalBB)) { 1206 if (OriginalLoop.contains(SBB)) 1207 continue; // not an exit block 1208 1209 for (PHINode &PN : SBB->phis()) { 1210 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB); 1211 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB); 1212 } 1213 } 1214 } 1215 } 1216 1217 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( 1218 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, 1219 BasicBlock *ContinuationBlock) const { 1220 // We start with a loop with a single latch: 1221 // 1222 // +--------------------+ 1223 // | | 1224 // | preheader | 1225 // | | 1226 // +--------+-----------+ 1227 // | ----------------\ 1228 // | / | 1229 // +--------v----v------+ | 1230 // | | | 1231 // | header | | 1232 // | | | 1233 // +--------------------+ | 1234 // | 1235 // ..... | 1236 // | 1237 // +--------------------+ | 1238 // | | | 1239 // | latch >----------/ 1240 // | | 1241 // +-------v------------+ 1242 // | 1243 // | 1244 // | +--------------------+ 1245 // | | | 1246 // +---> original exit | 1247 // | | 1248 // +--------------------+ 1249 // 1250 // We change the control flow to look like 1251 // 1252 // 1253 // +--------------------+ 1254 // | | 1255 // | preheader >-------------------------+ 1256 // | | | 1257 // +--------v-----------+ | 1258 // | /-------------+ | 1259 // | / | | 1260 // +--------v--v--------+ | | 1261 // | | | | 1262 // | header | | +--------+ | 1263 // | | | | | | 1264 // +--------------------+ | | +-----v-----v-----------+ 1265 // | | | | 1266 // | | | .pseudo.exit | 1267 // | | | | 1268 // | | +-----------v-----------+ 1269 // | | | 1270 // ..... | | | 1271 // | | +--------v-------------+ 1272 // +--------------------+ | | | | 1273 // | | | | | ContinuationBlock | 1274 // | latch >------+ | | | 1275 // | | | +----------------------+ 1276 // +---------v----------+ | 1277 // | | 1278 // | | 1279 // | +---------------^-----+ 1280 // | | | 1281 // +-----> .exit.selector | 1282 // | | 1283 // +----------v----------+ 1284 // | 1285 // +--------------------+ | 1286 // | | | 1287 // | original exit <----+ 1288 // | | 1289 // +--------------------+ 1290 1291 RewrittenRangeInfo RRI; 1292 1293 BasicBlock *BBInsertLocation = LS.Latch->getNextNode(); 1294 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", 1295 &F, BBInsertLocation); 1296 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, 1297 BBInsertLocation); 1298 1299 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); 1300 bool Increasing = LS.IndVarIncreasing; 1301 bool IsSignedPredicate = LS.IsSignedPredicate; 1302 1303 IRBuilder<> B(PreheaderJump); 1304 1305 // EnterLoopCond - is it okay to start executing this `LS'? 1306 Value *EnterLoopCond = nullptr; 1307 if (Increasing) 1308 EnterLoopCond = IsSignedPredicate 1309 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) 1310 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt); 1311 else 1312 EnterLoopCond = IsSignedPredicate 1313 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt) 1314 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt); 1315 1316 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); 1317 PreheaderJump->eraseFromParent(); 1318 1319 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); 1320 B.SetInsertPoint(LS.LatchBr); 1321 Value *TakeBackedgeLoopCond = nullptr; 1322 if (Increasing) 1323 TakeBackedgeLoopCond = IsSignedPredicate 1324 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt) 1325 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt); 1326 else 1327 TakeBackedgeLoopCond = IsSignedPredicate 1328 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt) 1329 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt); 1330 Value *CondForBranch = LS.LatchBrExitIdx == 1 1331 ? TakeBackedgeLoopCond 1332 : B.CreateNot(TakeBackedgeLoopCond); 1333 1334 LS.LatchBr->setCondition(CondForBranch); 1335 1336 B.SetInsertPoint(RRI.ExitSelector); 1337 1338 // IterationsLeft - are there any more iterations left, given the original 1339 // upper bound on the induction variable? If not, we branch to the "real" 1340 // exit. 1341 Value *IterationsLeft = nullptr; 1342 if (Increasing) 1343 IterationsLeft = IsSignedPredicate 1344 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt) 1345 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt); 1346 else 1347 IterationsLeft = IsSignedPredicate 1348 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt) 1349 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt); 1350 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); 1351 1352 BranchInst *BranchToContinuation = 1353 BranchInst::Create(ContinuationBlock, RRI.PseudoExit); 1354 1355 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of 1356 // each of the PHI nodes in the loop header. This feeds into the initial 1357 // value of the same PHI nodes if/when we continue execution. 1358 for (PHINode &PN : LS.Header->phis()) { 1359 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy", 1360 BranchToContinuation); 1361 1362 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader); 1363 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch), 1364 RRI.ExitSelector); 1365 RRI.PHIValuesAtPseudoExit.push_back(NewPHI); 1366 } 1367 1368 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end", 1369 BranchToContinuation); 1370 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); 1371 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector); 1372 1373 // The latch exit now has a branch from `RRI.ExitSelector' instead of 1374 // `LS.Latch'. The PHI nodes need to be updated to reflect that. 1375 for (PHINode &PN : LS.LatchExit->phis()) 1376 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector); 1377 1378 return RRI; 1379 } 1380 1381 void LoopConstrainer::rewriteIncomingValuesForPHIs( 1382 LoopStructure &LS, BasicBlock *ContinuationBlock, 1383 const LoopConstrainer::RewrittenRangeInfo &RRI) const { 1384 unsigned PHIIndex = 0; 1385 for (PHINode &PN : LS.Header->phis()) 1386 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) 1387 if (PN.getIncomingBlock(i) == ContinuationBlock) 1388 PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); 1389 1390 LS.IndVarStart = RRI.IndVarEnd; 1391 } 1392 1393 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, 1394 BasicBlock *OldPreheader, 1395 const char *Tag) const { 1396 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); 1397 BranchInst::Create(LS.Header, Preheader); 1398 1399 for (PHINode &PN : LS.Header->phis()) 1400 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) 1401 replacePHIBlock(&PN, OldPreheader, Preheader); 1402 1403 return Preheader; 1404 } 1405 1406 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { 1407 Loop *ParentLoop = OriginalLoop.getParentLoop(); 1408 if (!ParentLoop) 1409 return; 1410 1411 for (BasicBlock *BB : BBs) 1412 ParentLoop->addBasicBlockToLoop(BB, LI); 1413 } 1414 1415 Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent, 1416 ValueToValueMapTy &VM, 1417 bool IsSubloop) { 1418 Loop &New = *LI.AllocateLoop(); 1419 if (Parent) 1420 Parent->addChildLoop(&New); 1421 else 1422 LI.addTopLevelLoop(&New); 1423 LPMAddNewLoop(&New, IsSubloop); 1424 1425 // Add all of the blocks in Original to the new loop. 1426 for (auto *BB : Original->blocks()) 1427 if (LI.getLoopFor(BB) == Original) 1428 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI); 1429 1430 // Add all of the subloops to the new loop. 1431 for (Loop *SubLoop : *Original) 1432 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true); 1433 1434 return &New; 1435 } 1436 1437 bool LoopConstrainer::run() { 1438 BasicBlock *Preheader = nullptr; 1439 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); 1440 Preheader = OriginalLoop.getLoopPreheader(); 1441 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && 1442 "preconditions!"); 1443 1444 OriginalPreheader = Preheader; 1445 MainLoopPreheader = Preheader; 1446 1447 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate; 1448 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate); 1449 if (!MaybeSR.hasValue()) { 1450 DEBUG(dbgs() << "irce: could not compute subranges\n"); 1451 return false; 1452 } 1453 1454 SubRanges SR = MaybeSR.getValue(); 1455 bool Increasing = MainLoopStructure.IndVarIncreasing; 1456 IntegerType *IVTy = 1457 cast<IntegerType>(MainLoopStructure.IndVarBase->getType()); 1458 1459 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); 1460 Instruction *InsertPt = OriginalPreheader->getTerminator(); 1461 1462 // It would have been better to make `PreLoop' and `PostLoop' 1463 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy 1464 // constructor. 1465 ClonedLoop PreLoop, PostLoop; 1466 bool NeedsPreLoop = 1467 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); 1468 bool NeedsPostLoop = 1469 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); 1470 1471 Value *ExitPreLoopAt = nullptr; 1472 Value *ExitMainLoopAt = nullptr; 1473 const SCEVConstant *MinusOneS = 1474 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); 1475 1476 if (NeedsPreLoop) { 1477 const SCEV *ExitPreLoopAtSCEV = nullptr; 1478 1479 if (Increasing) 1480 ExitPreLoopAtSCEV = *SR.LowLimit; 1481 else { 1482 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) { 1483 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1484 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) 1485 << "\n"); 1486 return false; 1487 } 1488 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); 1489 } 1490 1491 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) { 1492 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1493 << " preloop exit limit " << *ExitPreLoopAtSCEV 1494 << " at block " << InsertPt->getParent()->getName() << "\n"); 1495 return false; 1496 } 1497 1498 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); 1499 ExitPreLoopAt->setName("exit.preloop.at"); 1500 } 1501 1502 if (NeedsPostLoop) { 1503 const SCEV *ExitMainLoopAtSCEV = nullptr; 1504 1505 if (Increasing) 1506 ExitMainLoopAtSCEV = *SR.HighLimit; 1507 else { 1508 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) { 1509 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1510 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) 1511 << "\n"); 1512 return false; 1513 } 1514 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); 1515 } 1516 1517 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) { 1518 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1519 << " main loop exit limit " << *ExitMainLoopAtSCEV 1520 << " at block " << InsertPt->getParent()->getName() << "\n"); 1521 return false; 1522 } 1523 1524 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); 1525 ExitMainLoopAt->setName("exit.mainloop.at"); 1526 } 1527 1528 // We clone these ahead of time so that we don't have to deal with changing 1529 // and temporarily invalid IR as we transform the loops. 1530 if (NeedsPreLoop) 1531 cloneLoop(PreLoop, "preloop"); 1532 if (NeedsPostLoop) 1533 cloneLoop(PostLoop, "postloop"); 1534 1535 RewrittenRangeInfo PreLoopRRI; 1536 1537 if (NeedsPreLoop) { 1538 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, 1539 PreLoop.Structure.Header); 1540 1541 MainLoopPreheader = 1542 createPreheader(MainLoopStructure, Preheader, "mainloop"); 1543 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, 1544 ExitPreLoopAt, MainLoopPreheader); 1545 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, 1546 PreLoopRRI); 1547 } 1548 1549 BasicBlock *PostLoopPreheader = nullptr; 1550 RewrittenRangeInfo PostLoopRRI; 1551 1552 if (NeedsPostLoop) { 1553 PostLoopPreheader = 1554 createPreheader(PostLoop.Structure, Preheader, "postloop"); 1555 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, 1556 ExitMainLoopAt, PostLoopPreheader); 1557 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, 1558 PostLoopRRI); 1559 } 1560 1561 BasicBlock *NewMainLoopPreheader = 1562 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; 1563 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, 1564 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, 1565 PostLoopRRI.ExitSelector, NewMainLoopPreheader}; 1566 1567 // Some of the above may be nullptr, filter them out before passing to 1568 // addToParentLoopIfNeeded. 1569 auto NewBlocksEnd = 1570 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); 1571 1572 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); 1573 1574 DT.recalculate(F); 1575 1576 // We need to first add all the pre and post loop blocks into the loop 1577 // structures (as part of createClonedLoopStructure), and then update the 1578 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating 1579 // LI when LoopSimplifyForm is generated. 1580 Loop *PreL = nullptr, *PostL = nullptr; 1581 if (!PreLoop.Blocks.empty()) { 1582 PreL = createClonedLoopStructure(&OriginalLoop, 1583 OriginalLoop.getParentLoop(), PreLoop.Map, 1584 /* IsSubLoop */ false); 1585 } 1586 1587 if (!PostLoop.Blocks.empty()) { 1588 PostL = 1589 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(), 1590 PostLoop.Map, /* IsSubLoop */ false); 1591 } 1592 1593 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms. 1594 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) { 1595 formLCSSARecursively(*L, DT, &LI, &SE); 1596 simplifyLoop(L, &DT, &LI, &SE, nullptr, true); 1597 // Pre/post loops are slow paths, we do not need to perform any loop 1598 // optimizations on them. 1599 if (!IsOriginalLoop) 1600 DisableAllLoopOptsOnLoop(*L); 1601 }; 1602 if (PreL) 1603 CanonicalizeLoop(PreL, false); 1604 if (PostL) 1605 CanonicalizeLoop(PostL, false); 1606 CanonicalizeLoop(&OriginalLoop, true); 1607 1608 return true; 1609 } 1610 1611 /// Computes and returns a range of values for the induction variable (IndVar) 1612 /// in which the range check can be safely elided. If it cannot compute such a 1613 /// range, returns None. 1614 Optional<InductiveRangeCheck::Range> 1615 InductiveRangeCheck::computeSafeIterationSpace( 1616 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar, 1617 bool IsLatchSigned) const { 1618 // IndVar is of the form "A + B * I" (where "I" is the canonical induction 1619 // variable, that may or may not exist as a real llvm::Value in the loop) and 1620 // this inductive range check is a range check on the "C + D * I" ("C" is 1621 // getBegin() and "D" is getStep()). We rewrite the value being range 1622 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". 1623 // 1624 // The actual inequalities we solve are of the form 1625 // 1626 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) 1627 // 1628 // Here L stands for upper limit of the safe iteration space. 1629 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid 1630 // overflows when calculating (0 - M) and (L - M) we, depending on type of 1631 // IV's iteration space, limit the calculations by borders of the iteration 1632 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0. 1633 // If we figured out that "anything greater than (-M) is safe", we strengthen 1634 // this to "everything greater than 0 is safe", assuming that values between 1635 // -M and 0 just do not exist in unsigned iteration space, and we don't want 1636 // to deal with overflown values. 1637 1638 if (!IndVar->isAffine()) 1639 return None; 1640 1641 const SCEV *A = IndVar->getStart(); 1642 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); 1643 if (!B) 1644 return None; 1645 assert(!B->isZero() && "Recurrence with zero step?"); 1646 1647 const SCEV *C = getBegin(); 1648 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep()); 1649 if (D != B) 1650 return None; 1651 1652 assert(!D->getValue()->isZero() && "Recurrence with zero step?"); 1653 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); 1654 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 1655 1656 // Subtract Y from X so that it does not go through border of the IV 1657 // iteration space. Mathematically, it is equivalent to: 1658 // 1659 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1] 1660 // 1661 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to 1662 // any width of bit grid). But after we take min/max, the result is 1663 // guaranteed to be within [INT_MIN, INT_MAX]. 1664 // 1665 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min 1666 // values, depending on type of latch condition that defines IV iteration 1667 // space. 1668 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) { 1669 if (IsLatchSigned) { 1670 // X is a number from signed range, Y is interpreted as signed. 1671 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only 1672 // thing we should care about is that we didn't cross SINT_MAX. 1673 // So, if Y is positive, we subtract Y safely. 1674 // Rule 1: Y > 0 ---> Y. 1675 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely. 1676 // Rule 2: Y >=s (X - SINT_MAX) ---> Y. 1677 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX). 1678 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX). 1679 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases. 1680 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax); 1681 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax), 1682 SCEV::FlagNSW); 1683 } else 1684 // X is a number from unsigned range, Y is interpreted as signed. 1685 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only 1686 // thing we should care about is that we didn't cross zero. 1687 // So, if Y is negative, we subtract Y safely. 1688 // Rule 1: Y <s 0 ---> Y. 1689 // If 0 <= Y <= X, we subtract Y safely. 1690 // Rule 2: Y <=s X ---> Y. 1691 // If 0 <= X < Y, we should stop at 0 and can only subtract X. 1692 // Rule 3: Y >s X ---> X. 1693 // It gives us smin(X, Y) to subtract in all cases. 1694 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW); 1695 }; 1696 const SCEV *M = SE.getMinusSCEV(C, A); 1697 const SCEV *Zero = SE.getZero(M->getType()); 1698 const SCEV *Begin = ClampedSubtract(Zero, M); 1699 const SCEV *End = ClampedSubtract(getEnd(), M); 1700 return InductiveRangeCheck::Range(Begin, End); 1701 } 1702 1703 static Optional<InductiveRangeCheck::Range> 1704 IntersectSignedRange(ScalarEvolution &SE, 1705 const Optional<InductiveRangeCheck::Range> &R1, 1706 const InductiveRangeCheck::Range &R2) { 1707 if (R2.isEmpty(SE, /* IsSigned */ true)) 1708 return None; 1709 if (!R1.hasValue()) 1710 return R2; 1711 auto &R1Value = R1.getValue(); 1712 // We never return empty ranges from this function, and R1 is supposed to be 1713 // a result of intersection. Thus, R1 is never empty. 1714 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && 1715 "We should never have empty R1!"); 1716 1717 // TODO: we could widen the smaller range and have this work; but for now we 1718 // bail out to keep things simple. 1719 if (R1Value.getType() != R2.getType()) 1720 return None; 1721 1722 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); 1723 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); 1724 1725 // If the resulting range is empty, just return None. 1726 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1727 if (Ret.isEmpty(SE, /* IsSigned */ true)) 1728 return None; 1729 return Ret; 1730 } 1731 1732 static Optional<InductiveRangeCheck::Range> 1733 IntersectUnsignedRange(ScalarEvolution &SE, 1734 const Optional<InductiveRangeCheck::Range> &R1, 1735 const InductiveRangeCheck::Range &R2) { 1736 if (R2.isEmpty(SE, /* IsSigned */ false)) 1737 return None; 1738 if (!R1.hasValue()) 1739 return R2; 1740 auto &R1Value = R1.getValue(); 1741 // We never return empty ranges from this function, and R1 is supposed to be 1742 // a result of intersection. Thus, R1 is never empty. 1743 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && 1744 "We should never have empty R1!"); 1745 1746 // TODO: we could widen the smaller range and have this work; but for now we 1747 // bail out to keep things simple. 1748 if (R1Value.getType() != R2.getType()) 1749 return None; 1750 1751 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin()); 1752 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd()); 1753 1754 // If the resulting range is empty, just return None. 1755 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1756 if (Ret.isEmpty(SE, /* IsSigned */ false)) 1757 return None; 1758 return Ret; 1759 } 1760 1761 PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM, 1762 LoopStandardAnalysisResults &AR, 1763 LPMUpdater &U) { 1764 Function *F = L.getHeader()->getParent(); 1765 const auto &FAM = 1766 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 1767 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 1768 InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI); 1769 auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) { 1770 if (!IsSubloop) 1771 U.addSiblingLoops(NL); 1772 }; 1773 bool Changed = IRCE.run(&L, LPMAddNewLoop); 1774 if (!Changed) 1775 return PreservedAnalyses::all(); 1776 1777 return getLoopPassPreservedAnalyses(); 1778 } 1779 1780 bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 1781 if (skipLoop(L)) 1782 return false; 1783 1784 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1785 BranchProbabilityInfo &BPI = 1786 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 1787 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1788 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1789 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI); 1790 auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) { 1791 LPM.addLoop(*NL); 1792 }; 1793 return IRCE.run(L, LPMAddNewLoop); 1794 } 1795 1796 bool InductiveRangeCheckElimination::run( 1797 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) { 1798 if (L->getBlocks().size() >= LoopSizeCutoff) { 1799 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n"); 1800 return false; 1801 } 1802 1803 BasicBlock *Preheader = L->getLoopPreheader(); 1804 if (!Preheader) { 1805 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); 1806 return false; 1807 } 1808 1809 LLVMContext &Context = Preheader->getContext(); 1810 SmallVector<InductiveRangeCheck, 16> RangeChecks; 1811 1812 for (auto BBI : L->getBlocks()) 1813 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) 1814 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, 1815 RangeChecks); 1816 1817 if (RangeChecks.empty()) 1818 return false; 1819 1820 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { 1821 OS << "irce: looking at loop "; L->print(OS); 1822 OS << "irce: loop has " << RangeChecks.size() 1823 << " inductive range checks: \n"; 1824 for (InductiveRangeCheck &IRC : RangeChecks) 1825 IRC.print(OS); 1826 }; 1827 1828 DEBUG(PrintRecognizedRangeChecks(dbgs())); 1829 1830 if (PrintRangeChecks) 1831 PrintRecognizedRangeChecks(errs()); 1832 1833 const char *FailureReason = nullptr; 1834 Optional<LoopStructure> MaybeLoopStructure = 1835 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); 1836 if (!MaybeLoopStructure.hasValue()) { 1837 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason 1838 << "\n";); 1839 return false; 1840 } 1841 LoopStructure LS = MaybeLoopStructure.getValue(); 1842 const SCEVAddRecExpr *IndVar = 1843 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep))); 1844 1845 Optional<InductiveRangeCheck::Range> SafeIterRange; 1846 Instruction *ExprInsertPt = Preheader->getTerminator(); 1847 1848 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; 1849 // Basing on the type of latch predicate, we interpret the IV iteration range 1850 // as signed or unsigned range. We use different min/max functions (signed or 1851 // unsigned) when intersecting this range with safe iteration ranges implied 1852 // by range checks. 1853 auto IntersectRange = 1854 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange; 1855 1856 IRBuilder<> B(ExprInsertPt); 1857 for (InductiveRangeCheck &IRC : RangeChecks) { 1858 auto Result = IRC.computeSafeIterationSpace(SE, IndVar, 1859 LS.IsSignedPredicate); 1860 if (Result.hasValue()) { 1861 auto MaybeSafeIterRange = 1862 IntersectRange(SE, SafeIterRange, Result.getValue()); 1863 if (MaybeSafeIterRange.hasValue()) { 1864 assert( 1865 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && 1866 "We should never return empty ranges!"); 1867 RangeChecksToEliminate.push_back(IRC); 1868 SafeIterRange = MaybeSafeIterRange.getValue(); 1869 } 1870 } 1871 } 1872 1873 if (!SafeIterRange.hasValue()) 1874 return false; 1875 1876 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, 1877 SafeIterRange.getValue()); 1878 bool Changed = LC.run(); 1879 1880 if (Changed) { 1881 auto PrintConstrainedLoopInfo = [L]() { 1882 dbgs() << "irce: in function "; 1883 dbgs() << L->getHeader()->getParent()->getName() << ": "; 1884 dbgs() << "constrained "; 1885 L->print(dbgs()); 1886 }; 1887 1888 DEBUG(PrintConstrainedLoopInfo()); 1889 1890 if (PrintChangedLoops) 1891 PrintConstrainedLoopInfo(); 1892 1893 // Optimize away the now-redundant range checks. 1894 1895 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { 1896 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() 1897 ? ConstantInt::getTrue(Context) 1898 : ConstantInt::getFalse(Context); 1899 IRC.getCheckUse()->set(FoldedRangeCheck); 1900 } 1901 } 1902 1903 return Changed; 1904 } 1905 1906 Pass *llvm::createInductiveRangeCheckEliminationPass() { 1907 return new IRCELegacyPass(); 1908 } 1909