1 //===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // The InductiveRangeCheckElimination pass splits a loop's iteration space into
10 // three disjoint ranges.  It does that in a way such that the loop running in
11 // the middle loop provably does not need range checks. As an example, it will
12 // convert
13 //
14 //   len = < known positive >
15 //   for (i = 0; i < n; i++) {
16 //     if (0 <= i && i < len) {
17 //       do_something();
18 //     } else {
19 //       throw_out_of_bounds();
20 //     }
21 //   }
22 //
23 // to
24 //
25 //   len = < known positive >
26 //   limit = smin(n, len)
27 //   // no first segment
28 //   for (i = 0; i < limit; i++) {
29 //     if (0 <= i && i < len) { // this check is fully redundant
30 //       do_something();
31 //     } else {
32 //       throw_out_of_bounds();
33 //     }
34 //   }
35 //   for (i = limit; i < n; i++) {
36 //     if (0 <= i && i < len) {
37 //       do_something();
38 //     } else {
39 //       throw_out_of_bounds();
40 //     }
41 //   }
42 //===----------------------------------------------------------------------===//
43 
44 #include "llvm/ADT/Optional.h"
45 #include "llvm/Analysis/BranchProbabilityInfo.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"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/PatternMatch.h"
59 #include "llvm/IR/ValueHandle.h"
60 #include "llvm/IR/Verifier.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/Scalar.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/Cloning.h"
67 #include "llvm/Transforms/Utils/LoopUtils.h"
68 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
69 #include "llvm/Transforms/Utils/UnrollLoop.h"
70 
71 using namespace llvm;
72 
73 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
74                                         cl::init(64));
75 
76 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
77                                        cl::init(false));
78 
79 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
80                                       cl::init(false));
81 
82 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
83                                           cl::Hidden, cl::init(10));
84 
85 #define DEBUG_TYPE "irce"
86 
87 namespace {
88 
89 /// An inductive range check is conditional branch in a loop with
90 ///
91 ///  1. a very cold successor (i.e. the branch jumps to that successor very
92 ///     rarely)
93 ///
94 ///  and
95 ///
96 ///  2. a condition that is provably true for some contiguous range of values
97 ///     taken by the containing loop's induction variable.
98 ///
99 class InductiveRangeCheck {
100   // Classifies a range check
101   enum RangeCheckKind : unsigned {
102     // Range check of the form "0 <= I".
103     RANGE_CHECK_LOWER = 1,
104 
105     // Range check of the form "I < L" where L is known positive.
106     RANGE_CHECK_UPPER = 2,
107 
108     // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
109     // conditions.
110     RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
111 
112     // Unrecognized range check condition.
113     RANGE_CHECK_UNKNOWN = (unsigned)-1
114   };
115 
116   static StringRef rangeCheckKindToStr(RangeCheckKind);
117 
118   const SCEV *Offset;
119   const SCEV *Scale;
120   Value *Length;
121   BranchInst *Branch;
122   RangeCheckKind Kind;
123 
124   static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
125                                             ScalarEvolution &SE, Value *&Index,
126                                             Value *&Length);
127 
128   static InductiveRangeCheck::RangeCheckKind
129   parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
130                   const SCEV *&Index, Value *&UpperLimit);
131 
132   InductiveRangeCheck() :
133     Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
134 
135 public:
136   const SCEV *getOffset() const { return Offset; }
137   const SCEV *getScale() const { return Scale; }
138   Value *getLength() const { return Length; }
139 
140   void print(raw_ostream &OS) const {
141     OS << "InductiveRangeCheck:\n";
142     OS << "  Kind: " << rangeCheckKindToStr(Kind) << "\n";
143     OS << "  Offset: ";
144     Offset->print(OS);
145     OS << "  Scale: ";
146     Scale->print(OS);
147     OS << "  Length: ";
148     if (Length)
149       Length->print(OS);
150     else
151       OS << "(null)";
152     OS << "\n  Branch: ";
153     getBranch()->print(OS);
154     OS << "\n";
155   }
156 
157 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
158   void dump() {
159     print(dbgs());
160   }
161 #endif
162 
163   BranchInst *getBranch() const { return Branch; }
164 
165   /// Represents an signed integer range [Range.getBegin(), Range.getEnd()).  If
166   /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
167 
168   class Range {
169     const SCEV *Begin;
170     const SCEV *End;
171 
172   public:
173     Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
174       assert(Begin->getType() == End->getType() && "ill-typed range!");
175     }
176 
177     Type *getType() const { return Begin->getType(); }
178     const SCEV *getBegin() const { return Begin; }
179     const SCEV *getEnd() const { return End; }
180   };
181 
182   typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
183 
184   /// This is the value the condition of the branch needs to evaluate to for the
185   /// branch to take the hot successor (see (1) above).
186   bool getPassingDirection() { return true; }
187 
188   /// Computes a range for the induction variable (IndVar) in which the range
189   /// check is redundant and can be constant-folded away.  The induction
190   /// variable is not required to be the canonical {0,+,1} induction variable.
191   Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
192                                             const SCEVAddRecExpr *IndVar,
193                                             IRBuilder<> &B) const;
194 
195   /// Create an inductive range check out of BI if possible, else return
196   /// nullptr.
197   static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
198                                      Loop *L, ScalarEvolution &SE,
199                                      BranchProbabilityInfo &BPI);
200 };
201 
202 class InductiveRangeCheckElimination : public LoopPass {
203   InductiveRangeCheck::AllocatorTy Allocator;
204 
205 public:
206   static char ID;
207   InductiveRangeCheckElimination() : LoopPass(ID) {
208     initializeInductiveRangeCheckEliminationPass(
209         *PassRegistry::getPassRegistry());
210   }
211 
212   void getAnalysisUsage(AnalysisUsage &AU) const override {
213     AU.addRequired<BranchProbabilityInfoWrapperPass>();
214     getLoopAnalysisUsage(AU);
215   }
216 
217   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
218 };
219 
220 char InductiveRangeCheckElimination::ID = 0;
221 }
222 
223 INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
224                       "Inductive range check elimination", false, false)
225 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
226 INITIALIZE_PASS_DEPENDENCY(LoopPass)
227 INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
228                     "Inductive range check elimination", false, false)
229 
230 StringRef InductiveRangeCheck::rangeCheckKindToStr(
231     InductiveRangeCheck::RangeCheckKind RCK) {
232   switch (RCK) {
233   case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
234     return "RANGE_CHECK_UNKNOWN";
235 
236   case InductiveRangeCheck::RANGE_CHECK_UPPER:
237     return "RANGE_CHECK_UPPER";
238 
239   case InductiveRangeCheck::RANGE_CHECK_LOWER:
240     return "RANGE_CHECK_LOWER";
241 
242   case InductiveRangeCheck::RANGE_CHECK_BOTH:
243     return "RANGE_CHECK_BOTH";
244   }
245 
246   llvm_unreachable("unknown range check type!");
247 }
248 
249 /// Parse a single ICmp instruction, `ICI`, into a range check.  If `ICI` cannot
250 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
251 /// `Index` and `Length` to `nullptr`.  Otherwise set `Index` to the value being
252 /// range checked, and set `Length` to the upper limit `Index` is being range
253 /// checked with if (and only if) the range check type is stronger or equal to
254 /// RANGE_CHECK_UPPER.
255 ///
256 InductiveRangeCheck::RangeCheckKind
257 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
258                                          ScalarEvolution &SE, Value *&Index,
259                                          Value *&Length) {
260 
261   auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
262     const SCEV *S = SE.getSCEV(V);
263     if (isa<SCEVCouldNotCompute>(S))
264       return false;
265 
266     return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
267            SE.isKnownNonNegative(S);
268   };
269 
270   using namespace llvm::PatternMatch;
271 
272   ICmpInst::Predicate Pred = ICI->getPredicate();
273   Value *LHS = ICI->getOperand(0);
274   Value *RHS = ICI->getOperand(1);
275 
276   switch (Pred) {
277   default:
278     return RANGE_CHECK_UNKNOWN;
279 
280   case ICmpInst::ICMP_SLE:
281     std::swap(LHS, RHS);
282   // fallthrough
283   case ICmpInst::ICMP_SGE:
284     if (match(RHS, m_ConstantInt<0>())) {
285       Index = LHS;
286       return RANGE_CHECK_LOWER;
287     }
288     return RANGE_CHECK_UNKNOWN;
289 
290   case ICmpInst::ICMP_SLT:
291     std::swap(LHS, RHS);
292   // fallthrough
293   case ICmpInst::ICMP_SGT:
294     if (match(RHS, m_ConstantInt<-1>())) {
295       Index = LHS;
296       return RANGE_CHECK_LOWER;
297     }
298 
299     if (IsNonNegativeAndNotLoopVarying(LHS)) {
300       Index = RHS;
301       Length = LHS;
302       return RANGE_CHECK_UPPER;
303     }
304     return RANGE_CHECK_UNKNOWN;
305 
306   case ICmpInst::ICMP_ULT:
307     std::swap(LHS, RHS);
308   // fallthrough
309   case ICmpInst::ICMP_UGT:
310     if (IsNonNegativeAndNotLoopVarying(LHS)) {
311       Index = RHS;
312       Length = LHS;
313       return RANGE_CHECK_BOTH;
314     }
315     return RANGE_CHECK_UNKNOWN;
316   }
317 
318   llvm_unreachable("default clause returns!");
319 }
320 
321 /// Parses an arbitrary condition into a range check.  `Length` is set only if
322 /// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
323 InductiveRangeCheck::RangeCheckKind
324 InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
325                                      Value *Condition, const SCEV *&Index,
326                                      Value *&Length) {
327   using namespace llvm::PatternMatch;
328 
329   Value *A = nullptr;
330   Value *B = nullptr;
331 
332   if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
333     Value *IndexA = nullptr, *IndexB = nullptr;
334     Value *LengthA = nullptr, *LengthB = nullptr;
335     ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
336 
337     if (!ICmpA || !ICmpB)
338       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
339 
340     auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
341     auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
342 
343     if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
344         RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
345       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
346 
347     if (IndexA != IndexB)
348       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
349 
350     if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
351       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
352 
353     Index = SE.getSCEV(IndexA);
354     if (isa<SCEVCouldNotCompute>(Index))
355       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
356 
357     Length = LengthA == nullptr ? LengthB : LengthA;
358 
359     return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
360   }
361 
362   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
363     Value *IndexVal = nullptr;
364 
365     auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
366 
367     if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
368       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
369 
370     Index = SE.getSCEV(IndexVal);
371     if (isa<SCEVCouldNotCompute>(Index))
372       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
373 
374     return RCKind;
375   }
376 
377   return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
378 }
379 
380 
381 InductiveRangeCheck *
382 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
383                             Loop *L, ScalarEvolution &SE,
384                             BranchProbabilityInfo &BPI) {
385 
386   if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
387     return nullptr;
388 
389   BranchProbability LikelyTaken(15, 16);
390 
391   if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
392     return nullptr;
393 
394   Value *Length = nullptr;
395   const SCEV *IndexSCEV = nullptr;
396 
397   auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
398                                                      IndexSCEV, Length);
399 
400   if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
401     return nullptr;
402 
403   assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
404   assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
405          "contract with SplitRangeCheckCondition!");
406 
407   const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
408   bool IsAffineIndex =
409       IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
410 
411   if (!IsAffineIndex)
412     return nullptr;
413 
414   InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
415   IRC->Length = Length;
416   IRC->Offset = IndexAddRec->getStart();
417   IRC->Scale = IndexAddRec->getStepRecurrence(SE);
418   IRC->Branch = BI;
419   IRC->Kind = RCKind;
420   return IRC;
421 }
422 
423 namespace {
424 
425 // Keeps track of the structure of a loop.  This is similar to llvm::Loop,
426 // except that it is more lightweight and can track the state of a loop through
427 // changing and potentially invalid IR.  This structure also formalizes the
428 // kinds of loops we can deal with -- ones that have a single latch that is also
429 // an exiting block *and* have a canonical induction variable.
430 struct LoopStructure {
431   const char *Tag;
432 
433   BasicBlock *Header;
434   BasicBlock *Latch;
435 
436   // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
437   // successor is `LatchExit', the exit block of the loop.
438   BranchInst *LatchBr;
439   BasicBlock *LatchExit;
440   unsigned LatchBrExitIdx;
441 
442   Value *IndVarNext;
443   Value *IndVarStart;
444   Value *LoopExitAt;
445   bool IndVarIncreasing;
446 
447   LoopStructure()
448       : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
449         LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
450         IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
451 
452   template <typename M> LoopStructure map(M Map) const {
453     LoopStructure Result;
454     Result.Tag = Tag;
455     Result.Header = cast<BasicBlock>(Map(Header));
456     Result.Latch = cast<BasicBlock>(Map(Latch));
457     Result.LatchBr = cast<BranchInst>(Map(LatchBr));
458     Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
459     Result.LatchBrExitIdx = LatchBrExitIdx;
460     Result.IndVarNext = Map(IndVarNext);
461     Result.IndVarStart = Map(IndVarStart);
462     Result.LoopExitAt = Map(LoopExitAt);
463     Result.IndVarIncreasing = IndVarIncreasing;
464     return Result;
465   }
466 
467   static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
468                                                     BranchProbabilityInfo &BPI,
469                                                     Loop &,
470                                                     const char *&);
471 };
472 
473 /// This class is used to constrain loops to run within a given iteration space.
474 /// The algorithm this class implements is given a Loop and a range [Begin,
475 /// End).  The algorithm then tries to break out a "main loop" out of the loop
476 /// it is given in a way that the "main loop" runs with the induction variable
477 /// in a subset of [Begin, End).  The algorithm emits appropriate pre and post
478 /// loops to run any remaining iterations.  The pre loop runs any iterations in
479 /// which the induction variable is < Begin, and the post loop runs any
480 /// iterations in which the induction variable is >= End.
481 ///
482 class LoopConstrainer {
483   // The representation of a clone of the original loop we started out with.
484   struct ClonedLoop {
485     // The cloned blocks
486     std::vector<BasicBlock *> Blocks;
487 
488     // `Map` maps values in the clonee into values in the cloned version
489     ValueToValueMapTy Map;
490 
491     // An instance of `LoopStructure` for the cloned loop
492     LoopStructure Structure;
493   };
494 
495   // Result of rewriting the range of a loop.  See changeIterationSpaceEnd for
496   // more details on what these fields mean.
497   struct RewrittenRangeInfo {
498     BasicBlock *PseudoExit;
499     BasicBlock *ExitSelector;
500     std::vector<PHINode *> PHIValuesAtPseudoExit;
501     PHINode *IndVarEnd;
502 
503     RewrittenRangeInfo()
504         : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
505   };
506 
507   // Calculated subranges we restrict the iteration space of the main loop to.
508   // See the implementation of `calculateSubRanges' for more details on how
509   // these fields are computed.  `LowLimit` is None if there is no restriction
510   // on low end of the restricted iteration space of the main loop.  `HighLimit`
511   // is None if there is no restriction on high end of the restricted iteration
512   // space of the main loop.
513 
514   struct SubRanges {
515     Optional<const SCEV *> LowLimit;
516     Optional<const SCEV *> HighLimit;
517   };
518 
519   // A utility function that does a `replaceUsesOfWith' on the incoming block
520   // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
521   // incoming block list with `ReplaceBy'.
522   static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
523                               BasicBlock *ReplaceBy);
524 
525   // Compute a safe set of limits for the main loop to run in -- effectively the
526   // intersection of `Range' and the iteration space of the original loop.
527   // Return None if unable to compute the set of subranges.
528   //
529   Optional<SubRanges> calculateSubRanges() const;
530 
531   // Clone `OriginalLoop' and return the result in CLResult.  The IR after
532   // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
533   // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
534   // but there is no such edge.
535   //
536   void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
537 
538   // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
539   // iteration space of the rewritten loop ends at ExitLoopAt.  The start of the
540   // iteration space is not changed.  `ExitLoopAt' is assumed to be slt
541   // `OriginalHeaderCount'.
542   //
543   // If there are iterations left to execute, control is made to jump to
544   // `ContinuationBlock', otherwise they take the normal loop exit.  The
545   // returned `RewrittenRangeInfo' object is populated as follows:
546   //
547   //  .PseudoExit is a basic block that unconditionally branches to
548   //      `ContinuationBlock'.
549   //
550   //  .ExitSelector is a basic block that decides, on exit from the loop,
551   //      whether to branch to the "true" exit or to `PseudoExit'.
552   //
553   //  .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
554   //      for each PHINode in the loop header on taking the pseudo exit.
555   //
556   // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
557   // preheader because it is made to branch to the loop header only
558   // conditionally.
559   //
560   RewrittenRangeInfo
561   changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
562                           Value *ExitLoopAt,
563                           BasicBlock *ContinuationBlock) const;
564 
565   // The loop denoted by `LS' has `OldPreheader' as its preheader.  This
566   // function creates a new preheader for `LS' and returns it.
567   //
568   BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
569                               const char *Tag) const;
570 
571   // `ContinuationBlockAndPreheader' was the continuation block for some call to
572   // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
573   // This function rewrites the PHI nodes in `LS.Header' to start with the
574   // correct value.
575   void rewriteIncomingValuesForPHIs(
576       LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
577       const LoopConstrainer::RewrittenRangeInfo &RRI) const;
578 
579   // Even though we do not preserve any passes at this time, we at least need to
580   // keep the parent loop structure consistent.  The `LPPassManager' seems to
581   // verify this after running a loop pass.  This function adds the list of
582   // blocks denoted by BBs to this loops parent loop if required.
583   void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
584 
585   // Some global state.
586   Function &F;
587   LLVMContext &Ctx;
588   ScalarEvolution &SE;
589 
590   // Information about the original loop we started out with.
591   Loop &OriginalLoop;
592   LoopInfo &OriginalLoopInfo;
593   const SCEV *LatchTakenCount;
594   BasicBlock *OriginalPreheader;
595 
596   // The preheader of the main loop.  This may or may not be different from
597   // `OriginalPreheader'.
598   BasicBlock *MainLoopPreheader;
599 
600   // The range we need to run the main loop in.
601   InductiveRangeCheck::Range Range;
602 
603   // The structure of the main loop (see comment at the beginning of this class
604   // for a definition)
605   LoopStructure MainLoopStructure;
606 
607 public:
608   LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
609                   ScalarEvolution &SE, InductiveRangeCheck::Range R)
610       : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
611         SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
612         OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
613         MainLoopStructure(LS) {}
614 
615   // Entry point for the algorithm.  Returns true on success.
616   bool run();
617 };
618 
619 }
620 
621 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
622                                       BasicBlock *ReplaceBy) {
623   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
624     if (PN->getIncomingBlock(i) == Block)
625       PN->setIncomingBlock(i, ReplaceBy);
626 }
627 
628 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
629   APInt SMax =
630       APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
631   return SE.getSignedRange(S).contains(SMax) &&
632          SE.getUnsignedRange(S).contains(SMax);
633 }
634 
635 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
636   APInt SMin =
637       APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
638   return SE.getSignedRange(S).contains(SMin) &&
639          SE.getUnsignedRange(S).contains(SMin);
640 }
641 
642 Optional<LoopStructure>
643 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
644                                   Loop &L, const char *&FailureReason) {
645   assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
646 
647   BasicBlock *Latch = L.getLoopLatch();
648   if (!L.isLoopExiting(Latch)) {
649     FailureReason = "no loop latch";
650     return None;
651   }
652 
653   BasicBlock *Header = L.getHeader();
654   BasicBlock *Preheader = L.getLoopPreheader();
655   if (!Preheader) {
656     FailureReason = "no preheader";
657     return None;
658   }
659 
660   BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
661   if (!LatchBr || LatchBr->isUnconditional()) {
662     FailureReason = "latch terminator not conditional branch";
663     return None;
664   }
665 
666   unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
667 
668   BranchProbability ExitProbability =
669     BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
670 
671   if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
672     FailureReason = "short running loop, not profitable";
673     return None;
674   }
675 
676   ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
677   if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
678     FailureReason = "latch terminator branch not conditional on integral icmp";
679     return None;
680   }
681 
682   const SCEV *LatchCount = SE.getExitCount(&L, Latch);
683   if (isa<SCEVCouldNotCompute>(LatchCount)) {
684     FailureReason = "could not compute latch count";
685     return None;
686   }
687 
688   ICmpInst::Predicate Pred = ICI->getPredicate();
689   Value *LeftValue = ICI->getOperand(0);
690   const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
691   IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
692 
693   Value *RightValue = ICI->getOperand(1);
694   const SCEV *RightSCEV = SE.getSCEV(RightValue);
695 
696   // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
697   if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
698     if (isa<SCEVAddRecExpr>(RightSCEV)) {
699       std::swap(LeftSCEV, RightSCEV);
700       std::swap(LeftValue, RightValue);
701       Pred = ICmpInst::getSwappedPredicate(Pred);
702     } else {
703       FailureReason = "no add recurrences in the icmp";
704       return None;
705     }
706   }
707 
708   auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
709     if (AR->getNoWrapFlags(SCEV::FlagNSW))
710       return true;
711 
712     IntegerType *Ty = cast<IntegerType>(AR->getType());
713     IntegerType *WideTy =
714         IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
715 
716     const SCEVAddRecExpr *ExtendAfterOp =
717         dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
718     if (ExtendAfterOp) {
719       const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
720       const SCEV *ExtendedStep =
721           SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
722 
723       bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
724                           ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
725 
726       if (NoSignedWrap)
727         return true;
728     }
729 
730     // We may have proved this when computing the sign extension above.
731     return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
732   };
733 
734   auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
735     if (!AR->isAffine())
736       return false;
737 
738     // Currently we only work with induction variables that have been proved to
739     // not wrap.  This restriction can potentially be lifted in the future.
740 
741     if (!HasNoSignedWrap(AR))
742       return false;
743 
744     if (const SCEVConstant *StepExpr =
745             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
746       ConstantInt *StepCI = StepExpr->getValue();
747       if (StepCI->isOne() || StepCI->isMinusOne()) {
748         IsIncreasing = StepCI->isOne();
749         return true;
750       }
751     }
752 
753     return false;
754   };
755 
756   // `ICI` is interpreted as taking the backedge if the *next* value of the
757   // induction variable satisfies some constraint.
758 
759   const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
760   bool IsIncreasing = false;
761   if (!IsInductionVar(IndVarNext, IsIncreasing)) {
762     FailureReason = "LHS in icmp not induction variable";
763     return None;
764   }
765 
766   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
767   // TODO: generalize the predicates here to also match their unsigned variants.
768   if (IsIncreasing) {
769     bool FoundExpectedPred =
770         (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
771         (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
772 
773     if (!FoundExpectedPred) {
774       FailureReason = "expected icmp slt semantically, found something else";
775       return None;
776     }
777 
778     if (LatchBrExitIdx == 0) {
779       if (CanBeSMax(SE, RightSCEV)) {
780         // TODO: this restriction is easily removable -- we just have to
781         // remember that the icmp was an slt and not an sle.
782         FailureReason = "limit may overflow when coercing sle to slt";
783         return None;
784       }
785 
786       IRBuilder<> B(&*Preheader->rbegin());
787       RightValue = B.CreateAdd(RightValue, One);
788     }
789 
790   } else {
791     bool FoundExpectedPred =
792         (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
793         (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
794 
795     if (!FoundExpectedPred) {
796       FailureReason = "expected icmp sgt semantically, found something else";
797       return None;
798     }
799 
800     if (LatchBrExitIdx == 0) {
801       if (CanBeSMin(SE, RightSCEV)) {
802         // TODO: this restriction is easily removable -- we just have to
803         // remember that the icmp was an sgt and not an sge.
804         FailureReason = "limit may overflow when coercing sge to sgt";
805         return None;
806       }
807 
808       IRBuilder<> B(&*Preheader->rbegin());
809       RightValue = B.CreateSub(RightValue, One);
810     }
811   }
812 
813   const SCEV *StartNext = IndVarNext->getStart();
814   const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
815   const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
816 
817   BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
818 
819   assert(SE.getLoopDisposition(LatchCount, &L) ==
820              ScalarEvolution::LoopInvariant &&
821          "loop variant exit count doesn't make sense!");
822 
823   assert(!L.contains(LatchExit) && "expected an exit block!");
824   const DataLayout &DL = Preheader->getModule()->getDataLayout();
825   Value *IndVarStartV =
826       SCEVExpander(SE, DL, "irce")
827           .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
828   IndVarStartV->setName("indvar.start");
829 
830   LoopStructure Result;
831 
832   Result.Tag = "main";
833   Result.Header = Header;
834   Result.Latch = Latch;
835   Result.LatchBr = LatchBr;
836   Result.LatchExit = LatchExit;
837   Result.LatchBrExitIdx = LatchBrExitIdx;
838   Result.IndVarStart = IndVarStartV;
839   Result.IndVarNext = LeftValue;
840   Result.IndVarIncreasing = IsIncreasing;
841   Result.LoopExitAt = RightValue;
842 
843   FailureReason = nullptr;
844 
845   return Result;
846 }
847 
848 Optional<LoopConstrainer::SubRanges>
849 LoopConstrainer::calculateSubRanges() const {
850   IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
851 
852   if (Range.getType() != Ty)
853     return None;
854 
855   LoopConstrainer::SubRanges Result;
856 
857   // I think we can be more aggressive here and make this nuw / nsw if the
858   // addition that feeds into the icmp for the latch's terminating branch is nuw
859   // / nsw.  In any case, a wrapping 2's complement addition is safe.
860   ConstantInt *One = ConstantInt::get(Ty, 1);
861   const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
862   const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
863 
864   bool Increasing = MainLoopStructure.IndVarIncreasing;
865 
866   // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
867   // range of values the induction variable takes.
868 
869   const SCEV *Smallest = nullptr, *Greatest = nullptr;
870 
871   if (Increasing) {
872     Smallest = Start;
873     Greatest = End;
874   } else {
875     // These two computations may sign-overflow.  Here is why that is okay:
876     //
877     // We know that the induction variable does not sign-overflow on any
878     // iteration except the last one, and it starts at `Start` and ends at
879     // `End`, decrementing by one every time.
880     //
881     //  * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
882     //    induction variable is decreasing we know that that the smallest value
883     //    the loop body is actually executed with is `INT_SMIN` == `Smallest`.
884     //
885     //  * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`.  In
886     //    that case, `Clamp` will always return `Smallest` and
887     //    [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
888     //    will be an empty range.  Returning an empty range is always safe.
889     //
890 
891     Smallest = SE.getAddExpr(End, SE.getSCEV(One));
892     Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
893   }
894 
895   auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
896     return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
897   };
898 
899   // In some cases we can prove that we don't need a pre or post loop
900 
901   bool ProvablyNoPreloop =
902       SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
903   if (!ProvablyNoPreloop)
904     Result.LowLimit = Clamp(Range.getBegin());
905 
906   bool ProvablyNoPostLoop =
907       SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
908   if (!ProvablyNoPostLoop)
909     Result.HighLimit = Clamp(Range.getEnd());
910 
911   return Result;
912 }
913 
914 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
915                                 const char *Tag) const {
916   for (BasicBlock *BB : OriginalLoop.getBlocks()) {
917     BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
918     Result.Blocks.push_back(Clone);
919     Result.Map[BB] = Clone;
920   }
921 
922   auto GetClonedValue = [&Result](Value *V) {
923     assert(V && "null values not in domain!");
924     auto It = Result.Map.find(V);
925     if (It == Result.Map.end())
926       return V;
927     return static_cast<Value *>(It->second);
928   };
929 
930   Result.Structure = MainLoopStructure.map(GetClonedValue);
931   Result.Structure.Tag = Tag;
932 
933   for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
934     BasicBlock *ClonedBB = Result.Blocks[i];
935     BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
936 
937     assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
938 
939     for (Instruction &I : *ClonedBB)
940       RemapInstruction(&I, Result.Map,
941                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
942 
943     // Exit blocks will now have one more predecessor and their PHI nodes need
944     // to be edited to reflect that.  No phi nodes need to be introduced because
945     // the loop is in LCSSA.
946 
947     for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
948          SBBI != SBBE; ++SBBI) {
949 
950       if (OriginalLoop.contains(*SBBI))
951         continue; // not an exit block
952 
953       for (Instruction &I : **SBBI) {
954         if (!isa<PHINode>(&I))
955           break;
956 
957         PHINode *PN = cast<PHINode>(&I);
958         Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
959         PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
960       }
961     }
962   }
963 }
964 
965 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
966     const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
967     BasicBlock *ContinuationBlock) const {
968 
969   // We start with a loop with a single latch:
970   //
971   //    +--------------------+
972   //    |                    |
973   //    |     preheader      |
974   //    |                    |
975   //    +--------+-----------+
976   //             |      ----------------\
977   //             |     /                |
978   //    +--------v----v------+          |
979   //    |                    |          |
980   //    |      header        |          |
981   //    |                    |          |
982   //    +--------------------+          |
983   //                                    |
984   //            .....                   |
985   //                                    |
986   //    +--------------------+          |
987   //    |                    |          |
988   //    |       latch        >----------/
989   //    |                    |
990   //    +-------v------------+
991   //            |
992   //            |
993   //            |   +--------------------+
994   //            |   |                    |
995   //            +--->   original exit    |
996   //                |                    |
997   //                +--------------------+
998   //
999   // We change the control flow to look like
1000   //
1001   //
1002   //    +--------------------+
1003   //    |                    |
1004   //    |     preheader      >-------------------------+
1005   //    |                    |                         |
1006   //    +--------v-----------+                         |
1007   //             |    /-------------+                  |
1008   //             |   /              |                  |
1009   //    +--------v--v--------+      |                  |
1010   //    |                    |      |                  |
1011   //    |      header        |      |   +--------+     |
1012   //    |                    |      |   |        |     |
1013   //    +--------------------+      |   |  +-----v-----v-----------+
1014   //                                |   |  |                       |
1015   //                                |   |  |     .pseudo.exit      |
1016   //                                |   |  |                       |
1017   //                                |   |  +-----------v-----------+
1018   //                                |   |              |
1019   //            .....               |   |              |
1020   //                                |   |     +--------v-------------+
1021   //    +--------------------+      |   |     |                      |
1022   //    |                    |      |   |     |   ContinuationBlock  |
1023   //    |       latch        >------+   |     |                      |
1024   //    |                    |          |     +----------------------+
1025   //    +---------v----------+          |
1026   //              |                     |
1027   //              |                     |
1028   //              |     +---------------^-----+
1029   //              |     |                     |
1030   //              +----->    .exit.selector   |
1031   //                    |                     |
1032   //                    +----------v----------+
1033   //                               |
1034   //     +--------------------+    |
1035   //     |                    |    |
1036   //     |   original exit    <----+
1037   //     |                    |
1038   //     +--------------------+
1039   //
1040 
1041   RewrittenRangeInfo RRI;
1042 
1043   auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1044   RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1045                                         &F, &*BBInsertLocation);
1046   RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1047                                       &*BBInsertLocation);
1048 
1049   BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
1050   bool Increasing = LS.IndVarIncreasing;
1051 
1052   IRBuilder<> B(PreheaderJump);
1053 
1054   // EnterLoopCond - is it okay to start executing this `LS'?
1055   Value *EnterLoopCond = Increasing
1056                              ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1057                              : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1058 
1059   B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1060   PreheaderJump->eraseFromParent();
1061 
1062   LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1063   B.SetInsertPoint(LS.LatchBr);
1064   Value *TakeBackedgeLoopCond =
1065       Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1066                  : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1067   Value *CondForBranch = LS.LatchBrExitIdx == 1
1068                              ? TakeBackedgeLoopCond
1069                              : B.CreateNot(TakeBackedgeLoopCond);
1070 
1071   LS.LatchBr->setCondition(CondForBranch);
1072 
1073   B.SetInsertPoint(RRI.ExitSelector);
1074 
1075   // IterationsLeft - are there any more iterations left, given the original
1076   // upper bound on the induction variable?  If not, we branch to the "real"
1077   // exit.
1078   Value *IterationsLeft = Increasing
1079                               ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1080                               : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1081   B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1082 
1083   BranchInst *BranchToContinuation =
1084       BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1085 
1086   // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1087   // each of the PHI nodes in the loop header.  This feeds into the initial
1088   // value of the same PHI nodes if/when we continue execution.
1089   for (Instruction &I : *LS.Header) {
1090     if (!isa<PHINode>(&I))
1091       break;
1092 
1093     PHINode *PN = cast<PHINode>(&I);
1094 
1095     PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1096                                       BranchToContinuation);
1097 
1098     NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1099     NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1100                         RRI.ExitSelector);
1101     RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1102   }
1103 
1104   RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1105                                   BranchToContinuation);
1106   RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1107   RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1108 
1109   // The latch exit now has a branch from `RRI.ExitSelector' instead of
1110   // `LS.Latch'.  The PHI nodes need to be updated to reflect that.
1111   for (Instruction &I : *LS.LatchExit) {
1112     if (PHINode *PN = dyn_cast<PHINode>(&I))
1113       replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1114     else
1115       break;
1116   }
1117 
1118   return RRI;
1119 }
1120 
1121 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1122     LoopStructure &LS, BasicBlock *ContinuationBlock,
1123     const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1124 
1125   unsigned PHIIndex = 0;
1126   for (Instruction &I : *LS.Header) {
1127     if (!isa<PHINode>(&I))
1128       break;
1129 
1130     PHINode *PN = cast<PHINode>(&I);
1131 
1132     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1133       if (PN->getIncomingBlock(i) == ContinuationBlock)
1134         PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1135   }
1136 
1137   LS.IndVarStart = RRI.IndVarEnd;
1138 }
1139 
1140 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1141                                              BasicBlock *OldPreheader,
1142                                              const char *Tag) const {
1143 
1144   BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1145   BranchInst::Create(LS.Header, Preheader);
1146 
1147   for (Instruction &I : *LS.Header) {
1148     if (!isa<PHINode>(&I))
1149       break;
1150 
1151     PHINode *PN = cast<PHINode>(&I);
1152     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1153       replacePHIBlock(PN, OldPreheader, Preheader);
1154   }
1155 
1156   return Preheader;
1157 }
1158 
1159 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1160   Loop *ParentLoop = OriginalLoop.getParentLoop();
1161   if (!ParentLoop)
1162     return;
1163 
1164   for (BasicBlock *BB : BBs)
1165     ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1166 }
1167 
1168 bool LoopConstrainer::run() {
1169   BasicBlock *Preheader = nullptr;
1170   LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1171   Preheader = OriginalLoop.getLoopPreheader();
1172   assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1173          "preconditions!");
1174 
1175   OriginalPreheader = Preheader;
1176   MainLoopPreheader = Preheader;
1177 
1178   Optional<SubRanges> MaybeSR = calculateSubRanges();
1179   if (!MaybeSR.hasValue()) {
1180     DEBUG(dbgs() << "irce: could not compute subranges\n");
1181     return false;
1182   }
1183 
1184   SubRanges SR = MaybeSR.getValue();
1185   bool Increasing = MainLoopStructure.IndVarIncreasing;
1186   IntegerType *IVTy =
1187       cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1188 
1189   SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1190   Instruction *InsertPt = OriginalPreheader->getTerminator();
1191 
1192   // It would have been better to make `PreLoop' and `PostLoop'
1193   // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1194   // constructor.
1195   ClonedLoop PreLoop, PostLoop;
1196   bool NeedsPreLoop =
1197       Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1198   bool NeedsPostLoop =
1199       Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1200 
1201   Value *ExitPreLoopAt = nullptr;
1202   Value *ExitMainLoopAt = nullptr;
1203   const SCEVConstant *MinusOneS =
1204       cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1205 
1206   if (NeedsPreLoop) {
1207     const SCEV *ExitPreLoopAtSCEV = nullptr;
1208 
1209     if (Increasing)
1210       ExitPreLoopAtSCEV = *SR.LowLimit;
1211     else {
1212       if (CanBeSMin(SE, *SR.HighLimit)) {
1213         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1214                      << "preloop exit limit.  HighLimit = " << *(*SR.HighLimit)
1215                      << "\n");
1216         return false;
1217       }
1218       ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1219     }
1220 
1221     ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1222     ExitPreLoopAt->setName("exit.preloop.at");
1223   }
1224 
1225   if (NeedsPostLoop) {
1226     const SCEV *ExitMainLoopAtSCEV = nullptr;
1227 
1228     if (Increasing)
1229       ExitMainLoopAtSCEV = *SR.HighLimit;
1230     else {
1231       if (CanBeSMin(SE, *SR.LowLimit)) {
1232         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1233                      << "mainloop exit limit.  LowLimit = " << *(*SR.LowLimit)
1234                      << "\n");
1235         return false;
1236       }
1237       ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1238     }
1239 
1240     ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1241     ExitMainLoopAt->setName("exit.mainloop.at");
1242   }
1243 
1244   // We clone these ahead of time so that we don't have to deal with changing
1245   // and temporarily invalid IR as we transform the loops.
1246   if (NeedsPreLoop)
1247     cloneLoop(PreLoop, "preloop");
1248   if (NeedsPostLoop)
1249     cloneLoop(PostLoop, "postloop");
1250 
1251   RewrittenRangeInfo PreLoopRRI;
1252 
1253   if (NeedsPreLoop) {
1254     Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1255                                                   PreLoop.Structure.Header);
1256 
1257     MainLoopPreheader =
1258         createPreheader(MainLoopStructure, Preheader, "mainloop");
1259     PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1260                                          ExitPreLoopAt, MainLoopPreheader);
1261     rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1262                                  PreLoopRRI);
1263   }
1264 
1265   BasicBlock *PostLoopPreheader = nullptr;
1266   RewrittenRangeInfo PostLoopRRI;
1267 
1268   if (NeedsPostLoop) {
1269     PostLoopPreheader =
1270         createPreheader(PostLoop.Structure, Preheader, "postloop");
1271     PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1272                                           ExitMainLoopAt, PostLoopPreheader);
1273     rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1274                                  PostLoopRRI);
1275   }
1276 
1277   BasicBlock *NewMainLoopPreheader =
1278       MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1279   BasicBlock *NewBlocks[] = {PostLoopPreheader,        PreLoopRRI.PseudoExit,
1280                              PreLoopRRI.ExitSelector,  PostLoopRRI.PseudoExit,
1281                              PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1282 
1283   // Some of the above may be nullptr, filter them out before passing to
1284   // addToParentLoopIfNeeded.
1285   auto NewBlocksEnd =
1286       std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1287 
1288   addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1289   addToParentLoopIfNeeded(PreLoop.Blocks);
1290   addToParentLoopIfNeeded(PostLoop.Blocks);
1291 
1292   return true;
1293 }
1294 
1295 /// Computes and returns a range of values for the induction variable (IndVar)
1296 /// in which the range check can be safely elided.  If it cannot compute such a
1297 /// range, returns None.
1298 Optional<InductiveRangeCheck::Range>
1299 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1300                                                const SCEVAddRecExpr *IndVar,
1301                                                IRBuilder<> &) const {
1302   // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1303   // variable, that may or may not exist as a real llvm::Value in the loop) and
1304   // this inductive range check is a range check on the "C + D * I" ("C" is
1305   // getOffset() and "D" is getScale()).  We rewrite the value being range
1306   // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1307   // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1308   // can be generalized as needed.
1309   //
1310   // The actual inequalities we solve are of the form
1311   //
1312   //   0 <= M + 1 * IndVar < L given L >= 0  (i.e. N == 1)
1313   //
1314   // The inequality is satisfied by -M <= IndVar < (L - M) [^1].  All additions
1315   // and subtractions are twos-complement wrapping and comparisons are signed.
1316   //
1317   // Proof:
1318   //
1319   //   If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1320   //   that -M <= (-M + L) [== Eq. 1].  Since L >= 0, if (-M + L) sign-overflows
1321   //   then (-M + L) < (-M).  Hence by [Eq. 1], (-M + L) could not have
1322   //   overflown.
1323   //
1324   //   This means IndVar = t + (-M) for t in [0, L).  Hence (IndVar + M) = t.
1325   //   Hence 0 <= (IndVar + M) < L
1326 
1327   // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1328   // 127, IndVar = 126 and L = -2 in an i8 world.
1329 
1330   if (!IndVar->isAffine())
1331     return None;
1332 
1333   const SCEV *A = IndVar->getStart();
1334   const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1335   if (!B)
1336     return None;
1337 
1338   const SCEV *C = getOffset();
1339   const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1340   if (D != B)
1341     return None;
1342 
1343   ConstantInt *ConstD = D->getValue();
1344   if (!(ConstD->isMinusOne() || ConstD->isOne()))
1345     return None;
1346 
1347   const SCEV *M = SE.getMinusSCEV(C, A);
1348 
1349   const SCEV *Begin = SE.getNegativeSCEV(M);
1350   const SCEV *UpperLimit = nullptr;
1351 
1352   // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1353   // We can potentially do much better here.
1354   if (Value *V = getLength()) {
1355     UpperLimit = SE.getSCEV(V);
1356   } else {
1357     assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1358     unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1359     UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1360   }
1361 
1362   const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1363   return InductiveRangeCheck::Range(Begin, End);
1364 }
1365 
1366 static Optional<InductiveRangeCheck::Range>
1367 IntersectRange(ScalarEvolution &SE,
1368                const Optional<InductiveRangeCheck::Range> &R1,
1369                const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1370   if (!R1.hasValue())
1371     return R2;
1372   auto &R1Value = R1.getValue();
1373 
1374   // TODO: we could widen the smaller range and have this work; but for now we
1375   // bail out to keep things simple.
1376   if (R1Value.getType() != R2.getType())
1377     return None;
1378 
1379   const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1380   const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1381 
1382   return InductiveRangeCheck::Range(NewBegin, NewEnd);
1383 }
1384 
1385 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1386   if (skipLoop(L))
1387     return false;
1388 
1389   if (L->getBlocks().size() >= LoopSizeCutoff) {
1390     DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1391     return false;
1392   }
1393 
1394   BasicBlock *Preheader = L->getLoopPreheader();
1395   if (!Preheader) {
1396     DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1397     return false;
1398   }
1399 
1400   LLVMContext &Context = Preheader->getContext();
1401   InductiveRangeCheck::AllocatorTy IRCAlloc;
1402   SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1403   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1404   BranchProbabilityInfo &BPI =
1405       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1406 
1407   for (auto BBI : L->getBlocks())
1408     if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1409       if (InductiveRangeCheck *IRC =
1410           InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1411         RangeChecks.push_back(IRC);
1412 
1413   if (RangeChecks.empty())
1414     return false;
1415 
1416   auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1417     OS << "irce: looking at loop "; L->print(OS);
1418     OS << "irce: loop has " << RangeChecks.size()
1419        << " inductive range checks: \n";
1420     for (InductiveRangeCheck *IRC : RangeChecks)
1421       IRC->print(OS);
1422   };
1423 
1424   DEBUG(PrintRecognizedRangeChecks(dbgs()));
1425 
1426   if (PrintRangeChecks)
1427     PrintRecognizedRangeChecks(errs());
1428 
1429   const char *FailureReason = nullptr;
1430   Optional<LoopStructure> MaybeLoopStructure =
1431       LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1432   if (!MaybeLoopStructure.hasValue()) {
1433     DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1434                  << "\n";);
1435     return false;
1436   }
1437   LoopStructure LS = MaybeLoopStructure.getValue();
1438   bool Increasing = LS.IndVarIncreasing;
1439   const SCEV *MinusOne =
1440       SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1441   const SCEVAddRecExpr *IndVar =
1442       cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1443 
1444   Optional<InductiveRangeCheck::Range> SafeIterRange;
1445   Instruction *ExprInsertPt = Preheader->getTerminator();
1446 
1447   SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1448 
1449   IRBuilder<> B(ExprInsertPt);
1450   for (InductiveRangeCheck *IRC : RangeChecks) {
1451     auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
1452     if (Result.hasValue()) {
1453       auto MaybeSafeIterRange =
1454         IntersectRange(SE, SafeIterRange, Result.getValue(), B);
1455       if (MaybeSafeIterRange.hasValue()) {
1456         RangeChecksToEliminate.push_back(IRC);
1457         SafeIterRange = MaybeSafeIterRange.getValue();
1458       }
1459     }
1460   }
1461 
1462   if (!SafeIterRange.hasValue())
1463     return false;
1464 
1465   LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1466                      SE, SafeIterRange.getValue());
1467   bool Changed = LC.run();
1468 
1469   if (Changed) {
1470     auto PrintConstrainedLoopInfo = [L]() {
1471       dbgs() << "irce: in function ";
1472       dbgs() << L->getHeader()->getParent()->getName() << ": ";
1473       dbgs() << "constrained ";
1474       L->print(dbgs());
1475     };
1476 
1477     DEBUG(PrintConstrainedLoopInfo());
1478 
1479     if (PrintChangedLoops)
1480       PrintConstrainedLoopInfo();
1481 
1482     // Optimize away the now-redundant range checks.
1483 
1484     for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1485       ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1486                                           ? ConstantInt::getTrue(Context)
1487                                           : ConstantInt::getFalse(Context);
1488       IRC->getBranch()->setCondition(FoldedRangeCheck);
1489     }
1490   }
1491 
1492   return Changed;
1493 }
1494 
1495 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1496   return new InductiveRangeCheckElimination;
1497 }
1498