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/InstructionSimplify.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Analysis/ScalarEvolution.h"
50 #include "llvm/Analysis/ScalarEvolutionExpander.h"
51 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
52 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/PatternMatch.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/IR/Verifier.h"
63 #include "llvm/Support/Debug.h"
65 #include "llvm/Transforms/Scalar.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Cloning.h"
68 #include "llvm/Transforms/Utils/LoopUtils.h"
69 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
70 #include "llvm/Transforms/Utils/UnrollLoop.h"
72 #include "llvm/Pass.h"
78 cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
81 cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
84 #define DEBUG_TYPE "irce"
88 /// An inductive range check is conditional branch in a loop with
90 /// 1. a very cold successor (i.e. the branch jumps to that successor very
95 /// 2. a condition that is provably true for some range of values taken by the
96 /// containing loop's induction variable.
98 /// Currently all inductive range checks are branches conditional on an
99 /// expression of the form
101 /// 0 <= (Offset + Scale * I) < Length
103 /// where `I' is the canonical induction variable of a loop to which Offset and
104 /// Scale are loop invariant, and Length is >= 0. Currently the 'false' branch
105 /// is considered cold, looking at profiling data to verify that is a TODO.
107 class InductiveRangeCheck {
113 InductiveRangeCheck() :
114 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
117 const SCEV *getOffset() const { return Offset; }
118 const SCEV *getScale() const { return Scale; }
119 Value *getLength() const { return Length; }
121 void print(raw_ostream &OS) const {
122 OS << "InductiveRangeCheck:\n";
130 getBranch()->print(OS);
133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
139 BranchInst *getBranch() const { return Branch; }
141 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
142 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
149 Range(Value *Begin, Value *End) : Begin(Begin), End(End) {
150 assert(Begin->getType() == End->getType() && "ill-typed range!");
153 Type *getType() const { return Begin->getType(); }
154 Value *getBegin() const { return Begin; }
155 Value *getEnd() const { return End; }
158 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
160 /// This is the value the condition of the branch needs to evaluate to for the
161 /// branch to take the hot successor (see (1) above).
162 bool getPassingDirection() { return true; }
164 /// Computes a range for the induction variable in which the range check is
165 /// redundant and can be constant-folded away.
166 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
167 IRBuilder<> &B) const;
169 /// Create an inductive range check out of BI if possible, else return
171 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
172 Loop *L, ScalarEvolution &SE);
175 class InductiveRangeCheckElimination : public LoopPass {
176 InductiveRangeCheck::AllocatorTy Allocator;
180 InductiveRangeCheckElimination() : LoopPass(ID) {
181 initializeInductiveRangeCheckEliminationPass(
182 *PassRegistry::getPassRegistry());
185 void getAnalysisUsage(AnalysisUsage &AU) const override {
186 AU.addRequired<LoopInfoWrapperPass>();
187 AU.addRequiredID(LoopSimplifyID);
188 AU.addRequiredID(LCSSAID);
189 AU.addRequired<ScalarEvolution>();
192 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
195 char InductiveRangeCheckElimination::ID = 0;
198 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
199 "Inductive range check elimination", false, false)
201 static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) {
202 using namespace llvm::PatternMatch;
204 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
205 Value *LHS = nullptr, *RHS = nullptr;
207 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
214 case ICmpInst::ICMP_SLE:
217 case ICmpInst::ICMP_SGE:
218 if (!match(RHS, m_ConstantInt<0>()))
223 case ICmpInst::ICMP_SLT:
226 case ICmpInst::ICMP_SGT:
227 if (!match(RHS, m_ConstantInt<-1>()))
234 static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) {
235 using namespace llvm::PatternMatch;
237 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
238 Value *LHS = nullptr, *RHS = nullptr;
240 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
247 case ICmpInst::ICMP_SGT:
250 case ICmpInst::ICMP_SLT:
256 case ICmpInst::ICMP_UGT:
259 case ICmpInst::ICMP_ULT:
267 /// Split a condition into something semantically equivalent to (0 <= I <
268 /// Limit), both comparisons signed and Len loop invariant on L and positive.
269 /// On success, return true and set Index to I and UpperLimit to Limit. Return
270 /// false on failure (we may still write to UpperLimit and Index on failure).
271 /// It does not try to interpret I as a loop index.
273 static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE,
274 Value *Condition, const SCEV *&Index,
275 Value *&UpperLimit) {
277 // TODO: currently this catches some silly cases like comparing "%idx slt 1".
278 // Our transformations are still correct, but less likely to be profitable in
279 // those cases. We have to come up with some heuristics that pick out the
280 // range checks that are more profitable to clone a loop for. This function
281 // in general can be made more robust.
283 using namespace llvm::PatternMatch;
287 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
289 // In these early checks we assume that the matched UpperLimit is positive.
290 // We'll verify that fact later, before returning true.
292 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
293 Value *IndexV = nullptr;
294 Value *ExpectedUpperBoundCheck = nullptr;
296 if (IsLowerBoundCheck(A, IndexV))
297 ExpectedUpperBoundCheck = B;
298 else if (IsLowerBoundCheck(B, IndexV))
299 ExpectedUpperBoundCheck = A;
303 if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit))
306 Index = SE.getSCEV(IndexV);
308 if (isa<SCEVCouldNotCompute>(Index))
311 } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
316 case ICmpInst::ICMP_SGT:
319 case ICmpInst::ICMP_SLT:
321 Index = SE.getSCEV(A);
322 if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index))
326 case ICmpInst::ICMP_UGT:
329 case ICmpInst::ICMP_ULT:
331 Index = SE.getSCEV(A);
332 if (isa<SCEVCouldNotCompute>(Index))
340 const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit);
341 if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) ||
342 !SE.isKnownNonNegative(UpperLimitSCEV))
345 if (SE.getLoopDisposition(UpperLimitSCEV, L) !=
346 ScalarEvolution::LoopInvariant) {
347 DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName()
349 dbgs() << " UpperLimit is not loop invariant: "
350 << UpperLimit->getName() << "\n";);
357 InductiveRangeCheck *
358 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
359 Loop *L, ScalarEvolution &SE) {
361 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
364 Value *Length = nullptr;
365 const SCEV *IndexSCEV = nullptr;
367 if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length))
370 assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!");
372 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
374 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
379 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
380 IRC->Length = Length;
381 IRC->Offset = IndexAddRec->getStart();
382 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
387 static Value *MaybeSimplify(Value *V) {
388 if (Instruction *I = dyn_cast<Instruction>(V))
389 if (Value *Simplified = SimplifyInstruction(I))
394 static Value *ConstructSMinOf(Value *X, Value *Y, IRBuilder<> &B) {
395 return MaybeSimplify(B.CreateSelect(B.CreateICmpSLT(X, Y), X, Y));
398 static Value *ConstructSMaxOf(Value *X, Value *Y, IRBuilder<> &B) {
399 return MaybeSimplify(B.CreateSelect(B.CreateICmpSGT(X, Y), X, Y));
404 /// This class is used to constrain loops to run within a given iteration space.
405 /// The algorithm this class implements is given a Loop and a range [Begin,
406 /// End). The algorithm then tries to break out a "main loop" out of the loop
407 /// it is given in a way that the "main loop" runs with the induction variable
408 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
409 /// loops to run any remaining iterations. The pre loop runs any iterations in
410 /// which the induction variable is < Begin, and the post loop runs any
411 /// iterations in which the induction variable is >= End.
413 class LoopConstrainer {
415 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
416 // except that it is more lightweight and can track the state of a loop
417 // through changing and potentially invalid IR. This structure also
418 // formalizes the kinds of loops we can deal with -- ones that have a single
419 // latch that is also an exiting block *and* have a canonical induction
421 struct LoopStructure {
427 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
428 // successor is `LatchExit', the exit block of the loop.
430 BasicBlock *LatchExit;
431 unsigned LatchBrExitIdx;
433 // The canonical induction variable. It's value is `CIVStart` on the 0th
434 // itertion and `CIVNext` for all iterations after that.
439 LoopStructure() : Tag(""), Header(nullptr), Latch(nullptr),
440 LatchBr(nullptr), LatchExit(nullptr),
441 LatchBrExitIdx(-1), CIV(nullptr),
442 CIVStart(nullptr), CIVNext(nullptr) { }
444 template <typename M> LoopStructure map(M Map) const {
445 LoopStructure Result;
447 Result.Header = cast<BasicBlock>(Map(Header));
448 Result.Latch = cast<BasicBlock>(Map(Latch));
449 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
450 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
451 Result.LatchBrExitIdx = LatchBrExitIdx;
452 Result.CIV = cast<PHINode>(Map(CIV));
453 Result.CIVNext = Map(CIVNext);
454 Result.CIVStart = Map(CIVStart);
459 // The representation of a clone of the original loop we started out with.
462 std::vector<BasicBlock *> Blocks;
464 // `Map` maps values in the clonee into values in the cloned version
465 ValueToValueMapTy Map;
467 // An instance of `LoopStructure` for the cloned loop
468 LoopStructure Structure;
471 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
472 // more details on what these fields mean.
473 struct RewrittenRangeInfo {
474 BasicBlock *PseudoExit;
475 BasicBlock *ExitSelector;
476 std::vector<PHINode *> PHIValuesAtPseudoExit;
478 RewrittenRangeInfo() : PseudoExit(nullptr), ExitSelector(nullptr) { }
481 // Calculated subranges we restrict the iteration space of the main loop to.
482 // See the implementation of `calculateSubRanges' for more details on how
483 // these fields are computed. `ExitPreLoopAt' is `None' if we don't need a
484 // pre loop. `ExitMainLoopAt' is `None' if we don't need a post loop.
486 Optional<Value *> ExitPreLoopAt;
487 Optional<Value *> ExitMainLoopAt;
490 // A utility function that does a `replaceUsesOfWith' on the incoming block
491 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
492 // incoming block list with `ReplaceBy'.
493 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
494 BasicBlock *ReplaceBy);
496 // Try to "parse" `OriginalLoop' and populate the various out parameters.
497 // Returns true on success, false on failure.
499 bool recognizeLoop(LoopStructure &LoopStructureOut,
500 const SCEV *&LatchCountOut, BasicBlock *&PreHeaderOut,
501 const char *&FailureReasonOut) const;
503 // Compute a safe set of limits for the main loop to run in -- effectively the
504 // intersection of `Range' and the iteration space of the original loop.
505 // Return the header count (1 + the latch taken count) in `HeaderCount'.
506 // Return None if unable to compute the set of subranges.
508 Optional<SubRanges> calculateSubRanges(Value *&HeaderCount) const;
510 // Clone `OriginalLoop' and return the result in CLResult. The IR after
511 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
512 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
513 // but there is no such edge.
515 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
517 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
518 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
519 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
520 // `OriginalHeaderCount'.
522 // If there are iterations left to execute, control is made to jump to
523 // `ContinuationBlock', otherwise they take the normal loop exit. The
524 // returned `RewrittenRangeInfo' object is populated as follows:
526 // .PseudoExit is a basic block that unconditionally branches to
527 // `ContinuationBlock'.
529 // .ExitSelector is a basic block that decides, on exit from the loop,
530 // whether to branch to the "true" exit or to `PseudoExit'.
532 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
533 // for each PHINode in the loop header on taking the pseudo exit.
535 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
536 // preheader because it is made to branch to the loop header only
540 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
542 BasicBlock *ContinuationBlock) const;
544 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
545 // function creates a new preheader for `LS' and returns it.
547 BasicBlock *createPreheader(const LoopConstrainer::LoopStructure &LS,
548 BasicBlock *OldPreheader, const char *Tag) const;
550 // `ContinuationBlockAndPreheader' was the continuation block for some call to
551 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
552 // This function rewrites the PHI nodes in `LS.Header' to start with the
554 void rewriteIncomingValuesForPHIs(
555 LoopConstrainer::LoopStructure &LS,
556 BasicBlock *ContinuationBlockAndPreheader,
557 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
559 // Even though we do not preserve any passes at this time, we at least need to
560 // keep the parent loop structure consistent. The `LPPassManager' seems to
561 // verify this after running a loop pass. This function adds the list of
562 // blocks denoted by the iterator range [BlocksBegin, BlocksEnd) to this loops
563 // parent loop if required.
564 template<typename IteratorTy>
565 void addToParentLoopIfNeeded(IteratorTy BlocksBegin, IteratorTy BlocksEnd);
567 // Some global state.
572 // Information about the original loop we started out with.
574 LoopInfo &OriginalLoopInfo;
575 const SCEV *LatchTakenCount;
576 BasicBlock *OriginalPreheader;
577 Value *OriginalHeaderCount;
579 // The preheader of the main loop. This may or may not be different from
580 // `OriginalPreheader'.
581 BasicBlock *MainLoopPreheader;
583 // The range we need to run the main loop in.
584 InductiveRangeCheck::Range Range;
586 // The structure of the main loop (see comment at the beginning of this class
588 LoopStructure MainLoopStructure;
591 LoopConstrainer(Loop &L, LoopInfo &LI, ScalarEvolution &SE,
592 InductiveRangeCheck::Range R)
593 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
594 OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
595 OriginalPreheader(nullptr), OriginalHeaderCount(nullptr),
596 MainLoopPreheader(nullptr), Range(R) { }
598 // Entry point for the algorithm. Returns true on success.
604 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
605 BasicBlock *ReplaceBy) {
606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
607 if (PN->getIncomingBlock(i) == Block)
608 PN->setIncomingBlock(i, ReplaceBy);
611 bool LoopConstrainer::recognizeLoop(LoopStructure &LoopStructureOut,
612 const SCEV *&LatchCountOut,
613 BasicBlock *&PreheaderOut,
614 const char *&FailureReason) const {
615 using namespace llvm::PatternMatch;
617 assert(OriginalLoop.isLoopSimplifyForm() &&
618 "should follow from addRequired<>");
620 BasicBlock *Latch = OriginalLoop.getLoopLatch();
621 if (!OriginalLoop.isLoopExiting(Latch)) {
622 FailureReason = "no loop latch";
626 PHINode *CIV = OriginalLoop.getCanonicalInductionVariable();
628 FailureReason = "no CIV";
632 BasicBlock *Header = OriginalLoop.getHeader();
633 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
635 FailureReason = "no preheader";
639 Value *CIVNext = CIV->getIncomingValueForBlock(Latch);
640 Value *CIVStart = CIV->getIncomingValueForBlock(Preheader);
642 const SCEV *LatchCount = SE.getExitCount(&OriginalLoop, Latch);
643 if (isa<SCEVCouldNotCompute>(LatchCount)) {
644 FailureReason = "could not compute latch count";
648 // While SCEV does most of the analysis for us, we still have to
649 // modify the latch; and currently we can only deal with certain
650 // kinds of latches. This can be made more sophisticated as needed.
652 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
654 if (!LatchBr || LatchBr->isUnconditional()) {
655 FailureReason = "latch terminator not conditional branch";
659 // Currently we only support a latch condition of the form:
661 // %condition = icmp slt %civNext, %limit
662 // br i1 %condition, label %header, label %exit
664 if (LatchBr->getSuccessor(0) != Header) {
665 FailureReason = "unknown latch form (header not first successor)";
669 Value *CIVComparedTo = nullptr;
670 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
671 if (!(match(LatchBr->getCondition(),
672 m_ICmp(Pred, m_Specific(CIVNext), m_Value(CIVComparedTo))) &&
673 Pred == ICmpInst::ICMP_SLT)) {
674 FailureReason = "unknown latch form (not slt)";
678 // IndVarSimplify will sometimes leave behind (in SCEV's cache) backedge-taken
679 // counts that are narrower than the canonical induction variable. These
680 // values are still accurate, and we could probably use them after sign/zero
681 // extension; but for now we just bail out of the transformation to keep
683 const SCEV *CIVComparedToSCEV = SE.getSCEV(CIVComparedTo);
684 if (isa<SCEVCouldNotCompute>(CIVComparedToSCEV) ||
685 CIVComparedToSCEV->getType() != LatchCount->getType()) {
686 FailureReason = "could not relate CIV to latch expression";
690 const SCEV *ShouldBeOne = SE.getMinusSCEV(CIVComparedToSCEV, LatchCount);
691 const SCEVConstant *SCEVOne = dyn_cast<SCEVConstant>(ShouldBeOne);
692 if (!SCEVOne || SCEVOne->getValue()->getValue() != 1) {
693 FailureReason = "unexpected header count in latch";
697 unsigned LatchBrExitIdx = 1;
698 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
700 assert(SE.getLoopDisposition(LatchCount, &OriginalLoop) ==
701 ScalarEvolution::LoopInvariant &&
702 "loop variant exit count doesn't make sense!");
704 assert(!OriginalLoop.contains(LatchExit) && "expected an exit block!");
706 LoopStructureOut.Tag = "main";
707 LoopStructureOut.Header = Header;
708 LoopStructureOut.Latch = Latch;
709 LoopStructureOut.LatchBr = LatchBr;
710 LoopStructureOut.LatchExit = LatchExit;
711 LoopStructureOut.LatchBrExitIdx = LatchBrExitIdx;
712 LoopStructureOut.CIV = CIV;
713 LoopStructureOut.CIVNext = CIVNext;
714 LoopStructureOut.CIVStart = CIVStart;
716 LatchCountOut = LatchCount;
717 PreheaderOut = Preheader;
718 FailureReason = nullptr;
723 Optional<LoopConstrainer::SubRanges>
724 LoopConstrainer::calculateSubRanges(Value *&HeaderCountOut) const {
725 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
727 if (Range.getType() != Ty)
730 SCEVExpander Expander(SE, "irce");
731 Instruction *InsertPt = OriginalPreheader->getTerminator();
734 MaybeSimplify(Expander.expandCodeFor(LatchTakenCount, Ty, InsertPt));
736 IRBuilder<> B(InsertPt);
738 LoopConstrainer::SubRanges Result;
740 // I think we can be more aggressive here and make this nuw / nsw if the
741 // addition that feeds into the icmp for the latch's terminating branch is nuw
742 // / nsw. In any case, a wrapping 2's complement addition is safe.
743 ConstantInt *One = ConstantInt::get(Ty, 1);
744 HeaderCountOut = MaybeSimplify(B.CreateAdd(LatchCountV, One, "header.count"));
746 const SCEV *RangeBegin = SE.getSCEV(Range.getBegin());
747 const SCEV *RangeEnd = SE.getSCEV(Range.getEnd());
748 const SCEV *HeaderCountSCEV = SE.getSCEV(HeaderCountOut);
749 const SCEV *Zero = SE.getConstant(Ty, 0);
751 // In some cases we can prove that we don't need a pre or post loop
753 bool ProvablyNoPreloop =
754 SE.isKnownPredicate(ICmpInst::ICMP_SLE, RangeBegin, Zero);
755 if (!ProvablyNoPreloop)
756 Result.ExitPreLoopAt = ConstructSMinOf(HeaderCountOut, Range.getBegin(), B);
758 bool ProvablyNoPostLoop =
759 SE.isKnownPredicate(ICmpInst::ICMP_SLE, HeaderCountSCEV, RangeEnd);
760 if (!ProvablyNoPostLoop)
761 Result.ExitMainLoopAt = ConstructSMinOf(HeaderCountOut, Range.getEnd(), B);
766 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
767 const char *Tag) const {
768 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
769 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
770 Result.Blocks.push_back(Clone);
771 Result.Map[BB] = Clone;
774 auto GetClonedValue = [&Result](Value *V) {
775 assert(V && "null values not in domain!");
776 auto It = Result.Map.find(V);
777 if (It == Result.Map.end())
779 return static_cast<Value *>(It->second);
782 Result.Structure = MainLoopStructure.map(GetClonedValue);
783 Result.Structure.Tag = Tag;
785 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
786 BasicBlock *ClonedBB = Result.Blocks[i];
787 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
789 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
791 for (Instruction &I : *ClonedBB)
792 RemapInstruction(&I, Result.Map,
793 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
795 // Exit blocks will now have one more predecessor and their PHI nodes need
796 // to be edited to reflect that. No phi nodes need to be introduced because
797 // the loop is in LCSSA.
799 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
800 SBBI != SBBE; ++SBBI) {
802 if (OriginalLoop.contains(*SBBI))
803 continue; // not an exit block
805 for (Instruction &I : **SBBI) {
806 if (!isa<PHINode>(&I))
809 PHINode *PN = cast<PHINode>(&I);
810 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
811 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
817 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
818 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitLoopAt,
819 BasicBlock *ContinuationBlock) const {
821 // We start with a loop with a single latch:
823 // +--------------------+
827 // +--------+-----------+
828 // | ----------------\
830 // +--------v----v------+ |
834 // +--------------------+ |
838 // +--------------------+ |
840 // | latch >----------/
842 // +-------v------------+
845 // | +--------------------+
847 // +---> original exit |
849 // +--------------------+
851 // We change the control flow to look like
854 // +--------------------+
856 // | preheader >-------------------------+
858 // +--------v-----------+ |
859 // | /-------------+ |
861 // +--------v--v--------+ | |
863 // | header | | +--------+ |
865 // +--------------------+ | | +-----v-----v-----------+
867 // | | | .pseudo.exit |
869 // | | +-----------v-----------+
872 // | | +--------v-------------+
873 // +--------------------+ | | | |
874 // | | | | | ContinuationBlock |
875 // | latch >------+ | | |
876 // | | | +----------------------+
877 // +---------v----------+ |
880 // | +---------------^-----+
882 // +-----> .exit.selector |
884 // +----------v----------+
886 // +--------------------+ |
888 // | original exit <----+
890 // +--------------------+
893 RewrittenRangeInfo RRI;
895 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
896 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
897 &F, BBInsertLocation);
898 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
901 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
903 IRBuilder<> B(PreheaderJump);
905 // EnterLoopCond - is it okay to start executing this `LS'?
906 Value *EnterLoopCond = B.CreateICmpSLT(LS.CIVStart, ExitLoopAt);
907 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
908 PreheaderJump->eraseFromParent();
910 assert(LS.LatchBrExitIdx == 1 && "generalize this as needed!");
912 B.SetInsertPoint(LS.LatchBr);
914 // ContinueCond - is it okay to execute the next iteration in `LS'?
915 Value *ContinueCond = B.CreateICmpSLT(LS.CIVNext, ExitLoopAt);
917 LS.LatchBr->setCondition(ContinueCond);
918 assert(LS.LatchBr->getSuccessor(LS.LatchBrExitIdx) == LS.LatchExit &&
920 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
922 B.SetInsertPoint(RRI.ExitSelector);
924 // IterationsLeft - are there any more iterations left, given the original
925 // upper bound on the induction variable? If not, we branch to the "real"
927 Value *IterationsLeft = B.CreateICmpSLT(LS.CIVNext, OriginalHeaderCount);
928 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
930 BranchInst *BranchToContinuation =
931 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
933 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
934 // each of the PHI nodes in the loop header. This feeds into the initial
935 // value of the same PHI nodes if/when we continue execution.
936 for (Instruction &I : *LS.Header) {
937 if (!isa<PHINode>(&I))
940 PHINode *PN = cast<PHINode>(&I);
942 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
943 BranchToContinuation);
945 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
946 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
948 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
951 // The latch exit now has a branch from `RRI.ExitSelector' instead of
952 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
953 for (Instruction &I : *LS.LatchExit) {
954 if (PHINode *PN = dyn_cast<PHINode>(&I))
955 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
963 void LoopConstrainer::rewriteIncomingValuesForPHIs(
964 LoopConstrainer::LoopStructure &LS, BasicBlock *ContinuationBlock,
965 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
967 unsigned PHIIndex = 0;
968 for (Instruction &I : *LS.Header) {
969 if (!isa<PHINode>(&I))
972 PHINode *PN = cast<PHINode>(&I);
974 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
975 if (PN->getIncomingBlock(i) == ContinuationBlock)
976 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
979 LS.CIVStart = LS.CIV->getIncomingValueForBlock(ContinuationBlock);
983 LoopConstrainer::createPreheader(const LoopConstrainer::LoopStructure &LS,
984 BasicBlock *OldPreheader,
985 const char *Tag) const {
987 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
988 BranchInst::Create(LS.Header, Preheader);
990 for (Instruction &I : *LS.Header) {
991 if (!isa<PHINode>(&I))
994 PHINode *PN = cast<PHINode>(&I);
995 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
996 replacePHIBlock(PN, OldPreheader, Preheader);
1002 template<typename IteratorTy>
1003 void LoopConstrainer::addToParentLoopIfNeeded(IteratorTy Begin,
1005 Loop *ParentLoop = OriginalLoop.getParentLoop();
1009 for (; Begin != End; Begin++)
1010 ParentLoop->addBasicBlockToLoop(*Begin, OriginalLoopInfo);
1013 bool LoopConstrainer::run() {
1014 BasicBlock *Preheader = nullptr;
1015 const char *CouldNotProceedBecause = nullptr;
1016 if (!recognizeLoop(MainLoopStructure, LatchTakenCount, Preheader,
1017 CouldNotProceedBecause)) {
1018 DEBUG(dbgs() << "irce: could not recognize loop, " << CouldNotProceedBecause
1023 OriginalPreheader = Preheader;
1024 MainLoopPreheader = Preheader;
1026 Optional<SubRanges> MaybeSR = calculateSubRanges(OriginalHeaderCount);
1027 if (!MaybeSR.hasValue()) {
1028 DEBUG(dbgs() << "irce: could not compute subranges\n");
1031 SubRanges SR = MaybeSR.getValue();
1033 // It would have been better to make `PreLoop' and `PostLoop'
1034 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1036 ClonedLoop PreLoop, PostLoop;
1037 bool NeedsPreLoop = SR.ExitPreLoopAt.hasValue();
1038 bool NeedsPostLoop = SR.ExitMainLoopAt.hasValue();
1040 // We clone these ahead of time so that we don't have to deal with changing
1041 // and temporarily invalid IR as we transform the loops.
1043 cloneLoop(PreLoop, "preloop");
1045 cloneLoop(PostLoop, "postloop");
1047 RewrittenRangeInfo PreLoopRRI;
1050 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1051 PreLoop.Structure.Header);
1054 createPreheader(MainLoopStructure, Preheader, "mainloop");
1056 changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1057 SR.ExitPreLoopAt.getValue(), MainLoopPreheader);
1058 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1062 BasicBlock *PostLoopPreheader = nullptr;
1063 RewrittenRangeInfo PostLoopRRI;
1065 if (NeedsPostLoop) {
1067 createPreheader(PostLoop.Structure, Preheader, "postloop");
1068 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1069 SR.ExitMainLoopAt.getValue(),
1071 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1075 SmallVector<BasicBlock *, 6> NewBlocks;
1076 NewBlocks.push_back(PostLoopPreheader);
1077 NewBlocks.push_back(PreLoopRRI.PseudoExit);
1078 NewBlocks.push_back(PreLoopRRI.ExitSelector);
1079 NewBlocks.push_back(PostLoopRRI.PseudoExit);
1080 NewBlocks.push_back(PostLoopRRI.ExitSelector);
1081 if (MainLoopPreheader != Preheader)
1082 NewBlocks.push_back(MainLoopPreheader);
1084 // Some of the above may be nullptr, filter them out before passing to
1085 // addToParentLoopIfNeeded.
1086 auto NewBlocksEnd = std::remove(NewBlocks.begin(), NewBlocks.end(), nullptr);
1088 typedef SmallVector<BasicBlock *, 6>::iterator SmallVectItTy;
1089 typedef std::vector<BasicBlock *>::iterator StdVectItTy;
1091 addToParentLoopIfNeeded<SmallVectItTy>(NewBlocks.begin(), NewBlocksEnd);
1092 addToParentLoopIfNeeded<StdVectItTy>(PreLoop.Blocks.begin(),
1093 PreLoop.Blocks.end());
1094 addToParentLoopIfNeeded<StdVectItTy>(PostLoop.Blocks.begin(),
1095 PostLoop.Blocks.end());
1100 /// Computes and returns a range of values for the induction variable in which
1101 /// the range check can be safely elided. If it cannot compute such a range,
1103 Optional<InductiveRangeCheck::Range>
1104 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1105 IRBuilder<> &B) const {
1107 // Currently we support inequalities of the form:
1109 // 0 <= Offset + 1 * CIV < L given L >= 0
1111 // The inequality is satisfied by -Offset <= CIV < (L - Offset) [^1]. All
1112 // additions and subtractions are twos-complement wrapping and comparisons are
1117 // If there exists CIV such that -Offset <= CIV < (L - Offset) then it
1118 // follows that -Offset <= (-Offset + L) [== Eq. 1]. Since L >= 0, if
1119 // (-Offset + L) sign-overflows then (-Offset + L) < (-Offset). Hence by
1120 // [Eq. 1], (-Offset + L) could not have overflown.
1122 // This means CIV = t + (-Offset) for t in [0, L). Hence (CIV + Offset) =
1123 // t. Hence 0 <= (CIV + Offset) < L
1125 // [^1]: Note that the solution does _not_ apply if L < 0; consider values
1126 // Offset = 127, CIV = 126 and L = -2 in an i8 world.
1128 const SCEVConstant *ScaleC = dyn_cast<SCEVConstant>(getScale());
1129 if (!(ScaleC && ScaleC->getValue()->getValue() == 1)) {
1130 DEBUG(dbgs() << "irce: could not compute safe iteration space for:\n";
1135 Value *OffsetV = SCEVExpander(SE, "safe.itr.space").expandCodeFor(
1136 getOffset(), getOffset()->getType(), B.GetInsertPoint());
1137 OffsetV = MaybeSimplify(OffsetV);
1139 Value *Begin = MaybeSimplify(B.CreateNeg(OffsetV));
1140 Value *End = MaybeSimplify(B.CreateSub(getLength(), OffsetV));
1142 return InductiveRangeCheck::Range(Begin, End);
1145 static Optional<InductiveRangeCheck::Range>
1146 IntersectRange(const Optional<InductiveRangeCheck::Range> &R1,
1147 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1150 auto &R1Value = R1.getValue();
1152 // TODO: we could widen the smaller range and have this work; but for now we
1153 // bail out to keep things simple.
1154 if (R1Value.getType() != R2.getType())
1157 Value *NewMin = ConstructSMaxOf(R1Value.getBegin(), R2.getBegin(), B);
1158 Value *NewMax = ConstructSMinOf(R1Value.getEnd(), R2.getEnd(), B);
1159 return InductiveRangeCheck::Range(NewMin, NewMax);
1162 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1163 if (L->getBlocks().size() >= LoopSizeCutoff) {
1164 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1168 BasicBlock *Preheader = L->getLoopPreheader();
1170 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1174 LLVMContext &Context = Preheader->getContext();
1175 InductiveRangeCheck::AllocatorTy IRCAlloc;
1176 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1177 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1179 for (auto BBI : L->getBlocks())
1180 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1181 if (InductiveRangeCheck *IRC =
1182 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE))
1183 RangeChecks.push_back(IRC);
1185 if (RangeChecks.empty())
1188 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1189 dbgs() << "irce: loop has " << RangeChecks.size()
1190 << " inductive range checks: \n";
1191 for (InductiveRangeCheck *IRC : RangeChecks)
1195 Optional<InductiveRangeCheck::Range> SafeIterRange;
1196 Instruction *ExprInsertPt = Preheader->getTerminator();
1198 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1200 IRBuilder<> B(ExprInsertPt);
1201 for (InductiveRangeCheck *IRC : RangeChecks) {
1202 auto Result = IRC->computeSafeIterationSpace(SE, B);
1203 if (Result.hasValue()) {
1204 auto MaybeSafeIterRange =
1205 IntersectRange(SafeIterRange, Result.getValue(), B);
1206 if (MaybeSafeIterRange.hasValue()) {
1207 RangeChecksToEliminate.push_back(IRC);
1208 SafeIterRange = MaybeSafeIterRange.getValue();
1213 if (!SafeIterRange.hasValue())
1216 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), SE,
1217 SafeIterRange.getValue());
1218 bool Changed = LC.run();
1221 auto PrintConstrainedLoopInfo = [L]() {
1222 dbgs() << "irce: in function ";
1223 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1224 dbgs() << "constrained ";
1228 DEBUG(PrintConstrainedLoopInfo());
1230 if (PrintChangedLoops)
1231 PrintConstrainedLoopInfo();
1233 // Optimize away the now-redundant range checks.
1235 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1236 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1237 ? ConstantInt::getTrue(Context)
1238 : ConstantInt::getFalse(Context);
1239 IRC->getBranch()->setCondition(FoldedRangeCheck);
1246 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1247 return new InductiveRangeCheckElimination;