LoopRerollPass.cpp: Use range-based loop. NFC.
[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/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AliasSetTracker.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpander.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/LoopUtils.h"
35
36 using namespace llvm;
37
38 #define DEBUG_TYPE "loop-reroll"
39
40 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
41
42 static cl::opt<unsigned>
43 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
44   cl::desc("The maximum increment for loop rerolling"));
45
46 // This loop re-rolling transformation aims to transform loops like this:
47 //
48 // int foo(int a);
49 // void bar(int *x) {
50 //   for (int i = 0; i < 500; i += 3) {
51 //     foo(i);
52 //     foo(i+1);
53 //     foo(i+2);
54 //   }
55 // }
56 //
57 // into a loop like this:
58 //
59 // void bar(int *x) {
60 //   for (int i = 0; i < 500; ++i)
61 //     foo(i);
62 // }
63 //
64 // It does this by looking for loops that, besides the latch code, are composed
65 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
66 // to the induction variable, and where each DAG is isomorphic to the DAG
67 // rooted at the induction variable (excepting the sub-DAGs which root the
68 // other induction-variable increments). In other words, we're looking for loop
69 // bodies of the form:
70 //
71 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
72 // f(%iv)
73 // %iv.1 = add %iv, 1                <-- a root increment
74 // f(%iv.1)
75 // %iv.2 = add %iv, 2                <-- a root increment
76 // f(%iv.2)
77 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
78 // f(%iv.scale_m_1)
79 // ...
80 // %iv.next = add %iv, scale
81 // %cmp = icmp(%iv, ...)
82 // br %cmp, header, exit
83 //
84 // where each f(i) is a set of instructions that, collectively, are a function
85 // only of i (and other loop-invariant values).
86 //
87 // As a special case, we can also reroll loops like this:
88 //
89 // int foo(int);
90 // void bar(int *x) {
91 //   for (int i = 0; i < 500; ++i) {
92 //     x[3*i] = foo(0);
93 //     x[3*i+1] = foo(0);
94 //     x[3*i+2] = foo(0);
95 //   }
96 // }
97 //
98 // into this:
99 //
100 // void bar(int *x) {
101 //   for (int i = 0; i < 1500; ++i)
102 //     x[i] = foo(0);
103 // }
104 //
105 // in which case, we're looking for inputs like this:
106 //
107 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
108 // %scaled.iv = mul %iv, scale
109 // f(%scaled.iv)
110 // %scaled.iv.1 = add %scaled.iv, 1
111 // f(%scaled.iv.1)
112 // %scaled.iv.2 = add %scaled.iv, 2
113 // f(%scaled.iv.2)
114 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
115 // f(%scaled.iv.scale_m_1)
116 // ...
117 // %iv.next = add %iv, 1
118 // %cmp = icmp(%iv, ...)
119 // br %cmp, header, exit
120
121 namespace {
122   class LoopReroll : public LoopPass {
123   public:
124     static char ID; // Pass ID, replacement for typeid
125     LoopReroll() : LoopPass(ID) {
126       initializeLoopRerollPass(*PassRegistry::getPassRegistry());
127     }
128
129     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
130
131     void getAnalysisUsage(AnalysisUsage &AU) const override {
132       AU.addRequired<AliasAnalysis>();
133       AU.addRequired<LoopInfo>();
134       AU.addPreserved<LoopInfo>();
135       AU.addRequired<DominatorTreeWrapperPass>();
136       AU.addPreserved<DominatorTreeWrapperPass>();
137       AU.addRequired<ScalarEvolution>();
138       AU.addRequired<TargetLibraryInfo>();
139     }
140
141 protected:
142     AliasAnalysis *AA;
143     LoopInfo *LI;
144     ScalarEvolution *SE;
145     const DataLayout *DL;
146     TargetLibraryInfo *TLI;
147     DominatorTree *DT;
148
149     typedef SmallVector<Instruction *, 16> SmallInstructionVector;
150     typedef SmallSet<Instruction *, 16>   SmallInstructionSet;
151
152     // A chain of isomorphic instructions, indentified by a single-use PHI,
153     // representing a reduction. Only the last value may be used outside the
154     // loop.
155     struct SimpleLoopReduction {
156       SimpleLoopReduction(Instruction *P, Loop *L)
157         : Valid(false), Instructions(1, P) {
158         assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
159         add(L);
160       }
161
162       bool valid() const {
163         return Valid;
164       }
165
166       Instruction *getPHI() const {
167         assert(Valid && "Using invalid reduction");
168         return Instructions.front();
169       }
170
171       Instruction *getReducedValue() const {
172         assert(Valid && "Using invalid reduction");
173         return Instructions.back();
174       }
175
176       Instruction *get(size_t i) const {
177         assert(Valid && "Using invalid reduction");
178         return Instructions[i+1];
179       }
180
181       Instruction *operator [] (size_t i) const { return get(i); }
182
183       // The size, ignoring the initial PHI.
184       size_t size() const {
185         assert(Valid && "Using invalid reduction");
186         return Instructions.size()-1;
187       }
188
189       typedef SmallInstructionVector::iterator iterator;
190       typedef SmallInstructionVector::const_iterator const_iterator;
191
192       iterator begin() {
193         assert(Valid && "Using invalid reduction");
194         return std::next(Instructions.begin());
195       }
196
197       const_iterator begin() const {
198         assert(Valid && "Using invalid reduction");
199         return std::next(Instructions.begin());
200       }
201
202       iterator end() { return Instructions.end(); }
203       const_iterator end() const { return Instructions.end(); }
204
205     protected:
206       bool Valid;
207       SmallInstructionVector Instructions;
208
209       void add(Loop *L);
210     };
211
212     // The set of all reductions, and state tracking of possible reductions
213     // during loop instruction processing.
214     struct ReductionTracker {
215       typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
216
217       // Add a new possible reduction.
218       void addSLR(SimpleLoopReduction &SLR) {
219         PossibleReds.push_back(SLR);
220       }
221
222       // Setup to track possible reductions corresponding to the provided
223       // rerolling scale. Only reductions with a number of non-PHI instructions
224       // that is divisible by the scale are considered. Three instructions sets
225       // are filled in:
226       //   - A set of all possible instructions in eligible reductions.
227       //   - A set of all PHIs in eligible reductions
228       //   - A set of all reduced values (last instructions) in eligible reductions.
229       void restrictToScale(uint64_t Scale,
230                            SmallInstructionSet &PossibleRedSet,
231                            SmallInstructionSet &PossibleRedPHISet,
232                            SmallInstructionSet &PossibleRedLastSet) {
233         PossibleRedIdx.clear();
234         PossibleRedIter.clear();
235         Reds.clear();
236
237         for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
238           if (PossibleReds[i].size() % Scale == 0) {
239             PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
240             PossibleRedPHISet.insert(PossibleReds[i].getPHI());
241
242             PossibleRedSet.insert(PossibleReds[i].getPHI());
243             PossibleRedIdx[PossibleReds[i].getPHI()] = i;
244             for (Instruction *J : PossibleReds[i]) {
245               PossibleRedSet.insert(J);
246               PossibleRedIdx[J] = i;
247             }
248           }
249       }
250
251       // The functions below are used while processing the loop instructions.
252
253       // Are the two instructions both from reductions, and furthermore, from
254       // the same reduction?
255       bool isPairInSame(Instruction *J1, Instruction *J2) {
256         DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
257         if (J1I != PossibleRedIdx.end()) {
258           DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
259           if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
260             return true;
261         }
262
263         return false;
264       }
265
266       // The two provided instructions, the first from the base iteration, and
267       // the second from iteration i, form a matched pair. If these are part of
268       // a reduction, record that fact.
269       void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
270         if (PossibleRedIdx.count(J1)) {
271           assert(PossibleRedIdx.count(J2) &&
272                  "Recording reduction vs. non-reduction instruction?");
273
274           PossibleRedIter[J1] = 0;
275           PossibleRedIter[J2] = i;
276
277           int Idx = PossibleRedIdx[J1];
278           assert(Idx == PossibleRedIdx[J2] &&
279                  "Recording pair from different reductions?");
280           Reds.insert(Idx);
281         }
282       }
283
284       // The functions below can be called after we've finished processing all
285       // instructions in the loop, and we know which reductions were selected.
286
287       // Is the provided instruction the PHI of a reduction selected for
288       // rerolling?
289       bool isSelectedPHI(Instruction *J) {
290         if (!isa<PHINode>(J))
291           return false;
292
293         for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
294              RI != RIE; ++RI) {
295           int i = *RI;
296           if (cast<Instruction>(J) == PossibleReds[i].getPHI())
297             return true;
298         }
299
300         return false;
301       }
302
303       bool validateSelected();
304       void replaceSelected();
305
306     protected:
307       // The vector of all possible reductions (for any scale).
308       SmallReductionVector PossibleReds;
309
310       DenseMap<Instruction *, int> PossibleRedIdx;
311       DenseMap<Instruction *, int> PossibleRedIter;
312       DenseSet<int> Reds;
313     };
314
315     void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
316     void collectPossibleReductions(Loop *L,
317            ReductionTracker &Reductions);
318     void collectInLoopUserSet(Loop *L,
319            const SmallInstructionVector &Roots,
320            const SmallInstructionSet &Exclude,
321            const SmallInstructionSet &Final,
322            DenseSet<Instruction *> &Users);
323     void collectInLoopUserSet(Loop *L,
324            Instruction * Root,
325            const SmallInstructionSet &Exclude,
326            const SmallInstructionSet &Final,
327            DenseSet<Instruction *> &Users);
328     bool findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
329                           Instruction *&IV,
330                           SmallInstructionVector &LoopIncs);
331     bool collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale, Instruction *IV,
332                          SmallVector<SmallInstructionVector, 32> &Roots,
333                          SmallInstructionSet &AllRoots,
334                          SmallInstructionVector &LoopIncs);
335     bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
336                 ReductionTracker &Reductions);
337   };
338 }
339
340 char LoopReroll::ID = 0;
341 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
342 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
343 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
344 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
345 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
346 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
347 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
348
349 Pass *llvm::createLoopRerollPass() {
350   return new LoopReroll;
351 }
352
353 // Returns true if the provided instruction is used outside the given loop.
354 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
355 // non-loop blocks to be outside the loop.
356 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
357   for (User *U : I->users())
358     if (!L->contains(cast<Instruction>(U)))
359       return true;
360
361   return false;
362 }
363
364 // Collect the list of loop induction variables with respect to which it might
365 // be possible to reroll the loop.
366 void LoopReroll::collectPossibleIVs(Loop *L,
367                                     SmallInstructionVector &PossibleIVs) {
368   BasicBlock *Header = L->getHeader();
369   for (BasicBlock::iterator I = Header->begin(),
370        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
371     if (!isa<PHINode>(I))
372       continue;
373     if (!I->getType()->isIntegerTy())
374       continue;
375
376     if (const SCEVAddRecExpr *PHISCEV =
377         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
378       if (PHISCEV->getLoop() != L)
379         continue;
380       if (!PHISCEV->isAffine())
381         continue;
382       if (const SCEVConstant *IncSCEV =
383           dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
384         if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
385           continue;
386         if (IncSCEV->getValue()->uge(MaxInc))
387           continue;
388
389         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
390               *PHISCEV << "\n");
391         PossibleIVs.push_back(I);
392       }
393     }
394   }
395 }
396
397 // Add the remainder of the reduction-variable chain to the instruction vector
398 // (the initial PHINode has already been added). If successful, the object is
399 // marked as valid.
400 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
401   assert(!Valid && "Cannot add to an already-valid chain");
402
403   // The reduction variable must be a chain of single-use instructions
404   // (including the PHI), except for the last value (which is used by the PHI
405   // and also outside the loop).
406   Instruction *C = Instructions.front();
407
408   do {
409     C = cast<Instruction>(*C->user_begin());
410     if (C->hasOneUse()) {
411       if (!C->isBinaryOp())
412         return;
413
414       if (!(isa<PHINode>(Instructions.back()) ||
415             C->isSameOperationAs(Instructions.back())))
416         return;
417
418       Instructions.push_back(C);
419     }
420   } while (C->hasOneUse());
421
422   if (Instructions.size() < 2 ||
423       !C->isSameOperationAs(Instructions.back()) ||
424       C->use_empty())
425     return;
426
427   // C is now the (potential) last instruction in the reduction chain.
428   for (User *U : C->users())
429     // The only in-loop user can be the initial PHI.
430     if (L->contains(cast<Instruction>(U)))
431       if (cast<Instruction>(U) != Instructions.front())
432         return;
433
434   Instructions.push_back(C);
435   Valid = true;
436 }
437
438 // Collect the vector of possible reduction variables.
439 void LoopReroll::collectPossibleReductions(Loop *L,
440   ReductionTracker &Reductions) {
441   BasicBlock *Header = L->getHeader();
442   for (BasicBlock::iterator I = Header->begin(),
443        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
444     if (!isa<PHINode>(I))
445       continue;
446     if (!I->getType()->isSingleValueType())
447       continue;
448
449     SimpleLoopReduction SLR(I, L);
450     if (!SLR.valid())
451       continue;
452
453     DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
454           SLR.size() << " chained instructions)\n");
455     Reductions.addSLR(SLR);
456   }
457 }
458
459 // Collect the set of all users of the provided root instruction. This set of
460 // users contains not only the direct users of the root instruction, but also
461 // all users of those users, and so on. There are two exceptions:
462 //
463 //   1. Instructions in the set of excluded instructions are never added to the
464 //   use set (even if they are users). This is used, for example, to exclude
465 //   including root increments in the use set of the primary IV.
466 //
467 //   2. Instructions in the set of final instructions are added to the use set
468 //   if they are users, but their users are not added. This is used, for
469 //   example, to prevent a reduction update from forcing all later reduction
470 //   updates into the use set.
471 void LoopReroll::collectInLoopUserSet(Loop *L,
472   Instruction *Root, const SmallInstructionSet &Exclude,
473   const SmallInstructionSet &Final,
474   DenseSet<Instruction *> &Users) {
475   SmallInstructionVector Queue(1, Root);
476   while (!Queue.empty()) {
477     Instruction *I = Queue.pop_back_val();
478     if (!Users.insert(I).second)
479       continue;
480
481     if (!Final.count(I))
482       for (Use &U : I->uses()) {
483         Instruction *User = cast<Instruction>(U.getUser());
484         if (PHINode *PN = dyn_cast<PHINode>(User)) {
485           // Ignore "wrap-around" uses to PHIs of this loop's header.
486           if (PN->getIncomingBlock(U) == L->getHeader())
487             continue;
488         }
489
490         if (L->contains(User) && !Exclude.count(User)) {
491           Queue.push_back(User);
492         }
493       }
494
495     // We also want to collect single-user "feeder" values.
496     for (User::op_iterator OI = I->op_begin(),
497          OIE = I->op_end(); OI != OIE; ++OI) {
498       if (Instruction *Op = dyn_cast<Instruction>(*OI))
499         if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
500             !Final.count(Op))
501           Queue.push_back(Op);
502     }
503   }
504 }
505
506 // Collect all of the users of all of the provided root instructions (combined
507 // into a single set).
508 void LoopReroll::collectInLoopUserSet(Loop *L,
509   const SmallInstructionVector &Roots,
510   const SmallInstructionSet &Exclude,
511   const SmallInstructionSet &Final,
512   DenseSet<Instruction *> &Users) {
513   for (SmallInstructionVector::const_iterator I = Roots.begin(),
514        IE = Roots.end(); I != IE; ++I)
515     collectInLoopUserSet(L, *I, Exclude, Final, Users);
516 }
517
518 static bool isSimpleLoadStore(Instruction *I) {
519   if (LoadInst *LI = dyn_cast<LoadInst>(I))
520     return LI->isSimple();
521   if (StoreInst *SI = dyn_cast<StoreInst>(I))
522     return SI->isSimple();
523   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
524     return !MI->isVolatile();
525   return false;
526 }
527
528 // Recognize loops that are setup like this:
529 //
530 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
531 // %scaled.iv = mul %iv, scale
532 // f(%scaled.iv)
533 // %scaled.iv.1 = add %scaled.iv, 1
534 // f(%scaled.iv.1)
535 // %scaled.iv.2 = add %scaled.iv, 2
536 // f(%scaled.iv.2)
537 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
538 // f(%scaled.iv.scale_m_1)
539 // ...
540 // %iv.next = add %iv, 1
541 // %cmp = icmp(%iv, ...)
542 // br %cmp, header, exit
543 //
544 // and, if found, set IV = %scaled.iv, and add %iv.next to LoopIncs.
545 bool LoopReroll::findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
546                                   Instruction *&IV,
547                                   SmallInstructionVector &LoopIncs) {
548   // This is a special case: here we're looking for all uses (except for
549   // the increment) to be multiplied by a common factor. The increment must
550   // be by one. This is to capture loops like:
551   //   for (int i = 0; i < 500; ++i) {
552   //     foo(3*i); foo(3*i+1); foo(3*i+2);
553   //   }
554   if (RealIV->getNumUses() != 2)
555     return false;
556   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
557   Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
558               *User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
559   if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
560     return false;
561   const SCEVAddRecExpr *User1SCEV =
562                          dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
563                        *User2SCEV =
564                          dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
565   if (!User1SCEV || !User1SCEV->isAffine() ||
566       !User2SCEV || !User2SCEV->isAffine())
567     return false;
568
569   // We assume below that User1 is the scale multiply and User2 is the
570   // increment. If this can't be true, then swap them.
571   if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
572     std::swap(User1, User2);
573     std::swap(User1SCEV, User2SCEV);
574   }
575
576   if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
577     return false;
578   assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
579          "Invalid non-unit step for multiplicative scaling");
580   LoopIncs.push_back(User2);
581
582   if (const SCEVConstant *MulScale =
583       dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
584     // Make sure that both the start and step have the same multiplier.
585     if (RealIVSCEV->getStart()->getType() != MulScale->getType())
586       return false;
587     if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
588         User1SCEV->getStart())
589       return false;
590
591     ConstantInt *MulScaleCI = MulScale->getValue();
592     if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
593       return false;
594     Scale = MulScaleCI->getZExtValue();
595     IV = User1;
596   } else
597     return false;
598
599   DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
600   return true;
601 }
602
603 // Collect all root increments with respect to the provided induction variable
604 // (normally the PHI, but sometimes a multiply). A root increment is an
605 // instruction, normally an add, with a positive constant less than Scale. In a
606 // rerollable loop, each of these increments is the root of an instruction
607 // graph isomorphic to the others. Also, we collect the final induction
608 // increment (the increment equal to the Scale), and its users in LoopIncs.
609 bool LoopReroll::collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale,
610                                  Instruction *IV,
611                                  SmallVector<SmallInstructionVector, 32> &Roots,
612                                  SmallInstructionSet &AllRoots,
613                                  SmallInstructionVector &LoopIncs) {
614   for (User *U : IV->users()) {
615     Instruction *UI = cast<Instruction>(U);
616     if (!SE->isSCEVable(UI->getType()))
617       continue;
618     if (UI->getType() != IV->getType())
619       continue;
620     if (!L->contains(UI))
621       continue;
622     if (hasUsesOutsideLoop(UI, L))
623       continue;
624
625     if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
626           SE->getSCEV(UI), SE->getSCEV(IV)))) {
627       uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
628       if (Idx > 0 && Idx < Scale) {
629         Roots[Idx-1].push_back(UI);
630         AllRoots.insert(UI);
631       } else if (Idx == Scale && Inc > 1) {
632         LoopIncs.push_back(UI);
633       }
634     }
635   }
636
637   if (Roots[0].empty())
638     return false;
639   bool AllSame = true;
640   for (unsigned i = 1; i < Scale-1; ++i)
641     if (Roots[i].size() != Roots[0].size()) {
642       AllSame = false;
643       break;
644     }
645
646   if (!AllSame)
647     return false;
648
649   return true;
650 }
651
652 // Validate the selected reductions. All iterations must have an isomorphic
653 // part of the reduction chain and, for non-associative reductions, the chain
654 // entries must appear in order.
655 bool LoopReroll::ReductionTracker::validateSelected() {
656   // For a non-associative reduction, the chain entries must appear in order.
657   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
658        RI != RIE; ++RI) {
659     int i = *RI;
660     int PrevIter = 0, BaseCount = 0, Count = 0;
661     for (Instruction *J : PossibleReds[i]) {
662       // Note that all instructions in the chain must have been found because
663       // all instructions in the function must have been assigned to some
664       // iteration.
665       int Iter = PossibleRedIter[J];
666       if (Iter != PrevIter && Iter != PrevIter + 1 &&
667           !PossibleReds[i].getReducedValue()->isAssociative()) {
668         DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
669                         J << "\n");
670         return false;
671       }
672
673       if (Iter != PrevIter) {
674         if (Count != BaseCount) {
675           DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
676                 " reduction use count " << Count <<
677                 " is not equal to the base use count " <<
678                 BaseCount << "\n");
679           return false;
680         }
681
682         Count = 0;
683       }
684
685       ++Count;
686       if (Iter == 0)
687         ++BaseCount;
688
689       PrevIter = Iter;
690     }
691   }
692
693   return true;
694 }
695
696 // For all selected reductions, remove all parts except those in the first
697 // iteration (and the PHI). Replace outside uses of the reduced value with uses
698 // of the first-iteration reduced value (in other words, reroll the selected
699 // reductions).
700 void LoopReroll::ReductionTracker::replaceSelected() {
701   // Fixup reductions to refer to the last instruction associated with the
702   // first iteration (not the last).
703   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
704        RI != RIE; ++RI) {
705     int i = *RI;
706     int j = 0;
707     for (int e = PossibleReds[i].size(); j != e; ++j)
708       if (PossibleRedIter[PossibleReds[i][j]] != 0) {
709         --j;
710         break;
711       }
712
713     // Replace users with the new end-of-chain value.
714     SmallInstructionVector Users;
715     for (User *U : PossibleReds[i].getReducedValue()->users())
716       Users.push_back(cast<Instruction>(U));
717
718     for (SmallInstructionVector::iterator J = Users.begin(),
719          JE = Users.end(); J != JE; ++J)
720       (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
721                               PossibleReds[i][j]);
722   }
723 }
724
725 // Reroll the provided loop with respect to the provided induction variable.
726 // Generally, we're looking for a loop like this:
727 //
728 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
729 // f(%iv)
730 // %iv.1 = add %iv, 1                <-- a root increment
731 // f(%iv.1)
732 // %iv.2 = add %iv, 2                <-- a root increment
733 // f(%iv.2)
734 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
735 // f(%iv.scale_m_1)
736 // ...
737 // %iv.next = add %iv, scale
738 // %cmp = icmp(%iv, ...)
739 // br %cmp, header, exit
740 //
741 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
742 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
743 // be intermixed with eachother. The restriction imposed by this algorithm is
744 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
745 // etc. be the same.
746 //
747 // First, we collect the use set of %iv, excluding the other increment roots.
748 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
749 // times, having collected the use set of f(%iv.(i+1)), during which we:
750 //   - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
751 //     the next unmatched instruction in f(%iv.(i+1)).
752 //   - Ensure that both matched instructions don't have any external users
753 //     (with the exception of last-in-chain reduction instructions).
754 //   - Track the (aliasing) write set, and other side effects, of all
755 //     instructions that belong to future iterations that come before the matched
756 //     instructions. If the matched instructions read from that write set, then
757 //     f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
758 //     f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
759 //     if any of these future instructions had side effects (could not be
760 //     speculatively executed), and so do the matched instructions, when we
761 //     cannot reorder those side-effect-producing instructions, and rerolling
762 //     fails.
763 //
764 // Finally, we make sure that all loop instructions are either loop increment
765 // roots, belong to simple latch code, parts of validated reductions, part of
766 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
767 // have been validated), then we reroll the loop.
768 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
769                         const SCEV *IterCount,
770                         ReductionTracker &Reductions) {
771   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
772   uint64_t Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
773                    getValue()->getZExtValue();
774   // The collection of loop increment instructions.
775   SmallInstructionVector LoopIncs;
776   uint64_t Scale = Inc;
777
778   // The effective induction variable, IV, is normally also the real induction
779   // variable. When we're dealing with a loop like:
780   //   for (int i = 0; i < 500; ++i)
781   //     x[3*i] = ...;
782   //     x[3*i+1] = ...;
783   //     x[3*i+2] = ...;
784   // then the real IV is still i, but the effective IV is (3*i).
785   Instruction *RealIV = IV;
786   if (Inc == 1 && !findScaleFromMul(RealIV, Scale, IV, LoopIncs))
787     return false;
788
789   assert(Scale <= MaxInc && "Scale is too large");
790   assert(Scale > 1 && "Scale must be at least 2");
791
792   // The set of increment instructions for each increment value.
793   SmallVector<SmallInstructionVector, 32> Roots(Scale-1);
794   SmallInstructionSet AllRoots;
795   if (!collectAllRoots(L, Inc, Scale, IV, Roots, AllRoots, LoopIncs))
796     return false;
797
798   DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
799                   *RealIV << "\n");
800
801   // An array of just the possible reductions for this scale factor. When we
802   // collect the set of all users of some root instructions, these reduction
803   // instructions are treated as 'final' (their uses are not considered).
804   // This is important because we don't want the root use set to search down
805   // the reduction chain.
806   SmallInstructionSet PossibleRedSet;
807   SmallInstructionSet PossibleRedLastSet, PossibleRedPHISet;
808   Reductions.restrictToScale(Scale, PossibleRedSet, PossibleRedPHISet,
809                              PossibleRedLastSet);
810
811   // We now need to check for equivalence of the use graph of each root with
812   // that of the primary induction variable (excluding the roots). Our goal
813   // here is not to solve the full graph isomorphism problem, but rather to
814   // catch common cases without a lot of work. As a result, we will assume
815   // that the relative order of the instructions in each unrolled iteration
816   // is the same (although we will not make an assumption about how the
817   // different iterations are intermixed). Note that while the order must be
818   // the same, the instructions may not be in the same basic block.
819   SmallInstructionSet Exclude(AllRoots);
820   Exclude.insert(LoopIncs.begin(), LoopIncs.end());
821
822   DenseSet<Instruction *> BaseUseSet;
823   collectInLoopUserSet(L, IV, Exclude, PossibleRedSet, BaseUseSet);
824
825   DenseSet<Instruction *> AllRootUses;
826   std::vector<DenseSet<Instruction *> > RootUseSets(Scale-1);
827
828   bool MatchFailed = false;
829   for (unsigned i = 0; i < Scale-1 && !MatchFailed; ++i) {
830     DenseSet<Instruction *> &RootUseSet = RootUseSets[i];
831     collectInLoopUserSet(L, Roots[i], SmallInstructionSet(),
832                          PossibleRedSet, RootUseSet);
833
834     DEBUG(dbgs() << "LRR: base use set size: " << BaseUseSet.size() <<
835                     " vs. iteration increment " << (i+1) <<
836                     " use set size: " << RootUseSet.size() << "\n");
837
838     if (BaseUseSet.size() != RootUseSet.size()) {
839       MatchFailed = true;
840       break;
841     }
842
843     // In addition to regular aliasing information, we need to look for
844     // instructions from later (future) iterations that have side effects
845     // preventing us from reordering them past other instructions with side
846     // effects.
847     bool FutureSideEffects = false;
848     AliasSetTracker AST(*AA);
849
850     // The map between instructions in f(%iv.(i+1)) and f(%iv).
851     DenseMap<Value *, Value *> BaseMap;
852
853     assert(L->getNumBlocks() == 1 && "Cannot handle multi-block loops");
854     for (BasicBlock::iterator J1 = Header->begin(), J2 = Header->begin(),
855          JE = Header->end(); J1 != JE && !MatchFailed; ++J1) {
856       if (cast<Instruction>(J1) == RealIV)
857         continue;
858       if (cast<Instruction>(J1) == IV)
859         continue;
860       if (!BaseUseSet.count(J1))
861         continue;
862       if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
863         continue;
864
865       while (J2 != JE && (!RootUseSet.count(J2) ||
866              std::find(Roots[i].begin(), Roots[i].end(), J2) !=
867                Roots[i].end())) {
868         // As we iterate through the instructions, instructions that don't
869         // belong to previous iterations (or the base case), must belong to
870         // future iterations. We want to track the alias set of writes from
871         // previous iterations.
872         if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
873             !AllRootUses.count(J2)) {
874           if (J2->mayWriteToMemory())
875             AST.add(J2);
876
877           // Note: This is specifically guarded by a check on isa<PHINode>,
878           // which while a valid (somewhat arbitrary) micro-optimization, is
879           // needed because otherwise isSafeToSpeculativelyExecute returns
880           // false on PHI nodes.
881           if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
882             FutureSideEffects = true;
883         }
884
885         ++J2;
886       }
887
888       if (!J1->isSameOperationAs(J2)) {
889         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
890                         " vs. " << *J2 << "\n");
891         MatchFailed = true;
892         break;
893       }
894
895       // Make sure that this instruction, which is in the use set of this
896       // root instruction, does not also belong to the base set or the set of
897       // some previous root instruction.
898       if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
899         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
900                         " vs. " << *J2 << " (prev. case overlap)\n");
901         MatchFailed = true;
902         break;
903       }
904
905       // Make sure that we don't alias with any instruction in the alias set
906       // tracker. If we do, then we depend on a future iteration, and we
907       // can't reroll.
908       if (J2->mayReadFromMemory()) {
909         for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
910              K != KE && !MatchFailed; ++K) {
911           if (K->aliasesUnknownInst(J2, *AA)) {
912             DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
913                             " vs. " << *J2 << " (depends on future store)\n");
914             MatchFailed = true;
915             break;
916           }
917         }
918       }
919
920       // If we've past an instruction from a future iteration that may have
921       // side effects, and this instruction might also, then we can't reorder
922       // them, and this matching fails. As an exception, we allow the alias
923       // set tracker to handle regular (simple) load/store dependencies.
924       if (FutureSideEffects &&
925             ((!isSimpleLoadStore(J1) &&
926               !isSafeToSpeculativelyExecute(J1, DL)) ||
927              (!isSimpleLoadStore(J2) &&
928               !isSafeToSpeculativelyExecute(J2, DL)))) {
929         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
930                         " vs. " << *J2 <<
931                         " (side effects prevent reordering)\n");
932         MatchFailed = true;
933         break;
934       }
935
936       // For instructions that are part of a reduction, if the operation is
937       // associative, then don't bother matching the operands (because we
938       // already know that the instructions are isomorphic, and the order
939       // within the iteration does not matter). For non-associative reductions,
940       // we do need to match the operands, because we need to reject
941       // out-of-order instructions within an iteration!
942       // For example (assume floating-point addition), we need to reject this:
943       //   x += a[i]; x += b[i];
944       //   x += a[i+1]; x += b[i+1];
945       //   x += b[i+2]; x += a[i+2];
946       bool InReduction = Reductions.isPairInSame(J1, J2);
947
948       if (!(InReduction && J1->isAssociative())) {
949         bool Swapped = false, SomeOpMatched = false;
950         for (unsigned j = 0; j < J1->getNumOperands() && !MatchFailed; ++j) {
951           Value *Op2 = J2->getOperand(j);
952
953           // If this is part of a reduction (and the operation is not
954           // associatve), then we match all operands, but not those that are
955           // part of the reduction.
956           if (InReduction)
957             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
958               if (Reductions.isPairInSame(J2, Op2I))
959                 continue;
960
961           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
962           if (BMI != BaseMap.end())
963             Op2 = BMI->second;
964           else if (std::find(Roots[i].begin(), Roots[i].end(),
965                              (Instruction*) Op2) != Roots[i].end())
966             Op2 = IV;
967
968           if (J1->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
969             // If we've not already decided to swap the matched operands, and
970             // we've not already matched our first operand (note that we could
971             // have skipped matching the first operand because it is part of a
972             // reduction above), and the instruction is commutative, then try
973             // the swapped match.
974             if (!Swapped && J1->isCommutative() && !SomeOpMatched &&
975                 J1->getOperand(!j) == Op2) {
976               Swapped = true;
977             } else {
978               DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
979                               " vs. " << *J2 << " (operand " << j << ")\n");
980               MatchFailed = true;
981               break;
982             }
983           }
984
985           SomeOpMatched = true;
986         }
987       }
988
989       if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
990           (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
991         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
992                         " vs. " << *J2 << " (uses outside loop)\n");
993         MatchFailed = true;
994         break;
995       }
996
997       if (!MatchFailed)
998         BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
999
1000       AllRootUses.insert(J2);
1001       Reductions.recordPair(J1, J2, i+1);
1002
1003       ++J2;
1004     }
1005   }
1006
1007   if (MatchFailed)
1008     return false;
1009
1010   DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1011                   *RealIV << "\n");
1012
1013   DenseSet<Instruction *> LoopIncUseSet;
1014   collectInLoopUserSet(L, LoopIncs, SmallInstructionSet(),
1015                        SmallInstructionSet(), LoopIncUseSet);
1016   DEBUG(dbgs() << "LRR: Loop increment set size: " <<
1017                   LoopIncUseSet.size() << "\n");
1018
1019   // Make sure that all instructions in the loop have been included in some
1020   // use set.
1021   for (BasicBlock::iterator J = Header->begin(), JE = Header->end();
1022        J != JE; ++J) {
1023     if (isa<DbgInfoIntrinsic>(J))
1024       continue;
1025     if (cast<Instruction>(J) == RealIV)
1026       continue;
1027     if (cast<Instruction>(J) == IV)
1028       continue;
1029     if (BaseUseSet.count(J) || AllRootUses.count(J) ||
1030         (LoopIncUseSet.count(J) && (J->isTerminator() ||
1031                                     isSafeToSpeculativelyExecute(J, DL))))
1032       continue;
1033
1034     if (AllRoots.count(J))
1035       continue;
1036
1037     if (Reductions.isSelectedPHI(J))
1038       continue;
1039
1040     DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
1041                     " unprocessed instruction found: " << *J << "\n");
1042     MatchFailed = true;
1043     break;
1044   }
1045
1046   if (MatchFailed)
1047     return false;
1048
1049   DEBUG(dbgs() << "LRR: all instructions processed from " <<
1050                   *RealIV << "\n");
1051
1052   if (!Reductions.validateSelected())
1053     return false;
1054
1055   // At this point, we've validated the rerolling, and we're committed to
1056   // making changes!
1057
1058   Reductions.replaceSelected();
1059
1060   // Remove instructions associated with non-base iterations.
1061   for (BasicBlock::reverse_iterator J = Header->rbegin();
1062        J != Header->rend();) {
1063     if (AllRootUses.count(&*J)) {
1064       Instruction *D = &*J;
1065       DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1066       D->eraseFromParent();
1067       continue;
1068     }
1069
1070     ++J;
1071   }
1072
1073   // Insert the new induction variable.
1074   const SCEV *Start = RealIVSCEV->getStart();
1075   if (Inc == 1)
1076     Start = SE->getMulExpr(Start,
1077                            SE->getConstant(Start->getType(), Scale));
1078   const SCEVAddRecExpr *H =
1079     cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
1080                            SE->getConstant(RealIVSCEV->getType(), 1),
1081                            L, SCEV::FlagAnyWrap));
1082   { // Limit the lifetime of SCEVExpander.
1083     SCEVExpander Expander(*SE, "reroll");
1084     Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1085
1086     for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
1087          JE = BaseUseSet.end(); J != JE; ++J)
1088       (*J)->replaceUsesOfWith(IV, NewIV);
1089
1090     if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1091       if (LoopIncUseSet.count(BI)) {
1092         const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1093         if (Inc == 1)
1094           ICSCEV =
1095             SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
1096         // Iteration count SCEV minus 1
1097         const SCEV *ICMinus1SCEV =
1098           SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1099
1100         Value *ICMinus1; // Iteration count minus 1
1101         if (isa<SCEVConstant>(ICMinus1SCEV)) {
1102           ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1103         } else {
1104           BasicBlock *Preheader = L->getLoopPreheader();
1105           if (!Preheader)
1106             Preheader = InsertPreheaderForLoop(L, this);
1107
1108           ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1109                                             Preheader->getTerminator());
1110         }
1111
1112         Value *Cond = new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1,
1113                                    "exitcond");
1114         BI->setCondition(Cond);
1115
1116         if (BI->getSuccessor(1) != Header)
1117           BI->swapSuccessors();
1118       }
1119     }
1120   }
1121
1122   SimplifyInstructionsInBlock(Header, DL, TLI);
1123   DeleteDeadPHIs(Header, TLI);
1124   ++NumRerolledLoops;
1125   return true;
1126 }
1127
1128 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1129   if (skipOptnoneFunction(L))
1130     return false;
1131
1132   AA = &getAnalysis<AliasAnalysis>();
1133   LI = &getAnalysis<LoopInfo>();
1134   SE = &getAnalysis<ScalarEvolution>();
1135   TLI = &getAnalysis<TargetLibraryInfo>();
1136   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1137   DL = DLP ? &DLP->getDataLayout() : nullptr;
1138   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1139
1140   BasicBlock *Header = L->getHeader();
1141   DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1142         "] Loop %" << Header->getName() << " (" <<
1143         L->getNumBlocks() << " block(s))\n");
1144
1145   bool Changed = false;
1146
1147   // For now, we'll handle only single BB loops.
1148   if (L->getNumBlocks() > 1)
1149     return Changed;
1150
1151   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1152     return Changed;
1153
1154   const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1155   const SCEV *IterCount =
1156     SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1157   DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1158
1159   // First, we need to find the induction variable with respect to which we can
1160   // reroll (there may be several possible options).
1161   SmallInstructionVector PossibleIVs;
1162   collectPossibleIVs(L, PossibleIVs);
1163
1164   if (PossibleIVs.empty()) {
1165     DEBUG(dbgs() << "LRR: No possible IVs found\n");
1166     return Changed;
1167   }
1168
1169   ReductionTracker Reductions;
1170   collectPossibleReductions(L, Reductions);
1171
1172   // For each possible IV, collect the associated possible set of 'root' nodes
1173   // (i+1, i+2, etc.).
1174   for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1175        IE = PossibleIVs.end(); I != IE; ++I)
1176     if (reroll(*I, L, Header, IterCount, Reductions)) {
1177       Changed = true;
1178       break;
1179     }
1180
1181   return Changed;
1182 }