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