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<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
86 cl::Hidden, cl::init(10));
88 #define DEBUG_TYPE "irce"
92 /// An inductive range check is conditional branch in a loop with
94 /// 1. a very cold successor (i.e. the branch jumps to that successor very
99 /// 2. a condition that is provably true for some contiguous range of values
100 /// taken by the containing loop's induction variable.
102 class InductiveRangeCheck {
103 // Classifies a range check
104 enum RangeCheckKind {
105 // Range check of the form "0 <= I".
106 RANGE_CHECK_LOWER = 1,
108 // Range check of the form "I < L" where L is known positive.
109 RANGE_CHECK_UPPER = 2,
111 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
113 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
115 // Unrecognized range check condition.
116 RANGE_CHECK_UNKNOWN = (unsigned)-1
119 static const char *rangeCheckKindToStr(RangeCheckKind);
127 static RangeCheckKind parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
128 Value *&Index, Value *&Length);
130 static InductiveRangeCheck::RangeCheckKind
131 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
132 const SCEV *&Index, Value *&UpperLimit);
134 InductiveRangeCheck() :
135 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
138 const SCEV *getOffset() const { return Offset; }
139 const SCEV *getScale() const { return Scale; }
140 Value *getLength() const { return Length; }
142 void print(raw_ostream &OS) const {
143 OS << "InductiveRangeCheck:\n";
144 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
155 getBranch()->print(OS);
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
165 BranchInst *getBranch() const { return Branch; }
167 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
168 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
175 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
176 assert(Begin->getType() == End->getType() && "ill-typed range!");
179 Type *getType() const { return Begin->getType(); }
180 const SCEV *getBegin() const { return Begin; }
181 const SCEV *getEnd() const { return End; }
184 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
186 /// This is the value the condition of the branch needs to evaluate to for the
187 /// branch to take the hot successor (see (1) above).
188 bool getPassingDirection() { return true; }
190 /// Computes a range for the induction variable (IndVar) in which the range
191 /// check is redundant and can be constant-folded away. The induction
192 /// variable is not required to be the canonical {0,+,1} induction variable.
193 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
194 const SCEVAddRecExpr *IndVar,
195 IRBuilder<> &B) const;
197 /// Create an inductive range check out of BI if possible, else return
199 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
200 Loop *L, ScalarEvolution &SE,
201 BranchProbabilityInfo &BPI);
204 class InductiveRangeCheckElimination : public LoopPass {
205 InductiveRangeCheck::AllocatorTy Allocator;
209 InductiveRangeCheckElimination() : LoopPass(ID) {
210 initializeInductiveRangeCheckEliminationPass(
211 *PassRegistry::getPassRegistry());
214 void getAnalysisUsage(AnalysisUsage &AU) const override {
215 AU.addRequired<LoopInfoWrapperPass>();
216 AU.addRequiredID(LoopSimplifyID);
217 AU.addRequiredID(LCSSAID);
218 AU.addRequired<ScalarEvolution>();
219 AU.addRequired<BranchProbabilityInfo>();
222 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
225 char InductiveRangeCheckElimination::ID = 0;
228 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
229 "Inductive range check elimination", false, false)
231 const char *InductiveRangeCheck::rangeCheckKindToStr(
232 InductiveRangeCheck::RangeCheckKind RCK) {
234 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
235 return "RANGE_CHECK_UNKNOWN";
237 case InductiveRangeCheck::RANGE_CHECK_UPPER:
238 return "RANGE_CHECK_UPPER";
240 case InductiveRangeCheck::RANGE_CHECK_LOWER:
241 return "RANGE_CHECK_LOWER";
243 case InductiveRangeCheck::RANGE_CHECK_BOTH:
244 return "RANGE_CHECK_BOTH";
247 llvm_unreachable("unknown range check type!");
250 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI`
252 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
253 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value
255 /// range checked, and set `Length` to the upper limit `Index` is being range
256 /// checked with if (and only if) the range check type is stronger or equal to
257 /// RANGE_CHECK_UPPER.
259 InductiveRangeCheck::RangeCheckKind
260 InductiveRangeCheck::parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
261 Value *&Index, Value *&Length) {
263 using namespace llvm::PatternMatch;
265 ICmpInst::Predicate Pred = ICI->getPredicate();
266 Value *LHS = ICI->getOperand(0);
267 Value *RHS = ICI->getOperand(1);
271 return RANGE_CHECK_UNKNOWN;
273 case ICmpInst::ICMP_SLE:
276 case ICmpInst::ICMP_SGE:
277 if (match(RHS, m_ConstantInt<0>())) {
279 return RANGE_CHECK_LOWER;
281 return RANGE_CHECK_UNKNOWN;
283 case ICmpInst::ICMP_SLT:
286 case ICmpInst::ICMP_SGT:
287 if (match(RHS, m_ConstantInt<-1>())) {
289 return RANGE_CHECK_LOWER;
292 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
295 return RANGE_CHECK_UPPER;
297 return RANGE_CHECK_UNKNOWN;
299 case ICmpInst::ICMP_ULT:
302 case ICmpInst::ICMP_UGT:
303 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
306 return RANGE_CHECK_BOTH;
308 return RANGE_CHECK_UNKNOWN;
311 llvm_unreachable("default clause returns!");
314 /// Parses an arbitrary condition into a range check. `Length` is set only if
315 /// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
316 InductiveRangeCheck::RangeCheckKind
317 InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
318 Value *Condition, const SCEV *&Index,
320 using namespace llvm::PatternMatch;
325 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
326 Value *IndexA = nullptr, *IndexB = nullptr;
327 Value *LengthA = nullptr, *LengthB = nullptr;
328 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
330 if (!ICmpA || !ICmpB)
331 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
333 auto RCKindA = parseRangeCheckICmp(ICmpA, SE, IndexA, LengthA);
334 auto RCKindB = parseRangeCheckICmp(ICmpB, SE, IndexB, LengthB);
336 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
337 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
338 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
340 if (IndexA != IndexB)
341 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
343 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
344 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
346 Index = SE.getSCEV(IndexA);
347 if (isa<SCEVCouldNotCompute>(Index))
348 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
350 Length = LengthA == nullptr ? LengthB : LengthA;
352 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
355 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
356 Value *IndexVal = nullptr;
358 auto RCKind = parseRangeCheckICmp(ICI, SE, IndexVal, Length);
360 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
361 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
363 Index = SE.getSCEV(IndexVal);
364 if (isa<SCEVCouldNotCompute>(Index))
365 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
370 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
374 InductiveRangeCheck *
375 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
376 Loop *L, ScalarEvolution &SE,
377 BranchProbabilityInfo &BPI) {
379 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
382 BranchProbability LikelyTaken(15, 16);
384 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
387 Value *Length = nullptr;
388 const SCEV *IndexSCEV = nullptr;
390 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
393 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
396 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
397 assert(!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) ||
398 Length && "contract with SplitRangeCheckCondition!");
400 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
402 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
407 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
408 IRC->Length = Length;
409 IRC->Offset = IndexAddRec->getStart();
410 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
418 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
419 // except that it is more lightweight and can track the state of a loop through
420 // changing and potentially invalid IR. This structure also formalizes the
421 // kinds of loops we can deal with -- ones that have a single latch that is also
422 // an exiting block *and* have a canonical induction variable.
423 struct LoopStructure {
429 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
430 // successor is `LatchExit', the exit block of the loop.
432 BasicBlock *LatchExit;
433 unsigned LatchBrExitIdx;
438 bool IndVarIncreasing;
441 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
442 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
443 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
445 template <typename M> LoopStructure map(M Map) const {
446 LoopStructure Result;
448 Result.Header = cast<BasicBlock>(Map(Header));
449 Result.Latch = cast<BasicBlock>(Map(Latch));
450 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
451 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
452 Result.LatchBrExitIdx = LatchBrExitIdx;
453 Result.IndVarNext = Map(IndVarNext);
454 Result.IndVarStart = Map(IndVarStart);
455 Result.LoopExitAt = Map(LoopExitAt);
456 Result.IndVarIncreasing = IndVarIncreasing;
460 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
461 BranchProbabilityInfo &BPI,
466 /// This class is used to constrain loops to run within a given iteration space.
467 /// The algorithm this class implements is given a Loop and a range [Begin,
468 /// End). The algorithm then tries to break out a "main loop" out of the loop
469 /// it is given in a way that the "main loop" runs with the induction variable
470 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
471 /// loops to run any remaining iterations. The pre loop runs any iterations in
472 /// which the induction variable is < Begin, and the post loop runs any
473 /// iterations in which the induction variable is >= End.
475 class LoopConstrainer {
476 // The representation of a clone of the original loop we started out with.
479 std::vector<BasicBlock *> Blocks;
481 // `Map` maps values in the clonee into values in the cloned version
482 ValueToValueMapTy Map;
484 // An instance of `LoopStructure` for the cloned loop
485 LoopStructure Structure;
488 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
489 // more details on what these fields mean.
490 struct RewrittenRangeInfo {
491 BasicBlock *PseudoExit;
492 BasicBlock *ExitSelector;
493 std::vector<PHINode *> PHIValuesAtPseudoExit;
497 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
500 // Calculated subranges we restrict the iteration space of the main loop to.
501 // See the implementation of `calculateSubRanges' for more details on how
502 // these fields are computed. `LowLimit` is None if there is no restriction
503 // on low end of the restricted iteration space of the main loop. `HighLimit`
504 // is None if there is no restriction on high end of the restricted iteration
505 // space of the main loop.
508 Optional<const SCEV *> LowLimit;
509 Optional<const SCEV *> HighLimit;
512 // A utility function that does a `replaceUsesOfWith' on the incoming block
513 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
514 // incoming block list with `ReplaceBy'.
515 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
516 BasicBlock *ReplaceBy);
518 // Compute a safe set of limits for the main loop to run in -- effectively the
519 // intersection of `Range' and the iteration space of the original loop.
520 // Return None if unable to compute the set of subranges.
522 Optional<SubRanges> calculateSubRanges() const;
524 // Clone `OriginalLoop' and return the result in CLResult. The IR after
525 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
526 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
527 // but there is no such edge.
529 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
531 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
532 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
533 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
534 // `OriginalHeaderCount'.
536 // If there are iterations left to execute, control is made to jump to
537 // `ContinuationBlock', otherwise they take the normal loop exit. The
538 // returned `RewrittenRangeInfo' object is populated as follows:
540 // .PseudoExit is a basic block that unconditionally branches to
541 // `ContinuationBlock'.
543 // .ExitSelector is a basic block that decides, on exit from the loop,
544 // whether to branch to the "true" exit or to `PseudoExit'.
546 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
547 // for each PHINode in the loop header on taking the pseudo exit.
549 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
550 // preheader because it is made to branch to the loop header only
554 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
556 BasicBlock *ContinuationBlock) const;
558 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
559 // function creates a new preheader for `LS' and returns it.
561 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
562 const char *Tag) const;
564 // `ContinuationBlockAndPreheader' was the continuation block for some call to
565 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
566 // This function rewrites the PHI nodes in `LS.Header' to start with the
568 void rewriteIncomingValuesForPHIs(
569 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
570 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
572 // Even though we do not preserve any passes at this time, we at least need to
573 // keep the parent loop structure consistent. The `LPPassManager' seems to
574 // verify this after running a loop pass. This function adds the list of
575 // blocks denoted by BBs to this loops parent loop if required.
576 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
578 // Some global state.
583 // Information about the original loop we started out with.
585 LoopInfo &OriginalLoopInfo;
586 const SCEV *LatchTakenCount;
587 BasicBlock *OriginalPreheader;
589 // The preheader of the main loop. This may or may not be different from
590 // `OriginalPreheader'.
591 BasicBlock *MainLoopPreheader;
593 // The range we need to run the main loop in.
594 InductiveRangeCheck::Range Range;
596 // The structure of the main loop (see comment at the beginning of this class
598 LoopStructure MainLoopStructure;
601 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
602 ScalarEvolution &SE, InductiveRangeCheck::Range R)
603 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
604 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
605 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
606 MainLoopStructure(LS) {}
608 // Entry point for the algorithm. Returns true on success.
614 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
615 BasicBlock *ReplaceBy) {
616 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
617 if (PN->getIncomingBlock(i) == Block)
618 PN->setIncomingBlock(i, ReplaceBy);
621 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
623 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
624 return SE.getSignedRange(S).contains(SMax) &&
625 SE.getUnsignedRange(S).contains(SMax);
628 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
630 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
631 return SE.getSignedRange(S).contains(SMin) &&
632 SE.getUnsignedRange(S).contains(SMin);
635 Optional<LoopStructure>
636 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
637 Loop &L, const char *&FailureReason) {
638 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
640 BasicBlock *Latch = L.getLoopLatch();
641 if (!L.isLoopExiting(Latch)) {
642 FailureReason = "no loop latch";
646 BasicBlock *Header = L.getHeader();
647 BasicBlock *Preheader = L.getLoopPreheader();
649 FailureReason = "no preheader";
653 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
654 if (!LatchBr || LatchBr->isUnconditional()) {
655 FailureReason = "latch terminator not conditional branch";
659 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
661 BranchProbability ExitProbability =
662 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
664 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
665 FailureReason = "short running loop, not profitable";
669 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
670 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
671 FailureReason = "latch terminator branch not conditional on integral icmp";
675 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
676 if (isa<SCEVCouldNotCompute>(LatchCount)) {
677 FailureReason = "could not compute latch count";
681 ICmpInst::Predicate Pred = ICI->getPredicate();
682 Value *LeftValue = ICI->getOperand(0);
683 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
684 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
686 Value *RightValue = ICI->getOperand(1);
687 const SCEV *RightSCEV = SE.getSCEV(RightValue);
689 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
690 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
691 if (isa<SCEVAddRecExpr>(RightSCEV)) {
692 std::swap(LeftSCEV, RightSCEV);
693 std::swap(LeftValue, RightValue);
694 Pred = ICmpInst::getSwappedPredicate(Pred);
696 FailureReason = "no add recurrences in the icmp";
701 auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
705 IntegerType *Ty = cast<IntegerType>(AR->getType());
706 IntegerType *WideTy =
707 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
709 // Currently we only work with induction variables that have been proved to
710 // not wrap. This restriction can potentially be lifted in the future.
712 const SCEVAddRecExpr *ExtendAfterOp =
713 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
717 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
718 const SCEV *ExtendedStep =
719 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
721 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
722 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
727 if (const SCEVConstant *StepExpr =
728 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
729 ConstantInt *StepCI = StepExpr->getValue();
730 if (StepCI->isOne() || StepCI->isMinusOne()) {
731 IsIncreasing = StepCI->isOne();
739 // `ICI` is interpreted as taking the backedge if the *next* value of the
740 // induction variable satisfies some constraint.
742 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
743 bool IsIncreasing = false;
744 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
745 FailureReason = "LHS in icmp not induction variable";
749 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
750 // TODO: generalize the predicates here to also match their unsigned variants.
752 bool FoundExpectedPred =
753 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
754 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
756 if (!FoundExpectedPred) {
757 FailureReason = "expected icmp slt semantically, found something else";
761 if (LatchBrExitIdx == 0) {
762 if (CanBeSMax(SE, RightSCEV)) {
763 // TODO: this restriction is easily removable -- we just have to
764 // remember that the icmp was an slt and not an sle.
765 FailureReason = "limit may overflow when coercing sle to slt";
769 IRBuilder<> B(&*Preheader->rbegin());
770 RightValue = B.CreateAdd(RightValue, One);
774 bool FoundExpectedPred =
775 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
776 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
778 if (!FoundExpectedPred) {
779 FailureReason = "expected icmp sgt semantically, found something else";
783 if (LatchBrExitIdx == 0) {
784 if (CanBeSMin(SE, RightSCEV)) {
785 // TODO: this restriction is easily removable -- we just have to
786 // remember that the icmp was an sgt and not an sge.
787 FailureReason = "limit may overflow when coercing sge to sgt";
791 IRBuilder<> B(&*Preheader->rbegin());
792 RightValue = B.CreateSub(RightValue, One);
796 const SCEV *StartNext = IndVarNext->getStart();
797 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
798 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
800 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
802 assert(SE.getLoopDisposition(LatchCount, &L) ==
803 ScalarEvolution::LoopInvariant &&
804 "loop variant exit count doesn't make sense!");
806 assert(!L.contains(LatchExit) && "expected an exit block!");
807 const DataLayout &DL = Preheader->getModule()->getDataLayout();
808 Value *IndVarStartV =
809 SCEVExpander(SE, DL, "irce")
810 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
811 IndVarStartV->setName("indvar.start");
813 LoopStructure Result;
816 Result.Header = Header;
817 Result.Latch = Latch;
818 Result.LatchBr = LatchBr;
819 Result.LatchExit = LatchExit;
820 Result.LatchBrExitIdx = LatchBrExitIdx;
821 Result.IndVarStart = IndVarStartV;
822 Result.IndVarNext = LeftValue;
823 Result.IndVarIncreasing = IsIncreasing;
824 Result.LoopExitAt = RightValue;
826 FailureReason = nullptr;
831 Optional<LoopConstrainer::SubRanges>
832 LoopConstrainer::calculateSubRanges() const {
833 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
835 if (Range.getType() != Ty)
838 LoopConstrainer::SubRanges Result;
840 // I think we can be more aggressive here and make this nuw / nsw if the
841 // addition that feeds into the icmp for the latch's terminating branch is nuw
842 // / nsw. In any case, a wrapping 2's complement addition is safe.
843 ConstantInt *One = ConstantInt::get(Ty, 1);
844 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
845 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
847 bool Increasing = MainLoopStructure.IndVarIncreasing;
849 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
850 // range of values the induction variable takes.
852 const SCEV *Smallest = nullptr, *Greatest = nullptr;
858 // These two computations may sign-overflow. Here is why that is okay:
860 // We know that the induction variable does not sign-overflow on any
861 // iteration except the last one, and it starts at `Start` and ends at
862 // `End`, decrementing by one every time.
864 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
865 // induction variable is decreasing we know that that the smallest value
866 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
868 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
869 // that case, `Clamp` will always return `Smallest` and
870 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
871 // will be an empty range. Returning an empty range is always safe.
874 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
875 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
878 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
879 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
882 // In some cases we can prove that we don't need a pre or post loop
884 bool ProvablyNoPreloop =
885 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
886 if (!ProvablyNoPreloop)
887 Result.LowLimit = Clamp(Range.getBegin());
889 bool ProvablyNoPostLoop =
890 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
891 if (!ProvablyNoPostLoop)
892 Result.HighLimit = Clamp(Range.getEnd());
897 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
898 const char *Tag) const {
899 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
900 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
901 Result.Blocks.push_back(Clone);
902 Result.Map[BB] = Clone;
905 auto GetClonedValue = [&Result](Value *V) {
906 assert(V && "null values not in domain!");
907 auto It = Result.Map.find(V);
908 if (It == Result.Map.end())
910 return static_cast<Value *>(It->second);
913 Result.Structure = MainLoopStructure.map(GetClonedValue);
914 Result.Structure.Tag = Tag;
916 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
917 BasicBlock *ClonedBB = Result.Blocks[i];
918 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
920 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
922 for (Instruction &I : *ClonedBB)
923 RemapInstruction(&I, Result.Map,
924 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
926 // Exit blocks will now have one more predecessor and their PHI nodes need
927 // to be edited to reflect that. No phi nodes need to be introduced because
928 // the loop is in LCSSA.
930 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
931 SBBI != SBBE; ++SBBI) {
933 if (OriginalLoop.contains(*SBBI))
934 continue; // not an exit block
936 for (Instruction &I : **SBBI) {
937 if (!isa<PHINode>(&I))
940 PHINode *PN = cast<PHINode>(&I);
941 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
942 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
948 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
949 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
950 BasicBlock *ContinuationBlock) const {
952 // We start with a loop with a single latch:
954 // +--------------------+
958 // +--------+-----------+
959 // | ----------------\
961 // +--------v----v------+ |
965 // +--------------------+ |
969 // +--------------------+ |
971 // | latch >----------/
973 // +-------v------------+
976 // | +--------------------+
978 // +---> original exit |
980 // +--------------------+
982 // We change the control flow to look like
985 // +--------------------+
987 // | preheader >-------------------------+
989 // +--------v-----------+ |
990 // | /-------------+ |
992 // +--------v--v--------+ | |
994 // | header | | +--------+ |
996 // +--------------------+ | | +-----v-----v-----------+
998 // | | | .pseudo.exit |
1000 // | | +-----------v-----------+
1003 // | | +--------v-------------+
1004 // +--------------------+ | | | |
1005 // | | | | | ContinuationBlock |
1006 // | latch >------+ | | |
1007 // | | | +----------------------+
1008 // +---------v----------+ |
1011 // | +---------------^-----+
1013 // +-----> .exit.selector |
1015 // +----------v----------+
1017 // +--------------------+ |
1019 // | original exit <----+
1021 // +--------------------+
1024 RewrittenRangeInfo RRI;
1026 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1027 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1028 &F, BBInsertLocation);
1029 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1032 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
1033 bool Increasing = LS.IndVarIncreasing;
1035 IRBuilder<> B(PreheaderJump);
1037 // EnterLoopCond - is it okay to start executing this `LS'?
1038 Value *EnterLoopCond = Increasing
1039 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1040 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1042 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1043 PreheaderJump->eraseFromParent();
1045 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1046 B.SetInsertPoint(LS.LatchBr);
1047 Value *TakeBackedgeLoopCond =
1048 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1049 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1050 Value *CondForBranch = LS.LatchBrExitIdx == 1
1051 ? TakeBackedgeLoopCond
1052 : B.CreateNot(TakeBackedgeLoopCond);
1054 LS.LatchBr->setCondition(CondForBranch);
1056 B.SetInsertPoint(RRI.ExitSelector);
1058 // IterationsLeft - are there any more iterations left, given the original
1059 // upper bound on the induction variable? If not, we branch to the "real"
1061 Value *IterationsLeft = Increasing
1062 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1063 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1064 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1066 BranchInst *BranchToContinuation =
1067 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1069 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1070 // each of the PHI nodes in the loop header. This feeds into the initial
1071 // value of the same PHI nodes if/when we continue execution.
1072 for (Instruction &I : *LS.Header) {
1073 if (!isa<PHINode>(&I))
1076 PHINode *PN = cast<PHINode>(&I);
1078 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1079 BranchToContinuation);
1081 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1082 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1084 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1087 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1088 BranchToContinuation);
1089 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1090 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1092 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1093 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1094 for (Instruction &I : *LS.LatchExit) {
1095 if (PHINode *PN = dyn_cast<PHINode>(&I))
1096 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1104 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1105 LoopStructure &LS, BasicBlock *ContinuationBlock,
1106 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1108 unsigned PHIIndex = 0;
1109 for (Instruction &I : *LS.Header) {
1110 if (!isa<PHINode>(&I))
1113 PHINode *PN = cast<PHINode>(&I);
1115 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1116 if (PN->getIncomingBlock(i) == ContinuationBlock)
1117 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1120 LS.IndVarStart = RRI.IndVarEnd;
1123 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1124 BasicBlock *OldPreheader,
1125 const char *Tag) const {
1127 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1128 BranchInst::Create(LS.Header, Preheader);
1130 for (Instruction &I : *LS.Header) {
1131 if (!isa<PHINode>(&I))
1134 PHINode *PN = cast<PHINode>(&I);
1135 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1136 replacePHIBlock(PN, OldPreheader, Preheader);
1142 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1143 Loop *ParentLoop = OriginalLoop.getParentLoop();
1147 for (BasicBlock *BB : BBs)
1148 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1151 bool LoopConstrainer::run() {
1152 BasicBlock *Preheader = nullptr;
1153 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1154 Preheader = OriginalLoop.getLoopPreheader();
1155 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1158 OriginalPreheader = Preheader;
1159 MainLoopPreheader = Preheader;
1161 Optional<SubRanges> MaybeSR = calculateSubRanges();
1162 if (!MaybeSR.hasValue()) {
1163 DEBUG(dbgs() << "irce: could not compute subranges\n");
1167 SubRanges SR = MaybeSR.getValue();
1168 bool Increasing = MainLoopStructure.IndVarIncreasing;
1170 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1172 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1173 Instruction *InsertPt = OriginalPreheader->getTerminator();
1175 // It would have been better to make `PreLoop' and `PostLoop'
1176 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1178 ClonedLoop PreLoop, PostLoop;
1180 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1181 bool NeedsPostLoop =
1182 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1184 Value *ExitPreLoopAt = nullptr;
1185 Value *ExitMainLoopAt = nullptr;
1186 const SCEVConstant *MinusOneS =
1187 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1190 const SCEV *ExitPreLoopAtSCEV = nullptr;
1193 ExitPreLoopAtSCEV = *SR.LowLimit;
1195 if (CanBeSMin(SE, *SR.HighLimit)) {
1196 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1197 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1201 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1204 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1205 ExitPreLoopAt->setName("exit.preloop.at");
1208 if (NeedsPostLoop) {
1209 const SCEV *ExitMainLoopAtSCEV = nullptr;
1212 ExitMainLoopAtSCEV = *SR.HighLimit;
1214 if (CanBeSMin(SE, *SR.LowLimit)) {
1215 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1216 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1220 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1223 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1224 ExitMainLoopAt->setName("exit.mainloop.at");
1227 // We clone these ahead of time so that we don't have to deal with changing
1228 // and temporarily invalid IR as we transform the loops.
1230 cloneLoop(PreLoop, "preloop");
1232 cloneLoop(PostLoop, "postloop");
1234 RewrittenRangeInfo PreLoopRRI;
1237 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1238 PreLoop.Structure.Header);
1241 createPreheader(MainLoopStructure, Preheader, "mainloop");
1242 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1243 ExitPreLoopAt, MainLoopPreheader);
1244 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1248 BasicBlock *PostLoopPreheader = nullptr;
1249 RewrittenRangeInfo PostLoopRRI;
1251 if (NeedsPostLoop) {
1253 createPreheader(PostLoop.Structure, Preheader, "postloop");
1254 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1255 ExitMainLoopAt, PostLoopPreheader);
1256 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1260 BasicBlock *NewMainLoopPreheader =
1261 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1262 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1263 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1264 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1266 // Some of the above may be nullptr, filter them out before passing to
1267 // addToParentLoopIfNeeded.
1269 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1271 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1272 addToParentLoopIfNeeded(PreLoop.Blocks);
1273 addToParentLoopIfNeeded(PostLoop.Blocks);
1278 /// Computes and returns a range of values for the induction variable (IndVar)
1279 /// in which the range check can be safely elided. If it cannot compute such a
1280 /// range, returns None.
1281 Optional<InductiveRangeCheck::Range>
1282 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1283 const SCEVAddRecExpr *IndVar,
1284 IRBuilder<> &) const {
1285 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1286 // variable, that may or may not exist as a real llvm::Value in the loop) and
1287 // this inductive range check is a range check on the "C + D * I" ("C" is
1288 // getOffset() and "D" is getScale()). We rewrite the value being range
1289 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1290 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1291 // can be generalized as needed.
1293 // The actual inequalities we solve are of the form
1295 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1297 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1298 // and subtractions are twos-complement wrapping and comparisons are signed.
1302 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1303 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1304 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1307 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1308 // Hence 0 <= (IndVar + M) < L
1310 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1311 // 127, IndVar = 126 and L = -2 in an i8 world.
1313 if (!IndVar->isAffine())
1316 const SCEV *A = IndVar->getStart();
1317 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1321 const SCEV *C = getOffset();
1322 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1326 ConstantInt *ConstD = D->getValue();
1327 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1330 const SCEV *M = SE.getMinusSCEV(C, A);
1332 const SCEV *Begin = SE.getNegativeSCEV(M);
1333 const SCEV *UpperLimit = nullptr;
1335 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1336 // We can potentially do much better here.
1337 if (Value *V = getLength()) {
1338 UpperLimit = SE.getSCEV(V);
1340 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1341 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1342 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1345 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1346 return InductiveRangeCheck::Range(Begin, End);
1349 static Optional<InductiveRangeCheck::Range>
1350 IntersectRange(ScalarEvolution &SE,
1351 const Optional<InductiveRangeCheck::Range> &R1,
1352 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1355 auto &R1Value = R1.getValue();
1357 // TODO: we could widen the smaller range and have this work; but for now we
1358 // bail out to keep things simple.
1359 if (R1Value.getType() != R2.getType())
1362 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1363 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1365 return InductiveRangeCheck::Range(NewBegin, NewEnd);
1368 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1369 if (L->getBlocks().size() >= LoopSizeCutoff) {
1370 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1374 BasicBlock *Preheader = L->getLoopPreheader();
1376 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1380 LLVMContext &Context = Preheader->getContext();
1381 InductiveRangeCheck::AllocatorTy IRCAlloc;
1382 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1383 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1384 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
1386 for (auto BBI : L->getBlocks())
1387 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1388 if (InductiveRangeCheck *IRC =
1389 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1390 RangeChecks.push_back(IRC);
1392 if (RangeChecks.empty())
1395 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1396 dbgs() << "irce: loop has " << RangeChecks.size()
1397 << " inductive range checks: \n";
1398 for (InductiveRangeCheck *IRC : RangeChecks)
1402 const char *FailureReason = nullptr;
1403 Optional<LoopStructure> MaybeLoopStructure =
1404 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1405 if (!MaybeLoopStructure.hasValue()) {
1406 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1410 LoopStructure LS = MaybeLoopStructure.getValue();
1411 bool Increasing = LS.IndVarIncreasing;
1412 const SCEV *MinusOne =
1413 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1414 const SCEVAddRecExpr *IndVar =
1415 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1417 Optional<InductiveRangeCheck::Range> SafeIterRange;
1418 Instruction *ExprInsertPt = Preheader->getTerminator();
1420 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1422 IRBuilder<> B(ExprInsertPt);
1423 for (InductiveRangeCheck *IRC : RangeChecks) {
1424 auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
1425 if (Result.hasValue()) {
1426 auto MaybeSafeIterRange =
1427 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
1428 if (MaybeSafeIterRange.hasValue()) {
1429 RangeChecksToEliminate.push_back(IRC);
1430 SafeIterRange = MaybeSafeIterRange.getValue();
1435 if (!SafeIterRange.hasValue())
1438 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1439 SE, SafeIterRange.getValue());
1440 bool Changed = LC.run();
1443 auto PrintConstrainedLoopInfo = [L]() {
1444 dbgs() << "irce: in function ";
1445 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1446 dbgs() << "constrained ";
1450 DEBUG(PrintConstrainedLoopInfo());
1452 if (PrintChangedLoops)
1453 PrintConstrainedLoopInfo();
1455 // Optimize away the now-redundant range checks.
1457 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1458 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1459 ? ConstantInt::getTrue(Context)
1460 : ConstantInt::getFalse(Context);
1461 IRC->getBranch()->setCondition(FoldedRangeCheck);
1468 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1469 return new InductiveRangeCheckElimination;