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 integer range [Range.first, Range.second). If Range.second
142 /// < Range.first, then the value denotes the empty range.
143 typedef std::pair<Value *, Value *> Range;
144 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
146 /// This is the value the condition of the branch needs to evaluate to for the
147 /// branch to take the hot successor (see (1) above).
148 bool getPassingDirection() { return true; }
150 /// Computes a range for the induction variable in which the range check is
151 /// redundant and can be constant-folded away.
152 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
153 IRBuilder<> &B) const;
155 /// Create an inductive range check out of BI if possible, else return
157 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
158 Loop *L, ScalarEvolution &SE);
161 class InductiveRangeCheckElimination : public LoopPass {
162 InductiveRangeCheck::AllocatorTy Allocator;
166 InductiveRangeCheckElimination() : LoopPass(ID) {
167 initializeInductiveRangeCheckEliminationPass(
168 *PassRegistry::getPassRegistry());
171 void getAnalysisUsage(AnalysisUsage &AU) const override {
172 AU.addRequired<LoopInfo>();
173 AU.addRequiredID(LoopSimplifyID);
174 AU.addRequiredID(LCSSAID);
175 AU.addRequired<ScalarEvolution>();
178 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
181 char InductiveRangeCheckElimination::ID = 0;
184 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
185 "Inductive range check elimination", false, false)
187 static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) {
188 using namespace llvm::PatternMatch;
190 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
191 Value *LHS = nullptr, *RHS = nullptr;
193 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
200 case ICmpInst::ICMP_SLE:
203 case ICmpInst::ICMP_SGE:
204 if (!match(RHS, m_ConstantInt<0>()))
209 case ICmpInst::ICMP_SLT:
212 case ICmpInst::ICMP_SGT:
213 if (!match(RHS, m_ConstantInt<-1>()))
220 static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) {
221 using namespace llvm::PatternMatch;
223 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
224 Value *LHS = nullptr, *RHS = nullptr;
226 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
233 case ICmpInst::ICMP_SGT:
236 case ICmpInst::ICMP_SLT:
242 case ICmpInst::ICMP_UGT:
245 case ICmpInst::ICMP_ULT:
253 /// Split a condition into something semantically equivalent to (0 <= I <
254 /// Limit), both comparisons signed and Len loop invariant on L and positive.
255 /// On success, return true and set Index to I and UpperLimit to Limit. Return
256 /// false on failure (we may still write to UpperLimit and Index on failure).
257 /// It does not try to interpret I as a loop index.
259 static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE,
260 Value *Condition, const SCEV *&Index,
261 Value *&UpperLimit) {
263 // TODO: currently this catches some silly cases like comparing "%idx slt 1".
264 // Our transformations are still correct, but less likely to be profitable in
265 // those cases. We have to come up with some heuristics that pick out the
266 // range checks that are more profitable to clone a loop for. This function
267 // in general can be made more robust.
269 using namespace llvm::PatternMatch;
273 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
275 // In these early checks we assume that the matched UpperLimit is positive.
276 // We'll verify that fact later, before returning true.
278 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
279 Value *IndexV = nullptr;
280 Value *ExpectedUpperBoundCheck = nullptr;
282 if (IsLowerBoundCheck(A, IndexV))
283 ExpectedUpperBoundCheck = B;
284 else if (IsLowerBoundCheck(B, IndexV))
285 ExpectedUpperBoundCheck = A;
289 if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit))
292 Index = SE.getSCEV(IndexV);
294 if (isa<SCEVCouldNotCompute>(Index))
297 } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
302 case ICmpInst::ICMP_SGT:
305 case ICmpInst::ICMP_SLT:
307 Index = SE.getSCEV(A);
308 if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index))
312 case ICmpInst::ICMP_UGT:
315 case ICmpInst::ICMP_ULT:
317 Index = SE.getSCEV(A);
318 if (isa<SCEVCouldNotCompute>(Index))
326 const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit);
327 if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) ||
328 !SE.isKnownNonNegative(UpperLimitSCEV))
331 if (SE.getLoopDisposition(UpperLimitSCEV, L) !=
332 ScalarEvolution::LoopInvariant) {
333 DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName()
335 dbgs() << " UpperLimit is not loop invariant: "
336 << UpperLimit->getName() << "\n";);
343 InductiveRangeCheck *
344 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
345 Loop *L, ScalarEvolution &SE) {
347 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
350 Value *Length = nullptr;
351 const SCEV *IndexSCEV = nullptr;
353 if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length))
356 assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!");
358 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
360 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
365 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
366 IRC->Length = Length;
367 IRC->Offset = IndexAddRec->getStart();
368 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
373 static Value *MaybeSimplify(Value *V) {
374 if (Instruction *I = dyn_cast<Instruction>(V))
375 if (Value *Simplified = SimplifyInstruction(I))
380 static Value *ConstructSMinOf(Value *X, Value *Y, IRBuilder<> &B) {
381 return MaybeSimplify(B.CreateSelect(B.CreateICmpSLT(X, Y), X, Y));
384 static Value *ConstructSMaxOf(Value *X, Value *Y, IRBuilder<> &B) {
385 return MaybeSimplify(B.CreateSelect(B.CreateICmpSGT(X, Y), X, Y));
390 /// This class is used to constrain loops to run within a given iteration space.
391 /// The algorithm this class implements is given a Loop and a range [Begin,
392 /// End). The algorithm then tries to break out a "main loop" out of the loop
393 /// it is given in a way that the "main loop" runs with the induction variable
394 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
395 /// loops to run any remaining iterations. The pre loop runs any iterations in
396 /// which the induction variable is < Begin, and the post loop runs any
397 /// iterations in which the induction variable is >= End.
399 class LoopConstrainer {
401 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
402 // except that it is more lightweight and can track the state of a loop
403 // through changing and potentially invalid IR. This structure also
404 // formalizes the kinds of loops we can deal with -- ones that have a single
405 // latch that is also an exiting block *and* have a canonical induction
407 struct LoopStructure {
413 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
414 // successor is `LatchExit', the exit block of the loop.
416 BasicBlock *LatchExit;
417 unsigned LatchBrExitIdx;
419 // The canonical induction variable. It's value is `CIVStart` on the 0th
420 // itertion and `CIVNext` for all iterations after that.
425 LoopStructure() : Tag(""), Header(nullptr), Latch(nullptr),
426 LatchBr(nullptr), LatchExit(nullptr),
427 LatchBrExitIdx(-1), CIV(nullptr),
428 CIVStart(nullptr), CIVNext(nullptr) { }
430 template <typename M> LoopStructure map(M Map) const {
431 LoopStructure Result;
433 Result.Header = cast<BasicBlock>(Map(Header));
434 Result.Latch = cast<BasicBlock>(Map(Latch));
435 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
436 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
437 Result.LatchBrExitIdx = LatchBrExitIdx;
438 Result.CIV = cast<PHINode>(Map(CIV));
439 Result.CIVNext = Map(CIVNext);
440 Result.CIVStart = Map(CIVStart);
445 // The representation of a clone of the original loop we started out with.
448 std::vector<BasicBlock *> Blocks;
450 // `Map` maps values in the clonee into values in the cloned version
451 ValueToValueMapTy Map;
453 // An instance of `LoopStructure` for the cloned loop
454 LoopStructure Structure;
457 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
458 // more details on what these fields mean.
459 struct RewrittenRangeInfo {
460 BasicBlock *PseudoExit;
461 BasicBlock *ExitSelector;
462 std::vector<PHINode *> PHIValuesAtPseudoExit;
464 RewrittenRangeInfo() : PseudoExit(nullptr), ExitSelector(nullptr) { }
467 // Calculated subranges we restrict the iteration space of the main loop to.
468 // See the implementation of `calculateSubRanges' for more details on how
469 // these fields are computed. `ExitPreLoopAt' is `None' if we don't need a
470 // pre loop. `ExitMainLoopAt' is `None' if we don't need a post loop.
472 Optional<Value *> ExitPreLoopAt;
473 Optional<Value *> ExitMainLoopAt;
476 // A utility function that does a `replaceUsesOfWith' on the incoming block
477 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
478 // incoming block list with `ReplaceBy'.
479 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
480 BasicBlock *ReplaceBy);
482 // Try to "parse" `OriginalLoop' and populate the various out parameters.
483 // Returns true on success, false on failure.
485 bool recognizeLoop(LoopStructure &LoopStructureOut,
486 const SCEV *&LatchCountOut, BasicBlock *&PreHeaderOut,
487 const char *&FailureReasonOut) const;
489 // Compute a safe set of limits for the main loop to run in -- effectively the
490 // intersection of `Range' and the iteration space of the original loop.
491 // Return the header count (1 + the latch taken count) in `HeaderCount'.
493 SubRanges calculateSubRanges(Value *&HeaderCount) const;
495 // Clone `OriginalLoop' and return the result in CLResult. The IR after
496 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
497 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
498 // but there is no such edge.
500 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
502 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
503 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
504 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
505 // `OriginalHeaderCount'.
507 // If there are iterations left to execute, control is made to jump to
508 // `ContinuationBlock', otherwise they take the normal loop exit. The
509 // returned `RewrittenRangeInfo' object is populated as follows:
511 // .PseudoExit is a basic block that unconditionally branches to
512 // `ContinuationBlock'.
514 // .ExitSelector is a basic block that decides, on exit from the loop,
515 // whether to branch to the "true" exit or to `PseudoExit'.
517 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
518 // for each PHINode in the loop header on taking the pseudo exit.
520 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
521 // preheader because it is made to branch to the loop header only
525 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
527 BasicBlock *ContinuationBlock) const;
529 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
530 // function creates a new preheader for `LS' and returns it.
532 BasicBlock *createPreheader(const LoopConstrainer::LoopStructure &LS,
533 BasicBlock *OldPreheader, const char *Tag) const;
535 // `ContinuationBlockAndPreheader' was the continuation block for some call to
536 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
537 // This function rewrites the PHI nodes in `LS.Header' to start with the
539 void rewriteIncomingValuesForPHIs(
540 LoopConstrainer::LoopStructure &LS,
541 BasicBlock *ContinuationBlockAndPreheader,
542 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
544 // Even though we do not preserve any passes at this time, we at least need to
545 // keep the parent loop structure consistent. The `LPPassManager' seems to
546 // verify this after running a loop pass. This function adds the list of
547 // blocks denoted by the iterator range [BlocksBegin, BlocksEnd) to this loops
548 // parent loop if required.
549 template<typename IteratorTy>
550 void addToParentLoopIfNeeded(IteratorTy BlocksBegin, IteratorTy BlocksEnd);
552 // Some global state.
557 // Information about the original loop we started out with.
559 LoopInfo &OriginalLoopInfo;
560 const SCEV *LatchTakenCount;
561 BasicBlock *OriginalPreheader;
562 Value *OriginalHeaderCount;
564 // The preheader of the main loop. This may or may not be different from
565 // `OriginalPreheader'.
566 BasicBlock *MainLoopPreheader;
568 // The range we need to run the main loop in.
569 InductiveRangeCheck::Range Range;
571 // The structure of the main loop (see comment at the beginning of this class
573 LoopStructure MainLoopStructure;
576 LoopConstrainer(Loop &L, LoopInfo &LI, ScalarEvolution &SE,
577 InductiveRangeCheck::Range R)
578 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
579 OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
580 OriginalPreheader(nullptr), OriginalHeaderCount(nullptr),
581 MainLoopPreheader(nullptr), Range(R) { }
583 // Entry point for the algorithm. Returns true on success.
589 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
590 BasicBlock *ReplaceBy) {
591 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
592 if (PN->getIncomingBlock(i) == Block)
593 PN->setIncomingBlock(i, ReplaceBy);
596 bool LoopConstrainer::recognizeLoop(LoopStructure &LoopStructureOut,
597 const SCEV *&LatchCountOut,
598 BasicBlock *&PreheaderOut,
599 const char *&FailureReason) const {
600 using namespace llvm::PatternMatch;
602 assert(OriginalLoop.isLoopSimplifyForm() &&
603 "should follow from addRequired<>");
605 BasicBlock *Latch = OriginalLoop.getLoopLatch();
606 if (!OriginalLoop.isLoopExiting(Latch)) {
607 FailureReason = "no loop latch";
611 PHINode *CIV = OriginalLoop.getCanonicalInductionVariable();
613 FailureReason = "no CIV";
617 BasicBlock *Header = OriginalLoop.getHeader();
618 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
620 FailureReason = "no preheader";
624 Value *CIVNext = CIV->getIncomingValueForBlock(Latch);
625 Value *CIVStart = CIV->getIncomingValueForBlock(Preheader);
627 const SCEV *LatchCount = SE.getExitCount(&OriginalLoop, Latch);
628 if (isa<SCEVCouldNotCompute>(LatchCount)) {
629 FailureReason = "could not compute latch count";
633 // While SCEV does most of the analysis for us, we still have to
634 // modify the latch; and currently we can only deal with certain
635 // kinds of latches. This can be made more sophisticated as needed.
637 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
639 if (!LatchBr || LatchBr->isUnconditional()) {
640 FailureReason = "latch terminator not conditional branch";
644 // Currently we only support a latch condition of the form:
646 // %condition = icmp slt %civNext, %limit
647 // br i1 %condition, label %header, label %exit
649 if (LatchBr->getSuccessor(0) != Header) {
650 FailureReason = "unknown latch form (header not first successor)";
654 Value *CIVComparedTo = nullptr;
655 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
656 if (!(match(LatchBr->getCondition(),
657 m_ICmp(Pred, m_Specific(CIVNext), m_Value(CIVComparedTo))) &&
658 Pred == ICmpInst::ICMP_SLT)) {
659 FailureReason = "unknown latch form (not slt)";
663 const SCEV *CIVComparedToSCEV = SE.getSCEV(CIVComparedTo);
664 if (isa<SCEVCouldNotCompute>(CIVComparedToSCEV)) {
665 FailureReason = "could not relate CIV to latch expression";
669 const SCEV *ShouldBeOne = SE.getMinusSCEV(CIVComparedToSCEV, LatchCount);
670 const SCEVConstant *SCEVOne = dyn_cast<SCEVConstant>(ShouldBeOne);
671 if (!SCEVOne || SCEVOne->getValue()->getValue() != 1) {
672 FailureReason = "unexpected header count in latch";
676 unsigned LatchBrExitIdx = 1;
677 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
679 assert(SE.getLoopDisposition(LatchCount, &OriginalLoop) ==
680 ScalarEvolution::LoopInvariant &&
681 "loop variant exit count doesn't make sense!");
683 assert(!OriginalLoop.contains(LatchExit) && "expected an exit block!");
685 LoopStructureOut.Tag = "main";
686 LoopStructureOut.Header = Header;
687 LoopStructureOut.Latch = Latch;
688 LoopStructureOut.LatchBr = LatchBr;
689 LoopStructureOut.LatchExit = LatchExit;
690 LoopStructureOut.LatchBrExitIdx = LatchBrExitIdx;
691 LoopStructureOut.CIV = CIV;
692 LoopStructureOut.CIVNext = CIVNext;
693 LoopStructureOut.CIVStart = CIVStart;
695 LatchCountOut = LatchCount;
696 PreheaderOut = Preheader;
697 FailureReason = nullptr;
702 LoopConstrainer::SubRanges
703 LoopConstrainer::calculateSubRanges(Value *&HeaderCountOut) const {
704 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
706 SCEVExpander Expander(SE, "irce");
707 Instruction *InsertPt = OriginalPreheader->getTerminator();
710 MaybeSimplify(Expander.expandCodeFor(LatchTakenCount, Ty, InsertPt));
712 IRBuilder<> B(InsertPt);
714 LoopConstrainer::SubRanges Result;
716 // I think we can be more aggressive here and make this nuw / nsw if the
717 // addition that feeds into the icmp for the latch's terminating branch is nuw
718 // / nsw. In any case, a wrapping 2's complement addition is safe.
719 ConstantInt *One = ConstantInt::get(Ty, 1);
720 HeaderCountOut = MaybeSimplify(B.CreateAdd(LatchCountV, One, "header.count"));
722 const SCEV *RangeBegin = SE.getSCEV(Range.first);
723 const SCEV *RangeEnd = SE.getSCEV(Range.second);
724 const SCEV *HeaderCountSCEV = SE.getSCEV(HeaderCountOut);
725 const SCEV *Zero = SE.getConstant(Ty, 0);
727 // In some cases we can prove that we don't need a pre or post loop
729 bool ProvablyNoPreloop =
730 SE.isKnownPredicate(ICmpInst::ICMP_SLE, RangeBegin, Zero);
731 if (!ProvablyNoPreloop)
732 Result.ExitPreLoopAt = ConstructSMinOf(HeaderCountOut, Range.first, B);
734 bool ProvablyNoPostLoop =
735 SE.isKnownPredicate(ICmpInst::ICMP_SLE, HeaderCountSCEV, RangeEnd);
736 if (!ProvablyNoPostLoop)
737 Result.ExitMainLoopAt = ConstructSMinOf(HeaderCountOut, Range.second, B);
742 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
743 const char *Tag) const {
744 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
745 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
746 Result.Blocks.push_back(Clone);
747 Result.Map[BB] = Clone;
750 auto GetClonedValue = [&Result](Value *V) {
751 assert(V && "null values not in domain!");
752 auto It = Result.Map.find(V);
753 if (It == Result.Map.end())
755 return static_cast<Value *>(It->second);
758 Result.Structure = MainLoopStructure.map(GetClonedValue);
759 Result.Structure.Tag = Tag;
761 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
762 BasicBlock *ClonedBB = Result.Blocks[i];
763 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
765 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
767 for (Instruction &I : *ClonedBB)
768 RemapInstruction(&I, Result.Map,
769 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
771 // Exit blocks will now have one more predecessor and their PHI nodes need
772 // to be edited to reflect that. No phi nodes need to be introduced because
773 // the loop is in LCSSA.
775 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
776 SBBI != SBBE; ++SBBI) {
778 if (OriginalLoop.contains(*SBBI))
779 continue; // not an exit block
781 for (Instruction &I : **SBBI) {
782 if (!isa<PHINode>(&I))
785 PHINode *PN = cast<PHINode>(&I);
786 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
787 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
793 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
794 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitLoopAt,
795 BasicBlock *ContinuationBlock) const {
797 // We start with a loop with a single latch:
799 // +--------------------+
803 // +--------+-----------+
804 // | ----------------\
806 // +--------v----v------+ |
810 // +--------------------+ |
814 // +--------------------+ |
816 // | latch >----------/
818 // +-------v------------+
821 // | +--------------------+
823 // +---> original exit |
825 // +--------------------+
827 // We change the control flow to look like
830 // +--------------------+
832 // | preheader >-------------------------+
834 // +--------v-----------+ |
835 // | /-------------+ |
837 // +--------v--v--------+ | |
839 // | header | | +--------+ |
841 // +--------------------+ | | +-----v-----v-----------+
843 // | | | .pseudo.exit |
845 // | | +-----------v-----------+
848 // | | +--------v-------------+
849 // +--------------------+ | | | |
850 // | | | | | ContinuationBlock |
851 // | latch >------+ | | |
852 // | | | +----------------------+
853 // +---------v----------+ |
856 // | +---------------^-----+
858 // +-----> .exit.selector |
860 // +----------v----------+
862 // +--------------------+ |
864 // | original exit <----+
866 // +--------------------+
869 RewrittenRangeInfo RRI;
871 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
872 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
873 &F, BBInsertLocation);
874 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
877 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
879 IRBuilder<> B(PreheaderJump);
881 // EnterLoopCond - is it okay to start executing this `LS'?
882 Value *EnterLoopCond = B.CreateICmpSLT(LS.CIVStart, ExitLoopAt);
883 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
884 PreheaderJump->eraseFromParent();
886 assert(LS.LatchBrExitIdx == 1 && "generalize this as needed!");
888 B.SetInsertPoint(LS.LatchBr);
890 // ContinueCond - is it okay to execute the next iteration in `LS'?
891 Value *ContinueCond = B.CreateICmpSLT(LS.CIVNext, ExitLoopAt);
893 LS.LatchBr->setCondition(ContinueCond);
894 assert(LS.LatchBr->getSuccessor(LS.LatchBrExitIdx) == LS.LatchExit &&
896 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
898 B.SetInsertPoint(RRI.ExitSelector);
900 // IterationsLeft - are there any more iterations left, given the original
901 // upper bound on the induction variable? If not, we branch to the "real"
903 Value *IterationsLeft = B.CreateICmpSLT(LS.CIVNext, OriginalHeaderCount);
904 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
906 BranchInst *BranchToContinuation =
907 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
909 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
910 // each of the PHI nodes in the loop header. This feeds into the initial
911 // value of the same PHI nodes if/when we continue execution.
912 for (Instruction &I : *LS.Header) {
913 if (!isa<PHINode>(&I))
916 PHINode *PN = cast<PHINode>(&I);
918 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
919 BranchToContinuation);
921 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
922 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
924 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
927 // The latch exit now has a branch from `RRI.ExitSelector' instead of
928 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
929 for (Instruction &I : *LS.LatchExit) {
930 if (PHINode *PN = dyn_cast<PHINode>(&I))
931 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
939 void LoopConstrainer::rewriteIncomingValuesForPHIs(
940 LoopConstrainer::LoopStructure &LS, BasicBlock *ContinuationBlock,
941 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
943 unsigned PHIIndex = 0;
944 for (Instruction &I : *LS.Header) {
945 if (!isa<PHINode>(&I))
948 PHINode *PN = cast<PHINode>(&I);
950 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
951 if (PN->getIncomingBlock(i) == ContinuationBlock)
952 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
955 LS.CIVStart = LS.CIV->getIncomingValueForBlock(ContinuationBlock);
959 LoopConstrainer::createPreheader(const LoopConstrainer::LoopStructure &LS,
960 BasicBlock *OldPreheader,
961 const char *Tag) const {
963 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
964 BranchInst::Create(LS.Header, Preheader);
966 for (Instruction &I : *LS.Header) {
967 if (!isa<PHINode>(&I))
970 PHINode *PN = cast<PHINode>(&I);
971 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
972 replacePHIBlock(PN, OldPreheader, Preheader);
978 template<typename IteratorTy>
979 void LoopConstrainer::addToParentLoopIfNeeded(IteratorTy Begin,
981 Loop *ParentLoop = OriginalLoop.getParentLoop();
985 auto &LoopInfoBase = OriginalLoopInfo.getBase();
986 for (; Begin != End; Begin++)
987 ParentLoop->addBasicBlockToLoop(*Begin, LoopInfoBase);
990 bool LoopConstrainer::run() {
991 BasicBlock *Preheader = nullptr;
992 const char *CouldNotProceedBecause = nullptr;
993 if (!recognizeLoop(MainLoopStructure, LatchTakenCount, Preheader,
994 CouldNotProceedBecause)) {
995 DEBUG(dbgs() << "irce: could not recognize loop, " << CouldNotProceedBecause
1000 OriginalPreheader = Preheader;
1001 MainLoopPreheader = Preheader;
1003 SubRanges SR = calculateSubRanges(OriginalHeaderCount);
1005 // It would have been better to make `PreLoop' and `PostLoop'
1006 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1008 ClonedLoop PreLoop, PostLoop;
1009 bool NeedsPreLoop = SR.ExitPreLoopAt.hasValue();
1010 bool NeedsPostLoop = SR.ExitMainLoopAt.hasValue();
1012 // We clone these ahead of time so that we don't have to deal with changing
1013 // and temporarily invalid IR as we transform the loops.
1015 cloneLoop(PreLoop, "preloop");
1017 cloneLoop(PostLoop, "postloop");
1019 RewrittenRangeInfo PreLoopRRI;
1022 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1023 PreLoop.Structure.Header);
1026 createPreheader(MainLoopStructure, Preheader, "mainloop");
1028 changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1029 SR.ExitPreLoopAt.getValue(), MainLoopPreheader);
1030 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1034 BasicBlock *PostLoopPreheader = nullptr;
1035 RewrittenRangeInfo PostLoopRRI;
1037 if (NeedsPostLoop) {
1039 createPreheader(PostLoop.Structure, Preheader, "postloop");
1040 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1041 SR.ExitMainLoopAt.getValue(),
1043 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1047 SmallVector<BasicBlock *, 6> NewBlocks;
1048 NewBlocks.push_back(PostLoopPreheader);
1049 NewBlocks.push_back(PreLoopRRI.PseudoExit);
1050 NewBlocks.push_back(PreLoopRRI.ExitSelector);
1051 NewBlocks.push_back(PostLoopRRI.PseudoExit);
1052 NewBlocks.push_back(PostLoopRRI.ExitSelector);
1053 if (MainLoopPreheader != Preheader)
1054 NewBlocks.push_back(MainLoopPreheader);
1056 // Some of the above may be nullptr, filter them out before passing to
1057 // addToParentLoopIfNeeded.
1058 auto NewBlocksEnd = std::remove(NewBlocks.begin(), NewBlocks.end(), nullptr);
1060 typedef SmallVector<BasicBlock *, 6>::iterator SmallVectItTy;
1061 typedef std::vector<BasicBlock *>::iterator StdVectItTy;
1063 addToParentLoopIfNeeded<SmallVectItTy>(NewBlocks.begin(), NewBlocksEnd);
1064 addToParentLoopIfNeeded<StdVectItTy>(PreLoop.Blocks.begin(),
1065 PreLoop.Blocks.end());
1066 addToParentLoopIfNeeded<StdVectItTy>(PostLoop.Blocks.begin(),
1067 PostLoop.Blocks.end());
1072 /// Computes and returns a range of values for the induction variable in which
1073 /// the range check can be safely elided. If it cannot compute such a range,
1075 Optional<InductiveRangeCheck::Range>
1076 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1077 IRBuilder<> &B) const {
1079 // Currently we support inequalities of the form:
1081 // 0 <= Offset + 1 * CIV < L given L >= 0
1083 // The inequality is satisfied by -Offset <= CIV < (L - Offset) [^1]. All
1084 // additions and subtractions are twos-complement wrapping and comparisons are
1089 // If there exists CIV such that -Offset <= CIV < (L - Offset) then it
1090 // follows that -Offset <= (-Offset + L) [== Eq. 1]. Since L >= 0, if
1091 // (-Offset + L) sign-overflows then (-Offset + L) < (-Offset). Hence by
1092 // [Eq. 1], (-Offset + L) could not have overflown.
1094 // This means CIV = t + (-Offset) for t in [0, L). Hence (CIV + Offset) =
1095 // t. Hence 0 <= (CIV + Offset) < L
1097 // [^1]: Note that the solution does _not_ apply if L < 0; consider values
1098 // Offset = 127, CIV = 126 and L = -2 in an i8 world.
1100 const SCEVConstant *ScaleC = dyn_cast<SCEVConstant>(getScale());
1101 if (!(ScaleC && ScaleC->getValue()->getValue() == 1)) {
1102 DEBUG(dbgs() << "irce: could not compute safe iteration space for:\n";
1107 Value *OffsetV = SCEVExpander(SE, "safe.itr.space").expandCodeFor(
1108 getOffset(), getOffset()->getType(), B.GetInsertPoint());
1109 OffsetV = MaybeSimplify(OffsetV);
1111 Value *Begin = MaybeSimplify(B.CreateNeg(OffsetV));
1112 Value *End = MaybeSimplify(B.CreateSub(getLength(), OffsetV));
1114 return std::make_pair(Begin, End);
1117 static InductiveRangeCheck::Range
1118 IntersectRange(const Optional<InductiveRangeCheck::Range> &R1,
1119 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1122 auto &R1Value = R1.getValue();
1124 Value *NewMin = ConstructSMaxOf(R1Value.first, R2.first, B);
1125 Value *NewMax = ConstructSMinOf(R1Value.second, R2.second, B);
1126 return std::make_pair(NewMin, NewMax);
1129 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1130 if (L->getBlocks().size() >= LoopSizeCutoff) {
1131 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1135 BasicBlock *Preheader = L->getLoopPreheader();
1137 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1141 LLVMContext &Context = Preheader->getContext();
1142 InductiveRangeCheck::AllocatorTy IRCAlloc;
1143 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1144 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1146 for (auto BBI : L->getBlocks())
1147 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1148 if (InductiveRangeCheck *IRC =
1149 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE))
1150 RangeChecks.push_back(IRC);
1152 if (RangeChecks.empty())
1155 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1156 dbgs() << "irce: loop has " << RangeChecks.size()
1157 << " inductive range checks: \n";
1158 for (InductiveRangeCheck *IRC : RangeChecks)
1162 Optional<InductiveRangeCheck::Range> SafeIterRange;
1163 Instruction *ExprInsertPt = Preheader->getTerminator();
1165 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1167 IRBuilder<> B(ExprInsertPt);
1168 for (InductiveRangeCheck *IRC : RangeChecks) {
1169 auto Result = IRC->computeSafeIterationSpace(SE, B);
1170 if (Result.hasValue()) {
1171 SafeIterRange = IntersectRange(SafeIterRange, Result.getValue(), B);
1172 RangeChecksToEliminate.push_back(IRC);
1176 if (!SafeIterRange.hasValue())
1179 LoopConstrainer LC(*L, getAnalysis<LoopInfo>(), SE, SafeIterRange.getValue());
1180 bool Changed = LC.run();
1183 auto PrintConstrainedLoopInfo = [L]() {
1184 dbgs() << "irce: in function ";
1185 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1186 dbgs() << "constrained ";
1190 DEBUG(PrintConstrainedLoopInfo());
1192 if (PrintChangedLoops)
1193 PrintConstrainedLoopInfo();
1195 // Optimize away the now-redundant range checks.
1197 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1198 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1199 ? ConstantInt::getTrue(Context)
1200 : ConstantInt::getFalse(Context);
1201 IRC->getBranch()->setCondition(FoldedRangeCheck);
1208 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1209 return new InductiveRangeCheckElimination;