blob: d1a54b877950004013b823bd68ae8fe6050e8208 [file] [log] [blame]
Eugene Zelenko306d2992017-10-18 21:46:47 +00001//===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
Hal Finkelbf45efd2013-11-16 23:59:05 +00002//
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
Eugene Zelenko306d2992017-10-18 21:46:47 +000014#include "llvm/ADT/APInt.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ADT/BitVector.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
James Molloy64419d42015-01-29 21:52:03 +000018#include "llvm/ADT/MapVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/STLExtras.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000020#include "llvm/ADT/SmallSet.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000021#include "llvm/ADT/SmallVector.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000022#include "llvm/ADT/Statistic.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/AliasSetTracker.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000025#include "llvm/Analysis/LoopInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000026#include "llvm/Analysis/LoopPass.h"
27#include "llvm/Analysis/ScalarEvolution.h"
28#include "llvm/Analysis/ScalarEvolutionExpander.h"
29#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000032#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000034#include "llvm/IR/DataLayout.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000035#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000037#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000041#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000042#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Use.h"
46#include "llvm/IR/User.h"
47#include "llvm/IR/Value.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/Casting.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000050#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000053#include "llvm/Transforms/Scalar.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000054#include "llvm/Transforms/Utils/BasicBlockUtils.h"
55#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000057#include <cassert>
58#include <cstddef>
59#include <cstdint>
60#include <cstdlib>
61#include <iterator>
62#include <map>
63#include <utility>
Hal Finkelbf45efd2013-11-16 23:59:05 +000064
65using namespace llvm;
66
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "loop-reroll"
68
Hal Finkelbf45efd2013-11-16 23:59:05 +000069STATISTIC(NumRerolledLoops, "Number of rerolled loops");
70
71static cl::opt<unsigned>
72MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
73 cl::desc("The maximum increment for loop rerolling"));
74
James Molloye805ad92015-02-12 15:54:14 +000075static cl::opt<unsigned>
76NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
77 cl::Hidden,
78 cl::desc("The maximum number of failures to tolerate"
79 " during fuzzy matching. (default: 400)"));
80
Hal Finkelbf45efd2013-11-16 23:59:05 +000081// This loop re-rolling transformation aims to transform loops like this:
82//
83// int foo(int a);
84// void bar(int *x) {
85// for (int i = 0; i < 500; i += 3) {
86// foo(i);
87// foo(i+1);
88// foo(i+2);
89// }
90// }
91//
92// into a loop like this:
93//
94// void bar(int *x) {
95// for (int i = 0; i < 500; ++i)
96// foo(i);
97// }
98//
99// It does this by looking for loops that, besides the latch code, are composed
100// of isomorphic DAGs of instructions, with each DAG rooted at some increment
101// to the induction variable, and where each DAG is isomorphic to the DAG
102// rooted at the induction variable (excepting the sub-DAGs which root the
103// other induction-variable increments). In other words, we're looking for loop
104// bodies of the form:
105//
106// %iv = phi [ (preheader, ...), (body, %iv.next) ]
107// f(%iv)
108// %iv.1 = add %iv, 1 <-- a root increment
109// f(%iv.1)
110// %iv.2 = add %iv, 2 <-- a root increment
111// f(%iv.2)
112// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
113// f(%iv.scale_m_1)
114// ...
115// %iv.next = add %iv, scale
116// %cmp = icmp(%iv, ...)
117// br %cmp, header, exit
118//
119// where each f(i) is a set of instructions that, collectively, are a function
120// only of i (and other loop-invariant values).
121//
122// As a special case, we can also reroll loops like this:
123//
124// int foo(int);
125// void bar(int *x) {
126// for (int i = 0; i < 500; ++i) {
127// x[3*i] = foo(0);
128// x[3*i+1] = foo(0);
129// x[3*i+2] = foo(0);
130// }
131// }
132//
133// into this:
134//
135// void bar(int *x) {
136// for (int i = 0; i < 1500; ++i)
137// x[i] = foo(0);
138// }
139//
140// in which case, we're looking for inputs like this:
141//
142// %iv = phi [ (preheader, ...), (body, %iv.next) ]
143// %scaled.iv = mul %iv, scale
144// f(%scaled.iv)
145// %scaled.iv.1 = add %scaled.iv, 1
146// f(%scaled.iv.1)
147// %scaled.iv.2 = add %scaled.iv, 2
148// f(%scaled.iv.2)
149// %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
150// f(%scaled.iv.scale_m_1)
151// ...
152// %iv.next = add %iv, 1
153// %cmp = icmp(%iv, ...)
154// br %cmp, header, exit
155
156namespace {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000157
James Molloy64419d42015-01-29 21:52:03 +0000158 enum IterationLimits {
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000159 /// The maximum number of iterations that we'll try and reroll.
160 IL_MaxRerollIterations = 32,
James Molloy64419d42015-01-29 21:52:03 +0000161 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000162 /// instructions that belong to all iterations.
163 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000164 IL_End
165 };
166
Hal Finkelbf45efd2013-11-16 23:59:05 +0000167 class LoopReroll : public LoopPass {
168 public:
169 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko306d2992017-10-18 21:46:47 +0000170
Hal Finkelbf45efd2013-11-16 23:59:05 +0000171 LoopReroll() : LoopPass(ID) {
172 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
173 }
174
Craig Topper3e4c6972014-03-05 09:10:37 +0000175 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000176
Craig Topper3e4c6972014-03-05 09:10:37 +0000177 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000178 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000179 getLoopAnalysisUsage(AU);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000180 }
181
James Molloy64419d42015-01-29 21:52:03 +0000182 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000183 AliasAnalysis *AA;
184 LoopInfo *LI;
185 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000186 TargetLibraryInfo *TLI;
187 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000188 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000189
Eugene Zelenko306d2992017-10-18 21:46:47 +0000190 using SmallInstructionVector = SmallVector<Instruction *, 16>;
191 using SmallInstructionSet = SmallSet<Instruction *, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000192
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000193 // Map between induction variable and its increment
194 DenseMap<Instruction *, int64_t> IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000195
Lawrence Hu1befea22016-04-30 00:51:22 +0000196 // For loop with multiple induction variable, remember the one used only to
197 // control the loop.
198 Instruction *LoopControlIV;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000199
200 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000201 // representing a reduction. Only the last value may be used outside the
202 // loop.
203 struct SimpleLoopReduction {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000204 SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000205 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
206 add(L);
207 }
208
209 bool valid() const {
210 return Valid;
211 }
212
213 Instruction *getPHI() const {
214 assert(Valid && "Using invalid reduction");
215 return Instructions.front();
216 }
217
218 Instruction *getReducedValue() const {
219 assert(Valid && "Using invalid reduction");
220 return Instructions.back();
221 }
222
223 Instruction *get(size_t i) const {
224 assert(Valid && "Using invalid reduction");
225 return Instructions[i+1];
226 }
227
228 Instruction *operator [] (size_t i) const { return get(i); }
229
230 // The size, ignoring the initial PHI.
231 size_t size() const {
232 assert(Valid && "Using invalid reduction");
233 return Instructions.size()-1;
234 }
235
Eugene Zelenko306d2992017-10-18 21:46:47 +0000236 using iterator = SmallInstructionVector::iterator;
237 using const_iterator = SmallInstructionVector::const_iterator;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000238
239 iterator begin() {
240 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000241 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000242 }
243
244 const_iterator begin() const {
245 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000246 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000247 }
248
249 iterator end() { return Instructions.end(); }
250 const_iterator end() const { return Instructions.end(); }
251
252 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000253 bool Valid = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000254 SmallInstructionVector Instructions;
255
256 void add(Loop *L);
257 };
258
259 // The set of all reductions, and state tracking of possible reductions
260 // during loop instruction processing.
261 struct ReductionTracker {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000262 using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000263
264 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000265 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000266
267 // Setup to track possible reductions corresponding to the provided
268 // rerolling scale. Only reductions with a number of non-PHI instructions
269 // that is divisible by the scale are considered. Three instructions sets
270 // are filled in:
271 // - A set of all possible instructions in eligible reductions.
272 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000273 // - A set of all reduced values (last instructions) in eligible
274 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000275 void restrictToScale(uint64_t Scale,
276 SmallInstructionSet &PossibleRedSet,
277 SmallInstructionSet &PossibleRedPHISet,
278 SmallInstructionSet &PossibleRedLastSet) {
279 PossibleRedIdx.clear();
280 PossibleRedIter.clear();
281 Reds.clear();
282
283 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
284 if (PossibleReds[i].size() % Scale == 0) {
285 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
286 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000287
Hal Finkelbf45efd2013-11-16 23:59:05 +0000288 PossibleRedSet.insert(PossibleReds[i].getPHI());
289 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000290 for (Instruction *J : PossibleReds[i]) {
291 PossibleRedSet.insert(J);
292 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000293 }
294 }
295 }
296
297 // The functions below are used while processing the loop instructions.
298
299 // Are the two instructions both from reductions, and furthermore, from
300 // the same reduction?
301 bool isPairInSame(Instruction *J1, Instruction *J2) {
302 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
303 if (J1I != PossibleRedIdx.end()) {
304 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
305 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
306 return true;
307 }
308
309 return false;
310 }
311
312 // The two provided instructions, the first from the base iteration, and
313 // the second from iteration i, form a matched pair. If these are part of
314 // a reduction, record that fact.
315 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
316 if (PossibleRedIdx.count(J1)) {
317 assert(PossibleRedIdx.count(J2) &&
318 "Recording reduction vs. non-reduction instruction?");
319
320 PossibleRedIter[J1] = 0;
321 PossibleRedIter[J2] = i;
322
323 int Idx = PossibleRedIdx[J1];
324 assert(Idx == PossibleRedIdx[J2] &&
325 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000326 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000327 }
328 }
329
330 // The functions below can be called after we've finished processing all
331 // instructions in the loop, and we know which reductions were selected.
332
Hal Finkelbf45efd2013-11-16 23:59:05 +0000333 bool validateSelected();
334 void replaceSelected();
335
336 protected:
337 // The vector of all possible reductions (for any scale).
338 SmallReductionVector PossibleReds;
339
340 DenseMap<Instruction *, int> PossibleRedIdx;
341 DenseMap<Instruction *, int> PossibleRedIter;
342 DenseSet<int> Reds;
343 };
344
James Molloyf1473592015-02-11 09:19:47 +0000345 // A DAGRootSet models an induction variable being used in a rerollable
346 // loop. For example,
347 //
348 // x[i*3+0] = y1
349 // x[i*3+1] = y2
350 // x[i*3+2] = y3
351 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000352 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000353 // +---+----+
354 // / | \
355 // ST[y1] +1 +2 <-- Roots
356 // | |
357 // ST[y2] ST[y3]
358 //
359 // There may be multiple DAGRoots, for example:
360 //
361 // x[i*2+0] = ... (1)
362 // x[i*2+1] = ... (1)
363 // x[i*2+4] = ... (2)
364 // x[i*2+5] = ... (2)
365 // x[(i+1234)*2+5678] = ... (3)
366 // x[(i+1234)*2+5679] = ... (3)
367 //
368 // The loop will be rerolled by adding a new loop induction variable,
369 // one for the Base instruction in each DAGRootSet.
370 //
371 struct DAGRootSet {
372 Instruction *BaseInst;
373 SmallInstructionVector Roots;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000374
James Molloyf1473592015-02-11 09:19:47 +0000375 // The instructions between IV and BaseInst (but not including BaseInst).
376 SmallInstructionSet SubsumedInsts;
377 };
378
James Molloy5f255eb2015-01-29 13:48:05 +0000379 // The set of all DAG roots, and state tracking of all roots
380 // for a particular induction variable.
381 struct DAGRootTracker {
382 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
383 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000384 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
385 bool PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +0000386 DenseMap<Instruction *, int64_t> &IncrMap,
387 Instruction *LoopCtrlIV)
Justin Bogner843fb202015-12-15 19:40:57 +0000388 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
Lawrence Hu1befea22016-04-30 00:51:22 +0000389 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
390 LoopControlIV(LoopCtrlIV) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000391
392 /// Stage 1: Find all the DAG roots for the induction variable.
393 bool findRoots();
Eugene Zelenko306d2992017-10-18 21:46:47 +0000394
James Molloy5f255eb2015-01-29 13:48:05 +0000395 /// Stage 2: Validate if the found roots are valid.
396 bool validate(ReductionTracker &Reductions);
Eugene Zelenko306d2992017-10-18 21:46:47 +0000397
James Molloy5f255eb2015-01-29 13:48:05 +0000398 /// Stage 3: Assuming validate() returned true, perform the
399 /// replacement.
400 /// @param IterCount The maximum iteration count of L.
401 void replace(const SCEV *IterCount);
402
403 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000404 using UsesTy = MapVector<Instruction *, BitVector>;
James Molloy64419d42015-01-29 21:52:03 +0000405
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000406 void findRootsRecursive(Instruction *IVU,
James Molloyf1473592015-02-11 09:19:47 +0000407 SmallInstructionSet SubsumedInsts);
408 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
409 bool collectPossibleRoots(Instruction *Base,
410 std::map<int64_t,Instruction*> &Roots);
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000411 bool validateRootSet(DAGRootSet &DRS);
James Molloy5f255eb2015-01-29 13:48:05 +0000412
James Molloy64419d42015-01-29 21:52:03 +0000413 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000414 void collectInLoopUserSet(const SmallInstructionVector &Roots,
415 const SmallInstructionSet &Exclude,
416 const SmallInstructionSet &Final,
417 DenseSet<Instruction *> &Users);
418 void collectInLoopUserSet(Instruction *Root,
419 const SmallInstructionSet &Exclude,
420 const SmallInstructionSet &Final,
421 DenseSet<Instruction *> &Users);
422
James Molloye805ad92015-02-12 15:54:14 +0000423 UsesTy::iterator nextInstr(int Val, UsesTy &In,
424 const SmallInstructionSet &Exclude,
425 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000426 bool isBaseInst(Instruction *I);
427 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000428 bool instrDependsOn(Instruction *I,
429 UsesTy::iterator Start,
430 UsesTy::iterator End);
Lawrence Hud3d51062016-01-25 19:43:45 +0000431 void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
Lawrence Hu1befea22016-04-30 00:51:22 +0000432 void updateNonLoopCtrlIncr();
James Molloy64419d42015-01-29 21:52:03 +0000433
James Molloy5f255eb2015-01-29 13:48:05 +0000434 LoopReroll *Parent;
435
436 // Members of Parent, replicated here for brevity.
437 Loop *L;
438 ScalarEvolution *SE;
439 AliasAnalysis *AA;
440 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000441 DominatorTree *DT;
442 LoopInfo *LI;
443 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000444
445 // The loop induction variable.
446 Instruction *IV;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000447
James Molloy5f255eb2015-01-29 13:48:05 +0000448 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000449 int64_t Inc;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000450
James Molloy5f255eb2015-01-29 13:48:05 +0000451 // Loop reroll count; if Inc == 1, this records the scaling applied
452 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
453 // If Inc is not 1, Scale = Inc.
454 uint64_t Scale;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000455
James Molloy5f255eb2015-01-29 13:48:05 +0000456 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000457 SmallVector<DAGRootSet,16> RootSets;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000458
James Molloy5f255eb2015-01-29 13:48:05 +0000459 // All increment instructions for IV.
460 SmallInstructionVector LoopIncs;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000461
James Molloy64419d42015-01-29 21:52:03 +0000462 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000463 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000464 // used in the loop increment mechanism).
465 UsesTy Uses;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000466
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000467 // Map between induction variable and its increment
468 DenseMap<Instruction *, int64_t> &IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000469
Lawrence Hu1befea22016-04-30 00:51:22 +0000470 Instruction *LoopControlIV;
James Molloy5f255eb2015-01-29 13:48:05 +0000471 };
472
Lawrence Hu1befea22016-04-30 00:51:22 +0000473 // Check if it is a compare-like instruction whose user is a branch
474 bool isCompareUsedByBranch(Instruction *I) {
475 auto *TI = I->getParent()->getTerminator();
476 if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
477 return false;
478 return I->hasOneUse() && TI->getOperand(0) == I;
479 };
480
481 bool isLoopControlIV(Loop *L, Instruction *IV);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000482 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
483 void collectPossibleReductions(Loop *L,
484 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000485 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
486 ReductionTracker &Reductions);
487 };
Eugene Zelenko306d2992017-10-18 21:46:47 +0000488
489} // end anonymous namespace
Hal Finkelbf45efd2013-11-16 23:59:05 +0000490
491char LoopReroll::ID = 0;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000492
Hal Finkelbf45efd2013-11-16 23:59:05 +0000493INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000494INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000495INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000496INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
497
498Pass *llvm::createLoopRerollPass() {
499 return new LoopReroll;
500}
501
502// Returns true if the provided instruction is used outside the given loop.
503// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
504// non-loop blocks to be outside the loop.
505static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000506 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000507 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000508 return true;
James Molloy64419d42015-01-29 21:52:03 +0000509 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000510 return false;
511}
512
Lawrence Hud3d51062016-01-25 19:43:45 +0000513static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
514 const SCEV *SCEVExpr,
515 Instruction &IV) {
516 const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
517
518 // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
519 // Return c1.
520 if (!MulSCEV && IV.getType()->isPointerTy())
521 if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
522 const PointerType *PTy = cast<PointerType>(IV.getType());
523 Type *ElTy = PTy->getElementType();
524 const SCEV *SizeOfExpr =
525 SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
526 if (IncSCEV->getValue()->getValue().isNegative()) {
527 const SCEV *NewSCEV =
528 SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
529 return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
530 } else {
531 return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
532 }
533 }
534
535 if (!MulSCEV)
536 return nullptr;
537
538 // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
539 // Return c.
540 const SCEVConstant *CIncSCEV = nullptr;
541 for (const SCEV *Operand : MulSCEV->operands()) {
542 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
543 CIncSCEV = Constant;
544 } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
545 Type *AllocTy;
546 if (!Unknown->isSizeOf(AllocTy))
547 break;
548 } else {
549 return nullptr;
550 }
551 }
552 return CIncSCEV;
553}
554
Lawrence Hu1befea22016-04-30 00:51:22 +0000555// Check if an IV is only used to control the loop. There are two cases:
556// 1. It only has one use which is loop increment, and the increment is only
Lawrence Hue58a8142016-05-10 21:16:49 +0000557// used by comparison and the PHI (could has sext with nsw in between), and the
558// comparison is only used by branch.
Lawrence Hu1befea22016-04-30 00:51:22 +0000559// 2. It is used by loop increment and the comparison, the loop increment is
560// only used by the PHI, and the comparison is used only by the branch.
561bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
Lawrence Hu1befea22016-04-30 00:51:22 +0000562 unsigned IVUses = IV->getNumUses();
563 if (IVUses != 2 && IVUses != 1)
564 return false;
565
566 for (auto *User : IV->users()) {
567 int32_t IncOrCmpUses = User->getNumUses();
568 bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
569
570 // User can only have one or two uses.
571 if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
572 return false;
573
574 // Case 1
575 if (IVUses == 1) {
576 // The only user must be the loop increment.
577 // The loop increment must have two uses.
578 if (IsCompInst || IncOrCmpUses != 2)
579 return false;
580 }
581
582 // Case 2
583 if (IVUses == 2 && IncOrCmpUses != 1)
584 return false;
585
586 // The users of the IV must be a binary operation or a comparison
587 if (auto *BO = dyn_cast<BinaryOperator>(User)) {
588 if (BO->getOpcode() == Instruction::Add) {
589 // Loop Increment
590 // User of Loop Increment should be either PHI or CMP
591 for (auto *UU : User->users()) {
592 if (PHINode *PN = dyn_cast<PHINode>(UU)) {
593 if (PN != IV)
594 return false;
595 }
Lawrence Hue58a8142016-05-10 21:16:49 +0000596 // Must be a CMP or an ext (of a value with nsw) then CMP
597 else {
598 Instruction *UUser = dyn_cast<Instruction>(UU);
599 // Skip SExt if we are extending an nsw value
600 // TODO: Allow ZExt too
Zvi Rackoverd9423972017-04-18 14:55:43 +0000601 if (BO->hasNoSignedWrap() && UUser && UUser->hasOneUse() &&
Lawrence Hue58a8142016-05-10 21:16:49 +0000602 isa<SExtInst>(UUser))
603 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
604 if (!isCompareUsedByBranch(UUser))
605 return false;
606 }
Lawrence Hu1befea22016-04-30 00:51:22 +0000607 }
608 } else
609 return false;
610 // Compare : can only have one use, and must be branch
611 } else if (!IsCompInst)
612 return false;
613 }
614 return true;
615}
616
Hal Finkelbf45efd2013-11-16 23:59:05 +0000617// Collect the list of loop induction variables with respect to which it might
618// be possible to reroll the loop.
619void LoopReroll::collectPossibleIVs(Loop *L,
620 SmallInstructionVector &PossibleIVs) {
621 BasicBlock *Header = L->getHeader();
622 for (BasicBlock::iterator I = Header->begin(),
623 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
624 if (!isa<PHINode>(I))
625 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000626 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000627 continue;
628
629 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000630 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000631 if (PHISCEV->getLoop() != L)
632 continue;
633 if (!PHISCEV->isAffine())
634 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000635 const SCEVConstant *IncSCEV = nullptr;
636 if (I->getType()->isPointerTy())
637 IncSCEV =
638 getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
639 else
640 IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
641 if (IncSCEV) {
642 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000643 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000644 continue;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000645 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000646 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
647 << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000648
649 if (isLoopControlIV(L, &*I)) {
650 assert(!LoopControlIV && "Found two loop control only IV");
651 LoopControlIV = &(*I);
652 DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I << " = "
653 << *PHISCEV << "\n");
654 } else
655 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000656 }
657 }
658 }
659}
660
661// Add the remainder of the reduction-variable chain to the instruction vector
662// (the initial PHINode has already been added). If successful, the object is
663// marked as valid.
664void LoopReroll::SimpleLoopReduction::add(Loop *L) {
665 assert(!Valid && "Cannot add to an already-valid chain");
666
667 // The reduction variable must be a chain of single-use instructions
668 // (including the PHI), except for the last value (which is used by the PHI
669 // and also outside the loop).
670 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000671 if (C->user_empty())
672 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000673
674 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000675 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000676 if (C->hasOneUse()) {
677 if (!C->isBinaryOp())
678 return;
679
680 if (!(isa<PHINode>(Instructions.back()) ||
681 C->isSameOperationAs(Instructions.back())))
682 return;
683
684 Instructions.push_back(C);
685 }
686 } while (C->hasOneUse());
687
688 if (Instructions.size() < 2 ||
689 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000690 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000691 return;
692
693 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000694 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000695 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000696 if (L->contains(cast<Instruction>(U)))
697 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000698 return;
James Molloy64419d42015-01-29 21:52:03 +0000699 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000700
701 Instructions.push_back(C);
702 Valid = true;
703}
704
705// Collect the vector of possible reduction variables.
706void LoopReroll::collectPossibleReductions(Loop *L,
707 ReductionTracker &Reductions) {
708 BasicBlock *Header = L->getHeader();
709 for (BasicBlock::iterator I = Header->begin(),
710 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
711 if (!isa<PHINode>(I))
712 continue;
713 if (!I->getType()->isSingleValueType())
714 continue;
715
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000716 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000717 if (!SLR.valid())
718 continue;
719
720 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
721 SLR.size() << " chained instructions)\n");
722 Reductions.addSLR(SLR);
723 }
724}
725
726// Collect the set of all users of the provided root instruction. This set of
727// users contains not only the direct users of the root instruction, but also
728// all users of those users, and so on. There are two exceptions:
729//
730// 1. Instructions in the set of excluded instructions are never added to the
731// use set (even if they are users). This is used, for example, to exclude
732// including root increments in the use set of the primary IV.
733//
734// 2. Instructions in the set of final instructions are added to the use set
735// if they are users, but their users are not added. This is used, for
736// example, to prevent a reduction update from forcing all later reduction
737// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000738void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000739 Instruction *Root, const SmallInstructionSet &Exclude,
740 const SmallInstructionSet &Final,
741 DenseSet<Instruction *> &Users) {
742 SmallInstructionVector Queue(1, Root);
743 while (!Queue.empty()) {
744 Instruction *I = Queue.pop_back_val();
745 if (!Users.insert(I).second)
746 continue;
747
748 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000749 for (Use &U : I->uses()) {
750 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000751 if (PHINode *PN = dyn_cast<PHINode>(User)) {
752 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000753 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000754 continue;
755 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000756
Hal Finkelbf45efd2013-11-16 23:59:05 +0000757 if (L->contains(User) && !Exclude.count(User)) {
758 Queue.push_back(User);
759 }
760 }
761
762 // We also want to collect single-user "feeder" values.
763 for (User::op_iterator OI = I->op_begin(),
764 OIE = I->op_end(); OI != OIE; ++OI) {
765 if (Instruction *Op = dyn_cast<Instruction>(*OI))
766 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
767 !Final.count(Op))
768 Queue.push_back(Op);
769 }
770 }
771}
772
773// Collect all of the users of all of the provided root instructions (combined
774// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000775void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000776 const SmallInstructionVector &Roots,
777 const SmallInstructionSet &Exclude,
778 const SmallInstructionSet &Final,
779 DenseSet<Instruction *> &Users) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000780 for (Instruction *Root : Roots)
781 collectInLoopUserSet(Root, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000782}
783
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000784static bool isUnorderedLoadStore(Instruction *I) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000785 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000786 return LI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000787 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000788 return SI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000789 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
790 return !MI->isVolatile();
791 return false;
792}
793
James Molloyf1473592015-02-11 09:19:47 +0000794/// Return true if IVU is a "simple" arithmetic operation.
795/// This is used for narrowing the search space for DAGRoots; only arithmetic
796/// and GEPs can be part of a DAGRoot.
797static bool isSimpleArithmeticOp(User *IVU) {
798 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
799 switch (I->getOpcode()) {
800 default: return false;
801 case Instruction::Add:
802 case Instruction::Sub:
803 case Instruction::Mul:
804 case Instruction::Shl:
805 case Instruction::AShr:
806 case Instruction::LShr:
807 case Instruction::GetElementPtr:
808 case Instruction::Trunc:
809 case Instruction::ZExt:
810 case Instruction::SExt:
811 return true;
812 }
813 }
814 return false;
815}
816
817static bool isLoopIncrement(User *U, Instruction *IV) {
818 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hud3d51062016-01-25 19:43:45 +0000819
820 if ((BO && BO->getOpcode() != Instruction::Add) ||
821 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000822 return false;
823
Lawrence Hud3d51062016-01-25 19:43:45 +0000824 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000825 PHINode *PN = dyn_cast<PHINode>(UU);
826 if (PN && PN == IV)
827 return true;
828 }
829 return false;
830}
831
832bool LoopReroll::DAGRootTracker::
833collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
834 SmallInstructionVector BaseUsers;
835
836 for (auto *I : Base->users()) {
837 ConstantInt *CI = nullptr;
838
839 if (isLoopIncrement(I, IV)) {
840 LoopIncs.push_back(cast<Instruction>(I));
841 continue;
842 }
843
844 // The root nodes must be either GEPs, ORs or ADDs.
845 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
846 if (BO->getOpcode() == Instruction::Add ||
847 BO->getOpcode() == Instruction::Or)
848 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
849 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
850 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
851 CI = dyn_cast<ConstantInt>(LastOperand);
852 }
853
854 if (!CI) {
855 if (Instruction *II = dyn_cast<Instruction>(I)) {
856 BaseUsers.push_back(II);
857 continue;
858 } else {
859 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
860 return false;
861 }
862 }
863
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000864 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000865 if (Roots.find(V) != Roots.end())
866 // No duplicates, please.
867 return false;
868
James Molloyf1473592015-02-11 09:19:47 +0000869 Roots[V] = cast<Instruction>(I);
870 }
871
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000872 // Make sure we have at least two roots.
873 if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
James Molloyf1473592015-02-11 09:19:47 +0000874 return false;
James Molloyf1473592015-02-11 09:19:47 +0000875
876 // If we found non-loop-inc, non-root users of Base, assume they are
877 // for the zeroth root index. This is because "add %a, 0" gets optimized
878 // away.
James Molloye32d8062015-02-16 17:02:00 +0000879 if (BaseUsers.size()) {
880 if (Roots.find(0) != Roots.end()) {
881 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
882 return false;
883 }
James Molloyf1473592015-02-11 09:19:47 +0000884 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000885 }
James Molloyf1473592015-02-11 09:19:47 +0000886
887 // Calculate the number of users of the base, or lowest indexed, iteration.
888 unsigned NumBaseUses = BaseUsers.size();
889 if (NumBaseUses == 0)
890 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000891
James Molloyf1473592015-02-11 09:19:47 +0000892 // Check that every node has the same number of users.
893 for (auto &KV : Roots) {
894 if (KV.first == 0)
895 continue;
Davide Italiano80fe9872017-04-18 21:42:21 +0000896 if (!KV.second->hasNUses(NumBaseUses)) {
James Molloyf1473592015-02-11 09:19:47 +0000897 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
898 << "#Base=" << NumBaseUses << ", #Root=" <<
899 KV.second->getNumUses() << "\n");
900 return false;
901 }
902 }
903
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000904 return true;
James Molloyf1473592015-02-11 09:19:47 +0000905}
906
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000907void LoopReroll::DAGRootTracker::
James Molloyf1473592015-02-11 09:19:47 +0000908findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
909 // Does the user look like it could be part of a root set?
910 // All its users must be simple arithmetic ops.
Davide Italiano80fe9872017-04-18 21:42:21 +0000911 if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000912 return;
James Molloyf1473592015-02-11 09:19:47 +0000913
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000914 if (I != IV && findRootsBase(I, SubsumedInsts))
915 return;
James Molloyf1473592015-02-11 09:19:47 +0000916
917 SubsumedInsts.insert(I);
918
919 for (User *V : I->users()) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000920 Instruction *I = cast<Instruction>(V);
David Majnemer0d955d02016-08-11 22:21:41 +0000921 if (is_contained(LoopIncs, I))
James Molloyf1473592015-02-11 09:19:47 +0000922 continue;
923
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000924 if (!isSimpleArithmeticOp(I))
925 continue;
926
927 // The recursive call makes a copy of SubsumedInsts.
928 findRootsRecursive(I, SubsumedInsts);
James Molloyf1473592015-02-11 09:19:47 +0000929 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000930}
931
932bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
933 if (DRS.Roots.empty())
934 return false;
935
936 // Consider a DAGRootSet with N-1 roots (so N different values including
937 // BaseInst).
938 // Define d = Roots[0] - BaseInst, which should be the same as
939 // Roots[I] - Roots[I-1] for all I in [1..N).
940 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
941 // loop iteration J.
942 //
943 // Now, For the loop iterations to be consecutive:
944 // D = d * N
945 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
946 if (!ADR)
947 return false;
948 unsigned N = DRS.Roots.size() + 1;
949 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
950 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
951 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
952 return false;
953
James Molloyf1473592015-02-11 09:19:47 +0000954 return true;
955}
956
957bool LoopReroll::DAGRootTracker::
958findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000959 // The base of a RootSet must be an AddRec, so it can be erased.
960 const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
961 if (!IVU_ADR || IVU_ADR->getLoop() != L)
James Molloyf1473592015-02-11 09:19:47 +0000962 return false;
963
964 std::map<int64_t, Instruction*> V;
965 if (!collectPossibleRoots(IVU, V))
966 return false;
967
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000968 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000969 // subsumed.
970 if (V.find(0) == V.end())
971 SubsumedInsts.insert(IVU);
972
973 // Partition the vector into monotonically increasing indexes.
974 DAGRootSet DRS;
975 DRS.BaseInst = nullptr;
976
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000977 SmallVector<DAGRootSet, 16> PotentialRootSets;
978
James Molloyf1473592015-02-11 09:19:47 +0000979 for (auto &KV : V) {
980 if (!DRS.BaseInst) {
981 DRS.BaseInst = KV.second;
982 DRS.SubsumedInsts = SubsumedInsts;
983 } else if (DRS.Roots.empty()) {
984 DRS.Roots.push_back(KV.second);
985 } else if (V.find(KV.first - 1) != V.end()) {
986 DRS.Roots.push_back(KV.second);
987 } else {
988 // Linear sequence terminated.
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000989 if (!validateRootSet(DRS))
990 return false;
991
992 // Construct a new DAGRootSet with the next sequence.
993 PotentialRootSets.push_back(DRS);
James Molloyf1473592015-02-11 09:19:47 +0000994 DRS.BaseInst = KV.second;
James Molloyf1473592015-02-11 09:19:47 +0000995 DRS.Roots.clear();
996 }
997 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000998
999 if (!validateRootSet(DRS))
1000 return false;
1001
1002 PotentialRootSets.push_back(DRS);
1003
1004 RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
James Molloyf1473592015-02-11 09:19:47 +00001005
1006 return true;
1007}
1008
James Molloy5f255eb2015-01-29 13:48:05 +00001009bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001010 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +00001011
James Molloyf1473592015-02-11 09:19:47 +00001012 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001013 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +00001014 for (auto *IVU : IV->users()) {
1015 if (isLoopIncrement(IVU, IV))
1016 LoopIncs.push_back(cast<Instruction>(IVU));
1017 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001018 findRootsRecursive(IV, SmallInstructionSet());
James Molloyf1473592015-02-11 09:19:47 +00001019 LoopIncs.push_back(IV);
1020 } else {
1021 if (!findRootsBase(IV, SmallInstructionSet()))
1022 return false;
1023 }
James Molloy5f255eb2015-01-29 13:48:05 +00001024
James Molloyf1473592015-02-11 09:19:47 +00001025 // Ensure all sets have the same size.
1026 if (RootSets.empty()) {
1027 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001028 return false;
James Molloyf1473592015-02-11 09:19:47 +00001029 }
1030 for (auto &V : RootSets) {
1031 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
1032 DEBUG(dbgs()
1033 << "LRR: Aborting because not all root sets have the same size\n");
1034 return false;
1035 }
1036 }
James Molloy5f255eb2015-01-29 13:48:05 +00001037
James Molloyf1473592015-02-11 09:19:47 +00001038 Scale = RootSets[0].Roots.size() + 1;
1039
1040 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +00001041 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +00001042 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +00001043 << "\n");
1044 return false;
1045 }
1046
James Molloyf1473592015-02-11 09:19:47 +00001047 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001048
1049 return true;
1050}
1051
James Molloy64419d42015-01-29 21:52:03 +00001052bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1053 // Populate the MapVector with all instructions in the block, in order first,
1054 // so we can iterate over the contents later in perfect order.
1055 for (auto &I : *L->getHeader()) {
1056 Uses[&I].resize(IL_End);
1057 }
James Molloy5f255eb2015-01-29 13:48:05 +00001058
James Molloy64419d42015-01-29 21:52:03 +00001059 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +00001060 for (auto &DRS : RootSets) {
1061 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1062 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1063 Exclude.insert(DRS.BaseInst);
1064 }
James Molloy64419d42015-01-29 21:52:03 +00001065 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1066
James Molloyf1473592015-02-11 09:19:47 +00001067 for (auto &DRS : RootSets) {
1068 DenseSet<Instruction*> VBase;
1069 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1070 for (auto *I : VBase) {
1071 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +00001072 }
1073
James Molloyf1473592015-02-11 09:19:47 +00001074 unsigned Idx = 1;
1075 for (auto *Root : DRS.Roots) {
1076 DenseSet<Instruction*> V;
1077 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1078
1079 // While we're here, check the use sets are the same size.
1080 if (V.size() != VBase.size()) {
1081 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
1082 return false;
1083 }
1084
1085 for (auto *I : V) {
1086 Uses[I].set(Idx);
1087 }
1088 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +00001089 }
James Molloyf1473592015-02-11 09:19:47 +00001090
1091 // Make sure our subsumed instructions are remembered too.
1092 for (auto *I : DRS.SubsumedInsts) {
1093 Uses[I].set(IL_All);
1094 }
James Molloy64419d42015-01-29 21:52:03 +00001095 }
1096
1097 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +00001098
James Molloy64419d42015-01-29 21:52:03 +00001099 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +00001100 for (auto &DRS : RootSets) {
1101 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1102 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1103 Exclude.insert(DRS.BaseInst);
1104 }
James Molloy64419d42015-01-29 21:52:03 +00001105
1106 DenseSet<Instruction*> V;
1107 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1108 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +00001109 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001110 }
James Molloy64419d42015-01-29 21:52:03 +00001111
1112 return true;
James Molloy64419d42015-01-29 21:52:03 +00001113}
1114
James Molloye805ad92015-02-12 15:54:14 +00001115/// Get the next instruction in "In" that is a member of set Val.
1116/// Start searching from StartI, and do not return anything in Exclude.
1117/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +00001118LoopReroll::DAGRootTracker::UsesTy::iterator
1119LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +00001120 const SmallInstructionSet &Exclude,
1121 UsesTy::iterator *StartI) {
1122 UsesTy::iterator I = StartI ? *StartI : In.begin();
1123 while (I != In.end() && (I->second.test(Val) == 0 ||
1124 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +00001125 ++I;
1126 return I;
1127}
1128
James Molloyf1473592015-02-11 09:19:47 +00001129bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1130 for (auto &DRS : RootSets) {
1131 if (DRS.BaseInst == I)
1132 return true;
1133 }
1134 return false;
1135}
1136
1137bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1138 for (auto &DRS : RootSets) {
David Majnemer0d955d02016-08-11 22:21:41 +00001139 if (is_contained(DRS.Roots, I))
James Molloyf1473592015-02-11 09:19:47 +00001140 return true;
1141 }
1142 return false;
1143}
1144
James Molloye805ad92015-02-12 15:54:14 +00001145/// Return true if instruction I depends on any instruction between
1146/// Start and End.
1147bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1148 UsesTy::iterator Start,
1149 UsesTy::iterator End) {
1150 for (auto *U : I->users()) {
1151 for (auto It = Start; It != End; ++It)
1152 if (U == It->first)
1153 return true;
1154 }
1155 return false;
1156}
1157
Weiming Zhao310770a2015-09-28 17:03:23 +00001158static bool isIgnorableInst(const Instruction *I) {
1159 if (isa<DbgInfoIntrinsic>(I))
1160 return true;
1161 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1162 if (!II)
1163 return false;
1164 switch (II->getIntrinsicID()) {
1165 default:
1166 return false;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001167 case Intrinsic::annotation:
Weiming Zhao310770a2015-09-28 17:03:23 +00001168 case Intrinsic::ptr_annotation:
1169 case Intrinsic::var_annotation:
1170 // TODO: the following intrinsics may also be whitelisted:
1171 // lifetime_start, lifetime_end, invariant_start, invariant_end
1172 return true;
1173 }
1174 return false;
1175}
1176
James Molloy64419d42015-01-29 21:52:03 +00001177bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001178 // We now need to check for equivalence of the use graph of each root with
1179 // that of the primary induction variable (excluding the roots). Our goal
1180 // here is not to solve the full graph isomorphism problem, but rather to
1181 // catch common cases without a lot of work. As a result, we will assume
1182 // that the relative order of the instructions in each unrolled iteration
1183 // is the same (although we will not make an assumption about how the
1184 // different iterations are intermixed). Note that while the order must be
1185 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001186
1187 // An array of just the possible reductions for this scale factor. When we
1188 // collect the set of all users of some root instructions, these reduction
1189 // instructions are treated as 'final' (their uses are not considered).
1190 // This is important because we don't want the root use set to search down
1191 // the reduction chain.
1192 SmallInstructionSet PossibleRedSet;
1193 SmallInstructionSet PossibleRedLastSet;
1194 SmallInstructionSet PossibleRedPHISet;
1195 Reductions.restrictToScale(Scale, PossibleRedSet,
1196 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001197
James Molloy64419d42015-01-29 21:52:03 +00001198 // Populate "Uses" with where each instruction is used.
1199 if (!collectUsedInstructions(PossibleRedSet))
1200 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001201
James Molloy64419d42015-01-29 21:52:03 +00001202 // Make sure we mark the reduction PHIs as used in all iterations.
1203 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001204 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001205 }
James Molloy5f255eb2015-01-29 13:48:05 +00001206
Lawrence Hu1befea22016-04-30 00:51:22 +00001207 // Make sure we mark loop-control-only PHIs as used in all iterations. See
1208 // comment above LoopReroll::isLoopControlIV for more information.
1209 BasicBlock *Header = L->getHeader();
1210 if (LoopControlIV && LoopControlIV != IV) {
1211 for (auto *U : LoopControlIV->users()) {
1212 Instruction *IVUser = dyn_cast<Instruction>(U);
1213 // IVUser could be loop increment or compare
1214 Uses[IVUser].set(IL_All);
1215 for (auto *UU : IVUser->users()) {
1216 Instruction *UUser = dyn_cast<Instruction>(UU);
1217 // UUser could be compare, PHI or branch
1218 Uses[UUser].set(IL_All);
Lawrence Hue58a8142016-05-10 21:16:49 +00001219 // Skip SExt
1220 if (isa<SExtInst>(UUser)) {
1221 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1222 Uses[UUser].set(IL_All);
1223 }
Lawrence Hu1befea22016-04-30 00:51:22 +00001224 // Is UUser a compare instruction?
1225 if (UU->hasOneUse()) {
1226 Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1227 if (BI == cast<BranchInst>(Header->getTerminator()))
1228 Uses[BI].set(IL_All);
1229 }
1230 }
1231 }
1232 }
1233
James Molloy64419d42015-01-29 21:52:03 +00001234 // Make sure all instructions in the loop are in one and only one
1235 // set.
1236 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001237 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
James Molloy64419d42015-01-29 21:52:03 +00001238 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1239 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1240 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001241 }
James Molloy64419d42015-01-29 21:52:03 +00001242 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001243
James Molloy64419d42015-01-29 21:52:03 +00001244 DEBUG(
1245 for (auto &KV : Uses) {
1246 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1247 }
1248 );
1249
1250 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001251 // In addition to regular aliasing information, we need to look for
1252 // instructions from later (future) iterations that have side effects
1253 // preventing us from reordering them past other instructions with side
1254 // effects.
1255 bool FutureSideEffects = false;
1256 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001257 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1258 DenseMap<Value *, Value *> BaseMap;
1259
James Molloy64419d42015-01-29 21:52:03 +00001260 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001261 SmallInstructionSet Visited;
1262 auto BaseIt = nextInstr(0, Uses, Visited);
1263 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001264 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001265
James Molloy64419d42015-01-29 21:52:03 +00001266 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1267 Instruction *BaseInst = BaseIt->first;
1268 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001269
James Molloy64419d42015-01-29 21:52:03 +00001270 // Skip over the IV or root instructions; only match their users.
1271 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001272 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001273 Visited.insert(BaseInst);
1274 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001275 Continue = true;
1276 }
James Molloyf1473592015-02-11 09:19:47 +00001277 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001278 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001279 Visited.insert(RootInst);
1280 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001281 Continue = true;
1282 }
1283 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001284
James Molloye805ad92015-02-12 15:54:14 +00001285 if (!BaseInst->isSameOperationAs(RootInst)) {
1286 // Last chance saloon. We don't try and solve the full isomorphism
1287 // problem, but try and at least catch the case where two instructions
1288 // *of different types* are round the wrong way. We won't be able to
1289 // efficiently tell, given two ADD instructions, which way around we
1290 // should match them, but given an ADD and a SUB, we can at least infer
1291 // which one is which.
1292 //
1293 // This should allow us to deal with a greater subset of the isomorphism
1294 // problem. It does however change a linear algorithm into a quadratic
1295 // one, so limit the number of probes we do.
1296 auto TryIt = RootIt;
1297 unsigned N = NumToleratedFailedMatches;
1298 while (TryIt != Uses.end() &&
1299 !BaseInst->isSameOperationAs(TryIt->first) &&
1300 N--) {
1301 ++TryIt;
1302 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1303 }
1304
1305 if (TryIt == Uses.end() || TryIt == RootIt ||
1306 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1307 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1308 " vs. " << *RootInst << "\n");
1309 return false;
1310 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001311
James Molloye805ad92015-02-12 15:54:14 +00001312 RootIt = TryIt;
1313 RootInst = TryIt->first;
1314 }
1315
James Molloy64419d42015-01-29 21:52:03 +00001316 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001317 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001318 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001319 //
James Molloye805ad92015-02-12 15:54:14 +00001320 // Note that because we allow a limited amount of flexibility in the order
1321 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1322 // case we've already checked this set of instructions so we shouldn't
1323 // do anything.
1324 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001325 Instruction *I = LastRootIt->first;
1326 if (LastRootIt->second.find_first() < (int)Iter)
1327 continue;
1328 if (I->mayWriteToMemory())
1329 AST.add(I);
1330 // Note: This is specifically guarded by a check on isa<PHINode>,
1331 // which while a valid (somewhat arbitrary) micro-optimization, is
1332 // needed because otherwise isSafeToSpeculativelyExecute returns
1333 // false on PHI nodes.
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001334 if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001335 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001336 // Intervening instructions cause side effects.
1337 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001338 }
1339
James Molloy5f255eb2015-01-29 13:48:05 +00001340 // Make sure that this instruction, which is in the use set of this
1341 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001342 // some other root instruction.
1343 if (RootIt->second.count() > 1) {
1344 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1345 " vs. " << *RootInst << " (prev. case overlap)\n");
1346 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001347 }
1348
1349 // Make sure that we don't alias with any instruction in the alias set
1350 // tracker. If we do, then we depend on a future iteration, and we
1351 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001352 if (RootInst->mayReadFromMemory())
1353 for (auto &K : AST) {
1354 if (K.aliasesUnknownInst(RootInst, *AA)) {
1355 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1356 " vs. " << *RootInst << " (depends on future store)\n");
1357 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001358 }
1359 }
James Molloy5f255eb2015-01-29 13:48:05 +00001360
1361 // If we've past an instruction from a future iteration that may have
1362 // side effects, and this instruction might also, then we can't reorder
1363 // them, and this matching fails. As an exception, we allow the alias
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001364 // set tracker to handle regular (unordered) load/store dependencies.
1365 if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001366 !isSafeToSpeculativelyExecute(BaseInst)) ||
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001367 (!isUnorderedLoadStore(RootInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001368 !isSafeToSpeculativelyExecute(RootInst)))) {
James Molloy64419d42015-01-29 21:52:03 +00001369 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1370 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001371 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001372 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001373 }
1374
1375 // For instructions that are part of a reduction, if the operation is
1376 // associative, then don't bother matching the operands (because we
1377 // already know that the instructions are isomorphic, and the order
1378 // within the iteration does not matter). For non-associative reductions,
1379 // we do need to match the operands, because we need to reject
1380 // out-of-order instructions within an iteration!
1381 // For example (assume floating-point addition), we need to reject this:
1382 // x += a[i]; x += b[i];
1383 // x += a[i+1]; x += b[i+1];
1384 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001385 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001386
James Molloy64419d42015-01-29 21:52:03 +00001387 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001388 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001389 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1390 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001391
1392 // If this is part of a reduction (and the operation is not
1393 // associatve), then we match all operands, but not those that are
1394 // part of the reduction.
1395 if (InReduction)
1396 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001397 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001398 continue;
1399
1400 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001401 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001402 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001403 } else {
1404 for (auto &DRS : RootSets) {
1405 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1406 Op2 = DRS.BaseInst;
1407 break;
1408 }
1409 }
1410 }
James Molloy5f255eb2015-01-29 13:48:05 +00001411
James Molloy64419d42015-01-29 21:52:03 +00001412 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001413 // If we've not already decided to swap the matched operands, and
1414 // we've not already matched our first operand (note that we could
1415 // have skipped matching the first operand because it is part of a
1416 // reduction above), and the instruction is commutative, then try
1417 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001418 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1419 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001420 Swapped = true;
1421 } else {
James Molloy64419d42015-01-29 21:52:03 +00001422 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1423 << " vs. " << *RootInst << " (operand " << j << ")\n");
1424 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001425 }
1426 }
1427
1428 SomeOpMatched = true;
1429 }
1430 }
1431
James Molloy64419d42015-01-29 21:52:03 +00001432 if ((!PossibleRedLastSet.count(BaseInst) &&
1433 hasUsesOutsideLoop(BaseInst, L)) ||
1434 (!PossibleRedLastSet.count(RootInst) &&
1435 hasUsesOutsideLoop(RootInst, L))) {
1436 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1437 " vs. " << *RootInst << " (uses outside loop)\n");
1438 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001439 }
1440
James Molloy64419d42015-01-29 21:52:03 +00001441 Reductions.recordPair(BaseInst, RootInst, Iter);
1442 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001443
James Molloy64419d42015-01-29 21:52:03 +00001444 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001445 Visited.insert(BaseInst);
1446 Visited.insert(RootInst);
1447 BaseIt = nextInstr(0, Uses, Visited);
1448 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001449 }
Eugene Zelenko306d2992017-10-18 21:46:47 +00001450 assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
1451 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001452 }
1453
James Molloy5f255eb2015-01-29 13:48:05 +00001454 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001455 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001456
Hal Finkelbf45efd2013-11-16 23:59:05 +00001457 return true;
1458}
1459
James Molloy5f255eb2015-01-29 13:48:05 +00001460void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1461 BasicBlock *Header = L->getHeader();
1462 // Remove instructions associated with non-base iterations.
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001463 for (BasicBlock::reverse_iterator J = Header->rbegin(), JE = Header->rend();
1464 J != JE;) {
James Molloy64419d42015-01-29 21:52:03 +00001465 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001466 if (I > 0 && I < IL_All) {
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001467 DEBUG(dbgs() << "LRR: removing: " << *J << "\n");
1468 J++->eraseFromParent();
James Molloy5f255eb2015-01-29 13:48:05 +00001469 continue;
1470 }
1471
1472 ++J;
1473 }
1474
Lawrence Hu1befea22016-04-30 00:51:22 +00001475 bool HasTwoIVs = LoopControlIV && LoopControlIV != IV;
1476
1477 if (HasTwoIVs) {
1478 updateNonLoopCtrlIncr();
1479 replaceIV(LoopControlIV, LoopControlIV, IterCount);
1480 } else
1481 // We need to create a new induction variable for each different BaseInst.
1482 for (auto &DRS : RootSets)
1483 // Insert the new induction variable.
1484 replaceIV(DRS.BaseInst, IV, IterCount);
Lawrence Hub917cd92016-01-25 19:36:30 +00001485
1486 SimplifyInstructionsInBlock(Header, TLI);
1487 DeleteDeadPHIs(Header, TLI);
Lawrence Hu84b61952016-01-25 18:53:39 +00001488}
1489
Lawrence Hu1befea22016-04-30 00:51:22 +00001490// For non-loop-control IVs, we only need to update the last increment
1491// with right amount, then we are done.
1492void LoopReroll::DAGRootTracker::updateNonLoopCtrlIncr() {
1493 const SCEV *NewInc = nullptr;
1494 for (auto *LoopInc : LoopIncs) {
1495 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LoopInc);
1496 const SCEVConstant *COp = nullptr;
1497 if (GEP && LoopInc->getOperand(0)->getType()->isPointerTy()) {
1498 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1499 } else {
1500 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(0)));
1501 if (!COp)
1502 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1503 }
1504
1505 assert(COp && "Didn't find constant operand of LoopInc!\n");
1506
1507 const APInt &AInt = COp->getValue()->getValue();
1508 const SCEV *ScaleSCEV = SE->getConstant(COp->getType(), Scale);
1509 if (AInt.isNegative()) {
1510 NewInc = SE->getNegativeSCEV(COp);
1511 NewInc = SE->getUDivExpr(NewInc, ScaleSCEV);
1512 NewInc = SE->getNegativeSCEV(NewInc);
1513 } else
1514 NewInc = SE->getUDivExpr(COp, ScaleSCEV);
1515
1516 LoopInc->setOperand(1, dyn_cast<SCEVConstant>(NewInc)->getValue());
1517 }
1518}
1519
Lawrence Hud3d51062016-01-25 19:43:45 +00001520void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1521 Instruction *InstIV,
1522 const SCEV *IterCount) {
1523 BasicBlock *Header = L->getHeader();
1524 int64_t Inc = IVToIncMap[InstIV];
Lawrence Hu1befea22016-04-30 00:51:22 +00001525 bool NeedNewIV = InstIV == LoopControlIV;
1526 bool Negative = !NeedNewIV && Inc < 0;
Lawrence Hud3d51062016-01-25 19:43:45 +00001527
1528 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1529 const SCEV *Start = RealIVSCEV->getStart();
1530
Lawrence Hu1befea22016-04-30 00:51:22 +00001531 if (NeedNewIV)
1532 Start = SE->getConstant(Start->getType(), 0);
1533
Lawrence Hud3d51062016-01-25 19:43:45 +00001534 const SCEV *SizeOfExpr = nullptr;
1535 const SCEV *IncrExpr =
1536 SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1537 if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1538 Type *ElTy = PTy->getElementType();
1539 SizeOfExpr =
1540 SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1541 IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1542 }
1543 const SCEV *NewIVSCEV =
1544 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1545
1546 { // Limit the lifetime of SCEVExpander.
1547 const DataLayout &DL = Header->getModule()->getDataLayout();
1548 SCEVExpander Expander(*SE, DL, "reroll");
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001549 Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
1550 Header->getFirstNonPHIOrDbg());
Lawrence Hud3d51062016-01-25 19:43:45 +00001551
1552 for (auto &KV : Uses)
1553 if (KV.second.find_first() == 0)
1554 KV.first->replaceUsesOfWith(Inst, NewIV);
1555
1556 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1557 // FIXME: Why do we need this check?
1558 if (Uses[BI].find_first() == IL_All) {
1559 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1560
Lawrence Hu1befea22016-04-30 00:51:22 +00001561 if (NeedNewIV)
1562 ICSCEV = SE->getMulExpr(IterCount,
1563 SE->getConstant(IterCount->getType(), Scale));
Lawrence Hu1befea22016-04-30 00:51:22 +00001564
Lawrence Hud3d51062016-01-25 19:43:45 +00001565 // Iteration count SCEV minus or plus 1
1566 const SCEV *MinusPlus1SCEV =
1567 SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1568 if (Inst->getType()->isPointerTy()) {
1569 assert(SizeOfExpr && "SizeOfExpr is not initialized");
1570 MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1571 }
1572
1573 const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1574 // Iteration count minus 1
Lawrence Hue58a8142016-05-10 21:16:49 +00001575 Instruction *InsertPtr = nullptr;
Lawrence Hud3d51062016-01-25 19:43:45 +00001576 if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
Lawrence Hue58a8142016-05-10 21:16:49 +00001577 InsertPtr = BI;
Lawrence Hud3d51062016-01-25 19:43:45 +00001578 } else {
1579 BasicBlock *Preheader = L->getLoopPreheader();
1580 if (!Preheader)
1581 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
Lawrence Hue58a8142016-05-10 21:16:49 +00001582 InsertPtr = Preheader->getTerminator();
Lawrence Hud3d51062016-01-25 19:43:45 +00001583 }
1584
Lawrence Hue58a8142016-05-10 21:16:49 +00001585 if (!isa<PointerType>(NewIV->getType()) && NeedNewIV &&
1586 (SE->getTypeSizeInBits(NewIV->getType()) <
1587 SE->getTypeSizeInBits(ICMinusPlus1SCEV->getType()))) {
1588 IRBuilder<> Builder(BI);
1589 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
1590 NewIV = Builder.CreateSExt(NewIV, ICMinusPlus1SCEV->getType());
1591 }
1592 Value *ICMinusPlus1 = Expander.expandCodeFor(
1593 ICMinusPlus1SCEV, NewIV->getType(), InsertPtr);
1594
Lawrence Hud3d51062016-01-25 19:43:45 +00001595 Value *Cond =
1596 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1597 BI->setCondition(Cond);
1598
1599 if (BI->getSuccessor(1) != Header)
1600 BI->swapSuccessors();
1601 }
1602 }
1603 }
1604}
1605
Hal Finkelbf45efd2013-11-16 23:59:05 +00001606// Validate the selected reductions. All iterations must have an isomorphic
1607// part of the reduction chain and, for non-associative reductions, the chain
1608// entries must appear in order.
1609bool LoopReroll::ReductionTracker::validateSelected() {
1610 // For a non-associative reduction, the chain entries must appear in order.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001611 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001612 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001613 for (Instruction *J : PossibleReds[i]) {
1614 // Note that all instructions in the chain must have been found because
1615 // all instructions in the function must have been assigned to some
1616 // iteration.
1617 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001618 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1619 !PossibleReds[i].getReducedValue()->isAssociative()) {
1620 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001621 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001622 return false;
1623 }
1624
1625 if (Iter != PrevIter) {
1626 if (Count != BaseCount) {
1627 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1628 " reduction use count " << Count <<
1629 " is not equal to the base use count " <<
1630 BaseCount << "\n");
1631 return false;
1632 }
1633
1634 Count = 0;
1635 }
1636
1637 ++Count;
1638 if (Iter == 0)
1639 ++BaseCount;
1640
1641 PrevIter = Iter;
1642 }
1643 }
1644
1645 return true;
1646}
1647
1648// For all selected reductions, remove all parts except those in the first
1649// iteration (and the PHI). Replace outside uses of the reduced value with uses
1650// of the first-iteration reduced value (in other words, reroll the selected
1651// reductions).
1652void LoopReroll::ReductionTracker::replaceSelected() {
1653 // Fixup reductions to refer to the last instruction associated with the
1654 // first iteration (not the last).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001655 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001656 int j = 0;
1657 for (int e = PossibleReds[i].size(); j != e; ++j)
1658 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1659 --j;
1660 break;
1661 }
1662
1663 // Replace users with the new end-of-chain value.
1664 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001665 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001666 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001667 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001668
Benjamin Kramer135f7352016-06-26 12:28:59 +00001669 for (Instruction *User : Users)
1670 User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
Hal Finkelbf45efd2013-11-16 23:59:05 +00001671 PossibleReds[i][j]);
1672 }
1673}
1674
1675// Reroll the provided loop with respect to the provided induction variable.
1676// Generally, we're looking for a loop like this:
1677//
1678// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1679// f(%iv)
1680// %iv.1 = add %iv, 1 <-- a root increment
1681// f(%iv.1)
1682// %iv.2 = add %iv, 2 <-- a root increment
1683// f(%iv.2)
1684// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1685// f(%iv.scale_m_1)
1686// ...
1687// %iv.next = add %iv, scale
1688// %cmp = icmp(%iv, ...)
1689// br %cmp, header, exit
1690//
1691// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1692// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1693// be intermixed with eachother. The restriction imposed by this algorithm is
1694// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1695// etc. be the same.
1696//
1697// First, we collect the use set of %iv, excluding the other increment roots.
1698// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1699// times, having collected the use set of f(%iv.(i+1)), during which we:
1700// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1701// the next unmatched instruction in f(%iv.(i+1)).
1702// - Ensure that both matched instructions don't have any external users
1703// (with the exception of last-in-chain reduction instructions).
1704// - Track the (aliasing) write set, and other side effects, of all
1705// instructions that belong to future iterations that come before the matched
1706// instructions. If the matched instructions read from that write set, then
1707// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1708// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1709// if any of these future instructions had side effects (could not be
1710// speculatively executed), and so do the matched instructions, when we
1711// cannot reorder those side-effect-producing instructions, and rerolling
1712// fails.
1713//
1714// Finally, we make sure that all loop instructions are either loop increment
1715// roots, belong to simple latch code, parts of validated reductions, part of
1716// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1717// have been validated), then we reroll the loop.
1718bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1719 const SCEV *IterCount,
1720 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001721 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +00001722 IVToIncMap, LoopControlIV);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001723
James Molloy5f255eb2015-01-29 13:48:05 +00001724 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001725 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001726 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001727 *IV << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001728
James Molloy5f255eb2015-01-29 13:48:05 +00001729 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001730 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001731 if (!Reductions.validateSelected())
1732 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001733 // At this point, we've validated the rerolling, and we're committed to
1734 // making changes!
1735
1736 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001737 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001738
Hal Finkelbf45efd2013-11-16 23:59:05 +00001739 ++NumRerolledLoops;
1740 return true;
1741}
1742
1743bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001744 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001745 return false;
1746
Chandler Carruth7b560d42015-09-09 17:55:00 +00001747 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001748 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001749 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001750 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001751 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001752 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001753
1754 BasicBlock *Header = L->getHeader();
1755 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1756 "] Loop %" << Header->getName() << " (" <<
1757 L->getNumBlocks() << " block(s))\n");
1758
Hal Finkelbf45efd2013-11-16 23:59:05 +00001759 // For now, we'll handle only single BB loops.
1760 if (L->getNumBlocks() > 1)
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001761 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001762
1763 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001764 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001765
1766 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001767 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Lawrence Hue58a8142016-05-10 21:16:49 +00001768 DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001769 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1770
1771 // First, we need to find the induction variable with respect to which we can
1772 // reroll (there may be several possible options).
1773 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001774 IVToIncMap.clear();
Lawrence Hu1befea22016-04-30 00:51:22 +00001775 LoopControlIV = nullptr;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001776 collectPossibleIVs(L, PossibleIVs);
1777
1778 if (PossibleIVs.empty()) {
1779 DEBUG(dbgs() << "LRR: No possible IVs found\n");
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001780 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001781 }
1782
1783 ReductionTracker Reductions;
1784 collectPossibleReductions(L, Reductions);
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001785 bool Changed = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001786
1787 // For each possible IV, collect the associated possible set of 'root' nodes
1788 // (i+1, i+2, etc.).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001789 for (Instruction *PossibleIV : PossibleIVs)
1790 if (reroll(PossibleIV, L, Header, IterCount, Reductions)) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001791 Changed = true;
1792 break;
1793 }
Lawrence Hue58a8142016-05-10 21:16:49 +00001794 DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001795
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001796 // Trip count of L has changed so SE must be re-evaluated.
1797 if (Changed)
1798 SE->forgetLoop(L);
1799
Hal Finkelbf45efd2013-11-16 23:59:05 +00001800 return Changed;
1801}