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