1 //===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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
14 // len = < known positive >
15 // for (i = 0; i < n; i++) {
16 // if (0 <= i && i < len) {
19 // throw_out_of_bounds();
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
32 // throw_out_of_bounds();
35 // for (i = limit; i < n; i++) {
36 // if (0 <= i && i < len) {
39 // throw_out_of_bounds();
42 //===----------------------------------------------------------------------===//
44 #include "llvm/ADT/Optional.h"
46 #include "llvm/Analysis/BranchProbabilityInfo.h"
47 #include "llvm/Analysis/InstructionSimplify.h"
48 #include "llvm/Analysis/LoopInfo.h"
49 #include "llvm/Analysis/LoopPass.h"
50 #include "llvm/Analysis/ScalarEvolution.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
53 #include "llvm/Analysis/ValueTracking.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/PatternMatch.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/IR/Verifier.h"
64 #include "llvm/Support/Debug.h"
66 #include "llvm/Transforms/Scalar.h"
67 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
68 #include "llvm/Transforms/Utils/Cloning.h"
69 #include "llvm/Transforms/Utils/LoopUtils.h"
70 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
71 #include "llvm/Transforms/Utils/UnrollLoop.h"
73 #include "llvm/Pass.h"
79 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
82 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
85 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
88 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
89 cl::Hidden, cl::init(10));
91 #define DEBUG_TYPE "irce"
95 /// An inductive range check is conditional branch in a loop with
97 /// 1. a very cold successor (i.e. the branch jumps to that successor very
102 /// 2. a condition that is provably true for some contiguous range of values
103 /// taken by the containing loop's induction variable.
105 class InductiveRangeCheck {
106 // Classifies a range check
107 enum RangeCheckKind : unsigned {
108 // Range check of the form "0 <= I".
109 RANGE_CHECK_LOWER = 1,
111 // Range check of the form "I < L" where L is known positive.
112 RANGE_CHECK_UPPER = 2,
114 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
116 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
118 // Unrecognized range check condition.
119 RANGE_CHECK_UNKNOWN = (unsigned)-1
122 static const char *rangeCheckKindToStr(RangeCheckKind);
130 static RangeCheckKind parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
131 Value *&Index, Value *&Length);
133 static InductiveRangeCheck::RangeCheckKind
134 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
135 const SCEV *&Index, Value *&UpperLimit);
137 InductiveRangeCheck() :
138 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
141 const SCEV *getOffset() const { return Offset; }
142 const SCEV *getScale() const { return Scale; }
143 Value *getLength() const { return Length; }
145 void print(raw_ostream &OS) const {
146 OS << "InductiveRangeCheck:\n";
147 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
158 getBranch()->print(OS);
162 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168 BranchInst *getBranch() const { return Branch; }
170 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
171 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
178 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
179 assert(Begin->getType() == End->getType() && "ill-typed range!");
182 Type *getType() const { return Begin->getType(); }
183 const SCEV *getBegin() const { return Begin; }
184 const SCEV *getEnd() const { return End; }
187 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
189 /// This is the value the condition of the branch needs to evaluate to for the
190 /// branch to take the hot successor (see (1) above).
191 bool getPassingDirection() { return true; }
193 /// Computes a range for the induction variable (IndVar) in which the range
194 /// check is redundant and can be constant-folded away. The induction
195 /// variable is not required to be the canonical {0,+,1} induction variable.
196 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
197 const SCEVAddRecExpr *IndVar,
198 IRBuilder<> &B) const;
200 /// Create an inductive range check out of BI if possible, else return
202 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
203 Loop *L, ScalarEvolution &SE,
204 BranchProbabilityInfo &BPI);
207 class InductiveRangeCheckElimination : public LoopPass {
208 InductiveRangeCheck::AllocatorTy Allocator;
212 InductiveRangeCheckElimination() : LoopPass(ID) {
213 initializeInductiveRangeCheckEliminationPass(
214 *PassRegistry::getPassRegistry());
217 void getAnalysisUsage(AnalysisUsage &AU) const override {
218 AU.addRequired<LoopInfoWrapperPass>();
219 AU.addRequiredID(LoopSimplifyID);
220 AU.addRequiredID(LCSSAID);
221 AU.addRequired<ScalarEvolution>();
222 AU.addRequired<BranchProbabilityInfo>();
225 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
228 char InductiveRangeCheckElimination::ID = 0;
231 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
232 "Inductive range check elimination", false, false)
234 const char *InductiveRangeCheck::rangeCheckKindToStr(
235 InductiveRangeCheck::RangeCheckKind RCK) {
237 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
238 return "RANGE_CHECK_UNKNOWN";
240 case InductiveRangeCheck::RANGE_CHECK_UPPER:
241 return "RANGE_CHECK_UPPER";
243 case InductiveRangeCheck::RANGE_CHECK_LOWER:
244 return "RANGE_CHECK_LOWER";
246 case InductiveRangeCheck::RANGE_CHECK_BOTH:
247 return "RANGE_CHECK_BOTH";
250 llvm_unreachable("unknown range check type!");
253 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI`
255 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
256 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value
258 /// range checked, and set `Length` to the upper limit `Index` is being range
259 /// checked with if (and only if) the range check type is stronger or equal to
260 /// RANGE_CHECK_UPPER.
262 InductiveRangeCheck::RangeCheckKind
263 InductiveRangeCheck::parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
264 Value *&Index, Value *&Length) {
266 using namespace llvm::PatternMatch;
268 ICmpInst::Predicate Pred = ICI->getPredicate();
269 Value *LHS = ICI->getOperand(0);
270 Value *RHS = ICI->getOperand(1);
274 return RANGE_CHECK_UNKNOWN;
276 case ICmpInst::ICMP_SLE:
279 case ICmpInst::ICMP_SGE:
280 if (match(RHS, m_ConstantInt<0>())) {
282 return RANGE_CHECK_LOWER;
284 return RANGE_CHECK_UNKNOWN;
286 case ICmpInst::ICMP_SLT:
289 case ICmpInst::ICMP_SGT:
290 if (match(RHS, m_ConstantInt<-1>())) {
292 return RANGE_CHECK_LOWER;
295 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
298 return RANGE_CHECK_UPPER;
300 return RANGE_CHECK_UNKNOWN;
302 case ICmpInst::ICMP_ULT:
305 case ICmpInst::ICMP_UGT:
306 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
309 return RANGE_CHECK_BOTH;
311 return RANGE_CHECK_UNKNOWN;
314 llvm_unreachable("default clause returns!");
317 /// Parses an arbitrary condition into a range check. `Length` is set only if
318 /// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
319 InductiveRangeCheck::RangeCheckKind
320 InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
321 Value *Condition, const SCEV *&Index,
323 using namespace llvm::PatternMatch;
328 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
329 Value *IndexA = nullptr, *IndexB = nullptr;
330 Value *LengthA = nullptr, *LengthB = nullptr;
331 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
333 if (!ICmpA || !ICmpB)
334 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
336 auto RCKindA = parseRangeCheckICmp(ICmpA, SE, IndexA, LengthA);
337 auto RCKindB = parseRangeCheckICmp(ICmpB, SE, IndexB, LengthB);
339 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
340 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
341 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
343 if (IndexA != IndexB)
344 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
346 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
347 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
349 Index = SE.getSCEV(IndexA);
350 if (isa<SCEVCouldNotCompute>(Index))
351 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
353 Length = LengthA == nullptr ? LengthB : LengthA;
355 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
358 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
359 Value *IndexVal = nullptr;
361 auto RCKind = parseRangeCheckICmp(ICI, SE, IndexVal, Length);
363 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
364 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
366 Index = SE.getSCEV(IndexVal);
367 if (isa<SCEVCouldNotCompute>(Index))
368 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
373 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
377 InductiveRangeCheck *
378 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
379 Loop *L, ScalarEvolution &SE,
380 BranchProbabilityInfo &BPI) {
382 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
385 BranchProbability LikelyTaken(15, 16);
387 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
390 Value *Length = nullptr;
391 const SCEV *IndexSCEV = nullptr;
393 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
396 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
399 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
400 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
401 "contract with SplitRangeCheckCondition!");
403 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
405 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
410 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
411 IRC->Length = Length;
412 IRC->Offset = IndexAddRec->getStart();
413 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
421 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
422 // except that it is more lightweight and can track the state of a loop through
423 // changing and potentially invalid IR. This structure also formalizes the
424 // kinds of loops we can deal with -- ones that have a single latch that is also
425 // an exiting block *and* have a canonical induction variable.
426 struct LoopStructure {
432 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
433 // successor is `LatchExit', the exit block of the loop.
435 BasicBlock *LatchExit;
436 unsigned LatchBrExitIdx;
441 bool IndVarIncreasing;
444 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
445 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
446 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
448 template <typename M> LoopStructure map(M Map) const {
449 LoopStructure Result;
451 Result.Header = cast<BasicBlock>(Map(Header));
452 Result.Latch = cast<BasicBlock>(Map(Latch));
453 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
454 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
455 Result.LatchBrExitIdx = LatchBrExitIdx;
456 Result.IndVarNext = Map(IndVarNext);
457 Result.IndVarStart = Map(IndVarStart);
458 Result.LoopExitAt = Map(LoopExitAt);
459 Result.IndVarIncreasing = IndVarIncreasing;
463 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
464 BranchProbabilityInfo &BPI,
469 /// This class is used to constrain loops to run within a given iteration space.
470 /// The algorithm this class implements is given a Loop and a range [Begin,
471 /// End). The algorithm then tries to break out a "main loop" out of the loop
472 /// it is given in a way that the "main loop" runs with the induction variable
473 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
474 /// loops to run any remaining iterations. The pre loop runs any iterations in
475 /// which the induction variable is < Begin, and the post loop runs any
476 /// iterations in which the induction variable is >= End.
478 class LoopConstrainer {
479 // The representation of a clone of the original loop we started out with.
482 std::vector<BasicBlock *> Blocks;
484 // `Map` maps values in the clonee into values in the cloned version
485 ValueToValueMapTy Map;
487 // An instance of `LoopStructure` for the cloned loop
488 LoopStructure Structure;
491 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
492 // more details on what these fields mean.
493 struct RewrittenRangeInfo {
494 BasicBlock *PseudoExit;
495 BasicBlock *ExitSelector;
496 std::vector<PHINode *> PHIValuesAtPseudoExit;
500 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
503 // Calculated subranges we restrict the iteration space of the main loop to.
504 // See the implementation of `calculateSubRanges' for more details on how
505 // these fields are computed. `LowLimit` is None if there is no restriction
506 // on low end of the restricted iteration space of the main loop. `HighLimit`
507 // is None if there is no restriction on high end of the restricted iteration
508 // space of the main loop.
511 Optional<const SCEV *> LowLimit;
512 Optional<const SCEV *> HighLimit;
515 // A utility function that does a `replaceUsesOfWith' on the incoming block
516 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
517 // incoming block list with `ReplaceBy'.
518 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
519 BasicBlock *ReplaceBy);
521 // Compute a safe set of limits for the main loop to run in -- effectively the
522 // intersection of `Range' and the iteration space of the original loop.
523 // Return None if unable to compute the set of subranges.
525 Optional<SubRanges> calculateSubRanges() const;
527 // Clone `OriginalLoop' and return the result in CLResult. The IR after
528 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
529 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
530 // but there is no such edge.
532 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
534 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
535 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
536 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
537 // `OriginalHeaderCount'.
539 // If there are iterations left to execute, control is made to jump to
540 // `ContinuationBlock', otherwise they take the normal loop exit. The
541 // returned `RewrittenRangeInfo' object is populated as follows:
543 // .PseudoExit is a basic block that unconditionally branches to
544 // `ContinuationBlock'.
546 // .ExitSelector is a basic block that decides, on exit from the loop,
547 // whether to branch to the "true" exit or to `PseudoExit'.
549 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
550 // for each PHINode in the loop header on taking the pseudo exit.
552 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
553 // preheader because it is made to branch to the loop header only
557 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
559 BasicBlock *ContinuationBlock) const;
561 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
562 // function creates a new preheader for `LS' and returns it.
564 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
565 const char *Tag) const;
567 // `ContinuationBlockAndPreheader' was the continuation block for some call to
568 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
569 // This function rewrites the PHI nodes in `LS.Header' to start with the
571 void rewriteIncomingValuesForPHIs(
572 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
573 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
575 // Even though we do not preserve any passes at this time, we at least need to
576 // keep the parent loop structure consistent. The `LPPassManager' seems to
577 // verify this after running a loop pass. This function adds the list of
578 // blocks denoted by BBs to this loops parent loop if required.
579 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
581 // Some global state.
586 // Information about the original loop we started out with.
588 LoopInfo &OriginalLoopInfo;
589 const SCEV *LatchTakenCount;
590 BasicBlock *OriginalPreheader;
592 // The preheader of the main loop. This may or may not be different from
593 // `OriginalPreheader'.
594 BasicBlock *MainLoopPreheader;
596 // The range we need to run the main loop in.
597 InductiveRangeCheck::Range Range;
599 // The structure of the main loop (see comment at the beginning of this class
601 LoopStructure MainLoopStructure;
604 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
605 ScalarEvolution &SE, InductiveRangeCheck::Range R)
606 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
607 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
608 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
609 MainLoopStructure(LS) {}
611 // Entry point for the algorithm. Returns true on success.
617 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
618 BasicBlock *ReplaceBy) {
619 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
620 if (PN->getIncomingBlock(i) == Block)
621 PN->setIncomingBlock(i, ReplaceBy);
624 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
626 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
627 return SE.getSignedRange(S).contains(SMax) &&
628 SE.getUnsignedRange(S).contains(SMax);
631 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
633 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
634 return SE.getSignedRange(S).contains(SMin) &&
635 SE.getUnsignedRange(S).contains(SMin);
638 Optional<LoopStructure>
639 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
640 Loop &L, const char *&FailureReason) {
641 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
643 BasicBlock *Latch = L.getLoopLatch();
644 if (!L.isLoopExiting(Latch)) {
645 FailureReason = "no loop latch";
649 BasicBlock *Header = L.getHeader();
650 BasicBlock *Preheader = L.getLoopPreheader();
652 FailureReason = "no preheader";
656 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
657 if (!LatchBr || LatchBr->isUnconditional()) {
658 FailureReason = "latch terminator not conditional branch";
662 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
664 BranchProbability ExitProbability =
665 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
667 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
668 FailureReason = "short running loop, not profitable";
672 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
673 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
674 FailureReason = "latch terminator branch not conditional on integral icmp";
678 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
679 if (isa<SCEVCouldNotCompute>(LatchCount)) {
680 FailureReason = "could not compute latch count";
684 ICmpInst::Predicate Pred = ICI->getPredicate();
685 Value *LeftValue = ICI->getOperand(0);
686 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
687 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
689 Value *RightValue = ICI->getOperand(1);
690 const SCEV *RightSCEV = SE.getSCEV(RightValue);
692 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
693 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
694 if (isa<SCEVAddRecExpr>(RightSCEV)) {
695 std::swap(LeftSCEV, RightSCEV);
696 std::swap(LeftValue, RightValue);
697 Pred = ICmpInst::getSwappedPredicate(Pred);
699 FailureReason = "no add recurrences in the icmp";
704 auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
708 IntegerType *Ty = cast<IntegerType>(AR->getType());
709 IntegerType *WideTy =
710 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
712 // Currently we only work with induction variables that have been proved to
713 // not wrap. This restriction can potentially be lifted in the future.
715 const SCEVAddRecExpr *ExtendAfterOp =
716 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
720 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
721 const SCEV *ExtendedStep =
722 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
724 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
725 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
730 if (const SCEVConstant *StepExpr =
731 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
732 ConstantInt *StepCI = StepExpr->getValue();
733 if (StepCI->isOne() || StepCI->isMinusOne()) {
734 IsIncreasing = StepCI->isOne();
742 // `ICI` is interpreted as taking the backedge if the *next* value of the
743 // induction variable satisfies some constraint.
745 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
746 bool IsIncreasing = false;
747 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
748 FailureReason = "LHS in icmp not induction variable";
752 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
753 // TODO: generalize the predicates here to also match their unsigned variants.
755 bool FoundExpectedPred =
756 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
757 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
759 if (!FoundExpectedPred) {
760 FailureReason = "expected icmp slt semantically, found something else";
764 if (LatchBrExitIdx == 0) {
765 if (CanBeSMax(SE, RightSCEV)) {
766 // TODO: this restriction is easily removable -- we just have to
767 // remember that the icmp was an slt and not an sle.
768 FailureReason = "limit may overflow when coercing sle to slt";
772 IRBuilder<> B(&*Preheader->rbegin());
773 RightValue = B.CreateAdd(RightValue, One);
777 bool FoundExpectedPred =
778 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
779 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
781 if (!FoundExpectedPred) {
782 FailureReason = "expected icmp sgt semantically, found something else";
786 if (LatchBrExitIdx == 0) {
787 if (CanBeSMin(SE, RightSCEV)) {
788 // TODO: this restriction is easily removable -- we just have to
789 // remember that the icmp was an sgt and not an sge.
790 FailureReason = "limit may overflow when coercing sge to sgt";
794 IRBuilder<> B(&*Preheader->rbegin());
795 RightValue = B.CreateSub(RightValue, One);
799 const SCEV *StartNext = IndVarNext->getStart();
800 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
801 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
803 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
805 assert(SE.getLoopDisposition(LatchCount, &L) ==
806 ScalarEvolution::LoopInvariant &&
807 "loop variant exit count doesn't make sense!");
809 assert(!L.contains(LatchExit) && "expected an exit block!");
810 const DataLayout &DL = Preheader->getModule()->getDataLayout();
811 Value *IndVarStartV =
812 SCEVExpander(SE, DL, "irce")
813 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
814 IndVarStartV->setName("indvar.start");
816 LoopStructure Result;
819 Result.Header = Header;
820 Result.Latch = Latch;
821 Result.LatchBr = LatchBr;
822 Result.LatchExit = LatchExit;
823 Result.LatchBrExitIdx = LatchBrExitIdx;
824 Result.IndVarStart = IndVarStartV;
825 Result.IndVarNext = LeftValue;
826 Result.IndVarIncreasing = IsIncreasing;
827 Result.LoopExitAt = RightValue;
829 FailureReason = nullptr;
834 Optional<LoopConstrainer::SubRanges>
835 LoopConstrainer::calculateSubRanges() const {
836 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
838 if (Range.getType() != Ty)
841 LoopConstrainer::SubRanges Result;
843 // I think we can be more aggressive here and make this nuw / nsw if the
844 // addition that feeds into the icmp for the latch's terminating branch is nuw
845 // / nsw. In any case, a wrapping 2's complement addition is safe.
846 ConstantInt *One = ConstantInt::get(Ty, 1);
847 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
848 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
850 bool Increasing = MainLoopStructure.IndVarIncreasing;
852 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
853 // range of values the induction variable takes.
855 const SCEV *Smallest = nullptr, *Greatest = nullptr;
861 // These two computations may sign-overflow. Here is why that is okay:
863 // We know that the induction variable does not sign-overflow on any
864 // iteration except the last one, and it starts at `Start` and ends at
865 // `End`, decrementing by one every time.
867 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
868 // induction variable is decreasing we know that that the smallest value
869 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
871 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
872 // that case, `Clamp` will always return `Smallest` and
873 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
874 // will be an empty range. Returning an empty range is always safe.
877 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
878 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
881 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
882 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
885 // In some cases we can prove that we don't need a pre or post loop
887 bool ProvablyNoPreloop =
888 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
889 if (!ProvablyNoPreloop)
890 Result.LowLimit = Clamp(Range.getBegin());
892 bool ProvablyNoPostLoop =
893 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
894 if (!ProvablyNoPostLoop)
895 Result.HighLimit = Clamp(Range.getEnd());
900 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
901 const char *Tag) const {
902 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
903 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
904 Result.Blocks.push_back(Clone);
905 Result.Map[BB] = Clone;
908 auto GetClonedValue = [&Result](Value *V) {
909 assert(V && "null values not in domain!");
910 auto It = Result.Map.find(V);
911 if (It == Result.Map.end())
913 return static_cast<Value *>(It->second);
916 Result.Structure = MainLoopStructure.map(GetClonedValue);
917 Result.Structure.Tag = Tag;
919 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
920 BasicBlock *ClonedBB = Result.Blocks[i];
921 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
923 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
925 for (Instruction &I : *ClonedBB)
926 RemapInstruction(&I, Result.Map,
927 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
929 // Exit blocks will now have one more predecessor and their PHI nodes need
930 // to be edited to reflect that. No phi nodes need to be introduced because
931 // the loop is in LCSSA.
933 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
934 SBBI != SBBE; ++SBBI) {
936 if (OriginalLoop.contains(*SBBI))
937 continue; // not an exit block
939 for (Instruction &I : **SBBI) {
940 if (!isa<PHINode>(&I))
943 PHINode *PN = cast<PHINode>(&I);
944 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
945 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
951 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
952 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
953 BasicBlock *ContinuationBlock) const {
955 // We start with a loop with a single latch:
957 // +--------------------+
961 // +--------+-----------+
962 // | ----------------\
964 // +--------v----v------+ |
968 // +--------------------+ |
972 // +--------------------+ |
974 // | latch >----------/
976 // +-------v------------+
979 // | +--------------------+
981 // +---> original exit |
983 // +--------------------+
985 // We change the control flow to look like
988 // +--------------------+
990 // | preheader >-------------------------+
992 // +--------v-----------+ |
993 // | /-------------+ |
995 // +--------v--v--------+ | |
997 // | header | | +--------+ |
999 // +--------------------+ | | +-----v-----v-----------+
1001 // | | | .pseudo.exit |
1003 // | | +-----------v-----------+
1006 // | | +--------v-------------+
1007 // +--------------------+ | | | |
1008 // | | | | | ContinuationBlock |
1009 // | latch >------+ | | |
1010 // | | | +----------------------+
1011 // +---------v----------+ |
1014 // | +---------------^-----+
1016 // +-----> .exit.selector |
1018 // +----------v----------+
1020 // +--------------------+ |
1022 // | original exit <----+
1024 // +--------------------+
1027 RewrittenRangeInfo RRI;
1029 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1030 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1031 &F, BBInsertLocation);
1032 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1035 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
1036 bool Increasing = LS.IndVarIncreasing;
1038 IRBuilder<> B(PreheaderJump);
1040 // EnterLoopCond - is it okay to start executing this `LS'?
1041 Value *EnterLoopCond = Increasing
1042 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1043 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1045 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1046 PreheaderJump->eraseFromParent();
1048 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1049 B.SetInsertPoint(LS.LatchBr);
1050 Value *TakeBackedgeLoopCond =
1051 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1052 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1053 Value *CondForBranch = LS.LatchBrExitIdx == 1
1054 ? TakeBackedgeLoopCond
1055 : B.CreateNot(TakeBackedgeLoopCond);
1057 LS.LatchBr->setCondition(CondForBranch);
1059 B.SetInsertPoint(RRI.ExitSelector);
1061 // IterationsLeft - are there any more iterations left, given the original
1062 // upper bound on the induction variable? If not, we branch to the "real"
1064 Value *IterationsLeft = Increasing
1065 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1066 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1067 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1069 BranchInst *BranchToContinuation =
1070 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1072 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1073 // each of the PHI nodes in the loop header. This feeds into the initial
1074 // value of the same PHI nodes if/when we continue execution.
1075 for (Instruction &I : *LS.Header) {
1076 if (!isa<PHINode>(&I))
1079 PHINode *PN = cast<PHINode>(&I);
1081 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1082 BranchToContinuation);
1084 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1085 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1087 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1090 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1091 BranchToContinuation);
1092 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1093 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1095 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1096 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1097 for (Instruction &I : *LS.LatchExit) {
1098 if (PHINode *PN = dyn_cast<PHINode>(&I))
1099 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1107 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1108 LoopStructure &LS, BasicBlock *ContinuationBlock,
1109 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1111 unsigned PHIIndex = 0;
1112 for (Instruction &I : *LS.Header) {
1113 if (!isa<PHINode>(&I))
1116 PHINode *PN = cast<PHINode>(&I);
1118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1119 if (PN->getIncomingBlock(i) == ContinuationBlock)
1120 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1123 LS.IndVarStart = RRI.IndVarEnd;
1126 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1127 BasicBlock *OldPreheader,
1128 const char *Tag) const {
1130 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1131 BranchInst::Create(LS.Header, Preheader);
1133 for (Instruction &I : *LS.Header) {
1134 if (!isa<PHINode>(&I))
1137 PHINode *PN = cast<PHINode>(&I);
1138 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1139 replacePHIBlock(PN, OldPreheader, Preheader);
1145 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1146 Loop *ParentLoop = OriginalLoop.getParentLoop();
1150 for (BasicBlock *BB : BBs)
1151 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1154 bool LoopConstrainer::run() {
1155 BasicBlock *Preheader = nullptr;
1156 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1157 Preheader = OriginalLoop.getLoopPreheader();
1158 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1161 OriginalPreheader = Preheader;
1162 MainLoopPreheader = Preheader;
1164 Optional<SubRanges> MaybeSR = calculateSubRanges();
1165 if (!MaybeSR.hasValue()) {
1166 DEBUG(dbgs() << "irce: could not compute subranges\n");
1170 SubRanges SR = MaybeSR.getValue();
1171 bool Increasing = MainLoopStructure.IndVarIncreasing;
1173 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1175 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1176 Instruction *InsertPt = OriginalPreheader->getTerminator();
1178 // It would have been better to make `PreLoop' and `PostLoop'
1179 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1181 ClonedLoop PreLoop, PostLoop;
1183 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1184 bool NeedsPostLoop =
1185 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1187 Value *ExitPreLoopAt = nullptr;
1188 Value *ExitMainLoopAt = nullptr;
1189 const SCEVConstant *MinusOneS =
1190 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1193 const SCEV *ExitPreLoopAtSCEV = nullptr;
1196 ExitPreLoopAtSCEV = *SR.LowLimit;
1198 if (CanBeSMin(SE, *SR.HighLimit)) {
1199 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1200 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1204 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1207 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1208 ExitPreLoopAt->setName("exit.preloop.at");
1211 if (NeedsPostLoop) {
1212 const SCEV *ExitMainLoopAtSCEV = nullptr;
1215 ExitMainLoopAtSCEV = *SR.HighLimit;
1217 if (CanBeSMin(SE, *SR.LowLimit)) {
1218 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1219 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1223 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1226 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1227 ExitMainLoopAt->setName("exit.mainloop.at");
1230 // We clone these ahead of time so that we don't have to deal with changing
1231 // and temporarily invalid IR as we transform the loops.
1233 cloneLoop(PreLoop, "preloop");
1235 cloneLoop(PostLoop, "postloop");
1237 RewrittenRangeInfo PreLoopRRI;
1240 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1241 PreLoop.Structure.Header);
1244 createPreheader(MainLoopStructure, Preheader, "mainloop");
1245 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1246 ExitPreLoopAt, MainLoopPreheader);
1247 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1251 BasicBlock *PostLoopPreheader = nullptr;
1252 RewrittenRangeInfo PostLoopRRI;
1254 if (NeedsPostLoop) {
1256 createPreheader(PostLoop.Structure, Preheader, "postloop");
1257 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1258 ExitMainLoopAt, PostLoopPreheader);
1259 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1263 BasicBlock *NewMainLoopPreheader =
1264 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1265 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1266 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1267 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1269 // Some of the above may be nullptr, filter them out before passing to
1270 // addToParentLoopIfNeeded.
1272 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1274 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1275 addToParentLoopIfNeeded(PreLoop.Blocks);
1276 addToParentLoopIfNeeded(PostLoop.Blocks);
1281 /// Computes and returns a range of values for the induction variable (IndVar)
1282 /// in which the range check can be safely elided. If it cannot compute such a
1283 /// range, returns None.
1284 Optional<InductiveRangeCheck::Range>
1285 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1286 const SCEVAddRecExpr *IndVar,
1287 IRBuilder<> &) const {
1288 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1289 // variable, that may or may not exist as a real llvm::Value in the loop) and
1290 // this inductive range check is a range check on the "C + D * I" ("C" is
1291 // getOffset() and "D" is getScale()). We rewrite the value being range
1292 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1293 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1294 // can be generalized as needed.
1296 // The actual inequalities we solve are of the form
1298 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1300 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1301 // and subtractions are twos-complement wrapping and comparisons are signed.
1305 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1306 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1307 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1310 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1311 // Hence 0 <= (IndVar + M) < L
1313 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1314 // 127, IndVar = 126 and L = -2 in an i8 world.
1316 if (!IndVar->isAffine())
1319 const SCEV *A = IndVar->getStart();
1320 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1324 const SCEV *C = getOffset();
1325 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1329 ConstantInt *ConstD = D->getValue();
1330 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1333 const SCEV *M = SE.getMinusSCEV(C, A);
1335 const SCEV *Begin = SE.getNegativeSCEV(M);
1336 const SCEV *UpperLimit = nullptr;
1338 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1339 // We can potentially do much better here.
1340 if (Value *V = getLength()) {
1341 UpperLimit = SE.getSCEV(V);
1343 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1344 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1345 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1348 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1349 return InductiveRangeCheck::Range(Begin, End);
1352 static Optional<InductiveRangeCheck::Range>
1353 IntersectRange(ScalarEvolution &SE,
1354 const Optional<InductiveRangeCheck::Range> &R1,
1355 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1358 auto &R1Value = R1.getValue();
1360 // TODO: we could widen the smaller range and have this work; but for now we
1361 // bail out to keep things simple.
1362 if (R1Value.getType() != R2.getType())
1365 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1366 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1368 return InductiveRangeCheck::Range(NewBegin, NewEnd);
1371 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1372 if (L->getBlocks().size() >= LoopSizeCutoff) {
1373 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1377 BasicBlock *Preheader = L->getLoopPreheader();
1379 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1383 LLVMContext &Context = Preheader->getContext();
1384 InductiveRangeCheck::AllocatorTy IRCAlloc;
1385 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1386 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1387 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
1389 for (auto BBI : L->getBlocks())
1390 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1391 if (InductiveRangeCheck *IRC =
1392 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1393 RangeChecks.push_back(IRC);
1395 if (RangeChecks.empty())
1398 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1399 OS << "irce: looking at loop "; L->print(OS);
1400 OS << "irce: loop has " << RangeChecks.size()
1401 << " inductive range checks: \n";
1402 for (InductiveRangeCheck *IRC : RangeChecks)
1406 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1408 if (PrintRangeChecks)
1409 PrintRecognizedRangeChecks(errs());
1411 const char *FailureReason = nullptr;
1412 Optional<LoopStructure> MaybeLoopStructure =
1413 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1414 if (!MaybeLoopStructure.hasValue()) {
1415 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1419 LoopStructure LS = MaybeLoopStructure.getValue();
1420 bool Increasing = LS.IndVarIncreasing;
1421 const SCEV *MinusOne =
1422 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1423 const SCEVAddRecExpr *IndVar =
1424 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1426 Optional<InductiveRangeCheck::Range> SafeIterRange;
1427 Instruction *ExprInsertPt = Preheader->getTerminator();
1429 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1431 IRBuilder<> B(ExprInsertPt);
1432 for (InductiveRangeCheck *IRC : RangeChecks) {
1433 auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
1434 if (Result.hasValue()) {
1435 auto MaybeSafeIterRange =
1436 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
1437 if (MaybeSafeIterRange.hasValue()) {
1438 RangeChecksToEliminate.push_back(IRC);
1439 SafeIterRange = MaybeSafeIterRange.getValue();
1444 if (!SafeIterRange.hasValue())
1447 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1448 SE, SafeIterRange.getValue());
1449 bool Changed = LC.run();
1452 auto PrintConstrainedLoopInfo = [L]() {
1453 dbgs() << "irce: in function ";
1454 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1455 dbgs() << "constrained ";
1459 DEBUG(PrintConstrainedLoopInfo());
1461 if (PrintChangedLoops)
1462 PrintConstrainedLoopInfo();
1464 // Optimize away the now-redundant range checks.
1466 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1467 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1468 ? ConstantInt::getTrue(Context)
1469 : ConstantInt::getFalse(Context);
1470 IRC->getBranch()->setCondition(FoldedRangeCheck);
1477 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1478 return new InductiveRangeCheckElimination;