blob: 83dd196f20e198eb8a487e3352713e8a930aacfe [file] [log] [blame]
Eugene Zelenko306d2992017-10-18 21:46:47 +00001//===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
Hal Finkelbf45efd2013-11-16 23:59:05 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements a simple loop reroller.
11//
12//===----------------------------------------------------------------------===//
13
Eugene Zelenko306d2992017-10-18 21:46:47 +000014#include "llvm/ADT/APInt.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ADT/BitVector.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
James Molloy64419d42015-01-29 21:52:03 +000018#include "llvm/ADT/MapVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/STLExtras.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000020#include "llvm/ADT/SmallSet.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000021#include "llvm/ADT/SmallVector.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000022#include "llvm/ADT/Statistic.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/AliasSetTracker.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000025#include "llvm/Analysis/LoopInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000026#include "llvm/Analysis/LoopPass.h"
27#include "llvm/Analysis/ScalarEvolution.h"
28#include "llvm/Analysis/ScalarEvolutionExpander.h"
29#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000031#include "llvm/Analysis/Utils/Local.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000032#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000033#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/Constants.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000035#include "llvm/IR/DataLayout.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000036#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000038#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Instructions.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000042#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000043#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/Type.h"
46#include "llvm/IR/Use.h"
47#include "llvm/IR/User.h"
48#include "llvm/IR/Value.h"
49#include "llvm/Pass.h"
50#include "llvm/Support/Casting.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000051#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000055#include "llvm/Transforms/Utils.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000056#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000057#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000058#include <cassert>
59#include <cstddef>
60#include <cstdint>
61#include <cstdlib>
62#include <iterator>
63#include <map>
64#include <utility>
Hal Finkelbf45efd2013-11-16 23:59:05 +000065
66using namespace llvm;
67
Chandler Carruth964daaa2014-04-22 02:55:47 +000068#define DEBUG_TYPE "loop-reroll"
69
Hal Finkelbf45efd2013-11-16 23:59:05 +000070STATISTIC(NumRerolledLoops, "Number of rerolled loops");
71
72static cl::opt<unsigned>
73MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
74 cl::desc("The maximum increment for loop rerolling"));
75
James Molloye805ad92015-02-12 15:54:14 +000076static cl::opt<unsigned>
77NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
78 cl::Hidden,
79 cl::desc("The maximum number of failures to tolerate"
80 " during fuzzy matching. (default: 400)"));
81
Hal Finkelbf45efd2013-11-16 23:59:05 +000082// This loop re-rolling transformation aims to transform loops like this:
83//
84// int foo(int a);
85// void bar(int *x) {
86// for (int i = 0; i < 500; i += 3) {
87// foo(i);
88// foo(i+1);
89// foo(i+2);
90// }
91// }
92//
93// into a loop like this:
94//
95// void bar(int *x) {
96// for (int i = 0; i < 500; ++i)
97// foo(i);
98// }
99//
100// It does this by looking for loops that, besides the latch code, are composed
101// of isomorphic DAGs of instructions, with each DAG rooted at some increment
102// to the induction variable, and where each DAG is isomorphic to the DAG
103// rooted at the induction variable (excepting the sub-DAGs which root the
104// other induction-variable increments). In other words, we're looking for loop
105// bodies of the form:
106//
107// %iv = phi [ (preheader, ...), (body, %iv.next) ]
108// f(%iv)
109// %iv.1 = add %iv, 1 <-- a root increment
110// f(%iv.1)
111// %iv.2 = add %iv, 2 <-- a root increment
112// f(%iv.2)
113// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
114// f(%iv.scale_m_1)
115// ...
116// %iv.next = add %iv, scale
117// %cmp = icmp(%iv, ...)
118// br %cmp, header, exit
119//
120// where each f(i) is a set of instructions that, collectively, are a function
121// only of i (and other loop-invariant values).
122//
123// As a special case, we can also reroll loops like this:
124//
125// int foo(int);
126// void bar(int *x) {
127// for (int i = 0; i < 500; ++i) {
128// x[3*i] = foo(0);
129// x[3*i+1] = foo(0);
130// x[3*i+2] = foo(0);
131// }
132// }
133//
134// into this:
135//
136// void bar(int *x) {
137// for (int i = 0; i < 1500; ++i)
138// x[i] = foo(0);
139// }
140//
141// in which case, we're looking for inputs like this:
142//
143// %iv = phi [ (preheader, ...), (body, %iv.next) ]
144// %scaled.iv = mul %iv, scale
145// f(%scaled.iv)
146// %scaled.iv.1 = add %scaled.iv, 1
147// f(%scaled.iv.1)
148// %scaled.iv.2 = add %scaled.iv, 2
149// f(%scaled.iv.2)
150// %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
151// f(%scaled.iv.scale_m_1)
152// ...
153// %iv.next = add %iv, 1
154// %cmp = icmp(%iv, ...)
155// br %cmp, header, exit
156
157namespace {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000158
James Molloy64419d42015-01-29 21:52:03 +0000159 enum IterationLimits {
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000160 /// The maximum number of iterations that we'll try and reroll.
161 IL_MaxRerollIterations = 32,
James Molloy64419d42015-01-29 21:52:03 +0000162 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000163 /// instructions that belong to all iterations.
164 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000165 IL_End
166 };
167
Hal Finkelbf45efd2013-11-16 23:59:05 +0000168 class LoopReroll : public LoopPass {
169 public:
170 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko306d2992017-10-18 21:46:47 +0000171
Hal Finkelbf45efd2013-11-16 23:59:05 +0000172 LoopReroll() : LoopPass(ID) {
173 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
174 }
175
Craig Topper3e4c6972014-03-05 09:10:37 +0000176 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000177
Craig Topper3e4c6972014-03-05 09:10:37 +0000178 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000179 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000180 getLoopAnalysisUsage(AU);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000181 }
182
James Molloy64419d42015-01-29 21:52:03 +0000183 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000184 AliasAnalysis *AA;
185 LoopInfo *LI;
186 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000187 TargetLibraryInfo *TLI;
188 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000189 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000190
Eugene Zelenko306d2992017-10-18 21:46:47 +0000191 using SmallInstructionVector = SmallVector<Instruction *, 16>;
192 using SmallInstructionSet = SmallSet<Instruction *, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000193
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000194 // Map between induction variable and its increment
195 DenseMap<Instruction *, int64_t> IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000196
Lawrence Hu1befea22016-04-30 00:51:22 +0000197 // For loop with multiple induction variable, remember the one used only to
198 // control the loop.
199 Instruction *LoopControlIV;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000200
201 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000202 // representing a reduction. Only the last value may be used outside the
203 // loop.
204 struct SimpleLoopReduction {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000205 SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000206 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
207 add(L);
208 }
209
210 bool valid() const {
211 return Valid;
212 }
213
214 Instruction *getPHI() const {
215 assert(Valid && "Using invalid reduction");
216 return Instructions.front();
217 }
218
219 Instruction *getReducedValue() const {
220 assert(Valid && "Using invalid reduction");
221 return Instructions.back();
222 }
223
224 Instruction *get(size_t i) const {
225 assert(Valid && "Using invalid reduction");
226 return Instructions[i+1];
227 }
228
229 Instruction *operator [] (size_t i) const { return get(i); }
230
231 // The size, ignoring the initial PHI.
232 size_t size() const {
233 assert(Valid && "Using invalid reduction");
234 return Instructions.size()-1;
235 }
236
Eugene Zelenko306d2992017-10-18 21:46:47 +0000237 using iterator = SmallInstructionVector::iterator;
238 using const_iterator = SmallInstructionVector::const_iterator;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000239
240 iterator begin() {
241 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000242 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000243 }
244
245 const_iterator begin() const {
246 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000247 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000248 }
249
250 iterator end() { return Instructions.end(); }
251 const_iterator end() const { return Instructions.end(); }
252
253 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000254 bool Valid = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000255 SmallInstructionVector Instructions;
256
257 void add(Loop *L);
258 };
259
260 // The set of all reductions, and state tracking of possible reductions
261 // during loop instruction processing.
262 struct ReductionTracker {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000263 using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000264
265 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000266 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000267
268 // Setup to track possible reductions corresponding to the provided
269 // rerolling scale. Only reductions with a number of non-PHI instructions
270 // that is divisible by the scale are considered. Three instructions sets
271 // are filled in:
272 // - A set of all possible instructions in eligible reductions.
273 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000274 // - A set of all reduced values (last instructions) in eligible
275 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000276 void restrictToScale(uint64_t Scale,
277 SmallInstructionSet &PossibleRedSet,
278 SmallInstructionSet &PossibleRedPHISet,
279 SmallInstructionSet &PossibleRedLastSet) {
280 PossibleRedIdx.clear();
281 PossibleRedIter.clear();
282 Reds.clear();
283
284 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
285 if (PossibleReds[i].size() % Scale == 0) {
286 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
287 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000288
Hal Finkelbf45efd2013-11-16 23:59:05 +0000289 PossibleRedSet.insert(PossibleReds[i].getPHI());
290 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000291 for (Instruction *J : PossibleReds[i]) {
292 PossibleRedSet.insert(J);
293 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000294 }
295 }
296 }
297
298 // The functions below are used while processing the loop instructions.
299
300 // Are the two instructions both from reductions, and furthermore, from
301 // the same reduction?
302 bool isPairInSame(Instruction *J1, Instruction *J2) {
303 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
304 if (J1I != PossibleRedIdx.end()) {
305 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
306 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
307 return true;
308 }
309
310 return false;
311 }
312
313 // The two provided instructions, the first from the base iteration, and
314 // the second from iteration i, form a matched pair. If these are part of
315 // a reduction, record that fact.
316 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
317 if (PossibleRedIdx.count(J1)) {
318 assert(PossibleRedIdx.count(J2) &&
319 "Recording reduction vs. non-reduction instruction?");
320
321 PossibleRedIter[J1] = 0;
322 PossibleRedIter[J2] = i;
323
324 int Idx = PossibleRedIdx[J1];
325 assert(Idx == PossibleRedIdx[J2] &&
326 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000327 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000328 }
329 }
330
331 // The functions below can be called after we've finished processing all
332 // instructions in the loop, and we know which reductions were selected.
333
Hal Finkelbf45efd2013-11-16 23:59:05 +0000334 bool validateSelected();
335 void replaceSelected();
336
337 protected:
338 // The vector of all possible reductions (for any scale).
339 SmallReductionVector PossibleReds;
340
341 DenseMap<Instruction *, int> PossibleRedIdx;
342 DenseMap<Instruction *, int> PossibleRedIter;
343 DenseSet<int> Reds;
344 };
345
James Molloyf1473592015-02-11 09:19:47 +0000346 // A DAGRootSet models an induction variable being used in a rerollable
347 // loop. For example,
348 //
349 // x[i*3+0] = y1
350 // x[i*3+1] = y2
351 // x[i*3+2] = y3
352 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000353 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000354 // +---+----+
355 // / | \
356 // ST[y1] +1 +2 <-- Roots
357 // | |
358 // ST[y2] ST[y3]
359 //
360 // There may be multiple DAGRoots, for example:
361 //
362 // x[i*2+0] = ... (1)
363 // x[i*2+1] = ... (1)
364 // x[i*2+4] = ... (2)
365 // x[i*2+5] = ... (2)
366 // x[(i+1234)*2+5678] = ... (3)
367 // x[(i+1234)*2+5679] = ... (3)
368 //
369 // The loop will be rerolled by adding a new loop induction variable,
370 // one for the Base instruction in each DAGRootSet.
371 //
372 struct DAGRootSet {
373 Instruction *BaseInst;
374 SmallInstructionVector Roots;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000375
James Molloyf1473592015-02-11 09:19:47 +0000376 // The instructions between IV and BaseInst (but not including BaseInst).
377 SmallInstructionSet SubsumedInsts;
378 };
379
James Molloy5f255eb2015-01-29 13:48:05 +0000380 // The set of all DAG roots, and state tracking of all roots
381 // for a particular induction variable.
382 struct DAGRootTracker {
383 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
384 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000385 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
386 bool PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +0000387 DenseMap<Instruction *, int64_t> &IncrMap,
388 Instruction *LoopCtrlIV)
Justin Bogner843fb202015-12-15 19:40:57 +0000389 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
Lawrence Hu1befea22016-04-30 00:51:22 +0000390 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
391 LoopControlIV(LoopCtrlIV) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000392
393 /// Stage 1: Find all the DAG roots for the induction variable.
394 bool findRoots();
Eugene Zelenko306d2992017-10-18 21:46:47 +0000395
James Molloy5f255eb2015-01-29 13:48:05 +0000396 /// Stage 2: Validate if the found roots are valid.
397 bool validate(ReductionTracker &Reductions);
Eugene Zelenko306d2992017-10-18 21:46:47 +0000398
James Molloy5f255eb2015-01-29 13:48:05 +0000399 /// Stage 3: Assuming validate() returned true, perform the
400 /// replacement.
401 /// @param IterCount The maximum iteration count of L.
402 void replace(const SCEV *IterCount);
403
404 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000405 using UsesTy = MapVector<Instruction *, BitVector>;
James Molloy64419d42015-01-29 21:52:03 +0000406
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000407 void findRootsRecursive(Instruction *IVU,
James Molloyf1473592015-02-11 09:19:47 +0000408 SmallInstructionSet SubsumedInsts);
409 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
410 bool collectPossibleRoots(Instruction *Base,
411 std::map<int64_t,Instruction*> &Roots);
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000412 bool validateRootSet(DAGRootSet &DRS);
James Molloy5f255eb2015-01-29 13:48:05 +0000413
James Molloy64419d42015-01-29 21:52:03 +0000414 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000415 void collectInLoopUserSet(const SmallInstructionVector &Roots,
416 const SmallInstructionSet &Exclude,
417 const SmallInstructionSet &Final,
418 DenseSet<Instruction *> &Users);
419 void collectInLoopUserSet(Instruction *Root,
420 const SmallInstructionSet &Exclude,
421 const SmallInstructionSet &Final,
422 DenseSet<Instruction *> &Users);
423
James Molloye805ad92015-02-12 15:54:14 +0000424 UsesTy::iterator nextInstr(int Val, UsesTy &In,
425 const SmallInstructionSet &Exclude,
426 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000427 bool isBaseInst(Instruction *I);
428 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000429 bool instrDependsOn(Instruction *I,
430 UsesTy::iterator Start,
431 UsesTy::iterator End);
Lawrence Hud3d51062016-01-25 19:43:45 +0000432 void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
Lawrence Hu1befea22016-04-30 00:51:22 +0000433 void updateNonLoopCtrlIncr();
James Molloy64419d42015-01-29 21:52:03 +0000434
James Molloy5f255eb2015-01-29 13:48:05 +0000435 LoopReroll *Parent;
436
437 // Members of Parent, replicated here for brevity.
438 Loop *L;
439 ScalarEvolution *SE;
440 AliasAnalysis *AA;
441 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000442 DominatorTree *DT;
443 LoopInfo *LI;
444 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000445
446 // The loop induction variable.
447 Instruction *IV;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000448
James Molloy5f255eb2015-01-29 13:48:05 +0000449 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000450 int64_t Inc;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000451
James Molloy5f255eb2015-01-29 13:48:05 +0000452 // Loop reroll count; if Inc == 1, this records the scaling applied
453 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
454 // If Inc is not 1, Scale = Inc.
455 uint64_t Scale;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000456
James Molloy5f255eb2015-01-29 13:48:05 +0000457 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000458 SmallVector<DAGRootSet,16> RootSets;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000459
James Molloy5f255eb2015-01-29 13:48:05 +0000460 // All increment instructions for IV.
461 SmallInstructionVector LoopIncs;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000462
James Molloy64419d42015-01-29 21:52:03 +0000463 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000464 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000465 // used in the loop increment mechanism).
466 UsesTy Uses;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000467
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000468 // Map between induction variable and its increment
469 DenseMap<Instruction *, int64_t> &IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000470
Lawrence Hu1befea22016-04-30 00:51:22 +0000471 Instruction *LoopControlIV;
James Molloy5f255eb2015-01-29 13:48:05 +0000472 };
473
Lawrence Hu1befea22016-04-30 00:51:22 +0000474 // Check if it is a compare-like instruction whose user is a branch
475 bool isCompareUsedByBranch(Instruction *I) {
476 auto *TI = I->getParent()->getTerminator();
477 if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
478 return false;
479 return I->hasOneUse() && TI->getOperand(0) == I;
480 };
481
482 bool isLoopControlIV(Loop *L, Instruction *IV);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000483 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
484 void collectPossibleReductions(Loop *L,
485 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000486 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
487 ReductionTracker &Reductions);
488 };
Eugene Zelenko306d2992017-10-18 21:46:47 +0000489
490} // end anonymous namespace
Hal Finkelbf45efd2013-11-16 23:59:05 +0000491
492char LoopReroll::ID = 0;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000493
Hal Finkelbf45efd2013-11-16 23:59:05 +0000494INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000495INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000496INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000497INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
498
499Pass *llvm::createLoopRerollPass() {
500 return new LoopReroll;
501}
502
503// Returns true if the provided instruction is used outside the given loop.
504// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
505// non-loop blocks to be outside the loop.
506static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000507 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000508 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000509 return true;
James Molloy64419d42015-01-29 21:52:03 +0000510 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000511 return false;
512}
513
Lawrence Hud3d51062016-01-25 19:43:45 +0000514static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
515 const SCEV *SCEVExpr,
516 Instruction &IV) {
517 const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
518
519 // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
520 // Return c1.
521 if (!MulSCEV && IV.getType()->isPointerTy())
522 if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
523 const PointerType *PTy = cast<PointerType>(IV.getType());
524 Type *ElTy = PTy->getElementType();
525 const SCEV *SizeOfExpr =
526 SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
527 if (IncSCEV->getValue()->getValue().isNegative()) {
528 const SCEV *NewSCEV =
529 SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
530 return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
531 } else {
532 return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
533 }
534 }
535
536 if (!MulSCEV)
537 return nullptr;
538
539 // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
540 // Return c.
541 const SCEVConstant *CIncSCEV = nullptr;
542 for (const SCEV *Operand : MulSCEV->operands()) {
543 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
544 CIncSCEV = Constant;
545 } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
546 Type *AllocTy;
547 if (!Unknown->isSizeOf(AllocTy))
548 break;
549 } else {
550 return nullptr;
551 }
552 }
553 return CIncSCEV;
554}
555
Lawrence Hu1befea22016-04-30 00:51:22 +0000556// Check if an IV is only used to control the loop. There are two cases:
557// 1. It only has one use which is loop increment, and the increment is only
Lawrence Hue58a8142016-05-10 21:16:49 +0000558// used by comparison and the PHI (could has sext with nsw in between), and the
559// comparison is only used by branch.
Lawrence Hu1befea22016-04-30 00:51:22 +0000560// 2. It is used by loop increment and the comparison, the loop increment is
561// only used by the PHI, and the comparison is used only by the branch.
562bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
Lawrence Hu1befea22016-04-30 00:51:22 +0000563 unsigned IVUses = IV->getNumUses();
564 if (IVUses != 2 && IVUses != 1)
565 return false;
566
567 for (auto *User : IV->users()) {
568 int32_t IncOrCmpUses = User->getNumUses();
569 bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
570
571 // User can only have one or two uses.
572 if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
573 return false;
574
575 // Case 1
576 if (IVUses == 1) {
577 // The only user must be the loop increment.
578 // The loop increment must have two uses.
579 if (IsCompInst || IncOrCmpUses != 2)
580 return false;
581 }
582
583 // Case 2
584 if (IVUses == 2 && IncOrCmpUses != 1)
585 return false;
586
587 // The users of the IV must be a binary operation or a comparison
588 if (auto *BO = dyn_cast<BinaryOperator>(User)) {
589 if (BO->getOpcode() == Instruction::Add) {
590 // Loop Increment
591 // User of Loop Increment should be either PHI or CMP
592 for (auto *UU : User->users()) {
593 if (PHINode *PN = dyn_cast<PHINode>(UU)) {
594 if (PN != IV)
595 return false;
596 }
Lawrence Hue58a8142016-05-10 21:16:49 +0000597 // Must be a CMP or an ext (of a value with nsw) then CMP
598 else {
599 Instruction *UUser = dyn_cast<Instruction>(UU);
600 // Skip SExt if we are extending an nsw value
601 // TODO: Allow ZExt too
Zvi Rackoverd9423972017-04-18 14:55:43 +0000602 if (BO->hasNoSignedWrap() && UUser && UUser->hasOneUse() &&
Lawrence Hue58a8142016-05-10 21:16:49 +0000603 isa<SExtInst>(UUser))
604 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
605 if (!isCompareUsedByBranch(UUser))
606 return false;
607 }
Lawrence Hu1befea22016-04-30 00:51:22 +0000608 }
609 } else
610 return false;
611 // Compare : can only have one use, and must be branch
612 } else if (!IsCompInst)
613 return false;
614 }
615 return true;
616}
617
Hal Finkelbf45efd2013-11-16 23:59:05 +0000618// Collect the list of loop induction variables with respect to which it might
619// be possible to reroll the loop.
620void LoopReroll::collectPossibleIVs(Loop *L,
621 SmallInstructionVector &PossibleIVs) {
622 BasicBlock *Header = L->getHeader();
623 for (BasicBlock::iterator I = Header->begin(),
624 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
625 if (!isa<PHINode>(I))
626 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000627 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000628 continue;
629
630 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000631 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000632 if (PHISCEV->getLoop() != L)
633 continue;
634 if (!PHISCEV->isAffine())
635 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000636 const SCEVConstant *IncSCEV = nullptr;
637 if (I->getType()->isPointerTy())
638 IncSCEV =
639 getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
640 else
641 IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
642 if (IncSCEV) {
643 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000644 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000645 continue;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000646 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000647 LLVM_DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
648 << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000649
650 if (isLoopControlIV(L, &*I)) {
651 assert(!LoopControlIV && "Found two loop control only IV");
652 LoopControlIV = &(*I);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000653 LLVM_DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I
654 << " = " << *PHISCEV << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000655 } else
656 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000657 }
658 }
659 }
660}
661
662// Add the remainder of the reduction-variable chain to the instruction vector
663// (the initial PHINode has already been added). If successful, the object is
664// marked as valid.
665void LoopReroll::SimpleLoopReduction::add(Loop *L) {
666 assert(!Valid && "Cannot add to an already-valid chain");
667
668 // The reduction variable must be a chain of single-use instructions
669 // (including the PHI), except for the last value (which is used by the PHI
670 // and also outside the loop).
671 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000672 if (C->user_empty())
673 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000674
675 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000676 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000677 if (C->hasOneUse()) {
678 if (!C->isBinaryOp())
679 return;
680
681 if (!(isa<PHINode>(Instructions.back()) ||
682 C->isSameOperationAs(Instructions.back())))
683 return;
684
685 Instructions.push_back(C);
686 }
687 } while (C->hasOneUse());
688
689 if (Instructions.size() < 2 ||
690 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000691 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000692 return;
693
694 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000695 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000696 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000697 if (L->contains(cast<Instruction>(U)))
698 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000699 return;
James Molloy64419d42015-01-29 21:52:03 +0000700 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000701
702 Instructions.push_back(C);
703 Valid = true;
704}
705
706// Collect the vector of possible reduction variables.
707void LoopReroll::collectPossibleReductions(Loop *L,
708 ReductionTracker &Reductions) {
709 BasicBlock *Header = L->getHeader();
710 for (BasicBlock::iterator I = Header->begin(),
711 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
712 if (!isa<PHINode>(I))
713 continue;
714 if (!I->getType()->isSingleValueType())
715 continue;
716
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000717 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000718 if (!SLR.valid())
719 continue;
720
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000721 LLVM_DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with "
722 << SLR.size() << " chained instructions)\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +0000723 Reductions.addSLR(SLR);
724 }
725}
726
727// Collect the set of all users of the provided root instruction. This set of
728// users contains not only the direct users of the root instruction, but also
729// all users of those users, and so on. There are two exceptions:
730//
731// 1. Instructions in the set of excluded instructions are never added to the
732// use set (even if they are users). This is used, for example, to exclude
733// including root increments in the use set of the primary IV.
734//
735// 2. Instructions in the set of final instructions are added to the use set
736// if they are users, but their users are not added. This is used, for
737// example, to prevent a reduction update from forcing all later reduction
738// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000739void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000740 Instruction *Root, const SmallInstructionSet &Exclude,
741 const SmallInstructionSet &Final,
742 DenseSet<Instruction *> &Users) {
743 SmallInstructionVector Queue(1, Root);
744 while (!Queue.empty()) {
745 Instruction *I = Queue.pop_back_val();
746 if (!Users.insert(I).second)
747 continue;
748
749 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000750 for (Use &U : I->uses()) {
751 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000752 if (PHINode *PN = dyn_cast<PHINode>(User)) {
753 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000754 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000755 continue;
756 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000757
Hal Finkelbf45efd2013-11-16 23:59:05 +0000758 if (L->contains(User) && !Exclude.count(User)) {
759 Queue.push_back(User);
760 }
761 }
762
763 // We also want to collect single-user "feeder" values.
764 for (User::op_iterator OI = I->op_begin(),
765 OIE = I->op_end(); OI != OIE; ++OI) {
766 if (Instruction *Op = dyn_cast<Instruction>(*OI))
767 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
768 !Final.count(Op))
769 Queue.push_back(Op);
770 }
771 }
772}
773
774// Collect all of the users of all of the provided root instructions (combined
775// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000776void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000777 const SmallInstructionVector &Roots,
778 const SmallInstructionSet &Exclude,
779 const SmallInstructionSet &Final,
780 DenseSet<Instruction *> &Users) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000781 for (Instruction *Root : Roots)
782 collectInLoopUserSet(Root, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000783}
784
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000785static bool isUnorderedLoadStore(Instruction *I) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000786 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000787 return LI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000788 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000789 return SI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000790 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
791 return !MI->isVolatile();
792 return false;
793}
794
James Molloyf1473592015-02-11 09:19:47 +0000795/// Return true if IVU is a "simple" arithmetic operation.
796/// This is used for narrowing the search space for DAGRoots; only arithmetic
797/// and GEPs can be part of a DAGRoot.
798static bool isSimpleArithmeticOp(User *IVU) {
799 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
800 switch (I->getOpcode()) {
801 default: return false;
802 case Instruction::Add:
803 case Instruction::Sub:
804 case Instruction::Mul:
805 case Instruction::Shl:
806 case Instruction::AShr:
807 case Instruction::LShr:
808 case Instruction::GetElementPtr:
809 case Instruction::Trunc:
810 case Instruction::ZExt:
811 case Instruction::SExt:
812 return true;
813 }
814 }
815 return false;
816}
817
818static bool isLoopIncrement(User *U, Instruction *IV) {
819 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hud3d51062016-01-25 19:43:45 +0000820
821 if ((BO && BO->getOpcode() != Instruction::Add) ||
822 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000823 return false;
824
Lawrence Hud3d51062016-01-25 19:43:45 +0000825 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000826 PHINode *PN = dyn_cast<PHINode>(UU);
827 if (PN && PN == IV)
828 return true;
829 }
830 return false;
831}
832
833bool LoopReroll::DAGRootTracker::
834collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
835 SmallInstructionVector BaseUsers;
836
837 for (auto *I : Base->users()) {
838 ConstantInt *CI = nullptr;
839
840 if (isLoopIncrement(I, IV)) {
841 LoopIncs.push_back(cast<Instruction>(I));
842 continue;
843 }
844
845 // The root nodes must be either GEPs, ORs or ADDs.
846 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
847 if (BO->getOpcode() == Instruction::Add ||
848 BO->getOpcode() == Instruction::Or)
849 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
850 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
851 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
852 CI = dyn_cast<ConstantInt>(LastOperand);
853 }
854
855 if (!CI) {
856 if (Instruction *II = dyn_cast<Instruction>(I)) {
857 BaseUsers.push_back(II);
858 continue;
859 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000860 LLVM_DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I
861 << "\n");
James Molloyf1473592015-02-11 09:19:47 +0000862 return false;
863 }
864 }
865
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000866 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000867 if (Roots.find(V) != Roots.end())
868 // No duplicates, please.
869 return false;
870
James Molloyf1473592015-02-11 09:19:47 +0000871 Roots[V] = cast<Instruction>(I);
872 }
873
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000874 // Make sure we have at least two roots.
875 if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
James Molloyf1473592015-02-11 09:19:47 +0000876 return false;
James Molloyf1473592015-02-11 09:19:47 +0000877
878 // If we found non-loop-inc, non-root users of Base, assume they are
879 // for the zeroth root index. This is because "add %a, 0" gets optimized
880 // away.
James Molloye32d8062015-02-16 17:02:00 +0000881 if (BaseUsers.size()) {
882 if (Roots.find(0) != Roots.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000883 LLVM_DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
James Molloye32d8062015-02-16 17:02:00 +0000884 return false;
885 }
James Molloyf1473592015-02-11 09:19:47 +0000886 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000887 }
James Molloyf1473592015-02-11 09:19:47 +0000888
889 // Calculate the number of users of the base, or lowest indexed, iteration.
890 unsigned NumBaseUses = BaseUsers.size();
891 if (NumBaseUses == 0)
892 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000893
James Molloyf1473592015-02-11 09:19:47 +0000894 // Check that every node has the same number of users.
895 for (auto &KV : Roots) {
896 if (KV.first == 0)
897 continue;
Davide Italiano80fe9872017-04-18 21:42:21 +0000898 if (!KV.second->hasNUses(NumBaseUses)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000899 LLVM_DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
900 << "#Base=" << NumBaseUses
901 << ", #Root=" << KV.second->getNumUses() << "\n");
James Molloyf1473592015-02-11 09:19:47 +0000902 return false;
903 }
904 }
905
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000906 return true;
James Molloyf1473592015-02-11 09:19:47 +0000907}
908
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000909void LoopReroll::DAGRootTracker::
James Molloyf1473592015-02-11 09:19:47 +0000910findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
911 // Does the user look like it could be part of a root set?
912 // All its users must be simple arithmetic ops.
Davide Italiano80fe9872017-04-18 21:42:21 +0000913 if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000914 return;
James Molloyf1473592015-02-11 09:19:47 +0000915
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000916 if (I != IV && findRootsBase(I, SubsumedInsts))
917 return;
James Molloyf1473592015-02-11 09:19:47 +0000918
919 SubsumedInsts.insert(I);
920
921 for (User *V : I->users()) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000922 Instruction *I = cast<Instruction>(V);
David Majnemer0d955d02016-08-11 22:21:41 +0000923 if (is_contained(LoopIncs, I))
James Molloyf1473592015-02-11 09:19:47 +0000924 continue;
925
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000926 if (!isSimpleArithmeticOp(I))
927 continue;
928
929 // The recursive call makes a copy of SubsumedInsts.
930 findRootsRecursive(I, SubsumedInsts);
James Molloyf1473592015-02-11 09:19:47 +0000931 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000932}
933
934bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
935 if (DRS.Roots.empty())
936 return false;
937
938 // Consider a DAGRootSet with N-1 roots (so N different values including
939 // BaseInst).
940 // Define d = Roots[0] - BaseInst, which should be the same as
941 // Roots[I] - Roots[I-1] for all I in [1..N).
942 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
943 // loop iteration J.
944 //
945 // Now, For the loop iterations to be consecutive:
946 // D = d * N
947 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
948 if (!ADR)
949 return false;
950 unsigned N = DRS.Roots.size() + 1;
951 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
952 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
953 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
954 return false;
955
James Molloyf1473592015-02-11 09:19:47 +0000956 return true;
957}
958
959bool LoopReroll::DAGRootTracker::
960findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000961 // The base of a RootSet must be an AddRec, so it can be erased.
962 const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
963 if (!IVU_ADR || IVU_ADR->getLoop() != L)
James Molloyf1473592015-02-11 09:19:47 +0000964 return false;
965
966 std::map<int64_t, Instruction*> V;
967 if (!collectPossibleRoots(IVU, V))
968 return false;
969
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000970 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000971 // subsumed.
972 if (V.find(0) == V.end())
973 SubsumedInsts.insert(IVU);
974
975 // Partition the vector into monotonically increasing indexes.
976 DAGRootSet DRS;
977 DRS.BaseInst = nullptr;
978
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000979 SmallVector<DAGRootSet, 16> PotentialRootSets;
980
James Molloyf1473592015-02-11 09:19:47 +0000981 for (auto &KV : V) {
982 if (!DRS.BaseInst) {
983 DRS.BaseInst = KV.second;
984 DRS.SubsumedInsts = SubsumedInsts;
985 } else if (DRS.Roots.empty()) {
986 DRS.Roots.push_back(KV.second);
987 } else if (V.find(KV.first - 1) != V.end()) {
988 DRS.Roots.push_back(KV.second);
989 } else {
990 // Linear sequence terminated.
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000991 if (!validateRootSet(DRS))
992 return false;
993
994 // Construct a new DAGRootSet with the next sequence.
995 PotentialRootSets.push_back(DRS);
James Molloyf1473592015-02-11 09:19:47 +0000996 DRS.BaseInst = KV.second;
James Molloyf1473592015-02-11 09:19:47 +0000997 DRS.Roots.clear();
998 }
999 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001000
1001 if (!validateRootSet(DRS))
1002 return false;
1003
1004 PotentialRootSets.push_back(DRS);
1005
1006 RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
James Molloyf1473592015-02-11 09:19:47 +00001007
1008 return true;
1009}
1010
James Molloy5f255eb2015-01-29 13:48:05 +00001011bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001012 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +00001013
James Molloyf1473592015-02-11 09:19:47 +00001014 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001015 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +00001016 for (auto *IVU : IV->users()) {
1017 if (isLoopIncrement(IVU, IV))
1018 LoopIncs.push_back(cast<Instruction>(IVU));
1019 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001020 findRootsRecursive(IV, SmallInstructionSet());
James Molloyf1473592015-02-11 09:19:47 +00001021 LoopIncs.push_back(IV);
1022 } else {
1023 if (!findRootsBase(IV, SmallInstructionSet()))
1024 return false;
1025 }
James Molloy5f255eb2015-01-29 13:48:05 +00001026
James Molloyf1473592015-02-11 09:19:47 +00001027 // Ensure all sets have the same size.
1028 if (RootSets.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001029 LLVM_DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001030 return false;
James Molloyf1473592015-02-11 09:19:47 +00001031 }
1032 for (auto &V : RootSets) {
1033 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001034 LLVM_DEBUG(
1035 dbgs()
1036 << "LRR: Aborting because not all root sets have the same size\n");
James Molloyf1473592015-02-11 09:19:47 +00001037 return false;
1038 }
1039 }
James Molloy5f255eb2015-01-29 13:48:05 +00001040
James Molloyf1473592015-02-11 09:19:47 +00001041 Scale = RootSets[0].Roots.size() + 1;
1042
1043 if (Scale > IL_MaxRerollIterations) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001044 LLVM_DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
1045 << "#Found=" << Scale
1046 << ", #Max=" << IL_MaxRerollIterations << "\n");
James Molloy64419d42015-01-29 21:52:03 +00001047 return false;
1048 }
1049
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001050 LLVM_DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale
1051 << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001052
1053 return true;
1054}
1055
James Molloy64419d42015-01-29 21:52:03 +00001056bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1057 // Populate the MapVector with all instructions in the block, in order first,
1058 // so we can iterate over the contents later in perfect order.
1059 for (auto &I : *L->getHeader()) {
1060 Uses[&I].resize(IL_End);
1061 }
James Molloy5f255eb2015-01-29 13:48:05 +00001062
James Molloy64419d42015-01-29 21:52:03 +00001063 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +00001064 for (auto &DRS : RootSets) {
1065 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1066 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1067 Exclude.insert(DRS.BaseInst);
1068 }
James Molloy64419d42015-01-29 21:52:03 +00001069 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1070
James Molloyf1473592015-02-11 09:19:47 +00001071 for (auto &DRS : RootSets) {
1072 DenseSet<Instruction*> VBase;
1073 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1074 for (auto *I : VBase) {
1075 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +00001076 }
1077
James Molloyf1473592015-02-11 09:19:47 +00001078 unsigned Idx = 1;
1079 for (auto *Root : DRS.Roots) {
1080 DenseSet<Instruction*> V;
1081 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1082
1083 // While we're here, check the use sets are the same size.
1084 if (V.size() != VBase.size()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001085 LLVM_DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
James Molloyf1473592015-02-11 09:19:47 +00001086 return false;
1087 }
1088
1089 for (auto *I : V) {
1090 Uses[I].set(Idx);
1091 }
1092 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +00001093 }
James Molloyf1473592015-02-11 09:19:47 +00001094
1095 // Make sure our subsumed instructions are remembered too.
1096 for (auto *I : DRS.SubsumedInsts) {
1097 Uses[I].set(IL_All);
1098 }
James Molloy64419d42015-01-29 21:52:03 +00001099 }
1100
1101 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +00001102
James Molloy64419d42015-01-29 21:52:03 +00001103 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +00001104 for (auto &DRS : RootSets) {
1105 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1106 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1107 Exclude.insert(DRS.BaseInst);
1108 }
James Molloy64419d42015-01-29 21:52:03 +00001109
1110 DenseSet<Instruction*> V;
1111 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1112 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +00001113 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001114 }
James Molloy64419d42015-01-29 21:52:03 +00001115
1116 return true;
James Molloy64419d42015-01-29 21:52:03 +00001117}
1118
James Molloye805ad92015-02-12 15:54:14 +00001119/// Get the next instruction in "In" that is a member of set Val.
1120/// Start searching from StartI, and do not return anything in Exclude.
1121/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +00001122LoopReroll::DAGRootTracker::UsesTy::iterator
1123LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +00001124 const SmallInstructionSet &Exclude,
1125 UsesTy::iterator *StartI) {
1126 UsesTy::iterator I = StartI ? *StartI : In.begin();
1127 while (I != In.end() && (I->second.test(Val) == 0 ||
1128 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +00001129 ++I;
1130 return I;
1131}
1132
James Molloyf1473592015-02-11 09:19:47 +00001133bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1134 for (auto &DRS : RootSets) {
1135 if (DRS.BaseInst == I)
1136 return true;
1137 }
1138 return false;
1139}
1140
1141bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1142 for (auto &DRS : RootSets) {
David Majnemer0d955d02016-08-11 22:21:41 +00001143 if (is_contained(DRS.Roots, I))
James Molloyf1473592015-02-11 09:19:47 +00001144 return true;
1145 }
1146 return false;
1147}
1148
James Molloye805ad92015-02-12 15:54:14 +00001149/// Return true if instruction I depends on any instruction between
1150/// Start and End.
1151bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1152 UsesTy::iterator Start,
1153 UsesTy::iterator End) {
1154 for (auto *U : I->users()) {
1155 for (auto It = Start; It != End; ++It)
1156 if (U == It->first)
1157 return true;
1158 }
1159 return false;
1160}
1161
Weiming Zhao310770a2015-09-28 17:03:23 +00001162static bool isIgnorableInst(const Instruction *I) {
1163 if (isa<DbgInfoIntrinsic>(I))
1164 return true;
1165 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1166 if (!II)
1167 return false;
1168 switch (II->getIntrinsicID()) {
1169 default:
1170 return false;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001171 case Intrinsic::annotation:
Weiming Zhao310770a2015-09-28 17:03:23 +00001172 case Intrinsic::ptr_annotation:
1173 case Intrinsic::var_annotation:
1174 // TODO: the following intrinsics may also be whitelisted:
1175 // lifetime_start, lifetime_end, invariant_start, invariant_end
1176 return true;
1177 }
1178 return false;
1179}
1180
James Molloy64419d42015-01-29 21:52:03 +00001181bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001182 // We now need to check for equivalence of the use graph of each root with
1183 // that of the primary induction variable (excluding the roots). Our goal
1184 // here is not to solve the full graph isomorphism problem, but rather to
1185 // catch common cases without a lot of work. As a result, we will assume
1186 // that the relative order of the instructions in each unrolled iteration
1187 // is the same (although we will not make an assumption about how the
1188 // different iterations are intermixed). Note that while the order must be
1189 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001190
1191 // An array of just the possible reductions for this scale factor. When we
1192 // collect the set of all users of some root instructions, these reduction
1193 // instructions are treated as 'final' (their uses are not considered).
1194 // This is important because we don't want the root use set to search down
1195 // the reduction chain.
1196 SmallInstructionSet PossibleRedSet;
1197 SmallInstructionSet PossibleRedLastSet;
1198 SmallInstructionSet PossibleRedPHISet;
1199 Reductions.restrictToScale(Scale, PossibleRedSet,
1200 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001201
James Molloy64419d42015-01-29 21:52:03 +00001202 // Populate "Uses" with where each instruction is used.
1203 if (!collectUsedInstructions(PossibleRedSet))
1204 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001205
James Molloy64419d42015-01-29 21:52:03 +00001206 // Make sure we mark the reduction PHIs as used in all iterations.
1207 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001208 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001209 }
James Molloy5f255eb2015-01-29 13:48:05 +00001210
Lawrence Hu1befea22016-04-30 00:51:22 +00001211 // Make sure we mark loop-control-only PHIs as used in all iterations. See
1212 // comment above LoopReroll::isLoopControlIV for more information.
1213 BasicBlock *Header = L->getHeader();
1214 if (LoopControlIV && LoopControlIV != IV) {
1215 for (auto *U : LoopControlIV->users()) {
1216 Instruction *IVUser = dyn_cast<Instruction>(U);
1217 // IVUser could be loop increment or compare
1218 Uses[IVUser].set(IL_All);
1219 for (auto *UU : IVUser->users()) {
1220 Instruction *UUser = dyn_cast<Instruction>(UU);
1221 // UUser could be compare, PHI or branch
1222 Uses[UUser].set(IL_All);
Lawrence Hue58a8142016-05-10 21:16:49 +00001223 // Skip SExt
1224 if (isa<SExtInst>(UUser)) {
1225 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1226 Uses[UUser].set(IL_All);
1227 }
Lawrence Hu1befea22016-04-30 00:51:22 +00001228 // Is UUser a compare instruction?
1229 if (UU->hasOneUse()) {
1230 Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1231 if (BI == cast<BranchInst>(Header->getTerminator()))
1232 Uses[BI].set(IL_All);
1233 }
1234 }
1235 }
1236 }
1237
James Molloy64419d42015-01-29 21:52:03 +00001238 // Make sure all instructions in the loop are in one and only one
1239 // set.
1240 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001241 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001242 LLVM_DEBUG(
1243 dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1244 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
James Molloy64419d42015-01-29 21:52:03 +00001245 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001246 }
James Molloy64419d42015-01-29 21:52:03 +00001247 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001248
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001249 LLVM_DEBUG(for (auto &KV
1250 : Uses) {
1251 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1252 });
James Molloy64419d42015-01-29 21:52:03 +00001253
1254 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001255 // In addition to regular aliasing information, we need to look for
1256 // instructions from later (future) iterations that have side effects
1257 // preventing us from reordering them past other instructions with side
1258 // effects.
1259 bool FutureSideEffects = false;
1260 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001261 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1262 DenseMap<Value *, Value *> BaseMap;
1263
James Molloy64419d42015-01-29 21:52:03 +00001264 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001265 SmallInstructionSet Visited;
1266 auto BaseIt = nextInstr(0, Uses, Visited);
1267 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001268 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001269
James Molloy64419d42015-01-29 21:52:03 +00001270 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1271 Instruction *BaseInst = BaseIt->first;
1272 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001273
James Molloy64419d42015-01-29 21:52:03 +00001274 // Skip over the IV or root instructions; only match their users.
1275 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001276 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001277 Visited.insert(BaseInst);
1278 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001279 Continue = true;
1280 }
James Molloyf1473592015-02-11 09:19:47 +00001281 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001282 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001283 Visited.insert(RootInst);
1284 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001285 Continue = true;
1286 }
1287 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001288
James Molloye805ad92015-02-12 15:54:14 +00001289 if (!BaseInst->isSameOperationAs(RootInst)) {
1290 // Last chance saloon. We don't try and solve the full isomorphism
1291 // problem, but try and at least catch the case where two instructions
1292 // *of different types* are round the wrong way. We won't be able to
1293 // efficiently tell, given two ADD instructions, which way around we
1294 // should match them, but given an ADD and a SUB, we can at least infer
1295 // which one is which.
1296 //
1297 // This should allow us to deal with a greater subset of the isomorphism
1298 // problem. It does however change a linear algorithm into a quadratic
1299 // one, so limit the number of probes we do.
1300 auto TryIt = RootIt;
1301 unsigned N = NumToleratedFailedMatches;
1302 while (TryIt != Uses.end() &&
1303 !BaseInst->isSameOperationAs(TryIt->first) &&
1304 N--) {
1305 ++TryIt;
1306 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1307 }
1308
1309 if (TryIt == Uses.end() || TryIt == RootIt ||
1310 instrDependsOn(TryIt->first, RootIt, TryIt)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001311 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1312 << *BaseInst << " vs. " << *RootInst << "\n");
James Molloye805ad92015-02-12 15:54:14 +00001313 return false;
1314 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001315
James Molloye805ad92015-02-12 15:54:14 +00001316 RootIt = TryIt;
1317 RootInst = TryIt->first;
1318 }
1319
James Molloy64419d42015-01-29 21:52:03 +00001320 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001321 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001322 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001323 //
James Molloye805ad92015-02-12 15:54:14 +00001324 // Note that because we allow a limited amount of flexibility in the order
1325 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1326 // case we've already checked this set of instructions so we shouldn't
1327 // do anything.
1328 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001329 Instruction *I = LastRootIt->first;
1330 if (LastRootIt->second.find_first() < (int)Iter)
1331 continue;
1332 if (I->mayWriteToMemory())
1333 AST.add(I);
1334 // Note: This is specifically guarded by a check on isa<PHINode>,
1335 // which while a valid (somewhat arbitrary) micro-optimization, is
1336 // needed because otherwise isSafeToSpeculativelyExecute returns
1337 // false on PHI nodes.
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001338 if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001339 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001340 // Intervening instructions cause side effects.
1341 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001342 }
1343
James Molloy5f255eb2015-01-29 13:48:05 +00001344 // Make sure that this instruction, which is in the use set of this
1345 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001346 // some other root instruction.
1347 if (RootIt->second.count() > 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001348 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1349 << " vs. " << *RootInst << " (prev. case overlap)\n");
James Molloy64419d42015-01-29 21:52:03 +00001350 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001351 }
1352
1353 // Make sure that we don't alias with any instruction in the alias set
1354 // tracker. If we do, then we depend on a future iteration, and we
1355 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001356 if (RootInst->mayReadFromMemory())
1357 for (auto &K : AST) {
1358 if (K.aliasesUnknownInst(RootInst, *AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001359 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1360 << *BaseInst << " vs. " << *RootInst
1361 << " (depends on future store)\n");
James Molloy64419d42015-01-29 21:52:03 +00001362 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001363 }
1364 }
James Molloy5f255eb2015-01-29 13:48:05 +00001365
1366 // If we've past an instruction from a future iteration that may have
1367 // side effects, and this instruction might also, then we can't reorder
1368 // them, and this matching fails. As an exception, we allow the alias
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001369 // set tracker to handle regular (unordered) load/store dependencies.
1370 if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001371 !isSafeToSpeculativelyExecute(BaseInst)) ||
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001372 (!isUnorderedLoadStore(RootInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001373 !isSafeToSpeculativelyExecute(RootInst)))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001374 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1375 << " vs. " << *RootInst
1376 << " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001377 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001378 }
1379
1380 // For instructions that are part of a reduction, if the operation is
1381 // associative, then don't bother matching the operands (because we
1382 // already know that the instructions are isomorphic, and the order
1383 // within the iteration does not matter). For non-associative reductions,
1384 // we do need to match the operands, because we need to reject
1385 // out-of-order instructions within an iteration!
1386 // For example (assume floating-point addition), we need to reject this:
1387 // x += a[i]; x += b[i];
1388 // x += a[i+1]; x += b[i+1];
1389 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001390 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001391
James Molloy64419d42015-01-29 21:52:03 +00001392 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001393 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001394 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1395 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001396
1397 // If this is part of a reduction (and the operation is not
1398 // associatve), then we match all operands, but not those that are
1399 // part of the reduction.
1400 if (InReduction)
1401 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001402 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001403 continue;
1404
1405 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001406 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001407 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001408 } else {
1409 for (auto &DRS : RootSets) {
1410 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1411 Op2 = DRS.BaseInst;
1412 break;
1413 }
1414 }
1415 }
James Molloy5f255eb2015-01-29 13:48:05 +00001416
James Molloy64419d42015-01-29 21:52:03 +00001417 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001418 // If we've not already decided to swap the matched operands, and
1419 // we've not already matched our first operand (note that we could
1420 // have skipped matching the first operand because it is part of a
1421 // reduction above), and the instruction is commutative, then try
1422 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001423 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1424 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001425 Swapped = true;
1426 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001427 LLVM_DEBUG(dbgs()
1428 << "LRR: iteration root match failed at " << *BaseInst
1429 << " vs. " << *RootInst << " (operand " << j << ")\n");
James Molloy64419d42015-01-29 21:52:03 +00001430 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001431 }
1432 }
1433
1434 SomeOpMatched = true;
1435 }
1436 }
1437
James Molloy64419d42015-01-29 21:52:03 +00001438 if ((!PossibleRedLastSet.count(BaseInst) &&
1439 hasUsesOutsideLoop(BaseInst, L)) ||
1440 (!PossibleRedLastSet.count(RootInst) &&
1441 hasUsesOutsideLoop(RootInst, L))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001442 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1443 << " vs. " << *RootInst << " (uses outside loop)\n");
James Molloy64419d42015-01-29 21:52:03 +00001444 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001445 }
1446
James Molloy64419d42015-01-29 21:52:03 +00001447 Reductions.recordPair(BaseInst, RootInst, Iter);
1448 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001449
James Molloy64419d42015-01-29 21:52:03 +00001450 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001451 Visited.insert(BaseInst);
1452 Visited.insert(RootInst);
1453 BaseIt = nextInstr(0, Uses, Visited);
1454 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001455 }
Eugene Zelenko306d2992017-10-18 21:46:47 +00001456 assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
1457 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001458 }
1459
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001460 LLVM_DEBUG(dbgs() << "LRR: Matched all iteration increments for " << *IV
1461 << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001462
Hal Finkelbf45efd2013-11-16 23:59:05 +00001463 return true;
1464}
1465
James Molloy5f255eb2015-01-29 13:48:05 +00001466void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1467 BasicBlock *Header = L->getHeader();
1468 // Remove instructions associated with non-base iterations.
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001469 for (BasicBlock::reverse_iterator J = Header->rbegin(), JE = Header->rend();
1470 J != JE;) {
James Molloy64419d42015-01-29 21:52:03 +00001471 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001472 if (I > 0 && I < IL_All) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001473 LLVM_DEBUG(dbgs() << "LRR: removing: " << *J << "\n");
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001474 J++->eraseFromParent();
James Molloy5f255eb2015-01-29 13:48:05 +00001475 continue;
1476 }
1477
1478 ++J;
1479 }
1480
Lawrence Hu1befea22016-04-30 00:51:22 +00001481 bool HasTwoIVs = LoopControlIV && LoopControlIV != IV;
1482
1483 if (HasTwoIVs) {
1484 updateNonLoopCtrlIncr();
1485 replaceIV(LoopControlIV, LoopControlIV, IterCount);
1486 } else
1487 // We need to create a new induction variable for each different BaseInst.
1488 for (auto &DRS : RootSets)
1489 // Insert the new induction variable.
1490 replaceIV(DRS.BaseInst, IV, IterCount);
Lawrence Hub917cd92016-01-25 19:36:30 +00001491
1492 SimplifyInstructionsInBlock(Header, TLI);
1493 DeleteDeadPHIs(Header, TLI);
Lawrence Hu84b61952016-01-25 18:53:39 +00001494}
1495
Lawrence Hu1befea22016-04-30 00:51:22 +00001496// For non-loop-control IVs, we only need to update the last increment
1497// with right amount, then we are done.
1498void LoopReroll::DAGRootTracker::updateNonLoopCtrlIncr() {
1499 const SCEV *NewInc = nullptr;
1500 for (auto *LoopInc : LoopIncs) {
1501 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LoopInc);
1502 const SCEVConstant *COp = nullptr;
1503 if (GEP && LoopInc->getOperand(0)->getType()->isPointerTy()) {
1504 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1505 } else {
1506 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(0)));
1507 if (!COp)
1508 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1509 }
1510
1511 assert(COp && "Didn't find constant operand of LoopInc!\n");
1512
1513 const APInt &AInt = COp->getValue()->getValue();
1514 const SCEV *ScaleSCEV = SE->getConstant(COp->getType(), Scale);
1515 if (AInt.isNegative()) {
1516 NewInc = SE->getNegativeSCEV(COp);
1517 NewInc = SE->getUDivExpr(NewInc, ScaleSCEV);
1518 NewInc = SE->getNegativeSCEV(NewInc);
1519 } else
1520 NewInc = SE->getUDivExpr(COp, ScaleSCEV);
1521
1522 LoopInc->setOperand(1, dyn_cast<SCEVConstant>(NewInc)->getValue());
1523 }
1524}
1525
Lawrence Hud3d51062016-01-25 19:43:45 +00001526void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1527 Instruction *InstIV,
1528 const SCEV *IterCount) {
1529 BasicBlock *Header = L->getHeader();
1530 int64_t Inc = IVToIncMap[InstIV];
Lawrence Hu1befea22016-04-30 00:51:22 +00001531 bool NeedNewIV = InstIV == LoopControlIV;
1532 bool Negative = !NeedNewIV && Inc < 0;
Lawrence Hud3d51062016-01-25 19:43:45 +00001533
1534 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1535 const SCEV *Start = RealIVSCEV->getStart();
1536
Lawrence Hu1befea22016-04-30 00:51:22 +00001537 if (NeedNewIV)
1538 Start = SE->getConstant(Start->getType(), 0);
1539
Lawrence Hud3d51062016-01-25 19:43:45 +00001540 const SCEV *SizeOfExpr = nullptr;
1541 const SCEV *IncrExpr =
1542 SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1543 if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1544 Type *ElTy = PTy->getElementType();
1545 SizeOfExpr =
1546 SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1547 IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1548 }
1549 const SCEV *NewIVSCEV =
1550 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1551
1552 { // Limit the lifetime of SCEVExpander.
1553 const DataLayout &DL = Header->getModule()->getDataLayout();
1554 SCEVExpander Expander(*SE, DL, "reroll");
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001555 Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
1556 Header->getFirstNonPHIOrDbg());
Lawrence Hud3d51062016-01-25 19:43:45 +00001557
1558 for (auto &KV : Uses)
1559 if (KV.second.find_first() == 0)
1560 KV.first->replaceUsesOfWith(Inst, NewIV);
1561
1562 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1563 // FIXME: Why do we need this check?
1564 if (Uses[BI].find_first() == IL_All) {
1565 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1566
Lawrence Hu1befea22016-04-30 00:51:22 +00001567 if (NeedNewIV)
1568 ICSCEV = SE->getMulExpr(IterCount,
1569 SE->getConstant(IterCount->getType(), Scale));
Lawrence Hu1befea22016-04-30 00:51:22 +00001570
Lawrence Hud3d51062016-01-25 19:43:45 +00001571 // Iteration count SCEV minus or plus 1
1572 const SCEV *MinusPlus1SCEV =
1573 SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1574 if (Inst->getType()->isPointerTy()) {
1575 assert(SizeOfExpr && "SizeOfExpr is not initialized");
1576 MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1577 }
1578
1579 const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1580 // Iteration count minus 1
Lawrence Hue58a8142016-05-10 21:16:49 +00001581 Instruction *InsertPtr = nullptr;
Lawrence Hud3d51062016-01-25 19:43:45 +00001582 if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
Lawrence Hue58a8142016-05-10 21:16:49 +00001583 InsertPtr = BI;
Lawrence Hud3d51062016-01-25 19:43:45 +00001584 } else {
1585 BasicBlock *Preheader = L->getLoopPreheader();
1586 if (!Preheader)
1587 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
Lawrence Hue58a8142016-05-10 21:16:49 +00001588 InsertPtr = Preheader->getTerminator();
Lawrence Hud3d51062016-01-25 19:43:45 +00001589 }
1590
Lawrence Hue58a8142016-05-10 21:16:49 +00001591 if (!isa<PointerType>(NewIV->getType()) && NeedNewIV &&
1592 (SE->getTypeSizeInBits(NewIV->getType()) <
1593 SE->getTypeSizeInBits(ICMinusPlus1SCEV->getType()))) {
1594 IRBuilder<> Builder(BI);
1595 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
1596 NewIV = Builder.CreateSExt(NewIV, ICMinusPlus1SCEV->getType());
1597 }
1598 Value *ICMinusPlus1 = Expander.expandCodeFor(
1599 ICMinusPlus1SCEV, NewIV->getType(), InsertPtr);
1600
Lawrence Hud3d51062016-01-25 19:43:45 +00001601 Value *Cond =
1602 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1603 BI->setCondition(Cond);
1604
1605 if (BI->getSuccessor(1) != Header)
1606 BI->swapSuccessors();
1607 }
1608 }
1609 }
1610}
1611
Hal Finkelbf45efd2013-11-16 23:59:05 +00001612// Validate the selected reductions. All iterations must have an isomorphic
1613// part of the reduction chain and, for non-associative reductions, the chain
1614// entries must appear in order.
1615bool LoopReroll::ReductionTracker::validateSelected() {
1616 // For a non-associative reduction, the chain entries must appear in order.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001617 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001618 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001619 for (Instruction *J : PossibleReds[i]) {
1620 // Note that all instructions in the chain must have been found because
1621 // all instructions in the function must have been assigned to some
1622 // iteration.
1623 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001624 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1625 !PossibleReds[i].getReducedValue()->isAssociative()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001626 LLVM_DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: "
1627 << J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001628 return false;
1629 }
1630
1631 if (Iter != PrevIter) {
1632 if (Count != BaseCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001633 LLVM_DEBUG(dbgs()
1634 << "LRR: Iteration " << PrevIter << " reduction use count "
1635 << Count << " is not equal to the base use count "
1636 << BaseCount << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001637 return false;
1638 }
1639
1640 Count = 0;
1641 }
1642
1643 ++Count;
1644 if (Iter == 0)
1645 ++BaseCount;
1646
1647 PrevIter = Iter;
1648 }
1649 }
1650
1651 return true;
1652}
1653
1654// For all selected reductions, remove all parts except those in the first
1655// iteration (and the PHI). Replace outside uses of the reduced value with uses
1656// of the first-iteration reduced value (in other words, reroll the selected
1657// reductions).
1658void LoopReroll::ReductionTracker::replaceSelected() {
1659 // Fixup reductions to refer to the last instruction associated with the
1660 // first iteration (not the last).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001661 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001662 int j = 0;
1663 for (int e = PossibleReds[i].size(); j != e; ++j)
1664 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1665 --j;
1666 break;
1667 }
1668
1669 // Replace users with the new end-of-chain value.
1670 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001671 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001672 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001673 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001674
Benjamin Kramer135f7352016-06-26 12:28:59 +00001675 for (Instruction *User : Users)
1676 User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
Hal Finkelbf45efd2013-11-16 23:59:05 +00001677 PossibleReds[i][j]);
1678 }
1679}
1680
1681// Reroll the provided loop with respect to the provided induction variable.
1682// Generally, we're looking for a loop like this:
1683//
1684// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1685// f(%iv)
1686// %iv.1 = add %iv, 1 <-- a root increment
1687// f(%iv.1)
1688// %iv.2 = add %iv, 2 <-- a root increment
1689// f(%iv.2)
1690// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1691// f(%iv.scale_m_1)
1692// ...
1693// %iv.next = add %iv, scale
1694// %cmp = icmp(%iv, ...)
1695// br %cmp, header, exit
1696//
1697// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1698// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1699// be intermixed with eachother. The restriction imposed by this algorithm is
1700// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1701// etc. be the same.
1702//
1703// First, we collect the use set of %iv, excluding the other increment roots.
1704// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1705// times, having collected the use set of f(%iv.(i+1)), during which we:
1706// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1707// the next unmatched instruction in f(%iv.(i+1)).
1708// - Ensure that both matched instructions don't have any external users
1709// (with the exception of last-in-chain reduction instructions).
1710// - Track the (aliasing) write set, and other side effects, of all
1711// instructions that belong to future iterations that come before the matched
1712// instructions. If the matched instructions read from that write set, then
1713// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1714// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1715// if any of these future instructions had side effects (could not be
1716// speculatively executed), and so do the matched instructions, when we
1717// cannot reorder those side-effect-producing instructions, and rerolling
1718// fails.
1719//
1720// Finally, we make sure that all loop instructions are either loop increment
1721// roots, belong to simple latch code, parts of validated reductions, part of
1722// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1723// have been validated), then we reroll the loop.
1724bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1725 const SCEV *IterCount,
1726 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001727 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +00001728 IVToIncMap, LoopControlIV);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001729
James Molloy5f255eb2015-01-29 13:48:05 +00001730 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001731 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001732 LLVM_DEBUG(dbgs() << "LRR: Found all root induction increments for: " << *IV
1733 << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001734
James Molloy5f255eb2015-01-29 13:48:05 +00001735 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001736 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001737 if (!Reductions.validateSelected())
1738 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001739 // At this point, we've validated the rerolling, and we're committed to
1740 // making changes!
1741
1742 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001743 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001744
Hal Finkelbf45efd2013-11-16 23:59:05 +00001745 ++NumRerolledLoops;
1746 return true;
1747}
1748
1749bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001750 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001751 return false;
1752
Chandler Carruth7b560d42015-09-09 17:55:00 +00001753 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001754 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001755 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001756 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001757 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001758 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001759
1760 BasicBlock *Header = L->getHeader();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001761 LLVM_DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << "] Loop %"
1762 << Header->getName() << " (" << L->getNumBlocks()
1763 << " block(s))\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001764
Hal Finkelbf45efd2013-11-16 23:59:05 +00001765 // For now, we'll handle only single BB loops.
1766 if (L->getNumBlocks() > 1)
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001767 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001768
1769 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001770 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001771
1772 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001773 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001774 LLVM_DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
1775 LLVM_DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001776
1777 // First, we need to find the induction variable with respect to which we can
1778 // reroll (there may be several possible options).
1779 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001780 IVToIncMap.clear();
Lawrence Hu1befea22016-04-30 00:51:22 +00001781 LoopControlIV = nullptr;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001782 collectPossibleIVs(L, PossibleIVs);
1783
1784 if (PossibleIVs.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << "LRR: No possible IVs found\n");
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001786 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001787 }
1788
1789 ReductionTracker Reductions;
1790 collectPossibleReductions(L, Reductions);
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001791 bool Changed = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001792
1793 // For each possible IV, collect the associated possible set of 'root' nodes
1794 // (i+1, i+2, etc.).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001795 for (Instruction *PossibleIV : PossibleIVs)
1796 if (reroll(PossibleIV, L, Header, IterCount, Reductions)) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001797 Changed = true;
1798 break;
1799 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001800 LLVM_DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001801
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001802 // Trip count of L has changed so SE must be re-evaluated.
1803 if (Changed)
1804 SE->forgetLoop(L);
1805
Hal Finkelbf45efd2013-11-16 23:59:05 +00001806 return Changed;
1807}