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