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