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