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