blob: 014bc43363f30f1c16b3d7077dcd92e7c302a0d0 [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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000027#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000030#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.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 {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000150 AU.addRequired<AAResultsWrapperPass>();
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>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000155 AU.addRequired<ScalarEvolutionWrapperPass>();
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;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000163 TargetLibraryInfo *TLI;
164 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000165 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000166
167 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
168 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
169
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000170 // Map between induction variable and its increment
171 DenseMap<Instruction *, int64_t> IVToIncMap;
172
173 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000174 // representing a reduction. Only the last value may be used outside the
175 // loop.
176 struct SimpleLoopReduction {
177 SimpleLoopReduction(Instruction *P, Loop *L)
178 : Valid(false), Instructions(1, P) {
179 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
180 add(L);
181 }
182
183 bool valid() const {
184 return Valid;
185 }
186
187 Instruction *getPHI() const {
188 assert(Valid && "Using invalid reduction");
189 return Instructions.front();
190 }
191
192 Instruction *getReducedValue() const {
193 assert(Valid && "Using invalid reduction");
194 return Instructions.back();
195 }
196
197 Instruction *get(size_t i) const {
198 assert(Valid && "Using invalid reduction");
199 return Instructions[i+1];
200 }
201
202 Instruction *operator [] (size_t i) const { return get(i); }
203
204 // The size, ignoring the initial PHI.
205 size_t size() const {
206 assert(Valid && "Using invalid reduction");
207 return Instructions.size()-1;
208 }
209
210 typedef SmallInstructionVector::iterator iterator;
211 typedef SmallInstructionVector::const_iterator const_iterator;
212
213 iterator begin() {
214 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000215 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000216 }
217
218 const_iterator begin() const {
219 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000220 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000221 }
222
223 iterator end() { return Instructions.end(); }
224 const_iterator end() const { return Instructions.end(); }
225
226 protected:
227 bool Valid;
228 SmallInstructionVector Instructions;
229
230 void add(Loop *L);
231 };
232
233 // The set of all reductions, and state tracking of possible reductions
234 // during loop instruction processing.
235 struct ReductionTracker {
236 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
237
238 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000239 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000240
241 // Setup to track possible reductions corresponding to the provided
242 // rerolling scale. Only reductions with a number of non-PHI instructions
243 // that is divisible by the scale are considered. Three instructions sets
244 // are filled in:
245 // - A set of all possible instructions in eligible reductions.
246 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000247 // - A set of all reduced values (last instructions) in eligible
248 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000249 void restrictToScale(uint64_t Scale,
250 SmallInstructionSet &PossibleRedSet,
251 SmallInstructionSet &PossibleRedPHISet,
252 SmallInstructionSet &PossibleRedLastSet) {
253 PossibleRedIdx.clear();
254 PossibleRedIter.clear();
255 Reds.clear();
256
257 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
258 if (PossibleReds[i].size() % Scale == 0) {
259 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
260 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000261
Hal Finkelbf45efd2013-11-16 23:59:05 +0000262 PossibleRedSet.insert(PossibleReds[i].getPHI());
263 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000264 for (Instruction *J : PossibleReds[i]) {
265 PossibleRedSet.insert(J);
266 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000267 }
268 }
269 }
270
271 // The functions below are used while processing the loop instructions.
272
273 // Are the two instructions both from reductions, and furthermore, from
274 // the same reduction?
275 bool isPairInSame(Instruction *J1, Instruction *J2) {
276 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
277 if (J1I != PossibleRedIdx.end()) {
278 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
279 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
280 return true;
281 }
282
283 return false;
284 }
285
286 // The two provided instructions, the first from the base iteration, and
287 // the second from iteration i, form a matched pair. If these are part of
288 // a reduction, record that fact.
289 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
290 if (PossibleRedIdx.count(J1)) {
291 assert(PossibleRedIdx.count(J2) &&
292 "Recording reduction vs. non-reduction instruction?");
293
294 PossibleRedIter[J1] = 0;
295 PossibleRedIter[J2] = i;
296
297 int Idx = PossibleRedIdx[J1];
298 assert(Idx == PossibleRedIdx[J2] &&
299 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000300 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000301 }
302 }
303
304 // The functions below can be called after we've finished processing all
305 // instructions in the loop, and we know which reductions were selected.
306
Hal Finkelbf45efd2013-11-16 23:59:05 +0000307 bool validateSelected();
308 void replaceSelected();
309
310 protected:
311 // The vector of all possible reductions (for any scale).
312 SmallReductionVector PossibleReds;
313
314 DenseMap<Instruction *, int> PossibleRedIdx;
315 DenseMap<Instruction *, int> PossibleRedIter;
316 DenseSet<int> Reds;
317 };
318
James Molloyf1473592015-02-11 09:19:47 +0000319 // A DAGRootSet models an induction variable being used in a rerollable
320 // loop. For example,
321 //
322 // x[i*3+0] = y1
323 // x[i*3+1] = y2
324 // x[i*3+2] = y3
325 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000326 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000327 // +---+----+
328 // / | \
329 // ST[y1] +1 +2 <-- Roots
330 // | |
331 // ST[y2] ST[y3]
332 //
333 // There may be multiple DAGRoots, for example:
334 //
335 // x[i*2+0] = ... (1)
336 // x[i*2+1] = ... (1)
337 // x[i*2+4] = ... (2)
338 // x[i*2+5] = ... (2)
339 // x[(i+1234)*2+5678] = ... (3)
340 // x[(i+1234)*2+5679] = ... (3)
341 //
342 // The loop will be rerolled by adding a new loop induction variable,
343 // one for the Base instruction in each DAGRootSet.
344 //
345 struct DAGRootSet {
346 Instruction *BaseInst;
347 SmallInstructionVector Roots;
348 // The instructions between IV and BaseInst (but not including BaseInst).
349 SmallInstructionSet SubsumedInsts;
350 };
351
James Molloy5f255eb2015-01-29 13:48:05 +0000352 // The set of all DAG roots, and state tracking of all roots
353 // for a particular induction variable.
354 struct DAGRootTracker {
355 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
356 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000357 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
358 bool PreserveLCSSA,
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000359 DenseMap<Instruction *, int64_t> &IncrMap)
Justin Bogner843fb202015-12-15 19:40:57 +0000360 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
361 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000362
363 /// Stage 1: Find all the DAG roots for the induction variable.
364 bool findRoots();
365 /// Stage 2: Validate if the found roots are valid.
366 bool validate(ReductionTracker &Reductions);
367 /// Stage 3: Assuming validate() returned true, perform the
368 /// replacement.
369 /// @param IterCount The maximum iteration count of L.
370 void replace(const SCEV *IterCount);
371
372 protected:
James Molloy64419d42015-01-29 21:52:03 +0000373 typedef MapVector<Instruction*, SmallBitVector> UsesTy;
374
James Molloyf1473592015-02-11 09:19:47 +0000375 bool findRootsRecursive(Instruction *IVU,
376 SmallInstructionSet SubsumedInsts);
377 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
378 bool collectPossibleRoots(Instruction *Base,
379 std::map<int64_t,Instruction*> &Roots);
James Molloy5f255eb2015-01-29 13:48:05 +0000380
James Molloy64419d42015-01-29 21:52:03 +0000381 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000382 void collectInLoopUserSet(const SmallInstructionVector &Roots,
383 const SmallInstructionSet &Exclude,
384 const SmallInstructionSet &Final,
385 DenseSet<Instruction *> &Users);
386 void collectInLoopUserSet(Instruction *Root,
387 const SmallInstructionSet &Exclude,
388 const SmallInstructionSet &Final,
389 DenseSet<Instruction *> &Users);
390
James Molloye805ad92015-02-12 15:54:14 +0000391 UsesTy::iterator nextInstr(int Val, UsesTy &In,
392 const SmallInstructionSet &Exclude,
393 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000394 bool isBaseInst(Instruction *I);
395 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000396 bool instrDependsOn(Instruction *I,
397 UsesTy::iterator Start,
398 UsesTy::iterator End);
Lawrence Hu84b61952016-01-25 18:53:39 +0000399 void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
James Molloy64419d42015-01-29 21:52:03 +0000400
James Molloy5f255eb2015-01-29 13:48:05 +0000401 LoopReroll *Parent;
402
403 // Members of Parent, replicated here for brevity.
404 Loop *L;
405 ScalarEvolution *SE;
406 AliasAnalysis *AA;
407 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000408 DominatorTree *DT;
409 LoopInfo *LI;
410 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000411
412 // The loop induction variable.
413 Instruction *IV;
414 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000415 int64_t Inc;
James Molloy5f255eb2015-01-29 13:48:05 +0000416 // Loop reroll count; if Inc == 1, this records the scaling applied
417 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
418 // If Inc is not 1, Scale = Inc.
419 uint64_t Scale;
James Molloy5f255eb2015-01-29 13:48:05 +0000420 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000421 SmallVector<DAGRootSet,16> RootSets;
James Molloy5f255eb2015-01-29 13:48:05 +0000422 // All increment instructions for IV.
423 SmallInstructionVector LoopIncs;
James Molloy64419d42015-01-29 21:52:03 +0000424 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000425 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000426 // used in the loop increment mechanism).
427 UsesTy Uses;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000428 // Map between induction variable and its increment
429 DenseMap<Instruction *, int64_t> &IVToIncMap;
James Molloy5f255eb2015-01-29 13:48:05 +0000430 };
431
Hal Finkelbf45efd2013-11-16 23:59:05 +0000432 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
433 void collectPossibleReductions(Loop *L,
434 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000435 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
436 ReductionTracker &Reductions);
437 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000438}
Hal Finkelbf45efd2013-11-16 23:59:05 +0000439
440char LoopReroll::ID = 0;
441INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000442INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000443INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000444INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000445INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000446INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000447INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
448
449Pass *llvm::createLoopRerollPass() {
450 return new LoopReroll;
451}
452
453// Returns true if the provided instruction is used outside the given loop.
454// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
455// non-loop blocks to be outside the loop.
456static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000457 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000458 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000459 return true;
James Molloy64419d42015-01-29 21:52:03 +0000460 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000461 return false;
462}
463
Lawrence Hu84b61952016-01-25 18:53:39 +0000464static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
465 const SCEV *SCEVExpr,
466 Instruction &IV) {
467 const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
468
469 // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
470 // Return c1.
471 if (!MulSCEV && IV.getType()->isPointerTy())
472 if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
473 const PointerType *PTy = cast<PointerType>(IV.getType());
474 Type *ElTy = PTy->getElementType();
475 const SCEV *SizeOfExpr =
476 SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
477 if (IncSCEV->getValue()->getValue().isNegative()) {
478 const SCEV *NewSCEV =
479 SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
480 return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
481 } else {
482 return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
483 }
484 }
485
486 if (!MulSCEV)
487 return nullptr;
488
489 // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
490 // Return c.
491 const SCEVConstant *CIncSCEV = nullptr;
492 for (const SCEV *Operand : MulSCEV->operands()) {
493 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
494 CIncSCEV = Constant;
495 } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
496 Type *AllocTy;
497 if (!Unknown->isSizeOf(AllocTy))
498 break;
499 } else {
500 return nullptr;
501 }
502 }
503 return CIncSCEV;
504}
505
Hal Finkelbf45efd2013-11-16 23:59:05 +0000506// Collect the list of loop induction variables with respect to which it might
507// be possible to reroll the loop.
508void LoopReroll::collectPossibleIVs(Loop *L,
509 SmallInstructionVector &PossibleIVs) {
510 BasicBlock *Header = L->getHeader();
511 for (BasicBlock::iterator I = Header->begin(),
512 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
513 if (!isa<PHINode>(I))
514 continue;
Lawrence Hu84b61952016-01-25 18:53:39 +0000515 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000516 continue;
517
518 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000519 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000520 if (PHISCEV->getLoop() != L)
521 continue;
522 if (!PHISCEV->isAffine())
523 continue;
Lawrence Hu84b61952016-01-25 18:53:39 +0000524 const SCEVConstant *IncSCEV = nullptr;
525 if (I->getType()->isPointerTy())
526 IncSCEV =
527 getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
528 else
529 IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
530 if (IncSCEV) {
531 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000532 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000533 continue;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000534 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000535 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
536 << "\n");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000537 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000538 }
539 }
540 }
541}
542
543// Add the remainder of the reduction-variable chain to the instruction vector
544// (the initial PHINode has already been added). If successful, the object is
545// marked as valid.
546void LoopReroll::SimpleLoopReduction::add(Loop *L) {
547 assert(!Valid && "Cannot add to an already-valid chain");
548
549 // The reduction variable must be a chain of single-use instructions
550 // (including the PHI), except for the last value (which is used by the PHI
551 // and also outside the loop).
552 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000553 if (C->user_empty())
554 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000555
556 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000557 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000558 if (C->hasOneUse()) {
559 if (!C->isBinaryOp())
560 return;
561
562 if (!(isa<PHINode>(Instructions.back()) ||
563 C->isSameOperationAs(Instructions.back())))
564 return;
565
566 Instructions.push_back(C);
567 }
568 } while (C->hasOneUse());
569
570 if (Instructions.size() < 2 ||
571 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000572 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000573 return;
574
575 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000576 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000577 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000578 if (L->contains(cast<Instruction>(U)))
579 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000580 return;
James Molloy64419d42015-01-29 21:52:03 +0000581 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000582
583 Instructions.push_back(C);
584 Valid = true;
585}
586
587// Collect the vector of possible reduction variables.
588void LoopReroll::collectPossibleReductions(Loop *L,
589 ReductionTracker &Reductions) {
590 BasicBlock *Header = L->getHeader();
591 for (BasicBlock::iterator I = Header->begin(),
592 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
593 if (!isa<PHINode>(I))
594 continue;
595 if (!I->getType()->isSingleValueType())
596 continue;
597
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000598 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000599 if (!SLR.valid())
600 continue;
601
602 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
603 SLR.size() << " chained instructions)\n");
604 Reductions.addSLR(SLR);
605 }
606}
607
608// Collect the set of all users of the provided root instruction. This set of
609// users contains not only the direct users of the root instruction, but also
610// all users of those users, and so on. There are two exceptions:
611//
612// 1. Instructions in the set of excluded instructions are never added to the
613// use set (even if they are users). This is used, for example, to exclude
614// including root increments in the use set of the primary IV.
615//
616// 2. Instructions in the set of final instructions are added to the use set
617// if they are users, but their users are not added. This is used, for
618// example, to prevent a reduction update from forcing all later reduction
619// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000620void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000621 Instruction *Root, const SmallInstructionSet &Exclude,
622 const SmallInstructionSet &Final,
623 DenseSet<Instruction *> &Users) {
624 SmallInstructionVector Queue(1, Root);
625 while (!Queue.empty()) {
626 Instruction *I = Queue.pop_back_val();
627 if (!Users.insert(I).second)
628 continue;
629
630 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000631 for (Use &U : I->uses()) {
632 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000633 if (PHINode *PN = dyn_cast<PHINode>(User)) {
634 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000635 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000636 continue;
637 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000638
Hal Finkelbf45efd2013-11-16 23:59:05 +0000639 if (L->contains(User) && !Exclude.count(User)) {
640 Queue.push_back(User);
641 }
642 }
643
644 // We also want to collect single-user "feeder" values.
645 for (User::op_iterator OI = I->op_begin(),
646 OIE = I->op_end(); OI != OIE; ++OI) {
647 if (Instruction *Op = dyn_cast<Instruction>(*OI))
648 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
649 !Final.count(Op))
650 Queue.push_back(Op);
651 }
652 }
653}
654
655// Collect all of the users of all of the provided root instructions (combined
656// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000657void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000658 const SmallInstructionVector &Roots,
659 const SmallInstructionSet &Exclude,
660 const SmallInstructionSet &Final,
661 DenseSet<Instruction *> &Users) {
662 for (SmallInstructionVector::const_iterator I = Roots.begin(),
663 IE = Roots.end(); I != IE; ++I)
James Molloy5f255eb2015-01-29 13:48:05 +0000664 collectInLoopUserSet(*I, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000665}
666
667static bool isSimpleLoadStore(Instruction *I) {
668 if (LoadInst *LI = dyn_cast<LoadInst>(I))
669 return LI->isSimple();
670 if (StoreInst *SI = dyn_cast<StoreInst>(I))
671 return SI->isSimple();
672 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
673 return !MI->isVolatile();
674 return false;
675}
676
James Molloyf1473592015-02-11 09:19:47 +0000677/// Return true if IVU is a "simple" arithmetic operation.
678/// This is used for narrowing the search space for DAGRoots; only arithmetic
679/// and GEPs can be part of a DAGRoot.
680static bool isSimpleArithmeticOp(User *IVU) {
681 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
682 switch (I->getOpcode()) {
683 default: return false;
684 case Instruction::Add:
685 case Instruction::Sub:
686 case Instruction::Mul:
687 case Instruction::Shl:
688 case Instruction::AShr:
689 case Instruction::LShr:
690 case Instruction::GetElementPtr:
691 case Instruction::Trunc:
692 case Instruction::ZExt:
693 case Instruction::SExt:
694 return true;
695 }
696 }
697 return false;
698}
699
700static bool isLoopIncrement(User *U, Instruction *IV) {
701 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hu84b61952016-01-25 18:53:39 +0000702
703 if ((BO && BO->getOpcode() != Instruction::Add) ||
704 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000705 return false;
706
Lawrence Hu84b61952016-01-25 18:53:39 +0000707 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000708 PHINode *PN = dyn_cast<PHINode>(UU);
709 if (PN && PN == IV)
710 return true;
711 }
712 return false;
713}
714
715bool LoopReroll::DAGRootTracker::
716collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
717 SmallInstructionVector BaseUsers;
718
719 for (auto *I : Base->users()) {
720 ConstantInt *CI = nullptr;
721
722 if (isLoopIncrement(I, IV)) {
723 LoopIncs.push_back(cast<Instruction>(I));
724 continue;
725 }
726
727 // The root nodes must be either GEPs, ORs or ADDs.
728 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
729 if (BO->getOpcode() == Instruction::Add ||
730 BO->getOpcode() == Instruction::Or)
731 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
732 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
733 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
734 CI = dyn_cast<ConstantInt>(LastOperand);
735 }
736
737 if (!CI) {
738 if (Instruction *II = dyn_cast<Instruction>(I)) {
739 BaseUsers.push_back(II);
740 continue;
741 } else {
742 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
743 return false;
744 }
745 }
746
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000747 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000748 if (Roots.find(V) != Roots.end())
749 // No duplicates, please.
750 return false;
751
James Molloyf1473592015-02-11 09:19:47 +0000752 Roots[V] = cast<Instruction>(I);
753 }
754
755 if (Roots.empty())
756 return false;
James Molloyf1473592015-02-11 09:19:47 +0000757
758 // If we found non-loop-inc, non-root users of Base, assume they are
759 // for the zeroth root index. This is because "add %a, 0" gets optimized
760 // away.
James Molloye32d8062015-02-16 17:02:00 +0000761 if (BaseUsers.size()) {
762 if (Roots.find(0) != Roots.end()) {
763 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
764 return false;
765 }
James Molloyf1473592015-02-11 09:19:47 +0000766 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000767 }
James Molloyf1473592015-02-11 09:19:47 +0000768
769 // Calculate the number of users of the base, or lowest indexed, iteration.
770 unsigned NumBaseUses = BaseUsers.size();
771 if (NumBaseUses == 0)
772 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000773
James Molloyf1473592015-02-11 09:19:47 +0000774 // Check that every node has the same number of users.
775 for (auto &KV : Roots) {
776 if (KV.first == 0)
777 continue;
778 if (KV.second->getNumUses() != NumBaseUses) {
779 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
780 << "#Base=" << NumBaseUses << ", #Root=" <<
781 KV.second->getNumUses() << "\n");
782 return false;
783 }
784 }
785
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000786 return true;
James Molloyf1473592015-02-11 09:19:47 +0000787}
788
789bool LoopReroll::DAGRootTracker::
790findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
791 // Does the user look like it could be part of a root set?
792 // All its users must be simple arithmetic ops.
793 if (I->getNumUses() > IL_MaxRerollIterations)
794 return false;
795
796 if ((I->getOpcode() == Instruction::Mul ||
797 I->getOpcode() == Instruction::PHI) &&
798 I != IV &&
799 findRootsBase(I, SubsumedInsts))
800 return true;
801
802 SubsumedInsts.insert(I);
803
804 for (User *V : I->users()) {
805 Instruction *I = dyn_cast<Instruction>(V);
806 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
807 continue;
808
809 if (!I || !isSimpleArithmeticOp(I) ||
810 !findRootsRecursive(I, SubsumedInsts))
811 return false;
812 }
813 return true;
814}
815
816bool LoopReroll::DAGRootTracker::
817findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
818
819 // The base instruction needs to be a multiply so
820 // that we can erase it.
821 if (IVU->getOpcode() != Instruction::Mul &&
822 IVU->getOpcode() != Instruction::PHI)
823 return false;
824
825 std::map<int64_t, Instruction*> V;
826 if (!collectPossibleRoots(IVU, V))
827 return false;
828
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000829 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000830 // subsumed.
831 if (V.find(0) == V.end())
832 SubsumedInsts.insert(IVU);
833
834 // Partition the vector into monotonically increasing indexes.
835 DAGRootSet DRS;
836 DRS.BaseInst = nullptr;
837
838 for (auto &KV : V) {
839 if (!DRS.BaseInst) {
840 DRS.BaseInst = KV.second;
841 DRS.SubsumedInsts = SubsumedInsts;
842 } else if (DRS.Roots.empty()) {
843 DRS.Roots.push_back(KV.second);
844 } else if (V.find(KV.first - 1) != V.end()) {
845 DRS.Roots.push_back(KV.second);
846 } else {
847 // Linear sequence terminated.
848 RootSets.push_back(DRS);
849 DRS.BaseInst = KV.second;
850 DRS.SubsumedInsts = SubsumedInsts;
851 DRS.Roots.clear();
852 }
853 }
854 RootSets.push_back(DRS);
855
856 return true;
857}
858
James Molloy5f255eb2015-01-29 13:48:05 +0000859bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000860 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +0000861
James Molloyf1473592015-02-11 09:19:47 +0000862 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000863 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +0000864 for (auto *IVU : IV->users()) {
865 if (isLoopIncrement(IVU, IV))
866 LoopIncs.push_back(cast<Instruction>(IVU));
867 }
868 if (!findRootsRecursive(IV, SmallInstructionSet()))
869 return false;
870 LoopIncs.push_back(IV);
871 } else {
872 if (!findRootsBase(IV, SmallInstructionSet()))
873 return false;
874 }
James Molloy5f255eb2015-01-29 13:48:05 +0000875
James Molloyf1473592015-02-11 09:19:47 +0000876 // Ensure all sets have the same size.
877 if (RootSets.empty()) {
878 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000879 return false;
James Molloyf1473592015-02-11 09:19:47 +0000880 }
881 for (auto &V : RootSets) {
882 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
883 DEBUG(dbgs()
884 << "LRR: Aborting because not all root sets have the same size\n");
885 return false;
886 }
887 }
James Molloy5f255eb2015-01-29 13:48:05 +0000888
James Molloyf1473592015-02-11 09:19:47 +0000889 // And ensure all loop iterations are consecutive. We rely on std::map
890 // providing ordered traversal.
891 for (auto &V : RootSets) {
892 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
893 if (!ADR)
894 return false;
895
896 // Consider a DAGRootSet with N-1 roots (so N different values including
897 // BaseInst).
898 // Define d = Roots[0] - BaseInst, which should be the same as
899 // Roots[I] - Roots[I-1] for all I in [1..N).
900 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
901 // loop iteration J.
902 //
903 // Now, For the loop iterations to be consecutive:
904 // D = d * N
905
906 unsigned N = V.Roots.size() + 1;
907 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
908 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
909 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
910 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
911 return false;
912 }
913 }
914 Scale = RootSets[0].Roots.size() + 1;
915
916 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +0000917 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +0000918 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +0000919 << "\n");
920 return false;
921 }
922
James Molloyf1473592015-02-11 09:19:47 +0000923 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000924
925 return true;
926}
927
James Molloy64419d42015-01-29 21:52:03 +0000928bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
929 // Populate the MapVector with all instructions in the block, in order first,
930 // so we can iterate over the contents later in perfect order.
931 for (auto &I : *L->getHeader()) {
932 Uses[&I].resize(IL_End);
933 }
James Molloy5f255eb2015-01-29 13:48:05 +0000934
James Molloy64419d42015-01-29 21:52:03 +0000935 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +0000936 for (auto &DRS : RootSets) {
937 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
938 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
939 Exclude.insert(DRS.BaseInst);
940 }
James Molloy64419d42015-01-29 21:52:03 +0000941 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
942
James Molloyf1473592015-02-11 09:19:47 +0000943 for (auto &DRS : RootSets) {
944 DenseSet<Instruction*> VBase;
945 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
946 for (auto *I : VBase) {
947 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +0000948 }
949
James Molloyf1473592015-02-11 09:19:47 +0000950 unsigned Idx = 1;
951 for (auto *Root : DRS.Roots) {
952 DenseSet<Instruction*> V;
953 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
954
955 // While we're here, check the use sets are the same size.
956 if (V.size() != VBase.size()) {
957 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
958 return false;
959 }
960
961 for (auto *I : V) {
962 Uses[I].set(Idx);
963 }
964 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +0000965 }
James Molloyf1473592015-02-11 09:19:47 +0000966
967 // Make sure our subsumed instructions are remembered too.
968 for (auto *I : DRS.SubsumedInsts) {
969 Uses[I].set(IL_All);
970 }
James Molloy64419d42015-01-29 21:52:03 +0000971 }
972
973 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +0000974
James Molloy64419d42015-01-29 21:52:03 +0000975 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +0000976 for (auto &DRS : RootSets) {
977 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
978 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
979 Exclude.insert(DRS.BaseInst);
980 }
James Molloy64419d42015-01-29 21:52:03 +0000981
982 DenseSet<Instruction*> V;
983 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
984 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +0000985 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +0000986 }
James Molloy64419d42015-01-29 21:52:03 +0000987
988 return true;
989
990}
991
James Molloye805ad92015-02-12 15:54:14 +0000992/// Get the next instruction in "In" that is a member of set Val.
993/// Start searching from StartI, and do not return anything in Exclude.
994/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +0000995LoopReroll::DAGRootTracker::UsesTy::iterator
996LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +0000997 const SmallInstructionSet &Exclude,
998 UsesTy::iterator *StartI) {
999 UsesTy::iterator I = StartI ? *StartI : In.begin();
1000 while (I != In.end() && (I->second.test(Val) == 0 ||
1001 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +00001002 ++I;
1003 return I;
1004}
1005
James Molloyf1473592015-02-11 09:19:47 +00001006bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1007 for (auto &DRS : RootSets) {
1008 if (DRS.BaseInst == I)
1009 return true;
1010 }
1011 return false;
1012}
1013
1014bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1015 for (auto &DRS : RootSets) {
1016 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
1017 return true;
1018 }
1019 return false;
1020}
1021
James Molloye805ad92015-02-12 15:54:14 +00001022/// Return true if instruction I depends on any instruction between
1023/// Start and End.
1024bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1025 UsesTy::iterator Start,
1026 UsesTy::iterator End) {
1027 for (auto *U : I->users()) {
1028 for (auto It = Start; It != End; ++It)
1029 if (U == It->first)
1030 return true;
1031 }
1032 return false;
1033}
1034
Weiming Zhao310770a2015-09-28 17:03:23 +00001035static bool isIgnorableInst(const Instruction *I) {
1036 if (isa<DbgInfoIntrinsic>(I))
1037 return true;
1038 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1039 if (!II)
1040 return false;
1041 switch (II->getIntrinsicID()) {
1042 default:
1043 return false;
1044 case llvm::Intrinsic::annotation:
1045 case Intrinsic::ptr_annotation:
1046 case Intrinsic::var_annotation:
1047 // TODO: the following intrinsics may also be whitelisted:
1048 // lifetime_start, lifetime_end, invariant_start, invariant_end
1049 return true;
1050 }
1051 return false;
1052}
1053
James Molloy64419d42015-01-29 21:52:03 +00001054bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001055 // We now need to check for equivalence of the use graph of each root with
1056 // that of the primary induction variable (excluding the roots). Our goal
1057 // here is not to solve the full graph isomorphism problem, but rather to
1058 // catch common cases without a lot of work. As a result, we will assume
1059 // that the relative order of the instructions in each unrolled iteration
1060 // is the same (although we will not make an assumption about how the
1061 // different iterations are intermixed). Note that while the order must be
1062 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001063
1064 // An array of just the possible reductions for this scale factor. When we
1065 // collect the set of all users of some root instructions, these reduction
1066 // instructions are treated as 'final' (their uses are not considered).
1067 // This is important because we don't want the root use set to search down
1068 // the reduction chain.
1069 SmallInstructionSet PossibleRedSet;
1070 SmallInstructionSet PossibleRedLastSet;
1071 SmallInstructionSet PossibleRedPHISet;
1072 Reductions.restrictToScale(Scale, PossibleRedSet,
1073 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001074
James Molloy64419d42015-01-29 21:52:03 +00001075 // Populate "Uses" with where each instruction is used.
1076 if (!collectUsedInstructions(PossibleRedSet))
1077 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001078
James Molloy64419d42015-01-29 21:52:03 +00001079 // Make sure we mark the reduction PHIs as used in all iterations.
1080 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001081 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001082 }
James Molloy5f255eb2015-01-29 13:48:05 +00001083
James Molloy64419d42015-01-29 21:52:03 +00001084 // Make sure all instructions in the loop are in one and only one
1085 // set.
1086 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001087 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
James Molloy64419d42015-01-29 21:52:03 +00001088 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1089 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1090 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001091 }
James Molloy64419d42015-01-29 21:52:03 +00001092 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001093
James Molloy64419d42015-01-29 21:52:03 +00001094 DEBUG(
1095 for (auto &KV : Uses) {
1096 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1097 }
1098 );
1099
1100 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001101 // In addition to regular aliasing information, we need to look for
1102 // instructions from later (future) iterations that have side effects
1103 // preventing us from reordering them past other instructions with side
1104 // effects.
1105 bool FutureSideEffects = false;
1106 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001107 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1108 DenseMap<Value *, Value *> BaseMap;
1109
James Molloy64419d42015-01-29 21:52:03 +00001110 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001111 SmallInstructionSet Visited;
1112 auto BaseIt = nextInstr(0, Uses, Visited);
1113 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001114 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001115
James Molloy64419d42015-01-29 21:52:03 +00001116 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1117 Instruction *BaseInst = BaseIt->first;
1118 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001119
James Molloy64419d42015-01-29 21:52:03 +00001120 // Skip over the IV or root instructions; only match their users.
1121 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001122 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001123 Visited.insert(BaseInst);
1124 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001125 Continue = true;
1126 }
James Molloyf1473592015-02-11 09:19:47 +00001127 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001128 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001129 Visited.insert(RootInst);
1130 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001131 Continue = true;
1132 }
1133 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001134
James Molloye805ad92015-02-12 15:54:14 +00001135 if (!BaseInst->isSameOperationAs(RootInst)) {
1136 // Last chance saloon. We don't try and solve the full isomorphism
1137 // problem, but try and at least catch the case where two instructions
1138 // *of different types* are round the wrong way. We won't be able to
1139 // efficiently tell, given two ADD instructions, which way around we
1140 // should match them, but given an ADD and a SUB, we can at least infer
1141 // which one is which.
1142 //
1143 // This should allow us to deal with a greater subset of the isomorphism
1144 // problem. It does however change a linear algorithm into a quadratic
1145 // one, so limit the number of probes we do.
1146 auto TryIt = RootIt;
1147 unsigned N = NumToleratedFailedMatches;
1148 while (TryIt != Uses.end() &&
1149 !BaseInst->isSameOperationAs(TryIt->first) &&
1150 N--) {
1151 ++TryIt;
1152 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1153 }
1154
1155 if (TryIt == Uses.end() || TryIt == RootIt ||
1156 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1157 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1158 " vs. " << *RootInst << "\n");
1159 return false;
1160 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001161
James Molloye805ad92015-02-12 15:54:14 +00001162 RootIt = TryIt;
1163 RootInst = TryIt->first;
1164 }
1165
James Molloy64419d42015-01-29 21:52:03 +00001166 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001167 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001168 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001169 //
James Molloye805ad92015-02-12 15:54:14 +00001170 // Note that because we allow a limited amount of flexibility in the order
1171 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1172 // case we've already checked this set of instructions so we shouldn't
1173 // do anything.
1174 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001175 Instruction *I = LastRootIt->first;
1176 if (LastRootIt->second.find_first() < (int)Iter)
1177 continue;
1178 if (I->mayWriteToMemory())
1179 AST.add(I);
1180 // Note: This is specifically guarded by a check on isa<PHINode>,
1181 // which while a valid (somewhat arbitrary) micro-optimization, is
1182 // needed because otherwise isSafeToSpeculativelyExecute returns
1183 // false on PHI nodes.
1184 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001185 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001186 // Intervening instructions cause side effects.
1187 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001188 }
1189
James Molloy5f255eb2015-01-29 13:48:05 +00001190 // Make sure that this instruction, which is in the use set of this
1191 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001192 // some other root instruction.
1193 if (RootIt->second.count() > 1) {
1194 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1195 " vs. " << *RootInst << " (prev. case overlap)\n");
1196 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001197 }
1198
1199 // Make sure that we don't alias with any instruction in the alias set
1200 // tracker. If we do, then we depend on a future iteration, and we
1201 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001202 if (RootInst->mayReadFromMemory())
1203 for (auto &K : AST) {
1204 if (K.aliasesUnknownInst(RootInst, *AA)) {
1205 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1206 " vs. " << *RootInst << " (depends on future store)\n");
1207 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001208 }
1209 }
James Molloy5f255eb2015-01-29 13:48:05 +00001210
1211 // If we've past an instruction from a future iteration that may have
1212 // side effects, and this instruction might also, then we can't reorder
1213 // them, and this matching fails. As an exception, we allow the alias
1214 // set tracker to handle regular (simple) load/store dependencies.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001215 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1216 !isSafeToSpeculativelyExecute(BaseInst)) ||
1217 (!isSimpleLoadStore(RootInst) &&
1218 !isSafeToSpeculativelyExecute(RootInst)))) {
James Molloy64419d42015-01-29 21:52:03 +00001219 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1220 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001221 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001222 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001223 }
1224
1225 // For instructions that are part of a reduction, if the operation is
1226 // associative, then don't bother matching the operands (because we
1227 // already know that the instructions are isomorphic, and the order
1228 // within the iteration does not matter). For non-associative reductions,
1229 // we do need to match the operands, because we need to reject
1230 // out-of-order instructions within an iteration!
1231 // For example (assume floating-point addition), we need to reject this:
1232 // x += a[i]; x += b[i];
1233 // x += a[i+1]; x += b[i+1];
1234 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001235 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001236
James Molloy64419d42015-01-29 21:52:03 +00001237 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001238 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001239 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1240 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001241
1242 // If this is part of a reduction (and the operation is not
1243 // associatve), then we match all operands, but not those that are
1244 // part of the reduction.
1245 if (InReduction)
1246 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001247 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001248 continue;
1249
1250 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001251 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001252 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001253 } else {
1254 for (auto &DRS : RootSets) {
1255 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1256 Op2 = DRS.BaseInst;
1257 break;
1258 }
1259 }
1260 }
James Molloy5f255eb2015-01-29 13:48:05 +00001261
James Molloy64419d42015-01-29 21:52:03 +00001262 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001263 // If we've not already decided to swap the matched operands, and
1264 // we've not already matched our first operand (note that we could
1265 // have skipped matching the first operand because it is part of a
1266 // reduction above), and the instruction is commutative, then try
1267 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001268 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1269 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001270 Swapped = true;
1271 } else {
James Molloy64419d42015-01-29 21:52:03 +00001272 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1273 << " vs. " << *RootInst << " (operand " << j << ")\n");
1274 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001275 }
1276 }
1277
1278 SomeOpMatched = true;
1279 }
1280 }
1281
James Molloy64419d42015-01-29 21:52:03 +00001282 if ((!PossibleRedLastSet.count(BaseInst) &&
1283 hasUsesOutsideLoop(BaseInst, L)) ||
1284 (!PossibleRedLastSet.count(RootInst) &&
1285 hasUsesOutsideLoop(RootInst, L))) {
1286 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1287 " vs. " << *RootInst << " (uses outside loop)\n");
1288 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001289 }
1290
James Molloy64419d42015-01-29 21:52:03 +00001291 Reductions.recordPair(BaseInst, RootInst, Iter);
1292 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001293
James Molloy64419d42015-01-29 21:52:03 +00001294 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001295 Visited.insert(BaseInst);
1296 Visited.insert(RootInst);
1297 BaseIt = nextInstr(0, Uses, Visited);
1298 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001299 }
James Molloy64419d42015-01-29 21:52:03 +00001300 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1301 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001302 }
1303
James Molloy5f255eb2015-01-29 13:48:05 +00001304 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001305 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001306
Hal Finkelbf45efd2013-11-16 23:59:05 +00001307 return true;
1308}
1309
James Molloy5f255eb2015-01-29 13:48:05 +00001310void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1311 BasicBlock *Header = L->getHeader();
1312 // Remove instructions associated with non-base iterations.
1313 for (BasicBlock::reverse_iterator J = Header->rbegin();
1314 J != Header->rend();) {
James Molloy64419d42015-01-29 21:52:03 +00001315 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001316 if (I > 0 && I < IL_All) {
James Molloy5f255eb2015-01-29 13:48:05 +00001317 Instruction *D = &*J;
1318 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1319 D->eraseFromParent();
1320 continue;
1321 }
1322
1323 ++J;
1324 }
1325
James Molloyf1473592015-02-11 09:19:47 +00001326 // We need to create a new induction variable for each different BaseInst.
Lawrence Hu84b61952016-01-25 18:53:39 +00001327 for (auto &DRS : RootSets)
James Molloyf1473592015-02-11 09:19:47 +00001328 // Insert the new induction variable.
Lawrence Hu84b61952016-01-25 18:53:39 +00001329 replaceIV(DRS.BaseInst, IV, IterCount);
James Molloy5f255eb2015-01-29 13:48:05 +00001330
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001331 SimplifyInstructionsInBlock(Header, TLI);
James Molloy5f255eb2015-01-29 13:48:05 +00001332 DeleteDeadPHIs(Header, TLI);
1333}
1334
Lawrence Hu84b61952016-01-25 18:53:39 +00001335void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1336 Instruction *InstIV,
1337 const SCEV *IterCount) {
1338 BasicBlock *Header = L->getHeader();
1339 int64_t Inc = IVToIncMap[InstIV];
1340 bool Negative = Inc < 0;
1341
1342 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1343 const SCEV *Start = RealIVSCEV->getStart();
1344
1345 const SCEV *SizeOfExpr = nullptr;
1346 const SCEV *IncrExpr =
1347 SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1348 if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1349 Type *ElTy = PTy->getElementType();
1350 SizeOfExpr =
1351 SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1352 IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1353 }
1354 const SCEV *NewIVSCEV =
1355 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1356
1357 { // Limit the lifetime of SCEVExpander.
1358 const DataLayout &DL = Header->getModule()->getDataLayout();
1359 SCEVExpander Expander(*SE, DL, "reroll");
1360 Value *NewIV =
1361 Expander.expandCodeFor(NewIVSCEV, InstIV->getType(), &Header->front());
1362
1363 for (auto &KV : Uses)
1364 if (KV.second.find_first() == 0)
1365 KV.first->replaceUsesOfWith(Inst, NewIV);
1366
1367 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1368 // FIXME: Why do we need this check?
1369 if (Uses[BI].find_first() == IL_All) {
1370 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1371
1372 // Iteration count SCEV minus or plus 1
1373 const SCEV *MinusPlus1SCEV =
1374 SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1375 if (Inst->getType()->isPointerTy()) {
1376 assert(SizeOfExpr && "SizeOfExpr is not initialized");
1377 MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1378 }
1379
1380 const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1381 // Iteration count minus 1
1382 Value *ICMinusPlus1 = nullptr;
1383 if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
1384 ICMinusPlus1 =
1385 Expander.expandCodeFor(ICMinusPlus1SCEV, NewIV->getType(), BI);
1386 } else {
1387 BasicBlock *Preheader = L->getLoopPreheader();
1388 if (!Preheader)
1389 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
1390 ICMinusPlus1 = Expander.expandCodeFor(
1391 ICMinusPlus1SCEV, NewIV->getType(), Preheader->getTerminator());
1392 }
1393
1394 Value *Cond =
1395 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1396 BI->setCondition(Cond);
1397
1398 if (BI->getSuccessor(1) != Header)
1399 BI->swapSuccessors();
1400 }
1401 }
1402 }
1403}
1404
Hal Finkelbf45efd2013-11-16 23:59:05 +00001405// Validate the selected reductions. All iterations must have an isomorphic
1406// part of the reduction chain and, for non-associative reductions, the chain
1407// entries must appear in order.
1408bool LoopReroll::ReductionTracker::validateSelected() {
1409 // For a non-associative reduction, the chain entries must appear in order.
1410 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1411 RI != RIE; ++RI) {
1412 int i = *RI;
1413 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001414 for (Instruction *J : PossibleReds[i]) {
1415 // Note that all instructions in the chain must have been found because
1416 // all instructions in the function must have been assigned to some
1417 // iteration.
1418 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001419 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1420 !PossibleReds[i].getReducedValue()->isAssociative()) {
1421 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001422 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001423 return false;
1424 }
1425
1426 if (Iter != PrevIter) {
1427 if (Count != BaseCount) {
1428 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1429 " reduction use count " << Count <<
1430 " is not equal to the base use count " <<
1431 BaseCount << "\n");
1432 return false;
1433 }
1434
1435 Count = 0;
1436 }
1437
1438 ++Count;
1439 if (Iter == 0)
1440 ++BaseCount;
1441
1442 PrevIter = Iter;
1443 }
1444 }
1445
1446 return true;
1447}
1448
1449// For all selected reductions, remove all parts except those in the first
1450// iteration (and the PHI). Replace outside uses of the reduced value with uses
1451// of the first-iteration reduced value (in other words, reroll the selected
1452// reductions).
1453void LoopReroll::ReductionTracker::replaceSelected() {
1454 // Fixup reductions to refer to the last instruction associated with the
1455 // first iteration (not the last).
1456 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1457 RI != RIE; ++RI) {
1458 int i = *RI;
1459 int j = 0;
1460 for (int e = PossibleReds[i].size(); j != e; ++j)
1461 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1462 --j;
1463 break;
1464 }
1465
1466 // Replace users with the new end-of-chain value.
1467 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001468 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001469 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001470 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001471
1472 for (SmallInstructionVector::iterator J = Users.begin(),
1473 JE = Users.end(); J != JE; ++J)
1474 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1475 PossibleReds[i][j]);
1476 }
1477}
1478
1479// Reroll the provided loop with respect to the provided induction variable.
1480// Generally, we're looking for a loop like this:
1481//
1482// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1483// f(%iv)
1484// %iv.1 = add %iv, 1 <-- a root increment
1485// f(%iv.1)
1486// %iv.2 = add %iv, 2 <-- a root increment
1487// f(%iv.2)
1488// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1489// f(%iv.scale_m_1)
1490// ...
1491// %iv.next = add %iv, scale
1492// %cmp = icmp(%iv, ...)
1493// br %cmp, header, exit
1494//
1495// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1496// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1497// be intermixed with eachother. The restriction imposed by this algorithm is
1498// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1499// etc. be the same.
1500//
1501// First, we collect the use set of %iv, excluding the other increment roots.
1502// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1503// times, having collected the use set of f(%iv.(i+1)), during which we:
1504// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1505// the next unmatched instruction in f(%iv.(i+1)).
1506// - Ensure that both matched instructions don't have any external users
1507// (with the exception of last-in-chain reduction instructions).
1508// - Track the (aliasing) write set, and other side effects, of all
1509// instructions that belong to future iterations that come before the matched
1510// instructions. If the matched instructions read from that write set, then
1511// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1512// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1513// if any of these future instructions had side effects (could not be
1514// speculatively executed), and so do the matched instructions, when we
1515// cannot reorder those side-effect-producing instructions, and rerolling
1516// fails.
1517//
1518// Finally, we make sure that all loop instructions are either loop increment
1519// roots, belong to simple latch code, parts of validated reductions, part of
1520// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1521// have been validated), then we reroll the loop.
1522bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1523 const SCEV *IterCount,
1524 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001525 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
1526 IVToIncMap);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001527
James Molloy5f255eb2015-01-29 13:48:05 +00001528 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001529 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001530 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001531 *IV << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001532
James Molloy5f255eb2015-01-29 13:48:05 +00001533 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001534 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001535 if (!Reductions.validateSelected())
1536 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001537 // At this point, we've validated the rerolling, and we're committed to
1538 // making changes!
1539
1540 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001541 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001542
Hal Finkelbf45efd2013-11-16 23:59:05 +00001543 ++NumRerolledLoops;
1544 return true;
1545}
1546
1547bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001548 if (skipOptnoneFunction(L))
1549 return false;
1550
Chandler Carruth7b560d42015-09-09 17:55:00 +00001551 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001552 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001553 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001554 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001555 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001556 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001557
1558 BasicBlock *Header = L->getHeader();
1559 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1560 "] Loop %" << Header->getName() << " (" <<
1561 L->getNumBlocks() << " block(s))\n");
1562
1563 bool Changed = false;
1564
1565 // For now, we'll handle only single BB loops.
1566 if (L->getNumBlocks() > 1)
1567 return Changed;
1568
1569 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1570 return Changed;
1571
1572 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001573 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Hal Finkelbf45efd2013-11-16 23:59:05 +00001574 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1575
1576 // First, we need to find the induction variable with respect to which we can
1577 // reroll (there may be several possible options).
1578 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001579 IVToIncMap.clear();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001580 collectPossibleIVs(L, PossibleIVs);
1581
1582 if (PossibleIVs.empty()) {
1583 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1584 return Changed;
1585 }
1586
1587 ReductionTracker Reductions;
1588 collectPossibleReductions(L, Reductions);
1589
1590 // For each possible IV, collect the associated possible set of 'root' nodes
1591 // (i+1, i+2, etc.).
1592 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1593 IE = PossibleIVs.end(); I != IE; ++I)
1594 if (reroll(*I, L, Header, IterCount, Reductions)) {
1595 Changed = true;
1596 break;
1597 }
1598
1599 return Changed;
1600}