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 //
10 // The InductiveRangeCheckElimination pass splits a loop's iteration space into
11 // three disjoint ranges.  It does that in a way such that the loop running in
12 // the middle loop provably does not need range checks. As an example, it will
13 // convert
14 //
15 //   len = < known positive >
16 //   for (i = 0; i < n; i++) {
17 //     if (0 <= i && i < len) {
18 //       do_something();
19 //     } else {
20 //       throw_out_of_bounds();
21 //     }
22 //   }
23 //
24 // to
25 //
26 //   len = < known positive >
27 //   limit = smin(n, len)
28 //   // no first segment
29 //   for (i = 0; i < limit; i++) {
30 //     if (0 <= i && i < len) { // this check is fully redundant
31 //       do_something();
32 //     } else {
33 //       throw_out_of_bounds();
34 //     }
35 //   }
36 //   for (i = limit; i < n; i++) {
37 //     if (0 <= i && i < len) {
38 //       do_something();
39 //     } else {
40 //       throw_out_of_bounds();
41 //     }
42 //   }
43 //
44 //===----------------------------------------------------------------------===//
45 
46 #include "llvm/ADT/APInt.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/None.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringRef.h"
53 #include "llvm/ADT/Twine.h"
54 #include "llvm/Analysis/BranchProbabilityInfo.h"
55 #include "llvm/Analysis/LoopInfo.h"
56 #include "llvm/Analysis/LoopPass.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpander.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstrTypes.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Metadata.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/PatternMatch.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/User.h"
75 #include "llvm/IR/Value.h"
76 #include "llvm/Pass.h"
77 #include "llvm/Support/BranchProbability.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Transforms/Scalar.h"
85 #include "llvm/Transforms/Utils/Cloning.h"
86 #include "llvm/Transforms/Utils/LoopSimplify.h"
87 #include "llvm/Transforms/Utils/LoopUtils.h"
88 #include "llvm/Transforms/Utils/ValueMapper.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <iterator>
92 #include <limits>
93 #include <utility>
94 #include <vector>
95 
96 using namespace llvm;
97 using namespace llvm::PatternMatch;
98 
99 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
100                                         cl::init(64));
101 
102 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
103                                        cl::init(false));
104 
105 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
106                                       cl::init(false));
107 
108 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
109                                           cl::Hidden, cl::init(10));
110 
111 static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
112                                              cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
115                                                  cl::Hidden, cl::init(true));
116 
117 static const char *ClonedLoopTag = "irce.loop.clone";
118 
119 #define DEBUG_TYPE "irce"
120 
121 namespace {
122 
123 /// An inductive range check is conditional branch in a loop with
124 ///
125 ///  1. a very cold successor (i.e. the branch jumps to that successor very
126 ///     rarely)
127 ///
128 ///  and
129 ///
130 ///  2. a condition that is provably true for some contiguous range of values
131 ///     taken by the containing loop's induction variable.
132 ///
133 class InductiveRangeCheck {
134   // Classifies a range check
135   enum RangeCheckKind : unsigned {
136     // Range check of the form "0 <= I".
137     RANGE_CHECK_LOWER = 1,
138 
139     // Range check of the form "I < L" where L is known positive.
140     RANGE_CHECK_UPPER = 2,
141 
142     // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
143     // conditions.
144     RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
145 
146     // Unrecognized range check condition.
147     RANGE_CHECK_UNKNOWN = (unsigned)-1
148   };
149 
150   static StringRef rangeCheckKindToStr(RangeCheckKind);
151 
152   const SCEV *Begin = nullptr;
153   const SCEV *Step = nullptr;
154   const SCEV *End = nullptr;
155   Use *CheckUse = nullptr;
156   RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
157   bool IsSigned = true;
158 
159   static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
160                                             ScalarEvolution &SE, Value *&Index,
161                                             Value *&Length, bool &IsSigned);
162 
163   static void
164   extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
165                              SmallVectorImpl<InductiveRangeCheck> &Checks,
166                              SmallPtrSetImpl<Value *> &Visited);
167 
168 public:
169   const SCEV *getBegin() const { return Begin; }
170   const SCEV *getStep() const { return Step; }
171   const SCEV *getEnd() const { return End; }
172   bool isSigned() const { return IsSigned; }
173 
174   void print(raw_ostream &OS) const {
175     OS << "InductiveRangeCheck:\n";
176     OS << "  Kind: " << rangeCheckKindToStr(Kind) << "\n";
177     OS << "  Begin: ";
178     Begin->print(OS);
179     OS << "  Step: ";
180     Step->print(OS);
181     OS << "  End: ";
182     if (End)
183       End->print(OS);
184     else
185       OS << "(null)";
186     OS << "\n  CheckUse: ";
187     getCheckUse()->getUser()->print(OS);
188     OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
189   }
190 
191   LLVM_DUMP_METHOD
192   void dump() {
193     print(dbgs());
194   }
195 
196   Use *getCheckUse() const { return CheckUse; }
197 
198   /// Represents an signed integer range [Range.getBegin(), Range.getEnd()).  If
199   /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
200 
201   class Range {
202     const SCEV *Begin;
203     const SCEV *End;
204 
205   public:
206     Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
207       assert(Begin->getType() == End->getType() && "ill-typed range!");
208     }
209 
210     Type *getType() const { return Begin->getType(); }
211     const SCEV *getBegin() const { return Begin; }
212     const SCEV *getEnd() const { return End; }
213     bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
214       if (Begin == End)
215         return true;
216       if (IsSigned)
217         return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
218       else
219         return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
220     }
221   };
222 
223   /// This is the value the condition of the branch needs to evaluate to for the
224   /// branch to take the hot successor (see (1) above).
225   bool getPassingDirection() { return true; }
226 
227   /// Computes a range for the induction variable (IndVar) in which the range
228   /// check is redundant and can be constant-folded away.  The induction
229   /// variable is not required to be the canonical {0,+,1} induction variable.
230   Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
231                                             const SCEVAddRecExpr *IndVar) const;
232 
233   /// Parse out a set of inductive range checks from \p BI and append them to \p
234   /// Checks.
235   ///
236   /// NB! There may be conditions feeding into \p BI that aren't inductive range
237   /// checks, and hence don't end up in \p Checks.
238   static void
239   extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
240                                BranchProbabilityInfo &BPI,
241                                SmallVectorImpl<InductiveRangeCheck> &Checks);
242 };
243 
244 class InductiveRangeCheckElimination : public LoopPass {
245 public:
246   static char ID;
247 
248   InductiveRangeCheckElimination() : LoopPass(ID) {
249     initializeInductiveRangeCheckEliminationPass(
250         *PassRegistry::getPassRegistry());
251   }
252 
253   void getAnalysisUsage(AnalysisUsage &AU) const override {
254     AU.addRequired<BranchProbabilityInfoWrapperPass>();
255     getLoopAnalysisUsage(AU);
256   }
257 
258   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
259 };
260 
261 } // end anonymous namespace
262 
263 char InductiveRangeCheckElimination::ID = 0;
264 
265 INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
266                       "Inductive range check elimination", false, false)
267 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
268 INITIALIZE_PASS_DEPENDENCY(LoopPass)
269 INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
270                     "Inductive range check elimination", false, false)
271 
272 StringRef InductiveRangeCheck::rangeCheckKindToStr(
273     InductiveRangeCheck::RangeCheckKind RCK) {
274   switch (RCK) {
275   case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
276     return "RANGE_CHECK_UNKNOWN";
277 
278   case InductiveRangeCheck::RANGE_CHECK_UPPER:
279     return "RANGE_CHECK_UPPER";
280 
281   case InductiveRangeCheck::RANGE_CHECK_LOWER:
282     return "RANGE_CHECK_LOWER";
283 
284   case InductiveRangeCheck::RANGE_CHECK_BOTH:
285     return "RANGE_CHECK_BOTH";
286   }
287 
288   llvm_unreachable("unknown range check type!");
289 }
290 
291 /// Parse a single ICmp instruction, `ICI`, into a range check.  If `ICI` cannot
292 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
293 /// `Index` and `Length` to `nullptr`.  Otherwise set `Index` to the value being
294 /// range checked, and set `Length` to the upper limit `Index` is being range
295 /// checked with if (and only if) the range check type is stronger or equal to
296 /// RANGE_CHECK_UPPER.
297 InductiveRangeCheck::RangeCheckKind
298 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
299                                          ScalarEvolution &SE, Value *&Index,
300                                          Value *&Length, bool &IsSigned) {
301   auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
302     const SCEV *S = SE.getSCEV(V);
303     if (isa<SCEVCouldNotCompute>(S))
304       return false;
305 
306     return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
307            SE.isKnownNonNegative(S);
308   };
309 
310   ICmpInst::Predicate Pred = ICI->getPredicate();
311   Value *LHS = ICI->getOperand(0);
312   Value *RHS = ICI->getOperand(1);
313 
314   switch (Pred) {
315   default:
316     return RANGE_CHECK_UNKNOWN;
317 
318   case ICmpInst::ICMP_SLE:
319     std::swap(LHS, RHS);
320     LLVM_FALLTHROUGH;
321   case ICmpInst::ICMP_SGE:
322     IsSigned = true;
323     if (match(RHS, m_ConstantInt<0>())) {
324       Index = LHS;
325       return RANGE_CHECK_LOWER;
326     }
327     return RANGE_CHECK_UNKNOWN;
328 
329   case ICmpInst::ICMP_SLT:
330     std::swap(LHS, RHS);
331     LLVM_FALLTHROUGH;
332   case ICmpInst::ICMP_SGT:
333     IsSigned = true;
334     if (match(RHS, m_ConstantInt<-1>())) {
335       Index = LHS;
336       return RANGE_CHECK_LOWER;
337     }
338 
339     if (IsNonNegativeAndNotLoopVarying(LHS)) {
340       Index = RHS;
341       Length = LHS;
342       return RANGE_CHECK_UPPER;
343     }
344     return RANGE_CHECK_UNKNOWN;
345 
346   case ICmpInst::ICMP_ULT:
347     std::swap(LHS, RHS);
348     LLVM_FALLTHROUGH;
349   case ICmpInst::ICMP_UGT:
350     IsSigned = false;
351     if (IsNonNegativeAndNotLoopVarying(LHS)) {
352       Index = RHS;
353       Length = LHS;
354       return RANGE_CHECK_BOTH;
355     }
356     return RANGE_CHECK_UNKNOWN;
357   }
358 
359   llvm_unreachable("default clause returns!");
360 }
361 
362 void InductiveRangeCheck::extractRangeChecksFromCond(
363     Loop *L, ScalarEvolution &SE, Use &ConditionUse,
364     SmallVectorImpl<InductiveRangeCheck> &Checks,
365     SmallPtrSetImpl<Value *> &Visited) {
366   Value *Condition = ConditionUse.get();
367   if (!Visited.insert(Condition).second)
368     return;
369 
370   if (match(Condition, m_And(m_Value(), m_Value()))) {
371     SmallVector<InductiveRangeCheck, 8> SubChecks;
372     extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
373                                SubChecks, Visited);
374     extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
375                                SubChecks, Visited);
376 
377     if (SubChecks.size() == 2) {
378       // Handle a special case where we know how to merge two checks separately
379       // checking the upper and lower bounds into a full range check.
380       const auto &RChkA = SubChecks[0];
381       const auto &RChkB = SubChecks[1];
382       if ((RChkA.End == RChkB.End || !RChkA.End || !RChkB.End) &&
383           RChkA.Begin == RChkB.Begin && RChkA.Step == RChkB.Step &&
384           RChkA.IsSigned == RChkB.IsSigned) {
385         // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
386         // But if one of them is a RANGE_CHECK_LOWER and the other is a
387         // RANGE_CHECK_UPPER (only possibility if they're different) then
388         // together they form a RANGE_CHECK_BOTH.
389         SubChecks[0].Kind =
390             (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
391         SubChecks[0].End = RChkA.End ? RChkA.End : RChkB.End;
392         SubChecks[0].CheckUse = &ConditionUse;
393         SubChecks[0].IsSigned = RChkA.IsSigned;
394 
395         // We updated one of the checks in place, now erase the other.
396         SubChecks.pop_back();
397       }
398     }
399 
400     Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
401     return;
402   }
403 
404   ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
405   if (!ICI)
406     return;
407 
408   Value *Length = nullptr, *Index;
409   bool IsSigned;
410   auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
411   if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
412     return;
413 
414   const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
415   bool IsAffineIndex =
416       IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
417 
418   if (!IsAffineIndex)
419     return;
420 
421   InductiveRangeCheck IRC;
422   IRC.End = Length ? SE.getSCEV(Length) : nullptr;
423   IRC.Begin = IndexAddRec->getStart();
424   IRC.Step = IndexAddRec->getStepRecurrence(SE);
425   IRC.CheckUse = &ConditionUse;
426   IRC.Kind = RCKind;
427   IRC.IsSigned = IsSigned;
428   Checks.push_back(IRC);
429 }
430 
431 void InductiveRangeCheck::extractRangeChecksFromBranch(
432     BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
433     SmallVectorImpl<InductiveRangeCheck> &Checks) {
434   if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
435     return;
436 
437   BranchProbability LikelyTaken(15, 16);
438 
439   if (!SkipProfitabilityChecks &&
440       BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
441     return;
442 
443   SmallPtrSet<Value *, 8> Visited;
444   InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
445                                                   Checks, Visited);
446 }
447 
448 // Add metadata to the loop L to disable loop optimizations. Callers need to
449 // confirm that optimizing loop L is not beneficial.
450 static void DisableAllLoopOptsOnLoop(Loop &L) {
451   // We do not care about any existing loopID related metadata for L, since we
452   // are setting all loop metadata to false.
453   LLVMContext &Context = L.getHeader()->getContext();
454   // Reserve first location for self reference to the LoopID metadata node.
455   MDNode *Dummy = MDNode::get(Context, {});
456   MDNode *DisableUnroll = MDNode::get(
457       Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
458   Metadata *FalseVal =
459       ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
460   MDNode *DisableVectorize = MDNode::get(
461       Context,
462       {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
463   MDNode *DisableLICMVersioning = MDNode::get(
464       Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
465   MDNode *DisableDistribution= MDNode::get(
466       Context,
467       {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
468   MDNode *NewLoopID =
469       MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
470                             DisableLICMVersioning, DisableDistribution});
471   // Set operand 0 to refer to the loop id itself.
472   NewLoopID->replaceOperandWith(0, NewLoopID);
473   L.setLoopID(NewLoopID);
474 }
475 
476 namespace {
477 
478 // Keeps track of the structure of a loop.  This is similar to llvm::Loop,
479 // except that it is more lightweight and can track the state of a loop through
480 // changing and potentially invalid IR.  This structure also formalizes the
481 // kinds of loops we can deal with -- ones that have a single latch that is also
482 // an exiting block *and* have a canonical induction variable.
483 struct LoopStructure {
484   const char *Tag = "";
485 
486   BasicBlock *Header = nullptr;
487   BasicBlock *Latch = nullptr;
488 
489   // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
490   // successor is `LatchExit', the exit block of the loop.
491   BranchInst *LatchBr = nullptr;
492   BasicBlock *LatchExit = nullptr;
493   unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
494 
495   // The loop represented by this instance of LoopStructure is semantically
496   // equivalent to:
497   //
498   // intN_ty inc = IndVarIncreasing ? 1 : -1;
499   // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
500   //
501   // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
502   //   ... body ...
503 
504   Value *IndVarBase = nullptr;
505   Value *IndVarStart = nullptr;
506   Value *IndVarStep = nullptr;
507   Value *LoopExitAt = nullptr;
508   bool IndVarIncreasing = false;
509   bool IsSignedPredicate = true;
510 
511   LoopStructure() = default;
512 
513   template <typename M> LoopStructure map(M Map) const {
514     LoopStructure Result;
515     Result.Tag = Tag;
516     Result.Header = cast<BasicBlock>(Map(Header));
517     Result.Latch = cast<BasicBlock>(Map(Latch));
518     Result.LatchBr = cast<BranchInst>(Map(LatchBr));
519     Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
520     Result.LatchBrExitIdx = LatchBrExitIdx;
521     Result.IndVarBase = Map(IndVarBase);
522     Result.IndVarStart = Map(IndVarStart);
523     Result.IndVarStep = Map(IndVarStep);
524     Result.LoopExitAt = Map(LoopExitAt);
525     Result.IndVarIncreasing = IndVarIncreasing;
526     Result.IsSignedPredicate = IsSignedPredicate;
527     return Result;
528   }
529 
530   static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
531                                                     BranchProbabilityInfo &BPI,
532                                                     Loop &,
533                                                     const char *&);
534 };
535 
536 /// This class is used to constrain loops to run within a given iteration space.
537 /// The algorithm this class implements is given a Loop and a range [Begin,
538 /// End).  The algorithm then tries to break out a "main loop" out of the loop
539 /// it is given in a way that the "main loop" runs with the induction variable
540 /// in a subset of [Begin, End).  The algorithm emits appropriate pre and post
541 /// loops to run any remaining iterations.  The pre loop runs any iterations in
542 /// which the induction variable is < Begin, and the post loop runs any
543 /// iterations in which the induction variable is >= End.
544 class LoopConstrainer {
545   // The representation of a clone of the original loop we started out with.
546   struct ClonedLoop {
547     // The cloned blocks
548     std::vector<BasicBlock *> Blocks;
549 
550     // `Map` maps values in the clonee into values in the cloned version
551     ValueToValueMapTy Map;
552 
553     // An instance of `LoopStructure` for the cloned loop
554     LoopStructure Structure;
555   };
556 
557   // Result of rewriting the range of a loop.  See changeIterationSpaceEnd for
558   // more details on what these fields mean.
559   struct RewrittenRangeInfo {
560     BasicBlock *PseudoExit = nullptr;
561     BasicBlock *ExitSelector = nullptr;
562     std::vector<PHINode *> PHIValuesAtPseudoExit;
563     PHINode *IndVarEnd = nullptr;
564 
565     RewrittenRangeInfo() = default;
566   };
567 
568   // Calculated subranges we restrict the iteration space of the main loop to.
569   // See the implementation of `calculateSubRanges' for more details on how
570   // these fields are computed.  `LowLimit` is None if there is no restriction
571   // on low end of the restricted iteration space of the main loop.  `HighLimit`
572   // is None if there is no restriction on high end of the restricted iteration
573   // space of the main loop.
574 
575   struct SubRanges {
576     Optional<const SCEV *> LowLimit;
577     Optional<const SCEV *> HighLimit;
578   };
579 
580   // A utility function that does a `replaceUsesOfWith' on the incoming block
581   // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
582   // incoming block list with `ReplaceBy'.
583   static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
584                               BasicBlock *ReplaceBy);
585 
586   // Compute a safe set of limits for the main loop to run in -- effectively the
587   // intersection of `Range' and the iteration space of the original loop.
588   // Return None if unable to compute the set of subranges.
589   Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
590 
591   // Clone `OriginalLoop' and return the result in CLResult.  The IR after
592   // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
593   // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
594   // but there is no such edge.
595   void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
596 
597   // Create the appropriate loop structure needed to describe a cloned copy of
598   // `Original`.  The clone is described by `VM`.
599   Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
600                                   ValueToValueMapTy &VM);
601 
602   // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
603   // iteration space of the rewritten loop ends at ExitLoopAt.  The start of the
604   // iteration space is not changed.  `ExitLoopAt' is assumed to be slt
605   // `OriginalHeaderCount'.
606   //
607   // If there are iterations left to execute, control is made to jump to
608   // `ContinuationBlock', otherwise they take the normal loop exit.  The
609   // returned `RewrittenRangeInfo' object is populated as follows:
610   //
611   //  .PseudoExit is a basic block that unconditionally branches to
612   //      `ContinuationBlock'.
613   //
614   //  .ExitSelector is a basic block that decides, on exit from the loop,
615   //      whether to branch to the "true" exit or to `PseudoExit'.
616   //
617   //  .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
618   //      for each PHINode in the loop header on taking the pseudo exit.
619   //
620   // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
621   // preheader because it is made to branch to the loop header only
622   // conditionally.
623   RewrittenRangeInfo
624   changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
625                           Value *ExitLoopAt,
626                           BasicBlock *ContinuationBlock) const;
627 
628   // The loop denoted by `LS' has `OldPreheader' as its preheader.  This
629   // function creates a new preheader for `LS' and returns it.
630   BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
631                               const char *Tag) const;
632 
633   // `ContinuationBlockAndPreheader' was the continuation block for some call to
634   // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
635   // This function rewrites the PHI nodes in `LS.Header' to start with the
636   // correct value.
637   void rewriteIncomingValuesForPHIs(
638       LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
639       const LoopConstrainer::RewrittenRangeInfo &RRI) const;
640 
641   // Even though we do not preserve any passes at this time, we at least need to
642   // keep the parent loop structure consistent.  The `LPPassManager' seems to
643   // verify this after running a loop pass.  This function adds the list of
644   // blocks denoted by BBs to this loops parent loop if required.
645   void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
646 
647   // Some global state.
648   Function &F;
649   LLVMContext &Ctx;
650   ScalarEvolution &SE;
651   DominatorTree &DT;
652   LPPassManager &LPM;
653   LoopInfo &LI;
654 
655   // Information about the original loop we started out with.
656   Loop &OriginalLoop;
657 
658   const SCEV *LatchTakenCount = nullptr;
659   BasicBlock *OriginalPreheader = nullptr;
660 
661   // The preheader of the main loop.  This may or may not be different from
662   // `OriginalPreheader'.
663   BasicBlock *MainLoopPreheader = nullptr;
664 
665   // The range we need to run the main loop in.
666   InductiveRangeCheck::Range Range;
667 
668   // The structure of the main loop (see comment at the beginning of this class
669   // for a definition)
670   LoopStructure MainLoopStructure;
671 
672 public:
673   LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
674                   const LoopStructure &LS, ScalarEvolution &SE,
675                   DominatorTree &DT, InductiveRangeCheck::Range R)
676       : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
677         SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
678         MainLoopStructure(LS) {}
679 
680   // Entry point for the algorithm.  Returns true on success.
681   bool run();
682 };
683 
684 } // end anonymous namespace
685 
686 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
687                                       BasicBlock *ReplaceBy) {
688   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
689     if (PN->getIncomingBlock(i) == Block)
690       PN->setIncomingBlock(i, ReplaceBy);
691 }
692 
693 static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
694   APInt Max = Signed ?
695       APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
696       APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
697   return SE.getSignedRange(S).contains(Max) &&
698          SE.getUnsignedRange(S).contains(Max);
699 }
700 
701 static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
702                            bool Signed) {
703   // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
704   assert(SE.isKnownNonNegative(S2) &&
705          "We expected the 2nd arg to be non-negative!");
706   const SCEV *Max = SE.getConstant(
707       Signed ? APInt::getSignedMaxValue(
708                    cast<IntegerType>(S1->getType())->getBitWidth())
709              : APInt::getMaxValue(
710                    cast<IntegerType>(S1->getType())->getBitWidth()));
711   const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
712   return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
713                               S1, CapForS1);
714 }
715 
716 static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
717   APInt Min = Signed ?
718       APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
719       APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
720   return SE.getSignedRange(S).contains(Min) &&
721          SE.getUnsignedRange(S).contains(Min);
722 }
723 
724 static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
725                            bool Signed) {
726   // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
727   assert(SE.isKnownNonPositive(S2) &&
728          "We expected the 2nd arg to be non-positive!");
729   const SCEV *Max = SE.getConstant(
730       Signed ? APInt::getSignedMinValue(
731                    cast<IntegerType>(S1->getType())->getBitWidth())
732              : APInt::getMinValue(
733                    cast<IntegerType>(S1->getType())->getBitWidth()));
734   const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
735   return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
736                               S1, CapForS1);
737 }
738 
739 Optional<LoopStructure>
740 LoopStructure::parseLoopStructure(ScalarEvolution &SE,
741                                   BranchProbabilityInfo &BPI,
742                                   Loop &L, const char *&FailureReason) {
743   if (!L.isLoopSimplifyForm()) {
744     FailureReason = "loop not in LoopSimplify form";
745     return None;
746   }
747 
748   BasicBlock *Latch = L.getLoopLatch();
749   assert(Latch && "Simplified loops only have one latch!");
750 
751   if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
752     FailureReason = "loop has already been cloned";
753     return None;
754   }
755 
756   if (!L.isLoopExiting(Latch)) {
757     FailureReason = "no loop latch";
758     return None;
759   }
760 
761   BasicBlock *Header = L.getHeader();
762   BasicBlock *Preheader = L.getLoopPreheader();
763   if (!Preheader) {
764     FailureReason = "no preheader";
765     return None;
766   }
767 
768   BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
769   if (!LatchBr || LatchBr->isUnconditional()) {
770     FailureReason = "latch terminator not conditional branch";
771     return None;
772   }
773 
774   unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
775 
776   BranchProbability ExitProbability =
777     BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
778 
779   if (!SkipProfitabilityChecks &&
780       ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
781     FailureReason = "short running loop, not profitable";
782     return None;
783   }
784 
785   ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
786   if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
787     FailureReason = "latch terminator branch not conditional on integral icmp";
788     return None;
789   }
790 
791   const SCEV *LatchCount = SE.getExitCount(&L, Latch);
792   if (isa<SCEVCouldNotCompute>(LatchCount)) {
793     FailureReason = "could not compute latch count";
794     return None;
795   }
796 
797   ICmpInst::Predicate Pred = ICI->getPredicate();
798   Value *LeftValue = ICI->getOperand(0);
799   const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
800   IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
801 
802   Value *RightValue = ICI->getOperand(1);
803   const SCEV *RightSCEV = SE.getSCEV(RightValue);
804 
805   // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
806   if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
807     if (isa<SCEVAddRecExpr>(RightSCEV)) {
808       std::swap(LeftSCEV, RightSCEV);
809       std::swap(LeftValue, RightValue);
810       Pred = ICmpInst::getSwappedPredicate(Pred);
811     } else {
812       FailureReason = "no add recurrences in the icmp";
813       return None;
814     }
815   }
816 
817   auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
818     if (AR->getNoWrapFlags(SCEV::FlagNSW))
819       return true;
820 
821     IntegerType *Ty = cast<IntegerType>(AR->getType());
822     IntegerType *WideTy =
823         IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
824 
825     const SCEVAddRecExpr *ExtendAfterOp =
826         dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
827     if (ExtendAfterOp) {
828       const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
829       const SCEV *ExtendedStep =
830           SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
831 
832       bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
833                           ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
834 
835       if (NoSignedWrap)
836         return true;
837     }
838 
839     // We may have proved this when computing the sign extension above.
840     return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
841   };
842 
843   // Here we check whether the suggested AddRec is an induction variable that
844   // can be handled (i.e. with known constant step), and if yes, calculate its
845   // step and identify whether it is increasing or decreasing.
846   auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
847                             ConstantInt *&StepCI) {
848     if (!AR->isAffine())
849       return false;
850 
851     // Currently we only work with induction variables that have been proved to
852     // not wrap.  This restriction can potentially be lifted in the future.
853 
854     if (!HasNoSignedWrap(AR))
855       return false;
856 
857     if (const SCEVConstant *StepExpr =
858             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
859       StepCI = StepExpr->getValue();
860       assert(!StepCI->isZero() && "Zero step?");
861       IsIncreasing = !StepCI->isNegative();
862       return true;
863     }
864 
865     return false;
866   };
867 
868   // `ICI` is interpreted as taking the backedge if the *next* value of the
869   // induction variable satisfies some constraint.
870 
871   const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
872   bool IsIncreasing = false;
873   bool IsSignedPredicate = true;
874   ConstantInt *StepCI;
875   if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
876     FailureReason = "LHS in icmp not induction variable";
877     return None;
878   }
879 
880   const SCEV *StartNext = IndVarBase->getStart();
881   const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
882   const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
883   const SCEV *Step = SE.getSCEV(StepCI);
884 
885   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
886   if (IsIncreasing) {
887     bool DecreasedRightValueByOne = false;
888     if (StepCI->isOne()) {
889       // Try to turn eq/ne predicates to those we can work with.
890       if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
891         // while (++i != len) {         while (++i < len) {
892         //   ...                 --->     ...
893         // }                            }
894         // If both parts are known non-negative, it is profitable to use
895         // unsigned comparison in increasing loop. This allows us to make the
896         // comparison check against "RightSCEV + 1" more optimistic.
897         if (SE.isKnownNonNegative(IndVarStart) &&
898             SE.isKnownNonNegative(RightSCEV))
899           Pred = ICmpInst::ICMP_ULT;
900         else
901           Pred = ICmpInst::ICMP_SLT;
902       else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
903                !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
904         // while (true) {               while (true) {
905         //   if (++i == len)     --->     if (++i > len - 1)
906         //     break;                       break;
907         //   ...                          ...
908         // }                            }
909         // TODO: Insert ICMP_UGT if both are non-negative?
910         Pred = ICmpInst::ICMP_SGT;
911         RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
912         DecreasedRightValueByOne = true;
913       }
914     }
915 
916     bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
917     bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
918     bool FoundExpectedPred =
919         (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
920 
921     if (!FoundExpectedPred) {
922       FailureReason = "expected icmp slt semantically, found something else";
923       return None;
924     }
925 
926     IsSignedPredicate =
927         Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
928 
929     if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
930       FailureReason = "unsigned latch conditions are explicitly prohibited";
931       return None;
932     }
933 
934     // The predicate that we need to check that the induction variable lies
935     // within bounds.
936     ICmpInst::Predicate BoundPred =
937         IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
938 
939     if (LatchBrExitIdx == 0) {
940       const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
941                                                  SE.getOne(Step->getType()));
942       if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
943         // TODO: this restriction is easily removable -- we just have to
944         // remember that the icmp was an slt and not an sle.
945         FailureReason = "limit may overflow when coercing le to lt";
946         return None;
947       }
948 
949       if (!SE.isLoopEntryGuardedByCond(
950               &L, BoundPred, IndVarStart,
951               SE.getAddExpr(RightSCEV, Step))) {
952         FailureReason = "Induction variable start not bounded by upper limit";
953         return None;
954       }
955 
956       // We need to increase the right value unless we have already decreased
957       // it virtually when we replaced EQ with SGT.
958       if (!DecreasedRightValueByOne) {
959         IRBuilder<> B(Preheader->getTerminator());
960         RightValue = B.CreateAdd(RightValue, One);
961       }
962     } else {
963       if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
964         FailureReason = "Induction variable start not bounded by upper limit";
965         return None;
966       }
967       assert(!DecreasedRightValueByOne &&
968              "Right value can be decreased only for LatchBrExitIdx == 0!");
969     }
970   } else {
971     bool IncreasedRightValueByOne = false;
972     if (StepCI->isMinusOne()) {
973       // Try to turn eq/ne predicates to those we can work with.
974       if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
975         // while (--i != len) {         while (--i > len) {
976         //   ...                 --->     ...
977         // }                            }
978         // We intentionally don't turn the predicate into UGT even if we know
979         // that both operands are non-negative, because it will only pessimize
980         // our check against "RightSCEV - 1".
981         Pred = ICmpInst::ICMP_SGT;
982       else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
983                !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
984         // while (true) {               while (true) {
985         //   if (--i == len)     --->     if (--i < len + 1)
986         //     break;                       break;
987         //   ...                          ...
988         // }                            }
989         // TODO: Insert ICMP_ULT if both are non-negative?
990         Pred = ICmpInst::ICMP_SLT;
991         RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
992         IncreasedRightValueByOne = true;
993       }
994     }
995 
996     bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
997     bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
998 
999     bool FoundExpectedPred =
1000         (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
1001 
1002     if (!FoundExpectedPred) {
1003       FailureReason = "expected icmp sgt semantically, found something else";
1004       return None;
1005     }
1006 
1007     IsSignedPredicate =
1008         Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
1009 
1010     if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
1011       FailureReason = "unsigned latch conditions are explicitly prohibited";
1012       return None;
1013     }
1014 
1015     // The predicate that we need to check that the induction variable lies
1016     // within bounds.
1017     ICmpInst::Predicate BoundPred =
1018         IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
1019 
1020     if (LatchBrExitIdx == 0) {
1021       const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
1022       if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
1023         // TODO: this restriction is easily removable -- we just have to
1024         // remember that the icmp was an sgt and not an sge.
1025         FailureReason = "limit may overflow when coercing ge to gt";
1026         return None;
1027       }
1028 
1029       if (!SE.isLoopEntryGuardedByCond(
1030               &L, BoundPred, IndVarStart,
1031               SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1032         FailureReason = "Induction variable start not bounded by lower limit";
1033         return None;
1034       }
1035 
1036       // We need to decrease the right value unless we have already increased
1037       // it virtually when we replaced EQ with SLT.
1038       if (!IncreasedRightValueByOne) {
1039         IRBuilder<> B(Preheader->getTerminator());
1040         RightValue = B.CreateSub(RightValue, One);
1041       }
1042     } else {
1043       if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
1044         FailureReason = "Induction variable start not bounded by lower limit";
1045         return None;
1046       }
1047       assert(!IncreasedRightValueByOne &&
1048              "Right value can be increased only for LatchBrExitIdx == 0!");
1049     }
1050   }
1051   BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1052 
1053   assert(SE.getLoopDisposition(LatchCount, &L) ==
1054              ScalarEvolution::LoopInvariant &&
1055          "loop variant exit count doesn't make sense!");
1056 
1057   assert(!L.contains(LatchExit) && "expected an exit block!");
1058   const DataLayout &DL = Preheader->getModule()->getDataLayout();
1059   Value *IndVarStartV =
1060       SCEVExpander(SE, DL, "irce")
1061           .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
1062   IndVarStartV->setName("indvar.start");
1063 
1064   LoopStructure Result;
1065 
1066   Result.Tag = "main";
1067   Result.Header = Header;
1068   Result.Latch = Latch;
1069   Result.LatchBr = LatchBr;
1070   Result.LatchExit = LatchExit;
1071   Result.LatchBrExitIdx = LatchBrExitIdx;
1072   Result.IndVarStart = IndVarStartV;
1073   Result.IndVarStep = StepCI;
1074   Result.IndVarBase = LeftValue;
1075   Result.IndVarIncreasing = IsIncreasing;
1076   Result.LoopExitAt = RightValue;
1077   Result.IsSignedPredicate = IsSignedPredicate;
1078 
1079   FailureReason = nullptr;
1080 
1081   return Result;
1082 }
1083 
1084 Optional<LoopConstrainer::SubRanges>
1085 LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
1086   IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1087 
1088   if (Range.getType() != Ty)
1089     return None;
1090 
1091   LoopConstrainer::SubRanges Result;
1092 
1093   // I think we can be more aggressive here and make this nuw / nsw if the
1094   // addition that feeds into the icmp for the latch's terminating branch is nuw
1095   // / nsw.  In any case, a wrapping 2's complement addition is safe.
1096   const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1097   const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
1098 
1099   bool Increasing = MainLoopStructure.IndVarIncreasing;
1100 
1101   // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1102   // [Smallest, GreatestSeen] is the range of values the induction variable
1103   // takes.
1104 
1105   const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
1106 
1107   const SCEV *One = SE.getOne(Ty);
1108   if (Increasing) {
1109     Smallest = Start;
1110     Greatest = End;
1111     // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1112     GreatestSeen = SE.getMinusSCEV(End, One);
1113   } else {
1114     // These two computations may sign-overflow.  Here is why that is okay:
1115     //
1116     // We know that the induction variable does not sign-overflow on any
1117     // iteration except the last one, and it starts at `Start` and ends at
1118     // `End`, decrementing by one every time.
1119     //
1120     //  * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1121     //    induction variable is decreasing we know that that the smallest value
1122     //    the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1123     //
1124     //  * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`.  In
1125     //    that case, `Clamp` will always return `Smallest` and
1126     //    [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1127     //    will be an empty range.  Returning an empty range is always safe.
1128 
1129     Smallest = SE.getAddExpr(End, One);
1130     Greatest = SE.getAddExpr(Start, One);
1131     GreatestSeen = Start;
1132   }
1133 
1134   auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
1135     return IsSignedPredicate
1136                ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1137                : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
1138   };
1139 
1140   // In some cases we can prove that we don't need a pre or post loop.
1141   ICmpInst::Predicate PredLE =
1142       IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1143   ICmpInst::Predicate PredLT =
1144       IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1145 
1146   bool ProvablyNoPreloop =
1147       SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
1148   if (!ProvablyNoPreloop)
1149     Result.LowLimit = Clamp(Range.getBegin());
1150 
1151   bool ProvablyNoPostLoop =
1152       SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
1153   if (!ProvablyNoPostLoop)
1154     Result.HighLimit = Clamp(Range.getEnd());
1155 
1156   return Result;
1157 }
1158 
1159 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1160                                 const char *Tag) const {
1161   for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1162     BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1163     Result.Blocks.push_back(Clone);
1164     Result.Map[BB] = Clone;
1165   }
1166 
1167   auto GetClonedValue = [&Result](Value *V) {
1168     assert(V && "null values not in domain!");
1169     auto It = Result.Map.find(V);
1170     if (It == Result.Map.end())
1171       return V;
1172     return static_cast<Value *>(It->second);
1173   };
1174 
1175   auto *ClonedLatch =
1176       cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1177   ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1178                                             MDNode::get(Ctx, {}));
1179 
1180   Result.Structure = MainLoopStructure.map(GetClonedValue);
1181   Result.Structure.Tag = Tag;
1182 
1183   for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1184     BasicBlock *ClonedBB = Result.Blocks[i];
1185     BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1186 
1187     assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1188 
1189     for (Instruction &I : *ClonedBB)
1190       RemapInstruction(&I, Result.Map,
1191                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1192 
1193     // Exit blocks will now have one more predecessor and their PHI nodes need
1194     // to be edited to reflect that.  No phi nodes need to be introduced because
1195     // the loop is in LCSSA.
1196 
1197     for (auto *SBB : successors(OriginalBB)) {
1198       if (OriginalLoop.contains(SBB))
1199         continue; // not an exit block
1200 
1201       for (Instruction &I : *SBB) {
1202         auto *PN = dyn_cast<PHINode>(&I);
1203         if (!PN)
1204           break;
1205 
1206         Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1207         PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1208       }
1209     }
1210   }
1211 }
1212 
1213 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
1214     const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
1215     BasicBlock *ContinuationBlock) const {
1216   // We start with a loop with a single latch:
1217   //
1218   //    +--------------------+
1219   //    |                    |
1220   //    |     preheader      |
1221   //    |                    |
1222   //    +--------+-----------+
1223   //             |      ----------------\
1224   //             |     /                |
1225   //    +--------v----v------+          |
1226   //    |                    |          |
1227   //    |      header        |          |
1228   //    |                    |          |
1229   //    +--------------------+          |
1230   //                                    |
1231   //            .....                   |
1232   //                                    |
1233   //    +--------------------+          |
1234   //    |                    |          |
1235   //    |       latch        >----------/
1236   //    |                    |
1237   //    +-------v------------+
1238   //            |
1239   //            |
1240   //            |   +--------------------+
1241   //            |   |                    |
1242   //            +--->   original exit    |
1243   //                |                    |
1244   //                +--------------------+
1245   //
1246   // We change the control flow to look like
1247   //
1248   //
1249   //    +--------------------+
1250   //    |                    |
1251   //    |     preheader      >-------------------------+
1252   //    |                    |                         |
1253   //    +--------v-----------+                         |
1254   //             |    /-------------+                  |
1255   //             |   /              |                  |
1256   //    +--------v--v--------+      |                  |
1257   //    |                    |      |                  |
1258   //    |      header        |      |   +--------+     |
1259   //    |                    |      |   |        |     |
1260   //    +--------------------+      |   |  +-----v-----v-----------+
1261   //                                |   |  |                       |
1262   //                                |   |  |     .pseudo.exit      |
1263   //                                |   |  |                       |
1264   //                                |   |  +-----------v-----------+
1265   //                                |   |              |
1266   //            .....               |   |              |
1267   //                                |   |     +--------v-------------+
1268   //    +--------------------+      |   |     |                      |
1269   //    |                    |      |   |     |   ContinuationBlock  |
1270   //    |       latch        >------+   |     |                      |
1271   //    |                    |          |     +----------------------+
1272   //    +---------v----------+          |
1273   //              |                     |
1274   //              |                     |
1275   //              |     +---------------^-----+
1276   //              |     |                     |
1277   //              +----->    .exit.selector   |
1278   //                    |                     |
1279   //                    +----------v----------+
1280   //                               |
1281   //     +--------------------+    |
1282   //     |                    |    |
1283   //     |   original exit    <----+
1284   //     |                    |
1285   //     +--------------------+
1286 
1287   RewrittenRangeInfo RRI;
1288 
1289   BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
1290   RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1291                                         &F, BBInsertLocation);
1292   RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1293                                       BBInsertLocation);
1294 
1295   BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
1296   bool Increasing = LS.IndVarIncreasing;
1297   bool IsSignedPredicate = LS.IsSignedPredicate;
1298 
1299   IRBuilder<> B(PreheaderJump);
1300 
1301   // EnterLoopCond - is it okay to start executing this `LS'?
1302   Value *EnterLoopCond = nullptr;
1303   if (Increasing)
1304     EnterLoopCond = IsSignedPredicate
1305                         ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1306                         : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1307   else
1308     EnterLoopCond = IsSignedPredicate
1309                         ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1310                         : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
1311 
1312   B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1313   PreheaderJump->eraseFromParent();
1314 
1315   LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1316   B.SetInsertPoint(LS.LatchBr);
1317   Value *TakeBackedgeLoopCond = nullptr;
1318   if (Increasing)
1319     TakeBackedgeLoopCond = IsSignedPredicate
1320                         ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1321                         : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
1322   else
1323     TakeBackedgeLoopCond = IsSignedPredicate
1324                         ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1325                         : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
1326   Value *CondForBranch = LS.LatchBrExitIdx == 1
1327                              ? TakeBackedgeLoopCond
1328                              : B.CreateNot(TakeBackedgeLoopCond);
1329 
1330   LS.LatchBr->setCondition(CondForBranch);
1331 
1332   B.SetInsertPoint(RRI.ExitSelector);
1333 
1334   // IterationsLeft - are there any more iterations left, given the original
1335   // upper bound on the induction variable?  If not, we branch to the "real"
1336   // exit.
1337   Value *IterationsLeft = nullptr;
1338   if (Increasing)
1339     IterationsLeft = IsSignedPredicate
1340                          ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1341                          : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
1342   else
1343     IterationsLeft = IsSignedPredicate
1344                          ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1345                          : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
1346   B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1347 
1348   BranchInst *BranchToContinuation =
1349       BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1350 
1351   // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1352   // each of the PHI nodes in the loop header.  This feeds into the initial
1353   // value of the same PHI nodes if/when we continue execution.
1354   for (Instruction &I : *LS.Header) {
1355     auto *PN = dyn_cast<PHINode>(&I);
1356     if (!PN)
1357       break;
1358 
1359     PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1360                                       BranchToContinuation);
1361 
1362     NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1363     NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1364                         RRI.ExitSelector);
1365     RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1366   }
1367 
1368   RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
1369                                   BranchToContinuation);
1370   RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1371   RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
1372 
1373   // The latch exit now has a branch from `RRI.ExitSelector' instead of
1374   // `LS.Latch'.  The PHI nodes need to be updated to reflect that.
1375   for (Instruction &I : *LS.LatchExit) {
1376     if (PHINode *PN = dyn_cast<PHINode>(&I))
1377       replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1378     else
1379       break;
1380   }
1381 
1382   return RRI;
1383 }
1384 
1385 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1386     LoopStructure &LS, BasicBlock *ContinuationBlock,
1387     const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1388   unsigned PHIIndex = 0;
1389   for (Instruction &I : *LS.Header) {
1390     auto *PN = dyn_cast<PHINode>(&I);
1391     if (!PN)
1392       break;
1393 
1394     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1395       if (PN->getIncomingBlock(i) == ContinuationBlock)
1396         PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1397   }
1398 
1399   LS.IndVarStart = RRI.IndVarEnd;
1400 }
1401 
1402 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1403                                              BasicBlock *OldPreheader,
1404                                              const char *Tag) const {
1405   BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1406   BranchInst::Create(LS.Header, Preheader);
1407 
1408   for (Instruction &I : *LS.Header) {
1409     auto *PN = dyn_cast<PHINode>(&I);
1410     if (!PN)
1411       break;
1412 
1413     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1414       replacePHIBlock(PN, OldPreheader, Preheader);
1415   }
1416 
1417   return Preheader;
1418 }
1419 
1420 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1421   Loop *ParentLoop = OriginalLoop.getParentLoop();
1422   if (!ParentLoop)
1423     return;
1424 
1425   for (BasicBlock *BB : BBs)
1426     ParentLoop->addBasicBlockToLoop(BB, LI);
1427 }
1428 
1429 Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1430                                                  ValueToValueMapTy &VM) {
1431   Loop &New = *LI.AllocateLoop();
1432   if (Parent)
1433     Parent->addChildLoop(&New);
1434   else
1435     LI.addTopLevelLoop(&New);
1436   LPM.addLoop(New);
1437 
1438   // Add all of the blocks in Original to the new loop.
1439   for (auto *BB : Original->blocks())
1440     if (LI.getLoopFor(BB) == Original)
1441       New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1442 
1443   // Add all of the subloops to the new loop.
1444   for (Loop *SubLoop : *Original)
1445     createClonedLoopStructure(SubLoop, &New, VM);
1446 
1447   return &New;
1448 }
1449 
1450 bool LoopConstrainer::run() {
1451   BasicBlock *Preheader = nullptr;
1452   LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1453   Preheader = OriginalLoop.getLoopPreheader();
1454   assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1455          "preconditions!");
1456 
1457   OriginalPreheader = Preheader;
1458   MainLoopPreheader = Preheader;
1459 
1460   bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1461   Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
1462   if (!MaybeSR.hasValue()) {
1463     DEBUG(dbgs() << "irce: could not compute subranges\n");
1464     return false;
1465   }
1466 
1467   SubRanges SR = MaybeSR.getValue();
1468   bool Increasing = MainLoopStructure.IndVarIncreasing;
1469   IntegerType *IVTy =
1470       cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
1471 
1472   SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1473   Instruction *InsertPt = OriginalPreheader->getTerminator();
1474 
1475   // It would have been better to make `PreLoop' and `PostLoop'
1476   // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1477   // constructor.
1478   ClonedLoop PreLoop, PostLoop;
1479   bool NeedsPreLoop =
1480       Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1481   bool NeedsPostLoop =
1482       Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1483 
1484   Value *ExitPreLoopAt = nullptr;
1485   Value *ExitMainLoopAt = nullptr;
1486   const SCEVConstant *MinusOneS =
1487       cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1488 
1489   if (NeedsPreLoop) {
1490     const SCEV *ExitPreLoopAtSCEV = nullptr;
1491 
1492     if (Increasing)
1493       ExitPreLoopAtSCEV = *SR.LowLimit;
1494     else {
1495       if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
1496         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1497                      << "preloop exit limit.  HighLimit = " << *(*SR.HighLimit)
1498                      << "\n");
1499         return false;
1500       }
1501       ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1502     }
1503 
1504     ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1505     ExitPreLoopAt->setName("exit.preloop.at");
1506   }
1507 
1508   if (NeedsPostLoop) {
1509     const SCEV *ExitMainLoopAtSCEV = nullptr;
1510 
1511     if (Increasing)
1512       ExitMainLoopAtSCEV = *SR.HighLimit;
1513     else {
1514       if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
1515         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1516                      << "mainloop exit limit.  LowLimit = " << *(*SR.LowLimit)
1517                      << "\n");
1518         return false;
1519       }
1520       ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1521     }
1522 
1523     ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1524     ExitMainLoopAt->setName("exit.mainloop.at");
1525   }
1526 
1527   // We clone these ahead of time so that we don't have to deal with changing
1528   // and temporarily invalid IR as we transform the loops.
1529   if (NeedsPreLoop)
1530     cloneLoop(PreLoop, "preloop");
1531   if (NeedsPostLoop)
1532     cloneLoop(PostLoop, "postloop");
1533 
1534   RewrittenRangeInfo PreLoopRRI;
1535 
1536   if (NeedsPreLoop) {
1537     Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1538                                                   PreLoop.Structure.Header);
1539 
1540     MainLoopPreheader =
1541         createPreheader(MainLoopStructure, Preheader, "mainloop");
1542     PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1543                                          ExitPreLoopAt, MainLoopPreheader);
1544     rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1545                                  PreLoopRRI);
1546   }
1547 
1548   BasicBlock *PostLoopPreheader = nullptr;
1549   RewrittenRangeInfo PostLoopRRI;
1550 
1551   if (NeedsPostLoop) {
1552     PostLoopPreheader =
1553         createPreheader(PostLoop.Structure, Preheader, "postloop");
1554     PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1555                                           ExitMainLoopAt, PostLoopPreheader);
1556     rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1557                                  PostLoopRRI);
1558   }
1559 
1560   BasicBlock *NewMainLoopPreheader =
1561       MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1562   BasicBlock *NewBlocks[] = {PostLoopPreheader,        PreLoopRRI.PseudoExit,
1563                              PreLoopRRI.ExitSelector,  PostLoopRRI.PseudoExit,
1564                              PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1565 
1566   // Some of the above may be nullptr, filter them out before passing to
1567   // addToParentLoopIfNeeded.
1568   auto NewBlocksEnd =
1569       std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1570 
1571   addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1572 
1573   DT.recalculate(F);
1574 
1575   // We need to first add all the pre and post loop blocks into the loop
1576   // structures (as part of createClonedLoopStructure), and then update the
1577   // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1578   // LI when LoopSimplifyForm is generated.
1579   Loop *PreL = nullptr, *PostL = nullptr;
1580   if (!PreLoop.Blocks.empty()) {
1581     PreL = createClonedLoopStructure(
1582         &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
1583   }
1584 
1585   if (!PostLoop.Blocks.empty()) {
1586     PostL = createClonedLoopStructure(
1587         &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
1588   }
1589 
1590   // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1591   auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1592     formLCSSARecursively(*L, DT, &LI, &SE);
1593     simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1594     // Pre/post loops are slow paths, we do not need to perform any loop
1595     // optimizations on them.
1596     if (!IsOriginalLoop)
1597       DisableAllLoopOptsOnLoop(*L);
1598   };
1599   if (PreL)
1600     CanonicalizeLoop(PreL, false);
1601   if (PostL)
1602     CanonicalizeLoop(PostL, false);
1603   CanonicalizeLoop(&OriginalLoop, true);
1604 
1605   return true;
1606 }
1607 
1608 /// Computes and returns a range of values for the induction variable (IndVar)
1609 /// in which the range check can be safely elided.  If it cannot compute such a
1610 /// range, returns None.
1611 Optional<InductiveRangeCheck::Range>
1612 InductiveRangeCheck::computeSafeIterationSpace(
1613     ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
1614   // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1615   // variable, that may or may not exist as a real llvm::Value in the loop) and
1616   // this inductive range check is a range check on the "C + D * I" ("C" is
1617   // getBegin() and "D" is getStep()).  We rewrite the value being range
1618   // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1619   //
1620   // The actual inequalities we solve are of the form
1621   //
1622   //   0 <= M + 1 * IndVar < L given L >= 0  (i.e. N == 1)
1623   //
1624   // The inequality is satisfied by -M <= IndVar < (L - M) [^1].  All additions
1625   // and subtractions are twos-complement wrapping and comparisons are signed.
1626   //
1627   // Proof:
1628   //
1629   //   If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1630   //   that -M <= (-M + L) [== Eq. 1].  Since L >= 0, if (-M + L) sign-overflows
1631   //   then (-M + L) < (-M).  Hence by [Eq. 1], (-M + L) could not have
1632   //   overflown.
1633   //
1634   //   This means IndVar = t + (-M) for t in [0, L).  Hence (IndVar + M) = t.
1635   //   Hence 0 <= (IndVar + M) < L
1636 
1637   // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1638   // 127, IndVar = 126 and L = -2 in an i8 world.
1639 
1640   if (!IndVar->isAffine())
1641     return None;
1642 
1643   const SCEV *A = IndVar->getStart();
1644   const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1645   if (!B)
1646     return None;
1647   assert(!B->isZero() && "Recurrence with zero step?");
1648 
1649   const SCEV *C = getBegin();
1650   const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
1651   if (D != B)
1652     return None;
1653 
1654   assert(!D->getValue()->isZero() && "Recurrence with zero step?");
1655 
1656   const SCEV *M = SE.getMinusSCEV(C, A);
1657   const SCEV *Begin = SE.getNegativeSCEV(M);
1658   const SCEV *UpperLimit = nullptr;
1659 
1660   // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1661   // We can potentially do much better here.
1662   if (const SCEV *L = getEnd())
1663     UpperLimit = L;
1664   else {
1665     assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1666     unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1667     UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1668   }
1669 
1670   const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1671   return InductiveRangeCheck::Range(Begin, End);
1672 }
1673 
1674 static Optional<InductiveRangeCheck::Range>
1675 IntersectSignedRange(ScalarEvolution &SE,
1676                      const Optional<InductiveRangeCheck::Range> &R1,
1677                      const InductiveRangeCheck::Range &R2) {
1678   if (R2.isEmpty(SE, /* IsSigned */ true))
1679     return None;
1680   if (!R1.hasValue())
1681     return R2;
1682   auto &R1Value = R1.getValue();
1683   // We never return empty ranges from this function, and R1 is supposed to be
1684   // a result of intersection. Thus, R1 is never empty.
1685   assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1686          "We should never have empty R1!");
1687 
1688   // TODO: we could widen the smaller range and have this work; but for now we
1689   // bail out to keep things simple.
1690   if (R1Value.getType() != R2.getType())
1691     return None;
1692 
1693   const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1694   const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1695 
1696   // If the resulting range is empty, just return None.
1697   auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1698   if (Ret.isEmpty(SE, /* IsSigned */ true))
1699     return None;
1700   return Ret;
1701 }
1702 
1703 static Optional<InductiveRangeCheck::Range>
1704 IntersectUnsignedRange(ScalarEvolution &SE,
1705                        const Optional<InductiveRangeCheck::Range> &R1,
1706                        const InductiveRangeCheck::Range &R2) {
1707   if (R2.isEmpty(SE, /* IsSigned */ false))
1708     return None;
1709   if (!R1.hasValue())
1710     return R2;
1711   auto &R1Value = R1.getValue();
1712   // We never return empty ranges from this function, and R1 is supposed to be
1713   // a result of intersection. Thus, R1 is never empty.
1714   assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1715          "We should never have empty R1!");
1716 
1717   // TODO: we could widen the smaller range and have this work; but for now we
1718   // bail out to keep things simple.
1719   if (R1Value.getType() != R2.getType())
1720     return None;
1721 
1722   const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1723   const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1724 
1725   // If the resulting range is empty, just return None.
1726   auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1727   if (Ret.isEmpty(SE, /* IsSigned */ false))
1728     return None;
1729   return Ret;
1730 }
1731 
1732 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1733   if (skipLoop(L))
1734     return false;
1735 
1736   if (L->getBlocks().size() >= LoopSizeCutoff) {
1737     DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1738     return false;
1739   }
1740 
1741   BasicBlock *Preheader = L->getLoopPreheader();
1742   if (!Preheader) {
1743     DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1744     return false;
1745   }
1746 
1747   LLVMContext &Context = Preheader->getContext();
1748   SmallVector<InductiveRangeCheck, 16> RangeChecks;
1749   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1750   BranchProbabilityInfo &BPI =
1751       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1752 
1753   for (auto BBI : L->getBlocks())
1754     if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1755       InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1756                                                         RangeChecks);
1757 
1758   if (RangeChecks.empty())
1759     return false;
1760 
1761   auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1762     OS << "irce: looking at loop "; L->print(OS);
1763     OS << "irce: loop has " << RangeChecks.size()
1764        << " inductive range checks: \n";
1765     for (InductiveRangeCheck &IRC : RangeChecks)
1766       IRC.print(OS);
1767   };
1768 
1769   DEBUG(PrintRecognizedRangeChecks(dbgs()));
1770 
1771   if (PrintRangeChecks)
1772     PrintRecognizedRangeChecks(errs());
1773 
1774   const char *FailureReason = nullptr;
1775   Optional<LoopStructure> MaybeLoopStructure =
1776       LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1777   if (!MaybeLoopStructure.hasValue()) {
1778     DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1779                  << "\n";);
1780     return false;
1781   }
1782   LoopStructure LS = MaybeLoopStructure.getValue();
1783   const SCEVAddRecExpr *IndVar =
1784       cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
1785 
1786   Optional<InductiveRangeCheck::Range> SafeIterRange;
1787   Instruction *ExprInsertPt = Preheader->getTerminator();
1788 
1789   SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
1790   auto RangeIsNonNegative = [&](InductiveRangeCheck::Range &R) {
1791     return SE.isKnownNonNegative(R.getBegin()) &&
1792            SE.isKnownNonNegative(R.getEnd());
1793   };
1794   // Basing on the type of latch predicate, we interpret the IV iteration range
1795   // as signed or unsigned range. We use different min/max functions (signed or
1796   // unsigned) when intersecting this range with safe iteration ranges implied
1797   // by range checks.
1798   auto IntersectRange =
1799       LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
1800 
1801   IRBuilder<> B(ExprInsertPt);
1802   for (InductiveRangeCheck &IRC : RangeChecks) {
1803     auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
1804     if (Result.hasValue()) {
1805       // Intersecting a signed and an unsigned ranges may produce incorrect
1806       // results because we can use neither signed nor unsigned min/max for
1807       // reliably correct intersection if a range contains negative values
1808       // which are either actually negative or big positive. Intersection is
1809       // safe in two following cases:
1810       // 1. Both ranges are signed/unsigned, then we use signed/unsigned min/max
1811       //    respectively for their intersection;
1812       // 2. IRC safe iteration space only contains values from [0, SINT_MAX].
1813       //    The interpretation of these values is unambiguous.
1814       // We take the type of IV iteration range as a reference (we will
1815       // intersect it with the resulting range of all IRC's later in
1816       // calculateSubRanges). Only ranges of IRC of the same type are considered
1817       // for removal unless we prove that its range doesn't contain ambiguous
1818       // values.
1819       if (IRC.isSigned() != LS.IsSignedPredicate &&
1820           !RangeIsNonNegative(Result.getValue()))
1821         continue;
1822       auto MaybeSafeIterRange =
1823           IntersectRange(SE, SafeIterRange, Result.getValue());
1824       if (MaybeSafeIterRange.hasValue()) {
1825         assert(
1826             !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1827             "We should never return empty ranges!");
1828         RangeChecksToEliminate.push_back(IRC);
1829         SafeIterRange = MaybeSafeIterRange.getValue();
1830       }
1831     }
1832   }
1833 
1834   if (!SafeIterRange.hasValue())
1835     return false;
1836 
1837   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1838   LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1839                      LS, SE, DT, SafeIterRange.getValue());
1840   bool Changed = LC.run();
1841 
1842   if (Changed) {
1843     auto PrintConstrainedLoopInfo = [L]() {
1844       dbgs() << "irce: in function ";
1845       dbgs() << L->getHeader()->getParent()->getName() << ": ";
1846       dbgs() << "constrained ";
1847       L->print(dbgs());
1848     };
1849 
1850     DEBUG(PrintConstrainedLoopInfo());
1851 
1852     if (PrintChangedLoops)
1853       PrintConstrainedLoopInfo();
1854 
1855     // Optimize away the now-redundant range checks.
1856 
1857     for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1858       ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1859                                           ? ConstantInt::getTrue(Context)
1860                                           : ConstantInt::getFalse(Context);
1861       IRC.getCheckUse()->set(FoldedRangeCheck);
1862     }
1863   }
1864 
1865   return Changed;
1866 }
1867 
1868 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1869   return new InductiveRangeCheckElimination;
1870 }
1871