blob: 3fb0a104c3fd8649c419c4f7ee1b67b86bdea193 [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"
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +000017#include "llvm/ADT/BitVector.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 {
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000131 /// The maximum number of iterations that we'll try and reroll.
132 IL_MaxRerollIterations = 32,
James Molloy64419d42015-01-29 21:52:03 +0000133 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000134 /// instructions that belong to all iterations.
135 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000136 IL_End
137 };
138
Hal Finkelbf45efd2013-11-16 23:59:05 +0000139 class LoopReroll : public LoopPass {
140 public:
141 static char ID; // Pass ID, replacement for typeid
142 LoopReroll() : LoopPass(ID) {
143 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
144 }
145
Craig Topper3e4c6972014-03-05 09:10:37 +0000146 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000147
Craig Topper3e4c6972014-03-05 09:10:37 +0000148 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000149 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000150 getLoopAnalysisUsage(AU);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000151 }
152
James Molloy64419d42015-01-29 21:52:03 +0000153 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000154 AliasAnalysis *AA;
155 LoopInfo *LI;
156 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000157 TargetLibraryInfo *TLI;
158 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000159 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000160
161 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
162 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
163
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000164 // Map between induction variable and its increment
165 DenseMap<Instruction *, int64_t> IVToIncMap;
166
167 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000168 // representing a reduction. Only the last value may be used outside the
169 // loop.
170 struct SimpleLoopReduction {
171 SimpleLoopReduction(Instruction *P, Loop *L)
172 : Valid(false), Instructions(1, P) {
173 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
174 add(L);
175 }
176
177 bool valid() const {
178 return Valid;
179 }
180
181 Instruction *getPHI() const {
182 assert(Valid && "Using invalid reduction");
183 return Instructions.front();
184 }
185
186 Instruction *getReducedValue() const {
187 assert(Valid && "Using invalid reduction");
188 return Instructions.back();
189 }
190
191 Instruction *get(size_t i) const {
192 assert(Valid && "Using invalid reduction");
193 return Instructions[i+1];
194 }
195
196 Instruction *operator [] (size_t i) const { return get(i); }
197
198 // The size, ignoring the initial PHI.
199 size_t size() const {
200 assert(Valid && "Using invalid reduction");
201 return Instructions.size()-1;
202 }
203
204 typedef SmallInstructionVector::iterator iterator;
205 typedef SmallInstructionVector::const_iterator const_iterator;
206
207 iterator begin() {
208 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000209 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000210 }
211
212 const_iterator begin() const {
213 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000214 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000215 }
216
217 iterator end() { return Instructions.end(); }
218 const_iterator end() const { return Instructions.end(); }
219
220 protected:
221 bool Valid;
222 SmallInstructionVector Instructions;
223
224 void add(Loop *L);
225 };
226
227 // The set of all reductions, and state tracking of possible reductions
228 // during loop instruction processing.
229 struct ReductionTracker {
230 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
231
232 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000233 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000234
235 // Setup to track possible reductions corresponding to the provided
236 // rerolling scale. Only reductions with a number of non-PHI instructions
237 // that is divisible by the scale are considered. Three instructions sets
238 // are filled in:
239 // - A set of all possible instructions in eligible reductions.
240 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000241 // - A set of all reduced values (last instructions) in eligible
242 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000243 void restrictToScale(uint64_t Scale,
244 SmallInstructionSet &PossibleRedSet,
245 SmallInstructionSet &PossibleRedPHISet,
246 SmallInstructionSet &PossibleRedLastSet) {
247 PossibleRedIdx.clear();
248 PossibleRedIter.clear();
249 Reds.clear();
250
251 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
252 if (PossibleReds[i].size() % Scale == 0) {
253 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
254 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000255
Hal Finkelbf45efd2013-11-16 23:59:05 +0000256 PossibleRedSet.insert(PossibleReds[i].getPHI());
257 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000258 for (Instruction *J : PossibleReds[i]) {
259 PossibleRedSet.insert(J);
260 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000261 }
262 }
263 }
264
265 // The functions below are used while processing the loop instructions.
266
267 // Are the two instructions both from reductions, and furthermore, from
268 // the same reduction?
269 bool isPairInSame(Instruction *J1, Instruction *J2) {
270 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
271 if (J1I != PossibleRedIdx.end()) {
272 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
273 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
274 return true;
275 }
276
277 return false;
278 }
279
280 // The two provided instructions, the first from the base iteration, and
281 // the second from iteration i, form a matched pair. If these are part of
282 // a reduction, record that fact.
283 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
284 if (PossibleRedIdx.count(J1)) {
285 assert(PossibleRedIdx.count(J2) &&
286 "Recording reduction vs. non-reduction instruction?");
287
288 PossibleRedIter[J1] = 0;
289 PossibleRedIter[J2] = i;
290
291 int Idx = PossibleRedIdx[J1];
292 assert(Idx == PossibleRedIdx[J2] &&
293 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000294 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000295 }
296 }
297
298 // The functions below can be called after we've finished processing all
299 // instructions in the loop, and we know which reductions were selected.
300
Hal Finkelbf45efd2013-11-16 23:59:05 +0000301 bool validateSelected();
302 void replaceSelected();
303
304 protected:
305 // The vector of all possible reductions (for any scale).
306 SmallReductionVector PossibleReds;
307
308 DenseMap<Instruction *, int> PossibleRedIdx;
309 DenseMap<Instruction *, int> PossibleRedIter;
310 DenseSet<int> Reds;
311 };
312
James Molloyf1473592015-02-11 09:19:47 +0000313 // A DAGRootSet models an induction variable being used in a rerollable
314 // loop. For example,
315 //
316 // x[i*3+0] = y1
317 // x[i*3+1] = y2
318 // x[i*3+2] = y3
319 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000320 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000321 // +---+----+
322 // / | \
323 // ST[y1] +1 +2 <-- Roots
324 // | |
325 // ST[y2] ST[y3]
326 //
327 // There may be multiple DAGRoots, for example:
328 //
329 // x[i*2+0] = ... (1)
330 // x[i*2+1] = ... (1)
331 // x[i*2+4] = ... (2)
332 // x[i*2+5] = ... (2)
333 // x[(i+1234)*2+5678] = ... (3)
334 // x[(i+1234)*2+5679] = ... (3)
335 //
336 // The loop will be rerolled by adding a new loop induction variable,
337 // one for the Base instruction in each DAGRootSet.
338 //
339 struct DAGRootSet {
340 Instruction *BaseInst;
341 SmallInstructionVector Roots;
342 // The instructions between IV and BaseInst (but not including BaseInst).
343 SmallInstructionSet SubsumedInsts;
344 };
345
James Molloy5f255eb2015-01-29 13:48:05 +0000346 // The set of all DAG roots, and state tracking of all roots
347 // for a particular induction variable.
348 struct DAGRootTracker {
349 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
350 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000351 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
352 bool PreserveLCSSA,
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000353 DenseMap<Instruction *, int64_t> &IncrMap)
Justin Bogner843fb202015-12-15 19:40:57 +0000354 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
355 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000356
357 /// Stage 1: Find all the DAG roots for the induction variable.
358 bool findRoots();
359 /// Stage 2: Validate if the found roots are valid.
360 bool validate(ReductionTracker &Reductions);
361 /// Stage 3: Assuming validate() returned true, perform the
362 /// replacement.
363 /// @param IterCount The maximum iteration count of L.
364 void replace(const SCEV *IterCount);
365
366 protected:
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000367 typedef MapVector<Instruction*, BitVector> UsesTy;
James Molloy64419d42015-01-29 21:52:03 +0000368
James Molloyf1473592015-02-11 09:19:47 +0000369 bool findRootsRecursive(Instruction *IVU,
370 SmallInstructionSet SubsumedInsts);
371 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
372 bool collectPossibleRoots(Instruction *Base,
373 std::map<int64_t,Instruction*> &Roots);
James Molloy5f255eb2015-01-29 13:48:05 +0000374
James Molloy64419d42015-01-29 21:52:03 +0000375 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000376 void collectInLoopUserSet(const SmallInstructionVector &Roots,
377 const SmallInstructionSet &Exclude,
378 const SmallInstructionSet &Final,
379 DenseSet<Instruction *> &Users);
380 void collectInLoopUserSet(Instruction *Root,
381 const SmallInstructionSet &Exclude,
382 const SmallInstructionSet &Final,
383 DenseSet<Instruction *> &Users);
384
James Molloye805ad92015-02-12 15:54:14 +0000385 UsesTy::iterator nextInstr(int Val, UsesTy &In,
386 const SmallInstructionSet &Exclude,
387 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000388 bool isBaseInst(Instruction *I);
389 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000390 bool instrDependsOn(Instruction *I,
391 UsesTy::iterator Start,
392 UsesTy::iterator End);
Lawrence Hud3d51062016-01-25 19:43:45 +0000393 void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
James Molloy64419d42015-01-29 21:52:03 +0000394
James Molloy5f255eb2015-01-29 13:48:05 +0000395 LoopReroll *Parent;
396
397 // Members of Parent, replicated here for brevity.
398 Loop *L;
399 ScalarEvolution *SE;
400 AliasAnalysis *AA;
401 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000402 DominatorTree *DT;
403 LoopInfo *LI;
404 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000405
406 // The loop induction variable.
407 Instruction *IV;
408 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000409 int64_t Inc;
James Molloy5f255eb2015-01-29 13:48:05 +0000410 // Loop reroll count; if Inc == 1, this records the scaling applied
411 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
412 // If Inc is not 1, Scale = Inc.
413 uint64_t Scale;
James Molloy5f255eb2015-01-29 13:48:05 +0000414 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000415 SmallVector<DAGRootSet,16> RootSets;
James Molloy5f255eb2015-01-29 13:48:05 +0000416 // All increment instructions for IV.
417 SmallInstructionVector LoopIncs;
James Molloy64419d42015-01-29 21:52:03 +0000418 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000419 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000420 // used in the loop increment mechanism).
421 UsesTy Uses;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000422 // Map between induction variable and its increment
423 DenseMap<Instruction *, int64_t> &IVToIncMap;
James Molloy5f255eb2015-01-29 13:48:05 +0000424 };
425
Hal Finkelbf45efd2013-11-16 23:59:05 +0000426 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
427 void collectPossibleReductions(Loop *L,
428 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000429 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
430 ReductionTracker &Reductions);
431 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000432}
Hal Finkelbf45efd2013-11-16 23:59:05 +0000433
434char LoopReroll::ID = 0;
435INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000436INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000437INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000438INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
439
440Pass *llvm::createLoopRerollPass() {
441 return new LoopReroll;
442}
443
444// Returns true if the provided instruction is used outside the given loop.
445// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
446// non-loop blocks to be outside the loop.
447static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000448 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000449 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000450 return true;
James Molloy64419d42015-01-29 21:52:03 +0000451 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000452 return false;
453}
454
Lawrence Hud3d51062016-01-25 19:43:45 +0000455static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
456 const SCEV *SCEVExpr,
457 Instruction &IV) {
458 const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
459
460 // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
461 // Return c1.
462 if (!MulSCEV && IV.getType()->isPointerTy())
463 if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
464 const PointerType *PTy = cast<PointerType>(IV.getType());
465 Type *ElTy = PTy->getElementType();
466 const SCEV *SizeOfExpr =
467 SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
468 if (IncSCEV->getValue()->getValue().isNegative()) {
469 const SCEV *NewSCEV =
470 SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
471 return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
472 } else {
473 return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
474 }
475 }
476
477 if (!MulSCEV)
478 return nullptr;
479
480 // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
481 // Return c.
482 const SCEVConstant *CIncSCEV = nullptr;
483 for (const SCEV *Operand : MulSCEV->operands()) {
484 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
485 CIncSCEV = Constant;
486 } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
487 Type *AllocTy;
488 if (!Unknown->isSizeOf(AllocTy))
489 break;
490 } else {
491 return nullptr;
492 }
493 }
494 return CIncSCEV;
495}
496
Hal Finkelbf45efd2013-11-16 23:59:05 +0000497// Collect the list of loop induction variables with respect to which it might
498// be possible to reroll the loop.
499void LoopReroll::collectPossibleIVs(Loop *L,
500 SmallInstructionVector &PossibleIVs) {
501 BasicBlock *Header = L->getHeader();
502 for (BasicBlock::iterator I = Header->begin(),
503 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
504 if (!isa<PHINode>(I))
505 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000506 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000507 continue;
508
509 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000510 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000511 if (PHISCEV->getLoop() != L)
512 continue;
513 if (!PHISCEV->isAffine())
514 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000515 const SCEVConstant *IncSCEV = nullptr;
516 if (I->getType()->isPointerTy())
517 IncSCEV =
518 getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
519 else
520 IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
521 if (IncSCEV) {
522 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000523 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000524 continue;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000525 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000526 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
527 << "\n");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000528 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000529 }
530 }
531 }
532}
533
534// Add the remainder of the reduction-variable chain to the instruction vector
535// (the initial PHINode has already been added). If successful, the object is
536// marked as valid.
537void LoopReroll::SimpleLoopReduction::add(Loop *L) {
538 assert(!Valid && "Cannot add to an already-valid chain");
539
540 // The reduction variable must be a chain of single-use instructions
541 // (including the PHI), except for the last value (which is used by the PHI
542 // and also outside the loop).
543 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000544 if (C->user_empty())
545 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000546
547 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000548 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000549 if (C->hasOneUse()) {
550 if (!C->isBinaryOp())
551 return;
552
553 if (!(isa<PHINode>(Instructions.back()) ||
554 C->isSameOperationAs(Instructions.back())))
555 return;
556
557 Instructions.push_back(C);
558 }
559 } while (C->hasOneUse());
560
561 if (Instructions.size() < 2 ||
562 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000563 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000564 return;
565
566 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000567 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000568 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000569 if (L->contains(cast<Instruction>(U)))
570 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000571 return;
James Molloy64419d42015-01-29 21:52:03 +0000572 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000573
574 Instructions.push_back(C);
575 Valid = true;
576}
577
578// Collect the vector of possible reduction variables.
579void LoopReroll::collectPossibleReductions(Loop *L,
580 ReductionTracker &Reductions) {
581 BasicBlock *Header = L->getHeader();
582 for (BasicBlock::iterator I = Header->begin(),
583 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
584 if (!isa<PHINode>(I))
585 continue;
586 if (!I->getType()->isSingleValueType())
587 continue;
588
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000589 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000590 if (!SLR.valid())
591 continue;
592
593 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
594 SLR.size() << " chained instructions)\n");
595 Reductions.addSLR(SLR);
596 }
597}
598
599// Collect the set of all users of the provided root instruction. This set of
600// users contains not only the direct users of the root instruction, but also
601// all users of those users, and so on. There are two exceptions:
602//
603// 1. Instructions in the set of excluded instructions are never added to the
604// use set (even if they are users). This is used, for example, to exclude
605// including root increments in the use set of the primary IV.
606//
607// 2. Instructions in the set of final instructions are added to the use set
608// if they are users, but their users are not added. This is used, for
609// example, to prevent a reduction update from forcing all later reduction
610// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000611void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000612 Instruction *Root, const SmallInstructionSet &Exclude,
613 const SmallInstructionSet &Final,
614 DenseSet<Instruction *> &Users) {
615 SmallInstructionVector Queue(1, Root);
616 while (!Queue.empty()) {
617 Instruction *I = Queue.pop_back_val();
618 if (!Users.insert(I).second)
619 continue;
620
621 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000622 for (Use &U : I->uses()) {
623 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000624 if (PHINode *PN = dyn_cast<PHINode>(User)) {
625 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000626 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000627 continue;
628 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000629
Hal Finkelbf45efd2013-11-16 23:59:05 +0000630 if (L->contains(User) && !Exclude.count(User)) {
631 Queue.push_back(User);
632 }
633 }
634
635 // We also want to collect single-user "feeder" values.
636 for (User::op_iterator OI = I->op_begin(),
637 OIE = I->op_end(); OI != OIE; ++OI) {
638 if (Instruction *Op = dyn_cast<Instruction>(*OI))
639 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
640 !Final.count(Op))
641 Queue.push_back(Op);
642 }
643 }
644}
645
646// Collect all of the users of all of the provided root instructions (combined
647// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000648void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000649 const SmallInstructionVector &Roots,
650 const SmallInstructionSet &Exclude,
651 const SmallInstructionSet &Final,
652 DenseSet<Instruction *> &Users) {
653 for (SmallInstructionVector::const_iterator I = Roots.begin(),
654 IE = Roots.end(); I != IE; ++I)
James Molloy5f255eb2015-01-29 13:48:05 +0000655 collectInLoopUserSet(*I, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000656}
657
658static bool isSimpleLoadStore(Instruction *I) {
659 if (LoadInst *LI = dyn_cast<LoadInst>(I))
660 return LI->isSimple();
661 if (StoreInst *SI = dyn_cast<StoreInst>(I))
662 return SI->isSimple();
663 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
664 return !MI->isVolatile();
665 return false;
666}
667
James Molloyf1473592015-02-11 09:19:47 +0000668/// Return true if IVU is a "simple" arithmetic operation.
669/// This is used for narrowing the search space for DAGRoots; only arithmetic
670/// and GEPs can be part of a DAGRoot.
671static bool isSimpleArithmeticOp(User *IVU) {
672 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
673 switch (I->getOpcode()) {
674 default: return false;
675 case Instruction::Add:
676 case Instruction::Sub:
677 case Instruction::Mul:
678 case Instruction::Shl:
679 case Instruction::AShr:
680 case Instruction::LShr:
681 case Instruction::GetElementPtr:
682 case Instruction::Trunc:
683 case Instruction::ZExt:
684 case Instruction::SExt:
685 return true;
686 }
687 }
688 return false;
689}
690
691static bool isLoopIncrement(User *U, Instruction *IV) {
692 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hud3d51062016-01-25 19:43:45 +0000693
694 if ((BO && BO->getOpcode() != Instruction::Add) ||
695 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000696 return false;
697
Lawrence Hud3d51062016-01-25 19:43:45 +0000698 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000699 PHINode *PN = dyn_cast<PHINode>(UU);
700 if (PN && PN == IV)
701 return true;
702 }
703 return false;
704}
705
706bool LoopReroll::DAGRootTracker::
707collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
708 SmallInstructionVector BaseUsers;
709
710 for (auto *I : Base->users()) {
711 ConstantInt *CI = nullptr;
712
713 if (isLoopIncrement(I, IV)) {
714 LoopIncs.push_back(cast<Instruction>(I));
715 continue;
716 }
717
718 // The root nodes must be either GEPs, ORs or ADDs.
719 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
720 if (BO->getOpcode() == Instruction::Add ||
721 BO->getOpcode() == Instruction::Or)
722 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
723 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
724 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
725 CI = dyn_cast<ConstantInt>(LastOperand);
726 }
727
728 if (!CI) {
729 if (Instruction *II = dyn_cast<Instruction>(I)) {
730 BaseUsers.push_back(II);
731 continue;
732 } else {
733 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
734 return false;
735 }
736 }
737
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000738 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000739 if (Roots.find(V) != Roots.end())
740 // No duplicates, please.
741 return false;
742
James Molloyf1473592015-02-11 09:19:47 +0000743 Roots[V] = cast<Instruction>(I);
744 }
745
746 if (Roots.empty())
747 return false;
James Molloyf1473592015-02-11 09:19:47 +0000748
749 // If we found non-loop-inc, non-root users of Base, assume they are
750 // for the zeroth root index. This is because "add %a, 0" gets optimized
751 // away.
James Molloye32d8062015-02-16 17:02:00 +0000752 if (BaseUsers.size()) {
753 if (Roots.find(0) != Roots.end()) {
754 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
755 return false;
756 }
James Molloyf1473592015-02-11 09:19:47 +0000757 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000758 }
James Molloyf1473592015-02-11 09:19:47 +0000759
760 // Calculate the number of users of the base, or lowest indexed, iteration.
761 unsigned NumBaseUses = BaseUsers.size();
762 if (NumBaseUses == 0)
763 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000764
James Molloyf1473592015-02-11 09:19:47 +0000765 // Check that every node has the same number of users.
766 for (auto &KV : Roots) {
767 if (KV.first == 0)
768 continue;
769 if (KV.second->getNumUses() != NumBaseUses) {
770 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
771 << "#Base=" << NumBaseUses << ", #Root=" <<
772 KV.second->getNumUses() << "\n");
773 return false;
774 }
775 }
776
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000777 return true;
James Molloyf1473592015-02-11 09:19:47 +0000778}
779
780bool LoopReroll::DAGRootTracker::
781findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
782 // Does the user look like it could be part of a root set?
783 // All its users must be simple arithmetic ops.
784 if (I->getNumUses() > IL_MaxRerollIterations)
785 return false;
786
787 if ((I->getOpcode() == Instruction::Mul ||
788 I->getOpcode() == Instruction::PHI) &&
789 I != IV &&
790 findRootsBase(I, SubsumedInsts))
791 return true;
792
793 SubsumedInsts.insert(I);
794
795 for (User *V : I->users()) {
796 Instruction *I = dyn_cast<Instruction>(V);
797 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
798 continue;
799
800 if (!I || !isSimpleArithmeticOp(I) ||
801 !findRootsRecursive(I, SubsumedInsts))
802 return false;
803 }
804 return true;
805}
806
807bool LoopReroll::DAGRootTracker::
808findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
809
810 // The base instruction needs to be a multiply so
811 // that we can erase it.
812 if (IVU->getOpcode() != Instruction::Mul &&
813 IVU->getOpcode() != Instruction::PHI)
814 return false;
815
816 std::map<int64_t, Instruction*> V;
817 if (!collectPossibleRoots(IVU, V))
818 return false;
819
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000820 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000821 // subsumed.
822 if (V.find(0) == V.end())
823 SubsumedInsts.insert(IVU);
824
825 // Partition the vector into monotonically increasing indexes.
826 DAGRootSet DRS;
827 DRS.BaseInst = nullptr;
828
829 for (auto &KV : V) {
830 if (!DRS.BaseInst) {
831 DRS.BaseInst = KV.second;
832 DRS.SubsumedInsts = SubsumedInsts;
833 } else if (DRS.Roots.empty()) {
834 DRS.Roots.push_back(KV.second);
835 } else if (V.find(KV.first - 1) != V.end()) {
836 DRS.Roots.push_back(KV.second);
837 } else {
838 // Linear sequence terminated.
839 RootSets.push_back(DRS);
840 DRS.BaseInst = KV.second;
841 DRS.SubsumedInsts = SubsumedInsts;
842 DRS.Roots.clear();
843 }
844 }
845 RootSets.push_back(DRS);
846
847 return true;
848}
849
James Molloy5f255eb2015-01-29 13:48:05 +0000850bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000851 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +0000852
James Molloyf1473592015-02-11 09:19:47 +0000853 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000854 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +0000855 for (auto *IVU : IV->users()) {
856 if (isLoopIncrement(IVU, IV))
857 LoopIncs.push_back(cast<Instruction>(IVU));
858 }
859 if (!findRootsRecursive(IV, SmallInstructionSet()))
860 return false;
861 LoopIncs.push_back(IV);
862 } else {
863 if (!findRootsBase(IV, SmallInstructionSet()))
864 return false;
865 }
James Molloy5f255eb2015-01-29 13:48:05 +0000866
James Molloyf1473592015-02-11 09:19:47 +0000867 // Ensure all sets have the same size.
868 if (RootSets.empty()) {
869 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000870 return false;
James Molloyf1473592015-02-11 09:19:47 +0000871 }
872 for (auto &V : RootSets) {
873 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
874 DEBUG(dbgs()
875 << "LRR: Aborting because not all root sets have the same size\n");
876 return false;
877 }
878 }
James Molloy5f255eb2015-01-29 13:48:05 +0000879
James Molloyf1473592015-02-11 09:19:47 +0000880 // And ensure all loop iterations are consecutive. We rely on std::map
881 // providing ordered traversal.
882 for (auto &V : RootSets) {
883 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
884 if (!ADR)
885 return false;
886
887 // Consider a DAGRootSet with N-1 roots (so N different values including
888 // BaseInst).
889 // Define d = Roots[0] - BaseInst, which should be the same as
890 // Roots[I] - Roots[I-1] for all I in [1..N).
891 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
892 // loop iteration J.
893 //
894 // Now, For the loop iterations to be consecutive:
895 // D = d * N
896
897 unsigned N = V.Roots.size() + 1;
898 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
899 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
900 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
901 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
902 return false;
903 }
904 }
905 Scale = RootSets[0].Roots.size() + 1;
906
907 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +0000908 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +0000909 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +0000910 << "\n");
911 return false;
912 }
913
James Molloyf1473592015-02-11 09:19:47 +0000914 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000915
916 return true;
917}
918
James Molloy64419d42015-01-29 21:52:03 +0000919bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
920 // Populate the MapVector with all instructions in the block, in order first,
921 // so we can iterate over the contents later in perfect order.
922 for (auto &I : *L->getHeader()) {
923 Uses[&I].resize(IL_End);
924 }
James Molloy5f255eb2015-01-29 13:48:05 +0000925
James Molloy64419d42015-01-29 21:52:03 +0000926 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +0000927 for (auto &DRS : RootSets) {
928 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
929 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
930 Exclude.insert(DRS.BaseInst);
931 }
James Molloy64419d42015-01-29 21:52:03 +0000932 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
933
James Molloyf1473592015-02-11 09:19:47 +0000934 for (auto &DRS : RootSets) {
935 DenseSet<Instruction*> VBase;
936 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
937 for (auto *I : VBase) {
938 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +0000939 }
940
James Molloyf1473592015-02-11 09:19:47 +0000941 unsigned Idx = 1;
942 for (auto *Root : DRS.Roots) {
943 DenseSet<Instruction*> V;
944 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
945
946 // While we're here, check the use sets are the same size.
947 if (V.size() != VBase.size()) {
948 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
949 return false;
950 }
951
952 for (auto *I : V) {
953 Uses[I].set(Idx);
954 }
955 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +0000956 }
James Molloyf1473592015-02-11 09:19:47 +0000957
958 // Make sure our subsumed instructions are remembered too.
959 for (auto *I : DRS.SubsumedInsts) {
960 Uses[I].set(IL_All);
961 }
James Molloy64419d42015-01-29 21:52:03 +0000962 }
963
964 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +0000965
James Molloy64419d42015-01-29 21:52:03 +0000966 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +0000967 for (auto &DRS : RootSets) {
968 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
969 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
970 Exclude.insert(DRS.BaseInst);
971 }
James Molloy64419d42015-01-29 21:52:03 +0000972
973 DenseSet<Instruction*> V;
974 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
975 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +0000976 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +0000977 }
James Molloy64419d42015-01-29 21:52:03 +0000978
979 return true;
980
981}
982
James Molloye805ad92015-02-12 15:54:14 +0000983/// Get the next instruction in "In" that is a member of set Val.
984/// Start searching from StartI, and do not return anything in Exclude.
985/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +0000986LoopReroll::DAGRootTracker::UsesTy::iterator
987LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +0000988 const SmallInstructionSet &Exclude,
989 UsesTy::iterator *StartI) {
990 UsesTy::iterator I = StartI ? *StartI : In.begin();
991 while (I != In.end() && (I->second.test(Val) == 0 ||
992 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +0000993 ++I;
994 return I;
995}
996
James Molloyf1473592015-02-11 09:19:47 +0000997bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
998 for (auto &DRS : RootSets) {
999 if (DRS.BaseInst == I)
1000 return true;
1001 }
1002 return false;
1003}
1004
1005bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1006 for (auto &DRS : RootSets) {
1007 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
1008 return true;
1009 }
1010 return false;
1011}
1012
James Molloye805ad92015-02-12 15:54:14 +00001013/// Return true if instruction I depends on any instruction between
1014/// Start and End.
1015bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1016 UsesTy::iterator Start,
1017 UsesTy::iterator End) {
1018 for (auto *U : I->users()) {
1019 for (auto It = Start; It != End; ++It)
1020 if (U == It->first)
1021 return true;
1022 }
1023 return false;
1024}
1025
Weiming Zhao310770a2015-09-28 17:03:23 +00001026static bool isIgnorableInst(const Instruction *I) {
1027 if (isa<DbgInfoIntrinsic>(I))
1028 return true;
1029 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1030 if (!II)
1031 return false;
1032 switch (II->getIntrinsicID()) {
1033 default:
1034 return false;
1035 case llvm::Intrinsic::annotation:
1036 case Intrinsic::ptr_annotation:
1037 case Intrinsic::var_annotation:
1038 // TODO: the following intrinsics may also be whitelisted:
1039 // lifetime_start, lifetime_end, invariant_start, invariant_end
1040 return true;
1041 }
1042 return false;
1043}
1044
James Molloy64419d42015-01-29 21:52:03 +00001045bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001046 // We now need to check for equivalence of the use graph of each root with
1047 // that of the primary induction variable (excluding the roots). Our goal
1048 // here is not to solve the full graph isomorphism problem, but rather to
1049 // catch common cases without a lot of work. As a result, we will assume
1050 // that the relative order of the instructions in each unrolled iteration
1051 // is the same (although we will not make an assumption about how the
1052 // different iterations are intermixed). Note that while the order must be
1053 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001054
1055 // An array of just the possible reductions for this scale factor. When we
1056 // collect the set of all users of some root instructions, these reduction
1057 // instructions are treated as 'final' (their uses are not considered).
1058 // This is important because we don't want the root use set to search down
1059 // the reduction chain.
1060 SmallInstructionSet PossibleRedSet;
1061 SmallInstructionSet PossibleRedLastSet;
1062 SmallInstructionSet PossibleRedPHISet;
1063 Reductions.restrictToScale(Scale, PossibleRedSet,
1064 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001065
James Molloy64419d42015-01-29 21:52:03 +00001066 // Populate "Uses" with where each instruction is used.
1067 if (!collectUsedInstructions(PossibleRedSet))
1068 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001069
James Molloy64419d42015-01-29 21:52:03 +00001070 // Make sure we mark the reduction PHIs as used in all iterations.
1071 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001072 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001073 }
James Molloy5f255eb2015-01-29 13:48:05 +00001074
James Molloy64419d42015-01-29 21:52:03 +00001075 // Make sure all instructions in the loop are in one and only one
1076 // set.
1077 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001078 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
James Molloy64419d42015-01-29 21:52:03 +00001079 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1080 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1081 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001082 }
James Molloy64419d42015-01-29 21:52:03 +00001083 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001084
James Molloy64419d42015-01-29 21:52:03 +00001085 DEBUG(
1086 for (auto &KV : Uses) {
1087 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1088 }
1089 );
1090
1091 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001092 // In addition to regular aliasing information, we need to look for
1093 // instructions from later (future) iterations that have side effects
1094 // preventing us from reordering them past other instructions with side
1095 // effects.
1096 bool FutureSideEffects = false;
1097 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001098 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1099 DenseMap<Value *, Value *> BaseMap;
1100
James Molloy64419d42015-01-29 21:52:03 +00001101 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001102 SmallInstructionSet Visited;
1103 auto BaseIt = nextInstr(0, Uses, Visited);
1104 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001105 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001106
James Molloy64419d42015-01-29 21:52:03 +00001107 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1108 Instruction *BaseInst = BaseIt->first;
1109 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001110
James Molloy64419d42015-01-29 21:52:03 +00001111 // Skip over the IV or root instructions; only match their users.
1112 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001113 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001114 Visited.insert(BaseInst);
1115 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001116 Continue = true;
1117 }
James Molloyf1473592015-02-11 09:19:47 +00001118 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001119 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001120 Visited.insert(RootInst);
1121 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001122 Continue = true;
1123 }
1124 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001125
James Molloye805ad92015-02-12 15:54:14 +00001126 if (!BaseInst->isSameOperationAs(RootInst)) {
1127 // Last chance saloon. We don't try and solve the full isomorphism
1128 // problem, but try and at least catch the case where two instructions
1129 // *of different types* are round the wrong way. We won't be able to
1130 // efficiently tell, given two ADD instructions, which way around we
1131 // should match them, but given an ADD and a SUB, we can at least infer
1132 // which one is which.
1133 //
1134 // This should allow us to deal with a greater subset of the isomorphism
1135 // problem. It does however change a linear algorithm into a quadratic
1136 // one, so limit the number of probes we do.
1137 auto TryIt = RootIt;
1138 unsigned N = NumToleratedFailedMatches;
1139 while (TryIt != Uses.end() &&
1140 !BaseInst->isSameOperationAs(TryIt->first) &&
1141 N--) {
1142 ++TryIt;
1143 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1144 }
1145
1146 if (TryIt == Uses.end() || TryIt == RootIt ||
1147 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1148 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1149 " vs. " << *RootInst << "\n");
1150 return false;
1151 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001152
James Molloye805ad92015-02-12 15:54:14 +00001153 RootIt = TryIt;
1154 RootInst = TryIt->first;
1155 }
1156
James Molloy64419d42015-01-29 21:52:03 +00001157 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001158 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001159 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001160 //
James Molloye805ad92015-02-12 15:54:14 +00001161 // Note that because we allow a limited amount of flexibility in the order
1162 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1163 // case we've already checked this set of instructions so we shouldn't
1164 // do anything.
1165 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001166 Instruction *I = LastRootIt->first;
1167 if (LastRootIt->second.find_first() < (int)Iter)
1168 continue;
1169 if (I->mayWriteToMemory())
1170 AST.add(I);
1171 // Note: This is specifically guarded by a check on isa<PHINode>,
1172 // which while a valid (somewhat arbitrary) micro-optimization, is
1173 // needed because otherwise isSafeToSpeculativelyExecute returns
1174 // false on PHI nodes.
1175 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001176 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001177 // Intervening instructions cause side effects.
1178 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001179 }
1180
James Molloy5f255eb2015-01-29 13:48:05 +00001181 // Make sure that this instruction, which is in the use set of this
1182 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001183 // some other root instruction.
1184 if (RootIt->second.count() > 1) {
1185 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1186 " vs. " << *RootInst << " (prev. case overlap)\n");
1187 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001188 }
1189
1190 // Make sure that we don't alias with any instruction in the alias set
1191 // tracker. If we do, then we depend on a future iteration, and we
1192 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001193 if (RootInst->mayReadFromMemory())
1194 for (auto &K : AST) {
1195 if (K.aliasesUnknownInst(RootInst, *AA)) {
1196 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1197 " vs. " << *RootInst << " (depends on future store)\n");
1198 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001199 }
1200 }
James Molloy5f255eb2015-01-29 13:48:05 +00001201
1202 // If we've past an instruction from a future iteration that may have
1203 // side effects, and this instruction might also, then we can't reorder
1204 // them, and this matching fails. As an exception, we allow the alias
1205 // set tracker to handle regular (simple) load/store dependencies.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001206 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1207 !isSafeToSpeculativelyExecute(BaseInst)) ||
1208 (!isSimpleLoadStore(RootInst) &&
1209 !isSafeToSpeculativelyExecute(RootInst)))) {
James Molloy64419d42015-01-29 21:52:03 +00001210 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1211 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001212 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001213 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001214 }
1215
1216 // For instructions that are part of a reduction, if the operation is
1217 // associative, then don't bother matching the operands (because we
1218 // already know that the instructions are isomorphic, and the order
1219 // within the iteration does not matter). For non-associative reductions,
1220 // we do need to match the operands, because we need to reject
1221 // out-of-order instructions within an iteration!
1222 // For example (assume floating-point addition), we need to reject this:
1223 // x += a[i]; x += b[i];
1224 // x += a[i+1]; x += b[i+1];
1225 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001226 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001227
James Molloy64419d42015-01-29 21:52:03 +00001228 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001229 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001230 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1231 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001232
1233 // If this is part of a reduction (and the operation is not
1234 // associatve), then we match all operands, but not those that are
1235 // part of the reduction.
1236 if (InReduction)
1237 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001238 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001239 continue;
1240
1241 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001242 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001243 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001244 } else {
1245 for (auto &DRS : RootSets) {
1246 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1247 Op2 = DRS.BaseInst;
1248 break;
1249 }
1250 }
1251 }
James Molloy5f255eb2015-01-29 13:48:05 +00001252
James Molloy64419d42015-01-29 21:52:03 +00001253 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001254 // If we've not already decided to swap the matched operands, and
1255 // we've not already matched our first operand (note that we could
1256 // have skipped matching the first operand because it is part of a
1257 // reduction above), and the instruction is commutative, then try
1258 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001259 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1260 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001261 Swapped = true;
1262 } else {
James Molloy64419d42015-01-29 21:52:03 +00001263 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1264 << " vs. " << *RootInst << " (operand " << j << ")\n");
1265 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001266 }
1267 }
1268
1269 SomeOpMatched = true;
1270 }
1271 }
1272
James Molloy64419d42015-01-29 21:52:03 +00001273 if ((!PossibleRedLastSet.count(BaseInst) &&
1274 hasUsesOutsideLoop(BaseInst, L)) ||
1275 (!PossibleRedLastSet.count(RootInst) &&
1276 hasUsesOutsideLoop(RootInst, L))) {
1277 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1278 " vs. " << *RootInst << " (uses outside loop)\n");
1279 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001280 }
1281
James Molloy64419d42015-01-29 21:52:03 +00001282 Reductions.recordPair(BaseInst, RootInst, Iter);
1283 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001284
James Molloy64419d42015-01-29 21:52:03 +00001285 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001286 Visited.insert(BaseInst);
1287 Visited.insert(RootInst);
1288 BaseIt = nextInstr(0, Uses, Visited);
1289 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001290 }
James Molloy64419d42015-01-29 21:52:03 +00001291 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1292 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001293 }
1294
James Molloy5f255eb2015-01-29 13:48:05 +00001295 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001296 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001297
Hal Finkelbf45efd2013-11-16 23:59:05 +00001298 return true;
1299}
1300
James Molloy5f255eb2015-01-29 13:48:05 +00001301void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1302 BasicBlock *Header = L->getHeader();
1303 // Remove instructions associated with non-base iterations.
1304 for (BasicBlock::reverse_iterator J = Header->rbegin();
1305 J != Header->rend();) {
James Molloy64419d42015-01-29 21:52:03 +00001306 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001307 if (I > 0 && I < IL_All) {
James Molloy5f255eb2015-01-29 13:48:05 +00001308 Instruction *D = &*J;
1309 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1310 D->eraseFromParent();
1311 continue;
1312 }
1313
1314 ++J;
1315 }
1316
James Molloyf1473592015-02-11 09:19:47 +00001317 // We need to create a new induction variable for each different BaseInst.
Lawrence Hud3d51062016-01-25 19:43:45 +00001318 for (auto &DRS : RootSets)
James Molloyf1473592015-02-11 09:19:47 +00001319 // Insert the new induction variable.
Lawrence Hud3d51062016-01-25 19:43:45 +00001320 replaceIV(DRS.BaseInst, IV, IterCount);
Lawrence Hub917cd92016-01-25 19:36:30 +00001321
1322 SimplifyInstructionsInBlock(Header, TLI);
1323 DeleteDeadPHIs(Header, TLI);
Lawrence Hu84b61952016-01-25 18:53:39 +00001324}
1325
Lawrence Hud3d51062016-01-25 19:43:45 +00001326void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1327 Instruction *InstIV,
1328 const SCEV *IterCount) {
1329 BasicBlock *Header = L->getHeader();
1330 int64_t Inc = IVToIncMap[InstIV];
1331 bool Negative = Inc < 0;
1332
1333 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1334 const SCEV *Start = RealIVSCEV->getStart();
1335
1336 const SCEV *SizeOfExpr = nullptr;
1337 const SCEV *IncrExpr =
1338 SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1339 if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1340 Type *ElTy = PTy->getElementType();
1341 SizeOfExpr =
1342 SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1343 IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1344 }
1345 const SCEV *NewIVSCEV =
1346 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1347
1348 { // Limit the lifetime of SCEVExpander.
1349 const DataLayout &DL = Header->getModule()->getDataLayout();
1350 SCEVExpander Expander(*SE, DL, "reroll");
1351 Value *NewIV =
1352 Expander.expandCodeFor(NewIVSCEV, InstIV->getType(), &Header->front());
1353
1354 for (auto &KV : Uses)
1355 if (KV.second.find_first() == 0)
1356 KV.first->replaceUsesOfWith(Inst, NewIV);
1357
1358 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1359 // FIXME: Why do we need this check?
1360 if (Uses[BI].find_first() == IL_All) {
1361 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1362
1363 // Iteration count SCEV minus or plus 1
1364 const SCEV *MinusPlus1SCEV =
1365 SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1366 if (Inst->getType()->isPointerTy()) {
1367 assert(SizeOfExpr && "SizeOfExpr is not initialized");
1368 MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1369 }
1370
1371 const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1372 // Iteration count minus 1
1373 Value *ICMinusPlus1 = nullptr;
1374 if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
1375 ICMinusPlus1 =
1376 Expander.expandCodeFor(ICMinusPlus1SCEV, NewIV->getType(), BI);
1377 } else {
1378 BasicBlock *Preheader = L->getLoopPreheader();
1379 if (!Preheader)
1380 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
1381 ICMinusPlus1 = Expander.expandCodeFor(
1382 ICMinusPlus1SCEV, NewIV->getType(), Preheader->getTerminator());
1383 }
1384
1385 Value *Cond =
1386 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1387 BI->setCondition(Cond);
1388
1389 if (BI->getSuccessor(1) != Header)
1390 BI->swapSuccessors();
1391 }
1392 }
1393 }
1394}
1395
Hal Finkelbf45efd2013-11-16 23:59:05 +00001396// Validate the selected reductions. All iterations must have an isomorphic
1397// part of the reduction chain and, for non-associative reductions, the chain
1398// entries must appear in order.
1399bool LoopReroll::ReductionTracker::validateSelected() {
1400 // For a non-associative reduction, the chain entries must appear in order.
1401 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1402 RI != RIE; ++RI) {
1403 int i = *RI;
1404 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001405 for (Instruction *J : PossibleReds[i]) {
1406 // Note that all instructions in the chain must have been found because
1407 // all instructions in the function must have been assigned to some
1408 // iteration.
1409 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001410 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1411 !PossibleReds[i].getReducedValue()->isAssociative()) {
1412 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001413 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001414 return false;
1415 }
1416
1417 if (Iter != PrevIter) {
1418 if (Count != BaseCount) {
1419 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1420 " reduction use count " << Count <<
1421 " is not equal to the base use count " <<
1422 BaseCount << "\n");
1423 return false;
1424 }
1425
1426 Count = 0;
1427 }
1428
1429 ++Count;
1430 if (Iter == 0)
1431 ++BaseCount;
1432
1433 PrevIter = Iter;
1434 }
1435 }
1436
1437 return true;
1438}
1439
1440// For all selected reductions, remove all parts except those in the first
1441// iteration (and the PHI). Replace outside uses of the reduced value with uses
1442// of the first-iteration reduced value (in other words, reroll the selected
1443// reductions).
1444void LoopReroll::ReductionTracker::replaceSelected() {
1445 // Fixup reductions to refer to the last instruction associated with the
1446 // first iteration (not the last).
1447 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1448 RI != RIE; ++RI) {
1449 int i = *RI;
1450 int j = 0;
1451 for (int e = PossibleReds[i].size(); j != e; ++j)
1452 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1453 --j;
1454 break;
1455 }
1456
1457 // Replace users with the new end-of-chain value.
1458 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001459 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001460 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001461 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001462
1463 for (SmallInstructionVector::iterator J = Users.begin(),
1464 JE = Users.end(); J != JE; ++J)
1465 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1466 PossibleReds[i][j]);
1467 }
1468}
1469
1470// Reroll the provided loop with respect to the provided induction variable.
1471// Generally, we're looking for a loop like this:
1472//
1473// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1474// f(%iv)
1475// %iv.1 = add %iv, 1 <-- a root increment
1476// f(%iv.1)
1477// %iv.2 = add %iv, 2 <-- a root increment
1478// f(%iv.2)
1479// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1480// f(%iv.scale_m_1)
1481// ...
1482// %iv.next = add %iv, scale
1483// %cmp = icmp(%iv, ...)
1484// br %cmp, header, exit
1485//
1486// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1487// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1488// be intermixed with eachother. The restriction imposed by this algorithm is
1489// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1490// etc. be the same.
1491//
1492// First, we collect the use set of %iv, excluding the other increment roots.
1493// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1494// times, having collected the use set of f(%iv.(i+1)), during which we:
1495// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1496// the next unmatched instruction in f(%iv.(i+1)).
1497// - Ensure that both matched instructions don't have any external users
1498// (with the exception of last-in-chain reduction instructions).
1499// - Track the (aliasing) write set, and other side effects, of all
1500// instructions that belong to future iterations that come before the matched
1501// instructions. If the matched instructions read from that write set, then
1502// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1503// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1504// if any of these future instructions had side effects (could not be
1505// speculatively executed), and so do the matched instructions, when we
1506// cannot reorder those side-effect-producing instructions, and rerolling
1507// fails.
1508//
1509// Finally, we make sure that all loop instructions are either loop increment
1510// roots, belong to simple latch code, parts of validated reductions, part of
1511// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1512// have been validated), then we reroll the loop.
1513bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1514 const SCEV *IterCount,
1515 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001516 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
1517 IVToIncMap);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001518
James Molloy5f255eb2015-01-29 13:48:05 +00001519 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001520 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001521 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001522 *IV << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001523
James Molloy5f255eb2015-01-29 13:48:05 +00001524 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001525 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001526 if (!Reductions.validateSelected())
1527 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001528 // At this point, we've validated the rerolling, and we're committed to
1529 // making changes!
1530
1531 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001532 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001533
Hal Finkelbf45efd2013-11-16 23:59:05 +00001534 ++NumRerolledLoops;
1535 return true;
1536}
1537
1538bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001539 if (skipOptnoneFunction(L))
1540 return false;
1541
Chandler Carruth7b560d42015-09-09 17:55:00 +00001542 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001543 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001544 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001545 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001546 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001547 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001548
1549 BasicBlock *Header = L->getHeader();
1550 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1551 "] Loop %" << Header->getName() << " (" <<
1552 L->getNumBlocks() << " block(s))\n");
1553
Hal Finkelbf45efd2013-11-16 23:59:05 +00001554 // For now, we'll handle only single BB loops.
1555 if (L->getNumBlocks() > 1)
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001556 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001557
1558 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001559 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001560
1561 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001562 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Hal Finkelbf45efd2013-11-16 23:59:05 +00001563 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1564
1565 // First, we need to find the induction variable with respect to which we can
1566 // reroll (there may be several possible options).
1567 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001568 IVToIncMap.clear();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001569 collectPossibleIVs(L, PossibleIVs);
1570
1571 if (PossibleIVs.empty()) {
1572 DEBUG(dbgs() << "LRR: No possible IVs found\n");
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001573 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001574 }
1575
1576 ReductionTracker Reductions;
1577 collectPossibleReductions(L, Reductions);
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001578 bool Changed = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001579
1580 // For each possible IV, collect the associated possible set of 'root' nodes
1581 // (i+1, i+2, etc.).
1582 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1583 IE = PossibleIVs.end(); I != IE; ++I)
1584 if (reroll(*I, L, Header, IterCount, Reductions)) {
1585 Changed = true;
1586 break;
1587 }
1588
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001589 // Trip count of L has changed so SE must be re-evaluated.
1590 if (Changed)
1591 SE->forgetLoop(L);
1592
Hal Finkelbf45efd2013-11-16 23:59:05 +00001593 return Changed;
1594}