[LIR] Make the LoopIdiomRecognize pass get analyses essentially the same
[oota-llvm.git] / lib / Transforms / Scalar / LoopRerollPass.cpp
1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements a simple loop reroller.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasSetTracker.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpander.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/LoopUtils.h"
37
38 using namespace llvm;
39
40 #define DEBUG_TYPE "loop-reroll"
41
42 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
43
44 static cl::opt<unsigned>
45 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46   cl::desc("The maximum increment for loop rerolling"));
47
48 static cl::opt<unsigned>
49 NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
50                           cl::Hidden,
51                           cl::desc("The maximum number of failures to tolerate"
52                                    " during fuzzy matching. (default: 400)"));
53
54 // This loop re-rolling transformation aims to transform loops like this:
55 //
56 // int foo(int a);
57 // void bar(int *x) {
58 //   for (int i = 0; i < 500; i += 3) {
59 //     foo(i);
60 //     foo(i+1);
61 //     foo(i+2);
62 //   }
63 // }
64 //
65 // into a loop like this:
66 //
67 // void bar(int *x) {
68 //   for (int i = 0; i < 500; ++i)
69 //     foo(i);
70 // }
71 //
72 // It does this by looking for loops that, besides the latch code, are composed
73 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
74 // to the induction variable, and where each DAG is isomorphic to the DAG
75 // rooted at the induction variable (excepting the sub-DAGs which root the
76 // other induction-variable increments). In other words, we're looking for loop
77 // bodies of the form:
78 //
79 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
80 // f(%iv)
81 // %iv.1 = add %iv, 1                <-- a root increment
82 // f(%iv.1)
83 // %iv.2 = add %iv, 2                <-- a root increment
84 // f(%iv.2)
85 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
86 // f(%iv.scale_m_1)
87 // ...
88 // %iv.next = add %iv, scale
89 // %cmp = icmp(%iv, ...)
90 // br %cmp, header, exit
91 //
92 // where each f(i) is a set of instructions that, collectively, are a function
93 // only of i (and other loop-invariant values).
94 //
95 // As a special case, we can also reroll loops like this:
96 //
97 // int foo(int);
98 // void bar(int *x) {
99 //   for (int i = 0; i < 500; ++i) {
100 //     x[3*i] = foo(0);
101 //     x[3*i+1] = foo(0);
102 //     x[3*i+2] = foo(0);
103 //   }
104 // }
105 //
106 // into this:
107 //
108 // void bar(int *x) {
109 //   for (int i = 0; i < 1500; ++i)
110 //     x[i] = foo(0);
111 // }
112 //
113 // in which case, we're looking for inputs like this:
114 //
115 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
116 // %scaled.iv = mul %iv, scale
117 // f(%scaled.iv)
118 // %scaled.iv.1 = add %scaled.iv, 1
119 // f(%scaled.iv.1)
120 // %scaled.iv.2 = add %scaled.iv, 2
121 // f(%scaled.iv.2)
122 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
123 // f(%scaled.iv.scale_m_1)
124 // ...
125 // %iv.next = add %iv, 1
126 // %cmp = icmp(%iv, ...)
127 // br %cmp, header, exit
128
129 namespace {
130   enum IterationLimits {
131     /// The maximum number of iterations that we'll try and reroll. This
132     /// has to be less than 25 in order to fit into a SmallBitVector.
133     IL_MaxRerollIterations = 16,
134     /// The bitvector index used by loop induction variables and other
135     /// instructions that belong to all iterations.
136     IL_All,
137     IL_End
138   };
139
140   class LoopReroll : public LoopPass {
141   public:
142     static char ID; // Pass ID, replacement for typeid
143     LoopReroll() : LoopPass(ID) {
144       initializeLoopRerollPass(*PassRegistry::getPassRegistry());
145     }
146
147     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
148
149     void getAnalysisUsage(AnalysisUsage &AU) const override {
150       AU.addRequired<AliasAnalysis>();
151       AU.addRequired<LoopInfoWrapperPass>();
152       AU.addPreserved<LoopInfoWrapperPass>();
153       AU.addRequired<DominatorTreeWrapperPass>();
154       AU.addPreserved<DominatorTreeWrapperPass>();
155       AU.addRequired<ScalarEvolution>();
156       AU.addRequired<TargetLibraryInfoWrapperPass>();
157     }
158
159   protected:
160     AliasAnalysis *AA;
161     LoopInfo *LI;
162     ScalarEvolution *SE;
163     TargetLibraryInfo *TLI;
164     DominatorTree *DT;
165
166     typedef SmallVector<Instruction *, 16> SmallInstructionVector;
167     typedef SmallSet<Instruction *, 16>   SmallInstructionSet;
168
169     // Map between induction variable and its increment
170     DenseMap<Instruction *, int64_t> IVToIncMap;
171
172     // A chain of isomorphic instructions, identified by a single-use PHI
173     // representing a reduction. Only the last value may be used outside the
174     // loop.
175     struct SimpleLoopReduction {
176       SimpleLoopReduction(Instruction *P, Loop *L)
177         : Valid(false), Instructions(1, P) {
178         assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
179         add(L);
180       }
181
182       bool valid() const {
183         return Valid;
184       }
185
186       Instruction *getPHI() const {
187         assert(Valid && "Using invalid reduction");
188         return Instructions.front();
189       }
190
191       Instruction *getReducedValue() const {
192         assert(Valid && "Using invalid reduction");
193         return Instructions.back();
194       }
195
196       Instruction *get(size_t i) const {
197         assert(Valid && "Using invalid reduction");
198         return Instructions[i+1];
199       }
200
201       Instruction *operator [] (size_t i) const { return get(i); }
202
203       // The size, ignoring the initial PHI.
204       size_t size() const {
205         assert(Valid && "Using invalid reduction");
206         return Instructions.size()-1;
207       }
208
209       typedef SmallInstructionVector::iterator iterator;
210       typedef SmallInstructionVector::const_iterator const_iterator;
211
212       iterator begin() {
213         assert(Valid && "Using invalid reduction");
214         return std::next(Instructions.begin());
215       }
216
217       const_iterator begin() const {
218         assert(Valid && "Using invalid reduction");
219         return std::next(Instructions.begin());
220       }
221
222       iterator end() { return Instructions.end(); }
223       const_iterator end() const { return Instructions.end(); }
224
225     protected:
226       bool Valid;
227       SmallInstructionVector Instructions;
228
229       void add(Loop *L);
230     };
231
232     // The set of all reductions, and state tracking of possible reductions
233     // during loop instruction processing.
234     struct ReductionTracker {
235       typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
236
237       // Add a new possible reduction.
238       void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
239
240       // Setup to track possible reductions corresponding to the provided
241       // rerolling scale. Only reductions with a number of non-PHI instructions
242       // that is divisible by the scale are considered. Three instructions sets
243       // are filled in:
244       //   - A set of all possible instructions in eligible reductions.
245       //   - A set of all PHIs in eligible reductions
246       //   - A set of all reduced values (last instructions) in eligible
247       //     reductions.
248       void restrictToScale(uint64_t Scale,
249                            SmallInstructionSet &PossibleRedSet,
250                            SmallInstructionSet &PossibleRedPHISet,
251                            SmallInstructionSet &PossibleRedLastSet) {
252         PossibleRedIdx.clear();
253         PossibleRedIter.clear();
254         Reds.clear();
255
256         for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
257           if (PossibleReds[i].size() % Scale == 0) {
258             PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
259             PossibleRedPHISet.insert(PossibleReds[i].getPHI());
260
261             PossibleRedSet.insert(PossibleReds[i].getPHI());
262             PossibleRedIdx[PossibleReds[i].getPHI()] = i;
263             for (Instruction *J : PossibleReds[i]) {
264               PossibleRedSet.insert(J);
265               PossibleRedIdx[J] = i;
266             }
267           }
268       }
269
270       // The functions below are used while processing the loop instructions.
271
272       // Are the two instructions both from reductions, and furthermore, from
273       // the same reduction?
274       bool isPairInSame(Instruction *J1, Instruction *J2) {
275         DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
276         if (J1I != PossibleRedIdx.end()) {
277           DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
278           if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
279             return true;
280         }
281
282         return false;
283       }
284
285       // The two provided instructions, the first from the base iteration, and
286       // the second from iteration i, form a matched pair. If these are part of
287       // a reduction, record that fact.
288       void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
289         if (PossibleRedIdx.count(J1)) {
290           assert(PossibleRedIdx.count(J2) &&
291                  "Recording reduction vs. non-reduction instruction?");
292
293           PossibleRedIter[J1] = 0;
294           PossibleRedIter[J2] = i;
295
296           int Idx = PossibleRedIdx[J1];
297           assert(Idx == PossibleRedIdx[J2] &&
298                  "Recording pair from different reductions?");
299           Reds.insert(Idx);
300         }
301       }
302
303       // The functions below can be called after we've finished processing all
304       // instructions in the loop, and we know which reductions were selected.
305
306       // Is the provided instruction the PHI of a reduction selected for
307       // rerolling?
308       bool isSelectedPHI(Instruction *J) {
309         if (!isa<PHINode>(J))
310           return false;
311
312         for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
313              RI != RIE; ++RI) {
314           int i = *RI;
315           if (cast<Instruction>(J) == PossibleReds[i].getPHI())
316             return true;
317         }
318
319         return false;
320       }
321
322       bool validateSelected();
323       void replaceSelected();
324
325     protected:
326       // The vector of all possible reductions (for any scale).
327       SmallReductionVector PossibleReds;
328
329       DenseMap<Instruction *, int> PossibleRedIdx;
330       DenseMap<Instruction *, int> PossibleRedIter;
331       DenseSet<int> Reds;
332     };
333
334     // A DAGRootSet models an induction variable being used in a rerollable
335     // loop. For example,
336     //
337     //   x[i*3+0] = y1
338     //   x[i*3+1] = y2
339     //   x[i*3+2] = y3
340     //
341     //   Base instruction -> i*3
342     //                    +---+----+
343     //                   /    |     \
344     //               ST[y1]  +1     +2  <-- Roots
345     //                        |      |
346     //                      ST[y2] ST[y3]
347     //
348     // There may be multiple DAGRoots, for example:
349     //
350     //   x[i*2+0] = ...   (1)
351     //   x[i*2+1] = ...   (1)
352     //   x[i*2+4] = ...   (2)
353     //   x[i*2+5] = ...   (2)
354     //   x[(i+1234)*2+5678] = ... (3)
355     //   x[(i+1234)*2+5679] = ... (3)
356     //
357     // The loop will be rerolled by adding a new loop induction variable,
358     // one for the Base instruction in each DAGRootSet.
359     //
360     struct DAGRootSet {
361       Instruction *BaseInst;
362       SmallInstructionVector Roots;
363       // The instructions between IV and BaseInst (but not including BaseInst).
364       SmallInstructionSet SubsumedInsts;
365     };
366
367     // The set of all DAG roots, and state tracking of all roots
368     // for a particular induction variable.
369     struct DAGRootTracker {
370       DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
371                      ScalarEvolution *SE, AliasAnalysis *AA,
372                      TargetLibraryInfo *TLI,
373                      DenseMap<Instruction *, int64_t> &IncrMap)
374           : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV),
375             IVToIncMap(IncrMap) {}
376
377       /// Stage 1: Find all the DAG roots for the induction variable.
378       bool findRoots();
379       /// Stage 2: Validate if the found roots are valid.
380       bool validate(ReductionTracker &Reductions);
381       /// Stage 3: Assuming validate() returned true, perform the
382       /// replacement.
383       /// @param IterCount The maximum iteration count of L.
384       void replace(const SCEV *IterCount);
385
386     protected:
387       typedef MapVector<Instruction*, SmallBitVector> UsesTy;
388
389       bool findRootsRecursive(Instruction *IVU,
390                               SmallInstructionSet SubsumedInsts);
391       bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
392       bool collectPossibleRoots(Instruction *Base,
393                                 std::map<int64_t,Instruction*> &Roots);
394
395       bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
396       void collectInLoopUserSet(const SmallInstructionVector &Roots,
397                                 const SmallInstructionSet &Exclude,
398                                 const SmallInstructionSet &Final,
399                                 DenseSet<Instruction *> &Users);
400       void collectInLoopUserSet(Instruction *Root,
401                                 const SmallInstructionSet &Exclude,
402                                 const SmallInstructionSet &Final,
403                                 DenseSet<Instruction *> &Users);
404
405       UsesTy::iterator nextInstr(int Val, UsesTy &In,
406                                  const SmallInstructionSet &Exclude,
407                                  UsesTy::iterator *StartI=nullptr);
408       bool isBaseInst(Instruction *I);
409       bool isRootInst(Instruction *I);
410       bool instrDependsOn(Instruction *I,
411                           UsesTy::iterator Start,
412                           UsesTy::iterator End);
413
414       LoopReroll *Parent;
415
416       // Members of Parent, replicated here for brevity.
417       Loop *L;
418       ScalarEvolution *SE;
419       AliasAnalysis *AA;
420       TargetLibraryInfo *TLI;
421
422       // The loop induction variable.
423       Instruction *IV;
424       // Loop step amount.
425       int64_t Inc;
426       // Loop reroll count; if Inc == 1, this records the scaling applied
427       // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
428       // If Inc is not 1, Scale = Inc.
429       uint64_t Scale;
430       // The roots themselves.
431       SmallVector<DAGRootSet,16> RootSets;
432       // All increment instructions for IV.
433       SmallInstructionVector LoopIncs;
434       // Map of all instructions in the loop (in order) to the iterations
435       // they are used in (or specially, IL_All for instructions
436       // used in the loop increment mechanism).
437       UsesTy Uses;
438       // Map between induction variable and its increment
439       DenseMap<Instruction *, int64_t> &IVToIncMap;
440     };
441
442     void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
443     void collectPossibleReductions(Loop *L,
444            ReductionTracker &Reductions);
445     bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
446                 ReductionTracker &Reductions);
447   };
448 }
449
450 char LoopReroll::ID = 0;
451 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
452 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
453 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
454 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
455 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
456 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
457 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
458
459 Pass *llvm::createLoopRerollPass() {
460   return new LoopReroll;
461 }
462
463 // Returns true if the provided instruction is used outside the given loop.
464 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
465 // non-loop blocks to be outside the loop.
466 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
467   for (User *U : I->users()) {
468     if (!L->contains(cast<Instruction>(U)))
469       return true;
470   }
471   return false;
472 }
473
474 // Collect the list of loop induction variables with respect to which it might
475 // be possible to reroll the loop.
476 void LoopReroll::collectPossibleIVs(Loop *L,
477                                     SmallInstructionVector &PossibleIVs) {
478   BasicBlock *Header = L->getHeader();
479   for (BasicBlock::iterator I = Header->begin(),
480        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
481     if (!isa<PHINode>(I))
482       continue;
483     if (!I->getType()->isIntegerTy())
484       continue;
485
486     if (const SCEVAddRecExpr *PHISCEV =
487         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
488       if (PHISCEV->getLoop() != L)
489         continue;
490       if (!PHISCEV->isAffine())
491         continue;
492       if (const SCEVConstant *IncSCEV =
493           dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
494         const APInt &AInt = IncSCEV->getValue()->getValue().abs();
495         if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
496           continue;
497         IVToIncMap[I] = IncSCEV->getValue()->getSExtValue();
498         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
499                      << "\n");
500         PossibleIVs.push_back(I);
501       }
502     }
503   }
504 }
505
506 // Add the remainder of the reduction-variable chain to the instruction vector
507 // (the initial PHINode has already been added). If successful, the object is
508 // marked as valid.
509 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
510   assert(!Valid && "Cannot add to an already-valid chain");
511
512   // The reduction variable must be a chain of single-use instructions
513   // (including the PHI), except for the last value (which is used by the PHI
514   // and also outside the loop).
515   Instruction *C = Instructions.front();
516   if (C->user_empty())
517     return;
518
519   do {
520     C = cast<Instruction>(*C->user_begin());
521     if (C->hasOneUse()) {
522       if (!C->isBinaryOp())
523         return;
524
525       if (!(isa<PHINode>(Instructions.back()) ||
526             C->isSameOperationAs(Instructions.back())))
527         return;
528
529       Instructions.push_back(C);
530     }
531   } while (C->hasOneUse());
532
533   if (Instructions.size() < 2 ||
534       !C->isSameOperationAs(Instructions.back()) ||
535       C->use_empty())
536     return;
537
538   // C is now the (potential) last instruction in the reduction chain.
539   for (User *U : C->users()) {
540     // The only in-loop user can be the initial PHI.
541     if (L->contains(cast<Instruction>(U)))
542       if (cast<Instruction>(U) != Instructions.front())
543         return;
544   }
545
546   Instructions.push_back(C);
547   Valid = true;
548 }
549
550 // Collect the vector of possible reduction variables.
551 void LoopReroll::collectPossibleReductions(Loop *L,
552   ReductionTracker &Reductions) {
553   BasicBlock *Header = L->getHeader();
554   for (BasicBlock::iterator I = Header->begin(),
555        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
556     if (!isa<PHINode>(I))
557       continue;
558     if (!I->getType()->isSingleValueType())
559       continue;
560
561     SimpleLoopReduction SLR(I, L);
562     if (!SLR.valid())
563       continue;
564
565     DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
566           SLR.size() << " chained instructions)\n");
567     Reductions.addSLR(SLR);
568   }
569 }
570
571 // Collect the set of all users of the provided root instruction. This set of
572 // users contains not only the direct users of the root instruction, but also
573 // all users of those users, and so on. There are two exceptions:
574 //
575 //   1. Instructions in the set of excluded instructions are never added to the
576 //   use set (even if they are users). This is used, for example, to exclude
577 //   including root increments in the use set of the primary IV.
578 //
579 //   2. Instructions in the set of final instructions are added to the use set
580 //   if they are users, but their users are not added. This is used, for
581 //   example, to prevent a reduction update from forcing all later reduction
582 //   updates into the use set.
583 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
584   Instruction *Root, const SmallInstructionSet &Exclude,
585   const SmallInstructionSet &Final,
586   DenseSet<Instruction *> &Users) {
587   SmallInstructionVector Queue(1, Root);
588   while (!Queue.empty()) {
589     Instruction *I = Queue.pop_back_val();
590     if (!Users.insert(I).second)
591       continue;
592
593     if (!Final.count(I))
594       for (Use &U : I->uses()) {
595         Instruction *User = cast<Instruction>(U.getUser());
596         if (PHINode *PN = dyn_cast<PHINode>(User)) {
597           // Ignore "wrap-around" uses to PHIs of this loop's header.
598           if (PN->getIncomingBlock(U) == L->getHeader())
599             continue;
600         }
601
602         if (L->contains(User) && !Exclude.count(User)) {
603           Queue.push_back(User);
604         }
605       }
606
607     // We also want to collect single-user "feeder" values.
608     for (User::op_iterator OI = I->op_begin(),
609          OIE = I->op_end(); OI != OIE; ++OI) {
610       if (Instruction *Op = dyn_cast<Instruction>(*OI))
611         if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
612             !Final.count(Op))
613           Queue.push_back(Op);
614     }
615   }
616 }
617
618 // Collect all of the users of all of the provided root instructions (combined
619 // into a single set).
620 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
621   const SmallInstructionVector &Roots,
622   const SmallInstructionSet &Exclude,
623   const SmallInstructionSet &Final,
624   DenseSet<Instruction *> &Users) {
625   for (SmallInstructionVector::const_iterator I = Roots.begin(),
626        IE = Roots.end(); I != IE; ++I)
627     collectInLoopUserSet(*I, Exclude, Final, Users);
628 }
629
630 static bool isSimpleLoadStore(Instruction *I) {
631   if (LoadInst *LI = dyn_cast<LoadInst>(I))
632     return LI->isSimple();
633   if (StoreInst *SI = dyn_cast<StoreInst>(I))
634     return SI->isSimple();
635   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
636     return !MI->isVolatile();
637   return false;
638 }
639
640 /// Return true if IVU is a "simple" arithmetic operation.
641 /// This is used for narrowing the search space for DAGRoots; only arithmetic
642 /// and GEPs can be part of a DAGRoot.
643 static bool isSimpleArithmeticOp(User *IVU) {
644   if (Instruction *I = dyn_cast<Instruction>(IVU)) {
645     switch (I->getOpcode()) {
646     default: return false;
647     case Instruction::Add:
648     case Instruction::Sub:
649     case Instruction::Mul:
650     case Instruction::Shl:
651     case Instruction::AShr:
652     case Instruction::LShr:
653     case Instruction::GetElementPtr:
654     case Instruction::Trunc:
655     case Instruction::ZExt:
656     case Instruction::SExt:
657       return true;
658     }
659   }
660   return false;
661 }
662
663 static bool isLoopIncrement(User *U, Instruction *IV) {
664   BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
665   if (!BO || BO->getOpcode() != Instruction::Add)
666     return false;
667
668   for (auto *UU : BO->users()) {
669     PHINode *PN = dyn_cast<PHINode>(UU);
670     if (PN && PN == IV)
671       return true;
672   }
673   return false;
674 }
675
676 bool LoopReroll::DAGRootTracker::
677 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
678   SmallInstructionVector BaseUsers;
679
680   for (auto *I : Base->users()) {
681     ConstantInt *CI = nullptr;
682
683     if (isLoopIncrement(I, IV)) {
684       LoopIncs.push_back(cast<Instruction>(I));
685       continue;
686     }
687
688     // The root nodes must be either GEPs, ORs or ADDs.
689     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
690       if (BO->getOpcode() == Instruction::Add ||
691           BO->getOpcode() == Instruction::Or)
692         CI = dyn_cast<ConstantInt>(BO->getOperand(1));
693     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
694       Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
695       CI = dyn_cast<ConstantInt>(LastOperand);
696     }
697
698     if (!CI) {
699       if (Instruction *II = dyn_cast<Instruction>(I)) {
700         BaseUsers.push_back(II);
701         continue;
702       } else {
703         DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
704         return false;
705       }
706     }
707
708     int64_t V = std::abs(CI->getValue().getSExtValue());
709     if (Roots.find(V) != Roots.end())
710       // No duplicates, please.
711       return false;
712
713     Roots[V] = cast<Instruction>(I);
714   }
715
716   if (Roots.empty())
717     return false;
718
719   // If we found non-loop-inc, non-root users of Base, assume they are
720   // for the zeroth root index. This is because "add %a, 0" gets optimized
721   // away.
722   if (BaseUsers.size()) {
723     if (Roots.find(0) != Roots.end()) {
724       DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
725       return false;
726     }
727     Roots[0] = Base;
728   }
729
730   // Calculate the number of users of the base, or lowest indexed, iteration.
731   unsigned NumBaseUses = BaseUsers.size();
732   if (NumBaseUses == 0)
733     NumBaseUses = Roots.begin()->second->getNumUses();
734
735   // Check that every node has the same number of users.
736   for (auto &KV : Roots) {
737     if (KV.first == 0)
738       continue;
739     if (KV.second->getNumUses() != NumBaseUses) {
740       DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
741             << "#Base=" << NumBaseUses << ", #Root=" <<
742             KV.second->getNumUses() << "\n");
743       return false;
744     }
745   }
746
747   return true;
748 }
749
750 bool LoopReroll::DAGRootTracker::
751 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
752   // Does the user look like it could be part of a root set?
753   // All its users must be simple arithmetic ops.
754   if (I->getNumUses() > IL_MaxRerollIterations)
755     return false;
756
757   if ((I->getOpcode() == Instruction::Mul ||
758        I->getOpcode() == Instruction::PHI) &&
759       I != IV &&
760       findRootsBase(I, SubsumedInsts))
761     return true;
762
763   SubsumedInsts.insert(I);
764
765   for (User *V : I->users()) {
766     Instruction *I = dyn_cast<Instruction>(V);
767     if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
768       continue;
769
770     if (!I || !isSimpleArithmeticOp(I) ||
771         !findRootsRecursive(I, SubsumedInsts))
772       return false;
773   }
774   return true;
775 }
776
777 bool LoopReroll::DAGRootTracker::
778 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
779
780   // The base instruction needs to be a multiply so
781   // that we can erase it.
782   if (IVU->getOpcode() != Instruction::Mul &&
783       IVU->getOpcode() != Instruction::PHI)
784     return false;
785
786   std::map<int64_t, Instruction*> V;
787   if (!collectPossibleRoots(IVU, V))
788     return false;
789
790   // If we didn't get a root for index zero, then IVU must be
791   // subsumed.
792   if (V.find(0) == V.end())
793     SubsumedInsts.insert(IVU);
794
795   // Partition the vector into monotonically increasing indexes.
796   DAGRootSet DRS;
797   DRS.BaseInst = nullptr;
798
799   for (auto &KV : V) {
800     if (!DRS.BaseInst) {
801       DRS.BaseInst = KV.second;
802       DRS.SubsumedInsts = SubsumedInsts;
803     } else if (DRS.Roots.empty()) {
804       DRS.Roots.push_back(KV.second);
805     } else if (V.find(KV.first - 1) != V.end()) {
806       DRS.Roots.push_back(KV.second);
807     } else {
808       // Linear sequence terminated.
809       RootSets.push_back(DRS);
810       DRS.BaseInst = KV.second;
811       DRS.SubsumedInsts = SubsumedInsts;
812       DRS.Roots.clear();
813     }
814   }
815   RootSets.push_back(DRS);
816
817   return true;
818 }
819
820 bool LoopReroll::DAGRootTracker::findRoots() {
821   Inc = IVToIncMap[IV];
822
823   assert(RootSets.empty() && "Unclean state!");
824   if (std::abs(Inc) == 1) {
825     for (auto *IVU : IV->users()) {
826       if (isLoopIncrement(IVU, IV))
827         LoopIncs.push_back(cast<Instruction>(IVU));
828     }
829     if (!findRootsRecursive(IV, SmallInstructionSet()))
830       return false;
831     LoopIncs.push_back(IV);
832   } else {
833     if (!findRootsBase(IV, SmallInstructionSet()))
834       return false;
835   }
836
837   // Ensure all sets have the same size.
838   if (RootSets.empty()) {
839     DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
840     return false;
841   }
842   for (auto &V : RootSets) {
843     if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
844       DEBUG(dbgs()
845             << "LRR: Aborting because not all root sets have the same size\n");
846       return false;
847     }
848   }
849
850   // And ensure all loop iterations are consecutive. We rely on std::map
851   // providing ordered traversal.
852   for (auto &V : RootSets) {
853     const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
854     if (!ADR)
855       return false;
856
857     // Consider a DAGRootSet with N-1 roots (so N different values including
858     //   BaseInst).
859     // Define d = Roots[0] - BaseInst, which should be the same as
860     //   Roots[I] - Roots[I-1] for all I in [1..N).
861     // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
862     //   loop iteration J.
863     //
864     // Now, For the loop iterations to be consecutive:
865     //   D = d * N
866
867     unsigned N = V.Roots.size() + 1;
868     const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
869     const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
870     if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
871       DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
872       return false;
873     }
874   }
875   Scale = RootSets[0].Roots.size() + 1;
876
877   if (Scale > IL_MaxRerollIterations) {
878     DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
879           << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
880           << "\n");
881     return false;
882   }
883
884   DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
885
886   return true;
887 }
888
889 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
890   // Populate the MapVector with all instructions in the block, in order first,
891   // so we can iterate over the contents later in perfect order.
892   for (auto &I : *L->getHeader()) {
893     Uses[&I].resize(IL_End);
894   }
895
896   SmallInstructionSet Exclude;
897   for (auto &DRS : RootSets) {
898     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
899     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
900     Exclude.insert(DRS.BaseInst);
901   }
902   Exclude.insert(LoopIncs.begin(), LoopIncs.end());
903
904   for (auto &DRS : RootSets) {
905     DenseSet<Instruction*> VBase;
906     collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
907     for (auto *I : VBase) {
908       Uses[I].set(0);
909     }
910
911     unsigned Idx = 1;
912     for (auto *Root : DRS.Roots) {
913       DenseSet<Instruction*> V;
914       collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
915
916       // While we're here, check the use sets are the same size.
917       if (V.size() != VBase.size()) {
918         DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
919         return false;
920       }
921
922       for (auto *I : V) {
923         Uses[I].set(Idx);
924       }
925       ++Idx;
926     }
927
928     // Make sure our subsumed instructions are remembered too.
929     for (auto *I : DRS.SubsumedInsts) {
930       Uses[I].set(IL_All);
931     }
932   }
933
934   // Make sure the loop increments are also accounted for.
935
936   Exclude.clear();
937   for (auto &DRS : RootSets) {
938     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
939     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
940     Exclude.insert(DRS.BaseInst);
941   }
942
943   DenseSet<Instruction*> V;
944   collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
945   for (auto *I : V) {
946     Uses[I].set(IL_All);
947   }
948
949   return true;
950
951 }
952
953 /// Get the next instruction in "In" that is a member of set Val.
954 /// Start searching from StartI, and do not return anything in Exclude.
955 /// If StartI is not given, start from In.begin().
956 LoopReroll::DAGRootTracker::UsesTy::iterator
957 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
958                                       const SmallInstructionSet &Exclude,
959                                       UsesTy::iterator *StartI) {
960   UsesTy::iterator I = StartI ? *StartI : In.begin();
961   while (I != In.end() && (I->second.test(Val) == 0 ||
962                            Exclude.count(I->first) != 0))
963     ++I;
964   return I;
965 }
966
967 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
968   for (auto &DRS : RootSets) {
969     if (DRS.BaseInst == I)
970       return true;
971   }
972   return false;
973 }
974
975 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
976   for (auto &DRS : RootSets) {
977     if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
978       return true;
979   }
980   return false;
981 }
982
983 /// Return true if instruction I depends on any instruction between
984 /// Start and End.
985 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
986                                                 UsesTy::iterator Start,
987                                                 UsesTy::iterator End) {
988   for (auto *U : I->users()) {
989     for (auto It = Start; It != End; ++It)
990       if (U == It->first)
991         return true;
992   }
993   return false;
994 }
995
996 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
997   // We now need to check for equivalence of the use graph of each root with
998   // that of the primary induction variable (excluding the roots). Our goal
999   // here is not to solve the full graph isomorphism problem, but rather to
1000   // catch common cases without a lot of work. As a result, we will assume
1001   // that the relative order of the instructions in each unrolled iteration
1002   // is the same (although we will not make an assumption about how the
1003   // different iterations are intermixed). Note that while the order must be
1004   // the same, the instructions may not be in the same basic block.
1005
1006   // An array of just the possible reductions for this scale factor. When we
1007   // collect the set of all users of some root instructions, these reduction
1008   // instructions are treated as 'final' (their uses are not considered).
1009   // This is important because we don't want the root use set to search down
1010   // the reduction chain.
1011   SmallInstructionSet PossibleRedSet;
1012   SmallInstructionSet PossibleRedLastSet;
1013   SmallInstructionSet PossibleRedPHISet;
1014   Reductions.restrictToScale(Scale, PossibleRedSet,
1015                              PossibleRedPHISet, PossibleRedLastSet);
1016
1017   // Populate "Uses" with where each instruction is used.
1018   if (!collectUsedInstructions(PossibleRedSet))
1019     return false;
1020
1021   // Make sure we mark the reduction PHIs as used in all iterations.
1022   for (auto *I : PossibleRedPHISet) {
1023     Uses[I].set(IL_All);
1024   }
1025
1026   // Make sure all instructions in the loop are in one and only one
1027   // set.
1028   for (auto &KV : Uses) {
1029     if (KV.second.count() != 1) {
1030       DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1031             << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1032       return false;
1033     }
1034   }
1035
1036   DEBUG(
1037     for (auto &KV : Uses) {
1038       dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1039     }
1040     );
1041
1042   for (unsigned Iter = 1; Iter < Scale; ++Iter) {
1043     // In addition to regular aliasing information, we need to look for
1044     // instructions from later (future) iterations that have side effects
1045     // preventing us from reordering them past other instructions with side
1046     // effects.
1047     bool FutureSideEffects = false;
1048     AliasSetTracker AST(*AA);
1049     // The map between instructions in f(%iv.(i+1)) and f(%iv).
1050     DenseMap<Value *, Value *> BaseMap;
1051
1052     // Compare iteration Iter to the base.
1053     SmallInstructionSet Visited;
1054     auto BaseIt = nextInstr(0, Uses, Visited);
1055     auto RootIt = nextInstr(Iter, Uses, Visited);
1056     auto LastRootIt = Uses.begin();
1057
1058     while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1059       Instruction *BaseInst = BaseIt->first;
1060       Instruction *RootInst = RootIt->first;
1061
1062       // Skip over the IV or root instructions; only match their users.
1063       bool Continue = false;
1064       if (isBaseInst(BaseInst)) {
1065         Visited.insert(BaseInst);
1066         BaseIt = nextInstr(0, Uses, Visited);
1067         Continue = true;
1068       }
1069       if (isRootInst(RootInst)) {
1070         LastRootIt = RootIt;
1071         Visited.insert(RootInst);
1072         RootIt = nextInstr(Iter, Uses, Visited);
1073         Continue = true;
1074       }
1075       if (Continue) continue;
1076
1077       if (!BaseInst->isSameOperationAs(RootInst)) {
1078         // Last chance saloon. We don't try and solve the full isomorphism
1079         // problem, but try and at least catch the case where two instructions
1080         // *of different types* are round the wrong way. We won't be able to
1081         // efficiently tell, given two ADD instructions, which way around we
1082         // should match them, but given an ADD and a SUB, we can at least infer
1083         // which one is which.
1084         //
1085         // This should allow us to deal with a greater subset of the isomorphism
1086         // problem. It does however change a linear algorithm into a quadratic
1087         // one, so limit the number of probes we do.
1088         auto TryIt = RootIt;
1089         unsigned N = NumToleratedFailedMatches;
1090         while (TryIt != Uses.end() &&
1091                !BaseInst->isSameOperationAs(TryIt->first) &&
1092                N--) {
1093           ++TryIt;
1094           TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1095         }
1096
1097         if (TryIt == Uses.end() || TryIt == RootIt ||
1098             instrDependsOn(TryIt->first, RootIt, TryIt)) {
1099           DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1100                 " vs. " << *RootInst << "\n");
1101           return false;
1102         }
1103
1104         RootIt = TryIt;
1105         RootInst = TryIt->first;
1106       }
1107
1108       // All instructions between the last root and this root
1109       // may belong to some other iteration. If they belong to a
1110       // future iteration, then they're dangerous to alias with.
1111       //
1112       // Note that because we allow a limited amount of flexibility in the order
1113       // that we visit nodes, LastRootIt might be *before* RootIt, in which
1114       // case we've already checked this set of instructions so we shouldn't
1115       // do anything.
1116       for (; LastRootIt < RootIt; ++LastRootIt) {
1117         Instruction *I = LastRootIt->first;
1118         if (LastRootIt->second.find_first() < (int)Iter)
1119           continue;
1120         if (I->mayWriteToMemory())
1121           AST.add(I);
1122         // Note: This is specifically guarded by a check on isa<PHINode>,
1123         // which while a valid (somewhat arbitrary) micro-optimization, is
1124         // needed because otherwise isSafeToSpeculativelyExecute returns
1125         // false on PHI nodes.
1126         if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
1127             !isSafeToSpeculativelyExecute(I))
1128           // Intervening instructions cause side effects.
1129           FutureSideEffects = true;
1130       }
1131
1132       // Make sure that this instruction, which is in the use set of this
1133       // root instruction, does not also belong to the base set or the set of
1134       // some other root instruction.
1135       if (RootIt->second.count() > 1) {
1136         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1137                         " vs. " << *RootInst << " (prev. case overlap)\n");
1138         return false;
1139       }
1140
1141       // Make sure that we don't alias with any instruction in the alias set
1142       // tracker. If we do, then we depend on a future iteration, and we
1143       // can't reroll.
1144       if (RootInst->mayReadFromMemory())
1145         for (auto &K : AST) {
1146           if (K.aliasesUnknownInst(RootInst, *AA)) {
1147             DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1148                             " vs. " << *RootInst << " (depends on future store)\n");
1149             return false;
1150           }
1151         }
1152
1153       // If we've past an instruction from a future iteration that may have
1154       // side effects, and this instruction might also, then we can't reorder
1155       // them, and this matching fails. As an exception, we allow the alias
1156       // set tracker to handle regular (simple) load/store dependencies.
1157       if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1158                                  !isSafeToSpeculativelyExecute(BaseInst)) ||
1159                                 (!isSimpleLoadStore(RootInst) &&
1160                                  !isSafeToSpeculativelyExecute(RootInst)))) {
1161         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1162                         " vs. " << *RootInst <<
1163                         " (side effects prevent reordering)\n");
1164         return false;
1165       }
1166
1167       // For instructions that are part of a reduction, if the operation is
1168       // associative, then don't bother matching the operands (because we
1169       // already know that the instructions are isomorphic, and the order
1170       // within the iteration does not matter). For non-associative reductions,
1171       // we do need to match the operands, because we need to reject
1172       // out-of-order instructions within an iteration!
1173       // For example (assume floating-point addition), we need to reject this:
1174       //   x += a[i]; x += b[i];
1175       //   x += a[i+1]; x += b[i+1];
1176       //   x += b[i+2]; x += a[i+2];
1177       bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
1178
1179       if (!(InReduction && BaseInst->isAssociative())) {
1180         bool Swapped = false, SomeOpMatched = false;
1181         for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1182           Value *Op2 = RootInst->getOperand(j);
1183
1184           // If this is part of a reduction (and the operation is not
1185           // associatve), then we match all operands, but not those that are
1186           // part of the reduction.
1187           if (InReduction)
1188             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
1189               if (Reductions.isPairInSame(RootInst, Op2I))
1190                 continue;
1191
1192           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1193           if (BMI != BaseMap.end()) {
1194             Op2 = BMI->second;
1195           } else {
1196             for (auto &DRS : RootSets) {
1197               if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1198                 Op2 = DRS.BaseInst;
1199                 break;
1200               }
1201             }
1202           }
1203
1204           if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
1205             // If we've not already decided to swap the matched operands, and
1206             // we've not already matched our first operand (note that we could
1207             // have skipped matching the first operand because it is part of a
1208             // reduction above), and the instruction is commutative, then try
1209             // the swapped match.
1210             if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1211                 BaseInst->getOperand(!j) == Op2) {
1212               Swapped = true;
1213             } else {
1214               DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1215                     << " vs. " << *RootInst << " (operand " << j << ")\n");
1216               return false;
1217             }
1218           }
1219
1220           SomeOpMatched = true;
1221         }
1222       }
1223
1224       if ((!PossibleRedLastSet.count(BaseInst) &&
1225            hasUsesOutsideLoop(BaseInst, L)) ||
1226           (!PossibleRedLastSet.count(RootInst) &&
1227            hasUsesOutsideLoop(RootInst, L))) {
1228         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1229                         " vs. " << *RootInst << " (uses outside loop)\n");
1230         return false;
1231       }
1232
1233       Reductions.recordPair(BaseInst, RootInst, Iter);
1234       BaseMap.insert(std::make_pair(RootInst, BaseInst));
1235
1236       LastRootIt = RootIt;
1237       Visited.insert(BaseInst);
1238       Visited.insert(RootInst);
1239       BaseIt = nextInstr(0, Uses, Visited);
1240       RootIt = nextInstr(Iter, Uses, Visited);
1241     }
1242     assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1243             "Mismatched set sizes!");
1244   }
1245
1246   DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1247                   *IV << "\n");
1248
1249   return true;
1250 }
1251
1252 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1253   BasicBlock *Header = L->getHeader();
1254   // Remove instructions associated with non-base iterations.
1255   for (BasicBlock::reverse_iterator J = Header->rbegin();
1256        J != Header->rend();) {
1257     unsigned I = Uses[&*J].find_first();
1258     if (I > 0 && I < IL_All) {
1259       Instruction *D = &*J;
1260       DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1261       D->eraseFromParent();
1262       continue;
1263     }
1264
1265     ++J;
1266   }
1267   bool Negative = IVToIncMap[IV] < 0;
1268   const DataLayout &DL = Header->getModule()->getDataLayout();
1269
1270   // We need to create a new induction variable for each different BaseInst.
1271   for (auto &DRS : RootSets) {
1272     // Insert the new induction variable.
1273     const SCEVAddRecExpr *RealIVSCEV =
1274       cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1275     const SCEV *Start = RealIVSCEV->getStart();
1276     const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>(SE->getAddRecExpr(
1277         Start, SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1), L,
1278         SCEV::FlagAnyWrap));
1279     { // Limit the lifetime of SCEVExpander.
1280       SCEVExpander Expander(*SE, DL, "reroll");
1281       Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1282
1283       for (auto &KV : Uses) {
1284         if (KV.second.find_first() == 0)
1285           KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
1286       }
1287
1288       if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1289         // FIXME: Why do we need this check?
1290         if (Uses[BI].find_first() == IL_All) {
1291           const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1292
1293           // Iteration count SCEV minus 1
1294           const SCEV *ICMinus1SCEV = SE->getMinusSCEV(
1295               ICSCEV, SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1));
1296
1297           Value *ICMinus1; // Iteration count minus 1
1298           if (isa<SCEVConstant>(ICMinus1SCEV)) {
1299             ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1300           } else {
1301             BasicBlock *Preheader = L->getLoopPreheader();
1302             if (!Preheader)
1303               Preheader = InsertPreheaderForLoop(L, Parent);
1304
1305             ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1306                                               Preheader->getTerminator());
1307           }
1308
1309           Value *Cond =
1310             new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1311           BI->setCondition(Cond);
1312
1313           if (BI->getSuccessor(1) != Header)
1314             BI->swapSuccessors();
1315         }
1316       }
1317     }
1318   }
1319
1320   SimplifyInstructionsInBlock(Header, TLI);
1321   DeleteDeadPHIs(Header, TLI);
1322 }
1323
1324 // Validate the selected reductions. All iterations must have an isomorphic
1325 // part of the reduction chain and, for non-associative reductions, the chain
1326 // entries must appear in order.
1327 bool LoopReroll::ReductionTracker::validateSelected() {
1328   // For a non-associative reduction, the chain entries must appear in order.
1329   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1330        RI != RIE; ++RI) {
1331     int i = *RI;
1332     int PrevIter = 0, BaseCount = 0, Count = 0;
1333     for (Instruction *J : PossibleReds[i]) {
1334       // Note that all instructions in the chain must have been found because
1335       // all instructions in the function must have been assigned to some
1336       // iteration.
1337       int Iter = PossibleRedIter[J];
1338       if (Iter != PrevIter && Iter != PrevIter + 1 &&
1339           !PossibleReds[i].getReducedValue()->isAssociative()) {
1340         DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1341                         J << "\n");
1342         return false;
1343       }
1344
1345       if (Iter != PrevIter) {
1346         if (Count != BaseCount) {
1347           DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1348                 " reduction use count " << Count <<
1349                 " is not equal to the base use count " <<
1350                 BaseCount << "\n");
1351           return false;
1352         }
1353
1354         Count = 0;
1355       }
1356
1357       ++Count;
1358       if (Iter == 0)
1359         ++BaseCount;
1360
1361       PrevIter = Iter;
1362     }
1363   }
1364
1365   return true;
1366 }
1367
1368 // For all selected reductions, remove all parts except those in the first
1369 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1370 // of the first-iteration reduced value (in other words, reroll the selected
1371 // reductions).
1372 void LoopReroll::ReductionTracker::replaceSelected() {
1373   // Fixup reductions to refer to the last instruction associated with the
1374   // first iteration (not the last).
1375   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1376        RI != RIE; ++RI) {
1377     int i = *RI;
1378     int j = 0;
1379     for (int e = PossibleReds[i].size(); j != e; ++j)
1380       if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1381         --j;
1382         break;
1383       }
1384
1385     // Replace users with the new end-of-chain value.
1386     SmallInstructionVector Users;
1387     for (User *U : PossibleReds[i].getReducedValue()->users()) {
1388       Users.push_back(cast<Instruction>(U));
1389     }
1390
1391     for (SmallInstructionVector::iterator J = Users.begin(),
1392          JE = Users.end(); J != JE; ++J)
1393       (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1394                               PossibleReds[i][j]);
1395   }
1396 }
1397
1398 // Reroll the provided loop with respect to the provided induction variable.
1399 // Generally, we're looking for a loop like this:
1400 //
1401 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1402 // f(%iv)
1403 // %iv.1 = add %iv, 1                <-- a root increment
1404 // f(%iv.1)
1405 // %iv.2 = add %iv, 2                <-- a root increment
1406 // f(%iv.2)
1407 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
1408 // f(%iv.scale_m_1)
1409 // ...
1410 // %iv.next = add %iv, scale
1411 // %cmp = icmp(%iv, ...)
1412 // br %cmp, header, exit
1413 //
1414 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1415 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1416 // be intermixed with eachother. The restriction imposed by this algorithm is
1417 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1418 // etc. be the same.
1419 //
1420 // First, we collect the use set of %iv, excluding the other increment roots.
1421 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1422 // times, having collected the use set of f(%iv.(i+1)), during which we:
1423 //   - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1424 //     the next unmatched instruction in f(%iv.(i+1)).
1425 //   - Ensure that both matched instructions don't have any external users
1426 //     (with the exception of last-in-chain reduction instructions).
1427 //   - Track the (aliasing) write set, and other side effects, of all
1428 //     instructions that belong to future iterations that come before the matched
1429 //     instructions. If the matched instructions read from that write set, then
1430 //     f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1431 //     f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1432 //     if any of these future instructions had side effects (could not be
1433 //     speculatively executed), and so do the matched instructions, when we
1434 //     cannot reorder those side-effect-producing instructions, and rerolling
1435 //     fails.
1436 //
1437 // Finally, we make sure that all loop instructions are either loop increment
1438 // roots, belong to simple latch code, parts of validated reductions, part of
1439 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1440 // have been validated), then we reroll the loop.
1441 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1442                         const SCEV *IterCount,
1443                         ReductionTracker &Reductions) {
1444   DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, IVToIncMap);
1445
1446   if (!DAGRoots.findRoots())
1447     return false;
1448   DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1449                   *IV << "\n");
1450
1451   if (!DAGRoots.validate(Reductions))
1452     return false;
1453   if (!Reductions.validateSelected())
1454     return false;
1455   // At this point, we've validated the rerolling, and we're committed to
1456   // making changes!
1457
1458   Reductions.replaceSelected();
1459   DAGRoots.replace(IterCount);
1460
1461   ++NumRerolledLoops;
1462   return true;
1463 }
1464
1465 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1466   if (skipOptnoneFunction(L))
1467     return false;
1468
1469   AA = &getAnalysis<AliasAnalysis>();
1470   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1471   SE = &getAnalysis<ScalarEvolution>();
1472   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1473   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1474
1475   BasicBlock *Header = L->getHeader();
1476   DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1477         "] Loop %" << Header->getName() << " (" <<
1478         L->getNumBlocks() << " block(s))\n");
1479
1480   bool Changed = false;
1481
1482   // For now, we'll handle only single BB loops.
1483   if (L->getNumBlocks() > 1)
1484     return Changed;
1485
1486   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1487     return Changed;
1488
1489   const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1490   const SCEV *IterCount =
1491     SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1492   DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1493
1494   // First, we need to find the induction variable with respect to which we can
1495   // reroll (there may be several possible options).
1496   SmallInstructionVector PossibleIVs;
1497   IVToIncMap.clear();
1498   collectPossibleIVs(L, PossibleIVs);
1499
1500   if (PossibleIVs.empty()) {
1501     DEBUG(dbgs() << "LRR: No possible IVs found\n");
1502     return Changed;
1503   }
1504
1505   ReductionTracker Reductions;
1506   collectPossibleReductions(L, Reductions);
1507
1508   // For each possible IV, collect the associated possible set of 'root' nodes
1509   // (i+1, i+2, etc.).
1510   for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1511        IE = PossibleIVs.end(); I != IE; ++I)
1512     if (reroll(*I, L, Header, IterCount, Reductions)) {
1513       Changed = true;
1514       break;
1515     }
1516
1517   return Changed;
1518 }