blob: 704299f3041e916c924b97998abf6ffdfb9ef87f [file] [log] [blame]
Hal Finkelbf45efd2013-11-16 23:59:05 +00001//===-- 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
Hal Finkelbf45efd2013-11-16 23:59:05 +000014#include "llvm/Transforms/Scalar.h"
James Molloy64419d42015-01-29 21:52:03 +000015#include "llvm/ADT/MapVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/STLExtras.h"
James Molloy64419d42015-01-29 21:52:03 +000017#include "llvm/ADT/SmallBitVector.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000018#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000020#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/ValueTracking.h"
27#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000029#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
35#include "llvm/Transforms/Utils/Local.h"
36#include "llvm/Transforms/Utils/LoopUtils.h"
37
38using namespace llvm;
39
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "loop-reroll"
41
Hal Finkelbf45efd2013-11-16 23:59:05 +000042STATISTIC(NumRerolledLoops, "Number of rerolled loops");
43
44static cl::opt<unsigned>
45MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46 cl::desc("The maximum increment for loop rerolling"));
47
James Molloye805ad92015-02-12 15:54:14 +000048static cl::opt<unsigned>
49NumToleratedFailedMatches("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
Hal Finkelbf45efd2013-11-16 23:59:05 +000054// 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
129namespace {
James Molloy64419d42015-01-29 21:52:03 +0000130 enum IterationLimits {
131 /// The maximum number of iterations that we'll try and reroll. This
132 /// has to be less than 25 in order to fit into a SmallBitVector.
133 IL_MaxRerollIterations = 16,
134 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000135 /// instructions that belong to all iterations.
136 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000137 IL_End
138 };
139
Hal Finkelbf45efd2013-11-16 23:59:05 +0000140 class LoopReroll : public LoopPass {
141 public:
142 static char ID; // Pass ID, replacement for typeid
143 LoopReroll() : LoopPass(ID) {
144 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
145 }
146
Craig Topper3e4c6972014-03-05 09:10:37 +0000147 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000148
Craig Topper3e4c6972014-03-05 09:10:37 +0000149 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000150 AU.addRequired<AliasAnalysis>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000153 AU.addRequired<DominatorTreeWrapperPass>();
154 AU.addPreserved<DominatorTreeWrapperPass>();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000155 AU.addRequired<ScalarEvolution>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000156 AU.addRequired<TargetLibraryInfoWrapperPass>();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000157 }
158
James Molloy64419d42015-01-29 21:52:03 +0000159 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000160 AliasAnalysis *AA;
161 LoopInfo *LI;
162 ScalarEvolution *SE;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000163 const DataLayout *DL;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000164 TargetLibraryInfo *TLI;
165 DominatorTree *DT;
166
167 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
168 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
169
170 // A chain of isomorphic instructions, indentified by a single-use PHI,
171 // representing a reduction. Only the last value may be used outside the
172 // loop.
173 struct SimpleLoopReduction {
174 SimpleLoopReduction(Instruction *P, Loop *L)
175 : Valid(false), Instructions(1, P) {
176 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
177 add(L);
178 }
179
180 bool valid() const {
181 return Valid;
182 }
183
184 Instruction *getPHI() const {
185 assert(Valid && "Using invalid reduction");
186 return Instructions.front();
187 }
188
189 Instruction *getReducedValue() const {
190 assert(Valid && "Using invalid reduction");
191 return Instructions.back();
192 }
193
194 Instruction *get(size_t i) const {
195 assert(Valid && "Using invalid reduction");
196 return Instructions[i+1];
197 }
198
199 Instruction *operator [] (size_t i) const { return get(i); }
200
201 // The size, ignoring the initial PHI.
202 size_t size() const {
203 assert(Valid && "Using invalid reduction");
204 return Instructions.size()-1;
205 }
206
207 typedef SmallInstructionVector::iterator iterator;
208 typedef SmallInstructionVector::const_iterator const_iterator;
209
210 iterator begin() {
211 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000212 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000213 }
214
215 const_iterator begin() const {
216 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000217 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000218 }
219
220 iterator end() { return Instructions.end(); }
221 const_iterator end() const { return Instructions.end(); }
222
223 protected:
224 bool Valid;
225 SmallInstructionVector Instructions;
226
227 void add(Loop *L);
228 };
229
230 // The set of all reductions, and state tracking of possible reductions
231 // during loop instruction processing.
232 struct ReductionTracker {
233 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
234
235 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000236 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000237
238 // Setup to track possible reductions corresponding to the provided
239 // rerolling scale. Only reductions with a number of non-PHI instructions
240 // that is divisible by the scale are considered. Three instructions sets
241 // are filled in:
242 // - A set of all possible instructions in eligible reductions.
243 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000244 // - A set of all reduced values (last instructions) in eligible
245 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000246 void restrictToScale(uint64_t Scale,
247 SmallInstructionSet &PossibleRedSet,
248 SmallInstructionSet &PossibleRedPHISet,
249 SmallInstructionSet &PossibleRedLastSet) {
250 PossibleRedIdx.clear();
251 PossibleRedIter.clear();
252 Reds.clear();
253
254 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
255 if (PossibleReds[i].size() % Scale == 0) {
256 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
257 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000258
Hal Finkelbf45efd2013-11-16 23:59:05 +0000259 PossibleRedSet.insert(PossibleReds[i].getPHI());
260 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000261 for (Instruction *J : PossibleReds[i]) {
262 PossibleRedSet.insert(J);
263 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000264 }
265 }
266 }
267
268 // The functions below are used while processing the loop instructions.
269
270 // Are the two instructions both from reductions, and furthermore, from
271 // the same reduction?
272 bool isPairInSame(Instruction *J1, Instruction *J2) {
273 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
274 if (J1I != PossibleRedIdx.end()) {
275 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
276 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
277 return true;
278 }
279
280 return false;
281 }
282
283 // The two provided instructions, the first from the base iteration, and
284 // the second from iteration i, form a matched pair. If these are part of
285 // a reduction, record that fact.
286 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
287 if (PossibleRedIdx.count(J1)) {
288 assert(PossibleRedIdx.count(J2) &&
289 "Recording reduction vs. non-reduction instruction?");
290
291 PossibleRedIter[J1] = 0;
292 PossibleRedIter[J2] = i;
293
294 int Idx = PossibleRedIdx[J1];
295 assert(Idx == PossibleRedIdx[J2] &&
296 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000297 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000298 }
299 }
300
301 // The functions below can be called after we've finished processing all
302 // instructions in the loop, and we know which reductions were selected.
303
304 // Is the provided instruction the PHI of a reduction selected for
305 // rerolling?
306 bool isSelectedPHI(Instruction *J) {
307 if (!isa<PHINode>(J))
308 return false;
309
310 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
311 RI != RIE; ++RI) {
312 int i = *RI;
313 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
314 return true;
315 }
316
317 return false;
318 }
319
320 bool validateSelected();
321 void replaceSelected();
322
323 protected:
324 // The vector of all possible reductions (for any scale).
325 SmallReductionVector PossibleReds;
326
327 DenseMap<Instruction *, int> PossibleRedIdx;
328 DenseMap<Instruction *, int> PossibleRedIter;
329 DenseSet<int> Reds;
330 };
331
James Molloyf1473592015-02-11 09:19:47 +0000332 // A DAGRootSet models an induction variable being used in a rerollable
333 // loop. For example,
334 //
335 // x[i*3+0] = y1
336 // x[i*3+1] = y2
337 // x[i*3+2] = y3
338 //
339 // Base instruction -> i*3
340 // +---+----+
341 // / | \
342 // ST[y1] +1 +2 <-- Roots
343 // | |
344 // ST[y2] ST[y3]
345 //
346 // There may be multiple DAGRoots, for example:
347 //
348 // x[i*2+0] = ... (1)
349 // x[i*2+1] = ... (1)
350 // x[i*2+4] = ... (2)
351 // x[i*2+5] = ... (2)
352 // x[(i+1234)*2+5678] = ... (3)
353 // x[(i+1234)*2+5679] = ... (3)
354 //
355 // The loop will be rerolled by adding a new loop induction variable,
356 // one for the Base instruction in each DAGRootSet.
357 //
358 struct DAGRootSet {
359 Instruction *BaseInst;
360 SmallInstructionVector Roots;
361 // The instructions between IV and BaseInst (but not including BaseInst).
362 SmallInstructionSet SubsumedInsts;
363 };
364
James Molloy5f255eb2015-01-29 13:48:05 +0000365 // The set of all DAG roots, and state tracking of all roots
366 // for a particular induction variable.
367 struct DAGRootTracker {
368 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
369 ScalarEvolution *SE, AliasAnalysis *AA,
370 TargetLibraryInfo *TLI, const DataLayout *DL)
371 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI),
372 DL(DL), IV(IV) {
373 }
374
375 /// Stage 1: Find all the DAG roots for the induction variable.
376 bool findRoots();
377 /// Stage 2: Validate if the found roots are valid.
378 bool validate(ReductionTracker &Reductions);
379 /// Stage 3: Assuming validate() returned true, perform the
380 /// replacement.
381 /// @param IterCount The maximum iteration count of L.
382 void replace(const SCEV *IterCount);
383
384 protected:
James Molloy64419d42015-01-29 21:52:03 +0000385 typedef MapVector<Instruction*, SmallBitVector> UsesTy;
386
James Molloyf1473592015-02-11 09:19:47 +0000387 bool findRootsRecursive(Instruction *IVU,
388 SmallInstructionSet SubsumedInsts);
389 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
390 bool collectPossibleRoots(Instruction *Base,
391 std::map<int64_t,Instruction*> &Roots);
James Molloy5f255eb2015-01-29 13:48:05 +0000392
James Molloy64419d42015-01-29 21:52:03 +0000393 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000394 void collectInLoopUserSet(const SmallInstructionVector &Roots,
395 const SmallInstructionSet &Exclude,
396 const SmallInstructionSet &Final,
397 DenseSet<Instruction *> &Users);
398 void collectInLoopUserSet(Instruction *Root,
399 const SmallInstructionSet &Exclude,
400 const SmallInstructionSet &Final,
401 DenseSet<Instruction *> &Users);
402
James Molloye805ad92015-02-12 15:54:14 +0000403 UsesTy::iterator nextInstr(int Val, UsesTy &In,
404 const SmallInstructionSet &Exclude,
405 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000406 bool isBaseInst(Instruction *I);
407 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000408 bool instrDependsOn(Instruction *I,
409 UsesTy::iterator Start,
410 UsesTy::iterator End);
James Molloy64419d42015-01-29 21:52:03 +0000411
James Molloy5f255eb2015-01-29 13:48:05 +0000412 LoopReroll *Parent;
413
414 // Members of Parent, replicated here for brevity.
415 Loop *L;
416 ScalarEvolution *SE;
417 AliasAnalysis *AA;
418 TargetLibraryInfo *TLI;
419 const DataLayout *DL;
420
421 // The loop induction variable.
422 Instruction *IV;
423 // Loop step amount.
424 uint64_t Inc;
425 // Loop reroll count; if Inc == 1, this records the scaling applied
426 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
427 // If Inc is not 1, Scale = Inc.
428 uint64_t Scale;
James Molloy5f255eb2015-01-29 13:48:05 +0000429 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000430 SmallVector<DAGRootSet,16> RootSets;
James Molloy5f255eb2015-01-29 13:48:05 +0000431 // All increment instructions for IV.
432 SmallInstructionVector LoopIncs;
James Molloy64419d42015-01-29 21:52:03 +0000433 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000434 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000435 // used in the loop increment mechanism).
436 UsesTy Uses;
James Molloy5f255eb2015-01-29 13:48:05 +0000437 };
438
Hal Finkelbf45efd2013-11-16 23:59:05 +0000439 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
440 void collectPossibleReductions(Loop *L,
441 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000442 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
443 ReductionTracker &Reductions);
444 };
445}
446
447char LoopReroll::ID = 0;
448INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
449INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000450INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000451INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000452INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000453INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000454INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
455
456Pass *llvm::createLoopRerollPass() {
457 return new LoopReroll;
458}
459
460// Returns true if the provided instruction is used outside the given loop.
461// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
462// non-loop blocks to be outside the loop.
463static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000464 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000465 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000466 return true;
James Molloy64419d42015-01-29 21:52:03 +0000467 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000468 return false;
469}
470
471// Collect the list of loop induction variables with respect to which it might
472// be possible to reroll the loop.
473void LoopReroll::collectPossibleIVs(Loop *L,
474 SmallInstructionVector &PossibleIVs) {
475 BasicBlock *Header = L->getHeader();
476 for (BasicBlock::iterator I = Header->begin(),
477 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
478 if (!isa<PHINode>(I))
479 continue;
480 if (!I->getType()->isIntegerTy())
481 continue;
482
483 if (const SCEVAddRecExpr *PHISCEV =
484 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
485 if (PHISCEV->getLoop() != L)
486 continue;
487 if (!PHISCEV->isAffine())
488 continue;
489 if (const SCEVConstant *IncSCEV =
490 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
491 if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
492 continue;
493 if (IncSCEV->getValue()->uge(MaxInc))
494 continue;
495
496 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
497 *PHISCEV << "\n");
498 PossibleIVs.push_back(I);
499 }
500 }
501 }
502}
503
504// Add the remainder of the reduction-variable chain to the instruction vector
505// (the initial PHINode has already been added). If successful, the object is
506// marked as valid.
507void LoopReroll::SimpleLoopReduction::add(Loop *L) {
508 assert(!Valid && "Cannot add to an already-valid chain");
509
510 // The reduction variable must be a chain of single-use instructions
511 // (including the PHI), except for the last value (which is used by the PHI
512 // and also outside the loop).
513 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000514 if (C->user_empty())
515 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000516
517 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000518 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000519 if (C->hasOneUse()) {
520 if (!C->isBinaryOp())
521 return;
522
523 if (!(isa<PHINode>(Instructions.back()) ||
524 C->isSameOperationAs(Instructions.back())))
525 return;
526
527 Instructions.push_back(C);
528 }
529 } while (C->hasOneUse());
530
531 if (Instructions.size() < 2 ||
532 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000533 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000534 return;
535
536 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000537 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000538 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000539 if (L->contains(cast<Instruction>(U)))
540 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000541 return;
James Molloy64419d42015-01-29 21:52:03 +0000542 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000543
544 Instructions.push_back(C);
545 Valid = true;
546}
547
548// Collect the vector of possible reduction variables.
549void LoopReroll::collectPossibleReductions(Loop *L,
550 ReductionTracker &Reductions) {
551 BasicBlock *Header = L->getHeader();
552 for (BasicBlock::iterator I = Header->begin(),
553 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
554 if (!isa<PHINode>(I))
555 continue;
556 if (!I->getType()->isSingleValueType())
557 continue;
558
559 SimpleLoopReduction SLR(I, L);
560 if (!SLR.valid())
561 continue;
562
563 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
564 SLR.size() << " chained instructions)\n");
565 Reductions.addSLR(SLR);
566 }
567}
568
569// Collect the set of all users of the provided root instruction. This set of
570// users contains not only the direct users of the root instruction, but also
571// all users of those users, and so on. There are two exceptions:
572//
573// 1. Instructions in the set of excluded instructions are never added to the
574// use set (even if they are users). This is used, for example, to exclude
575// including root increments in the use set of the primary IV.
576//
577// 2. Instructions in the set of final instructions are added to the use set
578// if they are users, but their users are not added. This is used, for
579// example, to prevent a reduction update from forcing all later reduction
580// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000581void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000582 Instruction *Root, const SmallInstructionSet &Exclude,
583 const SmallInstructionSet &Final,
584 DenseSet<Instruction *> &Users) {
585 SmallInstructionVector Queue(1, Root);
586 while (!Queue.empty()) {
587 Instruction *I = Queue.pop_back_val();
588 if (!Users.insert(I).second)
589 continue;
590
591 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000592 for (Use &U : I->uses()) {
593 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000594 if (PHINode *PN = dyn_cast<PHINode>(User)) {
595 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000596 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000597 continue;
598 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000599
Hal Finkelbf45efd2013-11-16 23:59:05 +0000600 if (L->contains(User) && !Exclude.count(User)) {
601 Queue.push_back(User);
602 }
603 }
604
605 // We also want to collect single-user "feeder" values.
606 for (User::op_iterator OI = I->op_begin(),
607 OIE = I->op_end(); OI != OIE; ++OI) {
608 if (Instruction *Op = dyn_cast<Instruction>(*OI))
609 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
610 !Final.count(Op))
611 Queue.push_back(Op);
612 }
613 }
614}
615
616// Collect all of the users of all of the provided root instructions (combined
617// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000618void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000619 const SmallInstructionVector &Roots,
620 const SmallInstructionSet &Exclude,
621 const SmallInstructionSet &Final,
622 DenseSet<Instruction *> &Users) {
623 for (SmallInstructionVector::const_iterator I = Roots.begin(),
624 IE = Roots.end(); I != IE; ++I)
James Molloy5f255eb2015-01-29 13:48:05 +0000625 collectInLoopUserSet(*I, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000626}
627
628static bool isSimpleLoadStore(Instruction *I) {
629 if (LoadInst *LI = dyn_cast<LoadInst>(I))
630 return LI->isSimple();
631 if (StoreInst *SI = dyn_cast<StoreInst>(I))
632 return SI->isSimple();
633 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
634 return !MI->isVolatile();
635 return false;
636}
637
James Molloyf1473592015-02-11 09:19:47 +0000638/// Return true if IVU is a "simple" arithmetic operation.
639/// This is used for narrowing the search space for DAGRoots; only arithmetic
640/// and GEPs can be part of a DAGRoot.
641static bool isSimpleArithmeticOp(User *IVU) {
642 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
643 switch (I->getOpcode()) {
644 default: return false;
645 case Instruction::Add:
646 case Instruction::Sub:
647 case Instruction::Mul:
648 case Instruction::Shl:
649 case Instruction::AShr:
650 case Instruction::LShr:
651 case Instruction::GetElementPtr:
652 case Instruction::Trunc:
653 case Instruction::ZExt:
654 case Instruction::SExt:
655 return true;
656 }
657 }
658 return false;
659}
660
661static bool isLoopIncrement(User *U, Instruction *IV) {
662 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
663 if (!BO || BO->getOpcode() != Instruction::Add)
664 return false;
665
666 for (auto *UU : BO->users()) {
667 PHINode *PN = dyn_cast<PHINode>(UU);
668 if (PN && PN == IV)
669 return true;
670 }
671 return false;
672}
673
674bool LoopReroll::DAGRootTracker::
675collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
676 SmallInstructionVector BaseUsers;
677
678 for (auto *I : Base->users()) {
679 ConstantInt *CI = nullptr;
680
681 if (isLoopIncrement(I, IV)) {
682 LoopIncs.push_back(cast<Instruction>(I));
683 continue;
684 }
685
686 // The root nodes must be either GEPs, ORs or ADDs.
687 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
688 if (BO->getOpcode() == Instruction::Add ||
689 BO->getOpcode() == Instruction::Or)
690 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
691 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
692 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
693 CI = dyn_cast<ConstantInt>(LastOperand);
694 }
695
696 if (!CI) {
697 if (Instruction *II = dyn_cast<Instruction>(I)) {
698 BaseUsers.push_back(II);
699 continue;
700 } else {
701 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
702 return false;
703 }
704 }
705
706 int64_t V = CI->getValue().getSExtValue();
707 if (Roots.find(V) != Roots.end())
708 // No duplicates, please.
709 return false;
710
711 // FIXME: Add support for negative values.
712 if (V < 0) {
713 DEBUG(dbgs() << "LRR: Aborting due to negative value: " << V << "\n");
714 return false;
715 }
716
717 Roots[V] = cast<Instruction>(I);
718 }
719
720 if (Roots.empty())
721 return false;
722
723 assert(Roots.find(0) == Roots.end() && "Didn't expect a zero index!");
724
725 // If we found non-loop-inc, non-root users of Base, assume they are
726 // for the zeroth root index. This is because "add %a, 0" gets optimized
727 // away.
728 if (BaseUsers.size())
729 Roots[0] = Base;
730
731 // Calculate the number of users of the base, or lowest indexed, iteration.
732 unsigned NumBaseUses = BaseUsers.size();
733 if (NumBaseUses == 0)
734 NumBaseUses = Roots.begin()->second->getNumUses();
735
736 // Check that every node has the same number of users.
737 for (auto &KV : Roots) {
738 if (KV.first == 0)
739 continue;
740 if (KV.second->getNumUses() != NumBaseUses) {
741 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
742 << "#Base=" << NumBaseUses << ", #Root=" <<
743 KV.second->getNumUses() << "\n");
744 return false;
745 }
746 }
747
748 return true;
749}
750
751bool LoopReroll::DAGRootTracker::
752findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
753 // Does the user look like it could be part of a root set?
754 // All its users must be simple arithmetic ops.
755 if (I->getNumUses() > IL_MaxRerollIterations)
756 return false;
757
758 if ((I->getOpcode() == Instruction::Mul ||
759 I->getOpcode() == Instruction::PHI) &&
760 I != IV &&
761 findRootsBase(I, SubsumedInsts))
762 return true;
763
764 SubsumedInsts.insert(I);
765
766 for (User *V : I->users()) {
767 Instruction *I = dyn_cast<Instruction>(V);
768 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
769 continue;
770
771 if (!I || !isSimpleArithmeticOp(I) ||
772 !findRootsRecursive(I, SubsumedInsts))
773 return false;
774 }
775 return true;
776}
777
778bool LoopReroll::DAGRootTracker::
779findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
780
781 // The base instruction needs to be a multiply so
782 // that we can erase it.
783 if (IVU->getOpcode() != Instruction::Mul &&
784 IVU->getOpcode() != Instruction::PHI)
785 return false;
786
787 std::map<int64_t, Instruction*> V;
788 if (!collectPossibleRoots(IVU, V))
789 return false;
790
791 // If we didn't get a root for index zero, then IVU must be
792 // subsumed.
793 if (V.find(0) == V.end())
794 SubsumedInsts.insert(IVU);
795
796 // Partition the vector into monotonically increasing indexes.
797 DAGRootSet DRS;
798 DRS.BaseInst = nullptr;
799
800 for (auto &KV : V) {
801 if (!DRS.BaseInst) {
802 DRS.BaseInst = KV.second;
803 DRS.SubsumedInsts = SubsumedInsts;
804 } else if (DRS.Roots.empty()) {
805 DRS.Roots.push_back(KV.second);
806 } else if (V.find(KV.first - 1) != V.end()) {
807 DRS.Roots.push_back(KV.second);
808 } else {
809 // Linear sequence terminated.
810 RootSets.push_back(DRS);
811 DRS.BaseInst = KV.second;
812 DRS.SubsumedInsts = SubsumedInsts;
813 DRS.Roots.clear();
814 }
815 }
816 RootSets.push_back(DRS);
817
818 return true;
819}
820
James Molloy5f255eb2015-01-29 13:48:05 +0000821bool LoopReroll::DAGRootTracker::findRoots() {
822
823 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
824 Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
825 getValue()->getZExtValue();
826
James Molloyf1473592015-02-11 09:19:47 +0000827 assert(RootSets.empty() && "Unclean state!");
828 if (Inc == 1) {
829 for (auto *IVU : IV->users()) {
830 if (isLoopIncrement(IVU, IV))
831 LoopIncs.push_back(cast<Instruction>(IVU));
832 }
833 if (!findRootsRecursive(IV, SmallInstructionSet()))
834 return false;
835 LoopIncs.push_back(IV);
836 } else {
837 if (!findRootsBase(IV, SmallInstructionSet()))
838 return false;
839 }
James Molloy5f255eb2015-01-29 13:48:05 +0000840
James Molloyf1473592015-02-11 09:19:47 +0000841 // Ensure all sets have the same size.
842 if (RootSets.empty()) {
843 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000844 return false;
James Molloyf1473592015-02-11 09:19:47 +0000845 }
846 for (auto &V : RootSets) {
847 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
848 DEBUG(dbgs()
849 << "LRR: Aborting because not all root sets have the same size\n");
850 return false;
851 }
852 }
James Molloy5f255eb2015-01-29 13:48:05 +0000853
James Molloyf1473592015-02-11 09:19:47 +0000854 // And ensure all loop iterations are consecutive. We rely on std::map
855 // providing ordered traversal.
856 for (auto &V : RootSets) {
857 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
858 if (!ADR)
859 return false;
860
861 // Consider a DAGRootSet with N-1 roots (so N different values including
862 // BaseInst).
863 // Define d = Roots[0] - BaseInst, which should be the same as
864 // Roots[I] - Roots[I-1] for all I in [1..N).
865 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
866 // loop iteration J.
867 //
868 // Now, For the loop iterations to be consecutive:
869 // D = d * N
870
871 unsigned N = V.Roots.size() + 1;
872 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
873 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
874 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
875 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
876 return false;
877 }
878 }
879 Scale = RootSets[0].Roots.size() + 1;
880
881 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +0000882 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +0000883 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +0000884 << "\n");
885 return false;
886 }
887
James Molloyf1473592015-02-11 09:19:47 +0000888 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000889
890 return true;
891}
892
James Molloy64419d42015-01-29 21:52:03 +0000893bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
894 // Populate the MapVector with all instructions in the block, in order first,
895 // so we can iterate over the contents later in perfect order.
896 for (auto &I : *L->getHeader()) {
897 Uses[&I].resize(IL_End);
898 }
James Molloy5f255eb2015-01-29 13:48:05 +0000899
James Molloy64419d42015-01-29 21:52:03 +0000900 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +0000901 for (auto &DRS : RootSets) {
902 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
903 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
904 Exclude.insert(DRS.BaseInst);
905 }
James Molloy64419d42015-01-29 21:52:03 +0000906 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
907
James Molloyf1473592015-02-11 09:19:47 +0000908 for (auto &DRS : RootSets) {
909 DenseSet<Instruction*> VBase;
910 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
911 for (auto *I : VBase) {
912 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +0000913 }
914
James Molloyf1473592015-02-11 09:19:47 +0000915 unsigned Idx = 1;
916 for (auto *Root : DRS.Roots) {
917 DenseSet<Instruction*> V;
918 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
919
920 // While we're here, check the use sets are the same size.
921 if (V.size() != VBase.size()) {
922 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
923 return false;
924 }
925
926 for (auto *I : V) {
927 Uses[I].set(Idx);
928 }
929 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +0000930 }
James Molloyf1473592015-02-11 09:19:47 +0000931
932 // Make sure our subsumed instructions are remembered too.
933 for (auto *I : DRS.SubsumedInsts) {
934 Uses[I].set(IL_All);
935 }
James Molloy64419d42015-01-29 21:52:03 +0000936 }
937
938 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +0000939
James Molloy64419d42015-01-29 21:52:03 +0000940 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +0000941 for (auto &DRS : RootSets) {
942 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
943 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
944 Exclude.insert(DRS.BaseInst);
945 }
James Molloy64419d42015-01-29 21:52:03 +0000946
947 DenseSet<Instruction*> V;
948 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
949 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +0000950 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +0000951 }
James Molloy64419d42015-01-29 21:52:03 +0000952
953 return true;
954
955}
956
James Molloye805ad92015-02-12 15:54:14 +0000957/// Get the next instruction in "In" that is a member of set Val.
958/// Start searching from StartI, and do not return anything in Exclude.
959/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +0000960LoopReroll::DAGRootTracker::UsesTy::iterator
961LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +0000962 const SmallInstructionSet &Exclude,
963 UsesTy::iterator *StartI) {
964 UsesTy::iterator I = StartI ? *StartI : In.begin();
965 while (I != In.end() && (I->second.test(Val) == 0 ||
966 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +0000967 ++I;
968 return I;
969}
970
James Molloyf1473592015-02-11 09:19:47 +0000971bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
972 for (auto &DRS : RootSets) {
973 if (DRS.BaseInst == I)
974 return true;
975 }
976 return false;
977}
978
979bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
980 for (auto &DRS : RootSets) {
981 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
982 return true;
983 }
984 return false;
985}
986
James Molloye805ad92015-02-12 15:54:14 +0000987/// Return true if instruction I depends on any instruction between
988/// Start and End.
989bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
990 UsesTy::iterator Start,
991 UsesTy::iterator End) {
992 for (auto *U : I->users()) {
993 for (auto It = Start; It != End; ++It)
994 if (U == It->first)
995 return true;
996 }
997 return false;
998}
999
James Molloy64419d42015-01-29 21:52:03 +00001000bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001001 // We now need to check for equivalence of the use graph of each root with
1002 // that of the primary induction variable (excluding the roots). Our goal
1003 // here is not to solve the full graph isomorphism problem, but rather to
1004 // catch common cases without a lot of work. As a result, we will assume
1005 // that the relative order of the instructions in each unrolled iteration
1006 // is the same (although we will not make an assumption about how the
1007 // different iterations are intermixed). Note that while the order must be
1008 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001009
1010 // An array of just the possible reductions for this scale factor. When we
1011 // collect the set of all users of some root instructions, these reduction
1012 // instructions are treated as 'final' (their uses are not considered).
1013 // This is important because we don't want the root use set to search down
1014 // the reduction chain.
1015 SmallInstructionSet PossibleRedSet;
1016 SmallInstructionSet PossibleRedLastSet;
1017 SmallInstructionSet PossibleRedPHISet;
1018 Reductions.restrictToScale(Scale, PossibleRedSet,
1019 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001020
James Molloy64419d42015-01-29 21:52:03 +00001021 // Populate "Uses" with where each instruction is used.
1022 if (!collectUsedInstructions(PossibleRedSet))
1023 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001024
James Molloy64419d42015-01-29 21:52:03 +00001025 // Make sure we mark the reduction PHIs as used in all iterations.
1026 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001027 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001028 }
James Molloy5f255eb2015-01-29 13:48:05 +00001029
James Molloy64419d42015-01-29 21:52:03 +00001030 // Make sure all instructions in the loop are in one and only one
1031 // set.
1032 for (auto &KV : Uses) {
1033 if (KV.second.count() != 1) {
1034 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1035 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1036 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001037 }
James Molloy64419d42015-01-29 21:52:03 +00001038 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001039
James Molloy64419d42015-01-29 21:52:03 +00001040 DEBUG(
1041 for (auto &KV : Uses) {
1042 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1043 }
1044 );
1045
1046 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001047 // In addition to regular aliasing information, we need to look for
1048 // instructions from later (future) iterations that have side effects
1049 // preventing us from reordering them past other instructions with side
1050 // effects.
1051 bool FutureSideEffects = false;
1052 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001053 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1054 DenseMap<Value *, Value *> BaseMap;
1055
James Molloy64419d42015-01-29 21:52:03 +00001056 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001057 SmallInstructionSet Visited;
1058 auto BaseIt = nextInstr(0, Uses, Visited);
1059 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001060 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001061
James Molloy64419d42015-01-29 21:52:03 +00001062 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1063 Instruction *BaseInst = BaseIt->first;
1064 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001065
James Molloy64419d42015-01-29 21:52:03 +00001066 // Skip over the IV or root instructions; only match their users.
1067 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001068 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001069 Visited.insert(BaseInst);
1070 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001071 Continue = true;
1072 }
James Molloyf1473592015-02-11 09:19:47 +00001073 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001074 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001075 Visited.insert(RootInst);
1076 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001077 Continue = true;
1078 }
1079 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001080
James Molloye805ad92015-02-12 15:54:14 +00001081 if (!BaseInst->isSameOperationAs(RootInst)) {
1082 // Last chance saloon. We don't try and solve the full isomorphism
1083 // problem, but try and at least catch the case where two instructions
1084 // *of different types* are round the wrong way. We won't be able to
1085 // efficiently tell, given two ADD instructions, which way around we
1086 // should match them, but given an ADD and a SUB, we can at least infer
1087 // which one is which.
1088 //
1089 // This should allow us to deal with a greater subset of the isomorphism
1090 // problem. It does however change a linear algorithm into a quadratic
1091 // one, so limit the number of probes we do.
1092 auto TryIt = RootIt;
1093 unsigned N = NumToleratedFailedMatches;
1094 while (TryIt != Uses.end() &&
1095 !BaseInst->isSameOperationAs(TryIt->first) &&
1096 N--) {
1097 ++TryIt;
1098 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1099 }
1100
1101 if (TryIt == Uses.end() || TryIt == RootIt ||
1102 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1103 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1104 " vs. " << *RootInst << "\n");
1105 return false;
1106 }
1107
1108 RootIt = TryIt;
1109 RootInst = TryIt->first;
1110 }
1111
James Molloy64419d42015-01-29 21:52:03 +00001112 // All instructions between the last root and this root
James Molloye805ad92015-02-12 15:54:14 +00001113 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001114 // future iteration, then they're dangerous to alias with.
James Molloye805ad92015-02-12 15:54:14 +00001115 //
1116 // Note that because we allow a limited amount of flexibility in the order
1117 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1118 // case we've already checked this set of instructions so we shouldn't
1119 // do anything.
1120 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001121 Instruction *I = LastRootIt->first;
1122 if (LastRootIt->second.find_first() < (int)Iter)
1123 continue;
1124 if (I->mayWriteToMemory())
1125 AST.add(I);
1126 // Note: This is specifically guarded by a check on isa<PHINode>,
1127 // which while a valid (somewhat arbitrary) micro-optimization, is
1128 // needed because otherwise isSafeToSpeculativelyExecute returns
1129 // false on PHI nodes.
1130 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
1131 !isSafeToSpeculativelyExecute(I, DL))
1132 // Intervening instructions cause side effects.
1133 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001134 }
1135
James Molloy5f255eb2015-01-29 13:48:05 +00001136 // Make sure that this instruction, which is in the use set of this
1137 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001138 // some other root instruction.
1139 if (RootIt->second.count() > 1) {
1140 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1141 " vs. " << *RootInst << " (prev. case overlap)\n");
1142 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001143 }
1144
1145 // Make sure that we don't alias with any instruction in the alias set
1146 // tracker. If we do, then we depend on a future iteration, and we
1147 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001148 if (RootInst->mayReadFromMemory())
1149 for (auto &K : AST) {
1150 if (K.aliasesUnknownInst(RootInst, *AA)) {
1151 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1152 " vs. " << *RootInst << " (depends on future store)\n");
1153 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001154 }
1155 }
James Molloy5f255eb2015-01-29 13:48:05 +00001156
1157 // If we've past an instruction from a future iteration that may have
1158 // side effects, and this instruction might also, then we can't reorder
1159 // them, and this matching fails. As an exception, we allow the alias
1160 // set tracker to handle regular (simple) load/store dependencies.
1161 if (FutureSideEffects &&
James Molloy64419d42015-01-29 21:52:03 +00001162 ((!isSimpleLoadStore(BaseInst) &&
1163 !isSafeToSpeculativelyExecute(BaseInst, DL)) ||
1164 (!isSimpleLoadStore(RootInst) &&
1165 !isSafeToSpeculativelyExecute(RootInst, DL)))) {
1166 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1167 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001168 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001169 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001170 }
1171
1172 // For instructions that are part of a reduction, if the operation is
1173 // associative, then don't bother matching the operands (because we
1174 // already know that the instructions are isomorphic, and the order
1175 // within the iteration does not matter). For non-associative reductions,
1176 // we do need to match the operands, because we need to reject
1177 // out-of-order instructions within an iteration!
1178 // For example (assume floating-point addition), we need to reject this:
1179 // x += a[i]; x += b[i];
1180 // x += a[i+1]; x += b[i+1];
1181 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001182 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001183
James Molloy64419d42015-01-29 21:52:03 +00001184 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001185 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001186 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1187 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001188
1189 // If this is part of a reduction (and the operation is not
1190 // associatve), then we match all operands, but not those that are
1191 // part of the reduction.
1192 if (InReduction)
1193 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001194 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001195 continue;
1196
1197 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001198 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001199 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001200 } else {
1201 for (auto &DRS : RootSets) {
1202 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1203 Op2 = DRS.BaseInst;
1204 break;
1205 }
1206 }
1207 }
James Molloy5f255eb2015-01-29 13:48:05 +00001208
James Molloy64419d42015-01-29 21:52:03 +00001209 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001210 // If we've not already decided to swap the matched operands, and
1211 // we've not already matched our first operand (note that we could
1212 // have skipped matching the first operand because it is part of a
1213 // reduction above), and the instruction is commutative, then try
1214 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001215 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1216 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001217 Swapped = true;
1218 } else {
James Molloy64419d42015-01-29 21:52:03 +00001219 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1220 << " vs. " << *RootInst << " (operand " << j << ")\n");
1221 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001222 }
1223 }
1224
1225 SomeOpMatched = true;
1226 }
1227 }
1228
James Molloy64419d42015-01-29 21:52:03 +00001229 if ((!PossibleRedLastSet.count(BaseInst) &&
1230 hasUsesOutsideLoop(BaseInst, L)) ||
1231 (!PossibleRedLastSet.count(RootInst) &&
1232 hasUsesOutsideLoop(RootInst, L))) {
1233 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1234 " vs. " << *RootInst << " (uses outside loop)\n");
1235 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001236 }
1237
James Molloy64419d42015-01-29 21:52:03 +00001238 Reductions.recordPair(BaseInst, RootInst, Iter);
1239 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001240
James Molloy64419d42015-01-29 21:52:03 +00001241 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001242 Visited.insert(BaseInst);
1243 Visited.insert(RootInst);
1244 BaseIt = nextInstr(0, Uses, Visited);
1245 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001246 }
James Molloy64419d42015-01-29 21:52:03 +00001247 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1248 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001249 }
1250
James Molloy5f255eb2015-01-29 13:48:05 +00001251 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001252 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001253
Hal Finkelbf45efd2013-11-16 23:59:05 +00001254 return true;
1255}
1256
James Molloy5f255eb2015-01-29 13:48:05 +00001257void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1258 BasicBlock *Header = L->getHeader();
1259 // Remove instructions associated with non-base iterations.
1260 for (BasicBlock::reverse_iterator J = Header->rbegin();
1261 J != Header->rend();) {
James Molloy64419d42015-01-29 21:52:03 +00001262 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001263 if (I > 0 && I < IL_All) {
James Molloy5f255eb2015-01-29 13:48:05 +00001264 Instruction *D = &*J;
1265 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1266 D->eraseFromParent();
1267 continue;
1268 }
1269
1270 ++J;
1271 }
1272
James Molloyf1473592015-02-11 09:19:47 +00001273 // We need to create a new induction variable for each different BaseInst.
1274 for (auto &DRS : RootSets) {
1275 // Insert the new induction variable.
1276 const SCEVAddRecExpr *RealIVSCEV =
1277 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1278 const SCEV *Start = RealIVSCEV->getStart();
1279 const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>
1280 (SE->getAddRecExpr(Start,
1281 SE->getConstant(RealIVSCEV->getType(), 1),
1282 L, SCEV::FlagAnyWrap));
1283 { // Limit the lifetime of SCEVExpander.
1284 SCEVExpander Expander(*SE, "reroll");
1285 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
James Molloy5f255eb2015-01-29 13:48:05 +00001286
James Molloyf1473592015-02-11 09:19:47 +00001287 for (auto &KV : Uses) {
1288 if (KV.second.find_first() == 0)
1289 KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
1290 }
James Molloy5f255eb2015-01-29 13:48:05 +00001291
James Molloyf1473592015-02-11 09:19:47 +00001292 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1293 // FIXME: Why do we need this check?
1294 if (Uses[BI].find_first() == IL_All) {
1295 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
James Molloy5f255eb2015-01-29 13:48:05 +00001296
James Molloyf1473592015-02-11 09:19:47 +00001297 // Iteration count SCEV minus 1
1298 const SCEV *ICMinus1SCEV =
1299 SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
James Molloy5f255eb2015-01-29 13:48:05 +00001300
James Molloyf1473592015-02-11 09:19:47 +00001301 Value *ICMinus1; // Iteration count minus 1
1302 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1303 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1304 } else {
1305 BasicBlock *Preheader = L->getLoopPreheader();
1306 if (!Preheader)
1307 Preheader = InsertPreheaderForLoop(L, Parent);
James Molloy5f255eb2015-01-29 13:48:05 +00001308
James Molloyf1473592015-02-11 09:19:47 +00001309 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1310 Preheader->getTerminator());
1311 }
1312
1313 Value *Cond =
James Molloy5f255eb2015-01-29 13:48:05 +00001314 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
James Molloyf1473592015-02-11 09:19:47 +00001315 BI->setCondition(Cond);
James Molloy5f255eb2015-01-29 13:48:05 +00001316
James Molloyf1473592015-02-11 09:19:47 +00001317 if (BI->getSuccessor(1) != Header)
1318 BI->swapSuccessors();
1319 }
James Molloy5f255eb2015-01-29 13:48:05 +00001320 }
1321 }
1322 }
1323
1324 SimplifyInstructionsInBlock(Header, DL, TLI);
1325 DeleteDeadPHIs(Header, TLI);
1326}
1327
Hal Finkelbf45efd2013-11-16 23:59:05 +00001328// Validate the selected reductions. All iterations must have an isomorphic
1329// part of the reduction chain and, for non-associative reductions, the chain
1330// entries must appear in order.
1331bool LoopReroll::ReductionTracker::validateSelected() {
1332 // For a non-associative reduction, the chain entries must appear in order.
1333 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1334 RI != RIE; ++RI) {
1335 int i = *RI;
1336 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001337 for (Instruction *J : PossibleReds[i]) {
1338 // Note that all instructions in the chain must have been found because
1339 // all instructions in the function must have been assigned to some
1340 // iteration.
1341 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001342 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1343 !PossibleReds[i].getReducedValue()->isAssociative()) {
1344 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001345 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001346 return false;
1347 }
1348
1349 if (Iter != PrevIter) {
1350 if (Count != BaseCount) {
1351 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1352 " reduction use count " << Count <<
1353 " is not equal to the base use count " <<
1354 BaseCount << "\n");
1355 return false;
1356 }
1357
1358 Count = 0;
1359 }
1360
1361 ++Count;
1362 if (Iter == 0)
1363 ++BaseCount;
1364
1365 PrevIter = Iter;
1366 }
1367 }
1368
1369 return true;
1370}
1371
1372// For all selected reductions, remove all parts except those in the first
1373// iteration (and the PHI). Replace outside uses of the reduced value with uses
1374// of the first-iteration reduced value (in other words, reroll the selected
1375// reductions).
1376void LoopReroll::ReductionTracker::replaceSelected() {
1377 // Fixup reductions to refer to the last instruction associated with the
1378 // first iteration (not the last).
1379 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1380 RI != RIE; ++RI) {
1381 int i = *RI;
1382 int j = 0;
1383 for (int e = PossibleReds[i].size(); j != e; ++j)
1384 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1385 --j;
1386 break;
1387 }
1388
1389 // Replace users with the new end-of-chain value.
1390 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001391 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001392 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001393 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001394
1395 for (SmallInstructionVector::iterator J = Users.begin(),
1396 JE = Users.end(); J != JE; ++J)
1397 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1398 PossibleReds[i][j]);
1399 }
1400}
1401
1402// Reroll the provided loop with respect to the provided induction variable.
1403// Generally, we're looking for a loop like this:
1404//
1405// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1406// f(%iv)
1407// %iv.1 = add %iv, 1 <-- a root increment
1408// f(%iv.1)
1409// %iv.2 = add %iv, 2 <-- a root increment
1410// f(%iv.2)
1411// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1412// f(%iv.scale_m_1)
1413// ...
1414// %iv.next = add %iv, scale
1415// %cmp = icmp(%iv, ...)
1416// br %cmp, header, exit
1417//
1418// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1419// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1420// be intermixed with eachother. The restriction imposed by this algorithm is
1421// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1422// etc. be the same.
1423//
1424// First, we collect the use set of %iv, excluding the other increment roots.
1425// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1426// times, having collected the use set of f(%iv.(i+1)), during which we:
1427// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1428// the next unmatched instruction in f(%iv.(i+1)).
1429// - Ensure that both matched instructions don't have any external users
1430// (with the exception of last-in-chain reduction instructions).
1431// - Track the (aliasing) write set, and other side effects, of all
1432// instructions that belong to future iterations that come before the matched
1433// instructions. If the matched instructions read from that write set, then
1434// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1435// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1436// if any of these future instructions had side effects (could not be
1437// speculatively executed), and so do the matched instructions, when we
1438// cannot reorder those side-effect-producing instructions, and rerolling
1439// fails.
1440//
1441// Finally, we make sure that all loop instructions are either loop increment
1442// roots, belong to simple latch code, parts of validated reductions, part of
1443// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1444// have been validated), then we reroll the loop.
1445bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1446 const SCEV *IterCount,
1447 ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001448 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DL);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001449
James Molloy5f255eb2015-01-29 13:48:05 +00001450 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001451 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001452 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001453 *IV << "\n");
1454
1455 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001456 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001457 if (!Reductions.validateSelected())
1458 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001459 // At this point, we've validated the rerolling, and we're committed to
1460 // making changes!
1461
1462 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001463 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001464
Hal Finkelbf45efd2013-11-16 23:59:05 +00001465 ++NumRerolledLoops;
1466 return true;
1467}
1468
1469bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001470 if (skipOptnoneFunction(L))
1471 return false;
1472
Hal Finkelbf45efd2013-11-16 23:59:05 +00001473 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001474 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001475 SE = &getAnalysis<ScalarEvolution>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001476 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Rafael Espindola93512512014-02-25 17:30:31 +00001477 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001478 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chandler Carruth73523022014-01-13 13:07:17 +00001479 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001480
1481 BasicBlock *Header = L->getHeader();
1482 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1483 "] Loop %" << Header->getName() << " (" <<
1484 L->getNumBlocks() << " block(s))\n");
1485
1486 bool Changed = false;
1487
1488 // For now, we'll handle only single BB loops.
1489 if (L->getNumBlocks() > 1)
1490 return Changed;
1491
1492 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1493 return Changed;
1494
1495 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1496 const SCEV *IterCount =
1497 SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1498 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1499
1500 // First, we need to find the induction variable with respect to which we can
1501 // reroll (there may be several possible options).
1502 SmallInstructionVector PossibleIVs;
1503 collectPossibleIVs(L, PossibleIVs);
1504
1505 if (PossibleIVs.empty()) {
1506 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1507 return Changed;
1508 }
1509
1510 ReductionTracker Reductions;
1511 collectPossibleReductions(L, Reductions);
1512
1513 // For each possible IV, collect the associated possible set of 'root' nodes
1514 // (i+1, i+2, etc.).
1515 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1516 IE = PossibleIVs.end(); I != IE; ++I)
1517 if (reroll(*I, L, Header, IterCount, Reductions)) {
1518 Changed = true;
1519 break;
1520 }
1521
1522 return Changed;
1523}