blob: 166b57f20b43fadb7a59c01e824dece53b2a37cb [file] [log] [blame]
Eugene Zelenko306d2992017-10-18 21:46:47 +00001//===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
Hal Finkelbf45efd2013-11-16 23:59:05 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Hal Finkelbf45efd2013-11-16 23:59:05 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements a simple loop reroller.
10//
11//===----------------------------------------------------------------------===//
12
Eugene Zelenko306d2992017-10-18 21:46:47 +000013#include "llvm/ADT/APInt.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/ADT/BitVector.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
James Molloy64419d42015-01-29 21:52:03 +000017#include "llvm/ADT/MapVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/STLExtras.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000020#include "llvm/ADT/SmallVector.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000021#include "llvm/ADT/Statistic.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/AliasSetTracker.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000024#include "llvm/Analysis/LoopInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000025#include "llvm/Analysis/LoopPass.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000030#include "llvm/Transforms/Utils/Local.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000032#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000034#include "llvm/IR/DataLayout.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000035#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000037#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000041#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000042#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Use.h"
46#include "llvm/IR/User.h"
47#include "llvm/IR/Value.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/Casting.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000050#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000053#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000054#include "llvm/Transforms/Utils.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000056#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000057#include <cassert>
58#include <cstddef>
59#include <cstdint>
60#include <cstdlib>
61#include <iterator>
62#include <map>
63#include <utility>
Hal Finkelbf45efd2013-11-16 23:59:05 +000064
65using namespace llvm;
66
Chandler Carruth964daaa2014-04-22 02:55:47 +000067#define DEBUG_TYPE "loop-reroll"
68
Hal Finkelbf45efd2013-11-16 23:59:05 +000069STATISTIC(NumRerolledLoops, "Number of rerolled loops");
70
71static cl::opt<unsigned>
James Molloye805ad92015-02-12 15:54:14 +000072NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
73 cl::Hidden,
74 cl::desc("The maximum number of failures to tolerate"
75 " during fuzzy matching. (default: 400)"));
76
Hal Finkelbf45efd2013-11-16 23:59:05 +000077// This loop re-rolling transformation aims to transform loops like this:
78//
79// int foo(int a);
80// void bar(int *x) {
81// for (int i = 0; i < 500; i += 3) {
82// foo(i);
83// foo(i+1);
84// foo(i+2);
85// }
86// }
87//
88// into a loop like this:
89//
90// void bar(int *x) {
91// for (int i = 0; i < 500; ++i)
92// foo(i);
93// }
94//
95// It does this by looking for loops that, besides the latch code, are composed
96// of isomorphic DAGs of instructions, with each DAG rooted at some increment
97// to the induction variable, and where each DAG is isomorphic to the DAG
98// rooted at the induction variable (excepting the sub-DAGs which root the
99// other induction-variable increments). In other words, we're looking for loop
100// bodies of the form:
101//
102// %iv = phi [ (preheader, ...), (body, %iv.next) ]
103// f(%iv)
104// %iv.1 = add %iv, 1 <-- a root increment
105// f(%iv.1)
106// %iv.2 = add %iv, 2 <-- a root increment
107// f(%iv.2)
108// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
109// f(%iv.scale_m_1)
110// ...
111// %iv.next = add %iv, scale
112// %cmp = icmp(%iv, ...)
113// br %cmp, header, exit
114//
115// where each f(i) is a set of instructions that, collectively, are a function
116// only of i (and other loop-invariant values).
117//
118// As a special case, we can also reroll loops like this:
119//
120// int foo(int);
121// void bar(int *x) {
122// for (int i = 0; i < 500; ++i) {
123// x[3*i] = foo(0);
124// x[3*i+1] = foo(0);
125// x[3*i+2] = foo(0);
126// }
127// }
128//
129// into this:
130//
131// void bar(int *x) {
132// for (int i = 0; i < 1500; ++i)
133// x[i] = foo(0);
134// }
135//
136// in which case, we're looking for inputs like this:
137//
138// %iv = phi [ (preheader, ...), (body, %iv.next) ]
139// %scaled.iv = mul %iv, scale
140// f(%scaled.iv)
141// %scaled.iv.1 = add %scaled.iv, 1
142// f(%scaled.iv.1)
143// %scaled.iv.2 = add %scaled.iv, 2
144// f(%scaled.iv.2)
145// %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
146// f(%scaled.iv.scale_m_1)
147// ...
148// %iv.next = add %iv, 1
149// %cmp = icmp(%iv, ...)
150// br %cmp, header, exit
151
152namespace {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000153
James Molloy64419d42015-01-29 21:52:03 +0000154 enum IterationLimits {
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000155 /// The maximum number of iterations that we'll try and reroll.
156 IL_MaxRerollIterations = 32,
James Molloy64419d42015-01-29 21:52:03 +0000157 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000158 /// instructions that belong to all iterations.
159 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000160 IL_End
161 };
162
Hal Finkelbf45efd2013-11-16 23:59:05 +0000163 class LoopReroll : public LoopPass {
164 public:
165 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko306d2992017-10-18 21:46:47 +0000166
Hal Finkelbf45efd2013-11-16 23:59:05 +0000167 LoopReroll() : LoopPass(ID) {
168 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
169 }
170
Craig Topper3e4c6972014-03-05 09:10:37 +0000171 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000172
Craig Topper3e4c6972014-03-05 09:10:37 +0000173 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000174 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000175 getLoopAnalysisUsage(AU);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000176 }
177
James Molloy64419d42015-01-29 21:52:03 +0000178 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000179 AliasAnalysis *AA;
180 LoopInfo *LI;
181 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000182 TargetLibraryInfo *TLI;
183 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000184 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000185
Eugene Zelenko306d2992017-10-18 21:46:47 +0000186 using SmallInstructionVector = SmallVector<Instruction *, 16>;
Craig Topper61998282018-06-09 05:04:20 +0000187 using SmallInstructionSet = SmallPtrSet<Instruction *, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000188
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000189 // Map between induction variable and its increment
190 DenseMap<Instruction *, int64_t> IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000191
Lawrence Hu1befea22016-04-30 00:51:22 +0000192 // For loop with multiple induction variable, remember the one used only to
193 // control the loop.
194 Instruction *LoopControlIV;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000195
196 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000197 // representing a reduction. Only the last value may be used outside the
198 // loop.
199 struct SimpleLoopReduction {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000200 SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000201 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
202 add(L);
203 }
204
205 bool valid() const {
206 return Valid;
207 }
208
209 Instruction *getPHI() const {
210 assert(Valid && "Using invalid reduction");
211 return Instructions.front();
212 }
213
214 Instruction *getReducedValue() const {
215 assert(Valid && "Using invalid reduction");
216 return Instructions.back();
217 }
218
219 Instruction *get(size_t i) const {
220 assert(Valid && "Using invalid reduction");
221 return Instructions[i+1];
222 }
223
224 Instruction *operator [] (size_t i) const { return get(i); }
225
226 // The size, ignoring the initial PHI.
227 size_t size() const {
228 assert(Valid && "Using invalid reduction");
229 return Instructions.size()-1;
230 }
231
Eugene Zelenko306d2992017-10-18 21:46:47 +0000232 using iterator = SmallInstructionVector::iterator;
233 using const_iterator = SmallInstructionVector::const_iterator;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000234
235 iterator begin() {
236 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000237 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000238 }
239
240 const_iterator begin() const {
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 iterator end() { return Instructions.end(); }
246 const_iterator end() const { return Instructions.end(); }
247
248 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000249 bool Valid = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000250 SmallInstructionVector Instructions;
251
252 void add(Loop *L);
253 };
254
255 // The set of all reductions, and state tracking of possible reductions
256 // during loop instruction processing.
257 struct ReductionTracker {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000258 using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000259
260 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000261 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000262
263 // Setup to track possible reductions corresponding to the provided
264 // rerolling scale. Only reductions with a number of non-PHI instructions
265 // that is divisible by the scale are considered. Three instructions sets
266 // are filled in:
267 // - A set of all possible instructions in eligible reductions.
268 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000269 // - A set of all reduced values (last instructions) in eligible
270 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000271 void restrictToScale(uint64_t Scale,
272 SmallInstructionSet &PossibleRedSet,
273 SmallInstructionSet &PossibleRedPHISet,
274 SmallInstructionSet &PossibleRedLastSet) {
275 PossibleRedIdx.clear();
276 PossibleRedIter.clear();
277 Reds.clear();
278
279 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
280 if (PossibleReds[i].size() % Scale == 0) {
281 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
282 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000283
Hal Finkelbf45efd2013-11-16 23:59:05 +0000284 PossibleRedSet.insert(PossibleReds[i].getPHI());
285 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000286 for (Instruction *J : PossibleReds[i]) {
287 PossibleRedSet.insert(J);
288 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000289 }
290 }
291 }
292
293 // The functions below are used while processing the loop instructions.
294
295 // Are the two instructions both from reductions, and furthermore, from
296 // the same reduction?
297 bool isPairInSame(Instruction *J1, Instruction *J2) {
298 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
299 if (J1I != PossibleRedIdx.end()) {
300 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
301 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
302 return true;
303 }
304
305 return false;
306 }
307
308 // The two provided instructions, the first from the base iteration, and
309 // the second from iteration i, form a matched pair. If these are part of
310 // a reduction, record that fact.
311 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
312 if (PossibleRedIdx.count(J1)) {
313 assert(PossibleRedIdx.count(J2) &&
314 "Recording reduction vs. non-reduction instruction?");
315
316 PossibleRedIter[J1] = 0;
317 PossibleRedIter[J2] = i;
318
319 int Idx = PossibleRedIdx[J1];
320 assert(Idx == PossibleRedIdx[J2] &&
321 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000322 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000323 }
324 }
325
326 // The functions below can be called after we've finished processing all
327 // instructions in the loop, and we know which reductions were selected.
328
Hal Finkelbf45efd2013-11-16 23:59:05 +0000329 bool validateSelected();
330 void replaceSelected();
331
332 protected:
333 // The vector of all possible reductions (for any scale).
334 SmallReductionVector PossibleReds;
335
336 DenseMap<Instruction *, int> PossibleRedIdx;
337 DenseMap<Instruction *, int> PossibleRedIter;
338 DenseSet<int> Reds;
339 };
340
James Molloyf1473592015-02-11 09:19:47 +0000341 // A DAGRootSet models an induction variable being used in a rerollable
342 // loop. For example,
343 //
344 // x[i*3+0] = y1
345 // x[i*3+1] = y2
346 // x[i*3+2] = y3
347 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000348 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000349 // +---+----+
350 // / | \
351 // ST[y1] +1 +2 <-- Roots
352 // | |
353 // ST[y2] ST[y3]
354 //
355 // There may be multiple DAGRoots, for example:
356 //
357 // x[i*2+0] = ... (1)
358 // x[i*2+1] = ... (1)
359 // x[i*2+4] = ... (2)
360 // x[i*2+5] = ... (2)
361 // x[(i+1234)*2+5678] = ... (3)
362 // x[(i+1234)*2+5679] = ... (3)
363 //
364 // The loop will be rerolled by adding a new loop induction variable,
365 // one for the Base instruction in each DAGRootSet.
366 //
367 struct DAGRootSet {
368 Instruction *BaseInst;
369 SmallInstructionVector Roots;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000370
James Molloyf1473592015-02-11 09:19:47 +0000371 // The instructions between IV and BaseInst (but not including BaseInst).
372 SmallInstructionSet SubsumedInsts;
373 };
374
James Molloy5f255eb2015-01-29 13:48:05 +0000375 // The set of all DAG roots, and state tracking of all roots
376 // for a particular induction variable.
377 struct DAGRootTracker {
378 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
379 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000380 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
381 bool PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +0000382 DenseMap<Instruction *, int64_t> &IncrMap,
383 Instruction *LoopCtrlIV)
Justin Bogner843fb202015-12-15 19:40:57 +0000384 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
Lawrence Hu1befea22016-04-30 00:51:22 +0000385 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
386 LoopControlIV(LoopCtrlIV) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000387
388 /// Stage 1: Find all the DAG roots for the induction variable.
389 bool findRoots();
Eugene Zelenko306d2992017-10-18 21:46:47 +0000390
James Molloy5f255eb2015-01-29 13:48:05 +0000391 /// Stage 2: Validate if the found roots are valid.
392 bool validate(ReductionTracker &Reductions);
Eugene Zelenko306d2992017-10-18 21:46:47 +0000393
James Molloy5f255eb2015-01-29 13:48:05 +0000394 /// Stage 3: Assuming validate() returned true, perform the
395 /// replacement.
Eli Friedman203eaaf2018-06-22 22:58:55 +0000396 /// @param BackedgeTakenCount The backedge-taken count of L.
397 void replace(const SCEV *BackedgeTakenCount);
James Molloy5f255eb2015-01-29 13:48:05 +0000398
399 protected:
Eugene Zelenko306d2992017-10-18 21:46:47 +0000400 using UsesTy = MapVector<Instruction *, BitVector>;
James Molloy64419d42015-01-29 21:52:03 +0000401
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000402 void findRootsRecursive(Instruction *IVU,
James Molloyf1473592015-02-11 09:19:47 +0000403 SmallInstructionSet SubsumedInsts);
404 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
405 bool collectPossibleRoots(Instruction *Base,
406 std::map<int64_t,Instruction*> &Roots);
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000407 bool validateRootSet(DAGRootSet &DRS);
James Molloy5f255eb2015-01-29 13:48:05 +0000408
James Molloy64419d42015-01-29 21:52:03 +0000409 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000410 void collectInLoopUserSet(const SmallInstructionVector &Roots,
411 const SmallInstructionSet &Exclude,
412 const SmallInstructionSet &Final,
413 DenseSet<Instruction *> &Users);
414 void collectInLoopUserSet(Instruction *Root,
415 const SmallInstructionSet &Exclude,
416 const SmallInstructionSet &Final,
417 DenseSet<Instruction *> &Users);
418
James Molloye805ad92015-02-12 15:54:14 +0000419 UsesTy::iterator nextInstr(int Val, UsesTy &In,
420 const SmallInstructionSet &Exclude,
421 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000422 bool isBaseInst(Instruction *I);
423 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000424 bool instrDependsOn(Instruction *I,
425 UsesTy::iterator Start,
426 UsesTy::iterator End);
Eli Friedman203eaaf2018-06-22 22:58:55 +0000427 void replaceIV(DAGRootSet &DRS, const SCEV *Start, const SCEV *IncrExpr);
James Molloy64419d42015-01-29 21:52:03 +0000428
James Molloy5f255eb2015-01-29 13:48:05 +0000429 LoopReroll *Parent;
430
431 // Members of Parent, replicated here for brevity.
432 Loop *L;
433 ScalarEvolution *SE;
434 AliasAnalysis *AA;
435 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000436 DominatorTree *DT;
437 LoopInfo *LI;
438 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000439
440 // The loop induction variable.
441 Instruction *IV;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000442
James Molloy5f255eb2015-01-29 13:48:05 +0000443 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000444 int64_t Inc;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000445
James Molloy5f255eb2015-01-29 13:48:05 +0000446 // Loop reroll count; if Inc == 1, this records the scaling applied
447 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
448 // If Inc is not 1, Scale = Inc.
449 uint64_t Scale;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000450
James Molloy5f255eb2015-01-29 13:48:05 +0000451 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000452 SmallVector<DAGRootSet,16> RootSets;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000453
James Molloy5f255eb2015-01-29 13:48:05 +0000454 // All increment instructions for IV.
455 SmallInstructionVector LoopIncs;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000456
James Molloy64419d42015-01-29 21:52:03 +0000457 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000458 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000459 // used in the loop increment mechanism).
460 UsesTy Uses;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000461
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000462 // Map between induction variable and its increment
463 DenseMap<Instruction *, int64_t> &IVToIncMap;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000464
Lawrence Hu1befea22016-04-30 00:51:22 +0000465 Instruction *LoopControlIV;
James Molloy5f255eb2015-01-29 13:48:05 +0000466 };
467
Lawrence Hu1befea22016-04-30 00:51:22 +0000468 // Check if it is a compare-like instruction whose user is a branch
469 bool isCompareUsedByBranch(Instruction *I) {
470 auto *TI = I->getParent()->getTerminator();
471 if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
472 return false;
473 return I->hasOneUse() && TI->getOperand(0) == I;
474 };
475
476 bool isLoopControlIV(Loop *L, Instruction *IV);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000477 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
478 void collectPossibleReductions(Loop *L,
479 ReductionTracker &Reductions);
Eli Friedman203eaaf2018-06-22 22:58:55 +0000480 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header,
481 const SCEV *BackedgeTakenCount, ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000482 };
Eugene Zelenko306d2992017-10-18 21:46:47 +0000483
484} // end anonymous namespace
Hal Finkelbf45efd2013-11-16 23:59:05 +0000485
486char LoopReroll::ID = 0;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000487
Hal Finkelbf45efd2013-11-16 23:59:05 +0000488INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000489INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000490INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000491INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
492
493Pass *llvm::createLoopRerollPass() {
494 return new LoopReroll;
495}
496
497// Returns true if the provided instruction is used outside the given loop.
498// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
499// non-loop blocks to be outside the loop.
500static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000501 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000502 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000503 return true;
James Molloy64419d42015-01-29 21:52:03 +0000504 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000505 return false;
506}
507
Lawrence Hu1befea22016-04-30 00:51:22 +0000508// Check if an IV is only used to control the loop. There are two cases:
509// 1. It only has one use which is loop increment, and the increment is only
Lawrence Hue58a8142016-05-10 21:16:49 +0000510// used by comparison and the PHI (could has sext with nsw in between), and the
511// comparison is only used by branch.
Lawrence Hu1befea22016-04-30 00:51:22 +0000512// 2. It is used by loop increment and the comparison, the loop increment is
513// only used by the PHI, and the comparison is used only by the branch.
514bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
Lawrence Hu1befea22016-04-30 00:51:22 +0000515 unsigned IVUses = IV->getNumUses();
516 if (IVUses != 2 && IVUses != 1)
517 return false;
518
519 for (auto *User : IV->users()) {
520 int32_t IncOrCmpUses = User->getNumUses();
521 bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
522
523 // User can only have one or two uses.
524 if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
525 return false;
526
527 // Case 1
528 if (IVUses == 1) {
529 // The only user must be the loop increment.
530 // The loop increment must have two uses.
531 if (IsCompInst || IncOrCmpUses != 2)
532 return false;
533 }
534
535 // Case 2
536 if (IVUses == 2 && IncOrCmpUses != 1)
537 return false;
538
539 // The users of the IV must be a binary operation or a comparison
540 if (auto *BO = dyn_cast<BinaryOperator>(User)) {
541 if (BO->getOpcode() == Instruction::Add) {
542 // Loop Increment
543 // User of Loop Increment should be either PHI or CMP
544 for (auto *UU : User->users()) {
545 if (PHINode *PN = dyn_cast<PHINode>(UU)) {
546 if (PN != IV)
547 return false;
548 }
Lawrence Hue58a8142016-05-10 21:16:49 +0000549 // Must be a CMP or an ext (of a value with nsw) then CMP
550 else {
551 Instruction *UUser = dyn_cast<Instruction>(UU);
552 // Skip SExt if we are extending an nsw value
553 // TODO: Allow ZExt too
Zvi Rackoverd9423972017-04-18 14:55:43 +0000554 if (BO->hasNoSignedWrap() && UUser && UUser->hasOneUse() &&
Lawrence Hue58a8142016-05-10 21:16:49 +0000555 isa<SExtInst>(UUser))
556 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
557 if (!isCompareUsedByBranch(UUser))
558 return false;
559 }
Lawrence Hu1befea22016-04-30 00:51:22 +0000560 }
561 } else
562 return false;
563 // Compare : can only have one use, and must be branch
564 } else if (!IsCompInst)
565 return false;
566 }
567 return true;
568}
569
Hal Finkelbf45efd2013-11-16 23:59:05 +0000570// Collect the list of loop induction variables with respect to which it might
571// be possible to reroll the loop.
572void LoopReroll::collectPossibleIVs(Loop *L,
573 SmallInstructionVector &PossibleIVs) {
574 BasicBlock *Header = L->getHeader();
575 for (BasicBlock::iterator I = Header->begin(),
576 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
577 if (!isa<PHINode>(I))
578 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000579 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000580 continue;
581
582 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000583 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000584 if (PHISCEV->getLoop() != L)
585 continue;
586 if (!PHISCEV->isAffine())
587 continue;
Eli Friedman203eaaf2018-06-22 22:58:55 +0000588 auto IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
Lawrence Hud3d51062016-01-25 19:43:45 +0000589 if (IncSCEV) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000590 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
592 << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000593
594 if (isLoopControlIV(L, &*I)) {
595 assert(!LoopControlIV && "Found two loop control only IV");
596 LoopControlIV = &(*I);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000597 LLVM_DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I
598 << " = " << *PHISCEV << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000599 } else
600 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000601 }
602 }
603 }
604}
605
606// Add the remainder of the reduction-variable chain to the instruction vector
607// (the initial PHINode has already been added). If successful, the object is
608// marked as valid.
609void LoopReroll::SimpleLoopReduction::add(Loop *L) {
610 assert(!Valid && "Cannot add to an already-valid chain");
611
612 // The reduction variable must be a chain of single-use instructions
613 // (including the PHI), except for the last value (which is used by the PHI
614 // and also outside the loop).
615 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000616 if (C->user_empty())
617 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000618
619 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000620 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000621 if (C->hasOneUse()) {
622 if (!C->isBinaryOp())
623 return;
624
625 if (!(isa<PHINode>(Instructions.back()) ||
626 C->isSameOperationAs(Instructions.back())))
627 return;
628
629 Instructions.push_back(C);
630 }
631 } while (C->hasOneUse());
632
633 if (Instructions.size() < 2 ||
634 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000635 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000636 return;
637
638 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000639 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000640 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000641 if (L->contains(cast<Instruction>(U)))
642 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000643 return;
James Molloy64419d42015-01-29 21:52:03 +0000644 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000645
646 Instructions.push_back(C);
647 Valid = true;
648}
649
650// Collect the vector of possible reduction variables.
651void LoopReroll::collectPossibleReductions(Loop *L,
652 ReductionTracker &Reductions) {
653 BasicBlock *Header = L->getHeader();
654 for (BasicBlock::iterator I = Header->begin(),
655 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
656 if (!isa<PHINode>(I))
657 continue;
658 if (!I->getType()->isSingleValueType())
659 continue;
660
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000661 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000662 if (!SLR.valid())
663 continue;
664
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000665 LLVM_DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with "
666 << SLR.size() << " chained instructions)\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +0000667 Reductions.addSLR(SLR);
668 }
669}
670
671// Collect the set of all users of the provided root instruction. This set of
672// users contains not only the direct users of the root instruction, but also
673// all users of those users, and so on. There are two exceptions:
674//
675// 1. Instructions in the set of excluded instructions are never added to the
676// use set (even if they are users). This is used, for example, to exclude
677// including root increments in the use set of the primary IV.
678//
679// 2. Instructions in the set of final instructions are added to the use set
680// if they are users, but their users are not added. This is used, for
681// example, to prevent a reduction update from forcing all later reduction
682// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000683void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000684 Instruction *Root, const SmallInstructionSet &Exclude,
685 const SmallInstructionSet &Final,
686 DenseSet<Instruction *> &Users) {
687 SmallInstructionVector Queue(1, Root);
688 while (!Queue.empty()) {
689 Instruction *I = Queue.pop_back_val();
690 if (!Users.insert(I).second)
691 continue;
692
693 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000694 for (Use &U : I->uses()) {
695 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000696 if (PHINode *PN = dyn_cast<PHINode>(User)) {
697 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000698 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000699 continue;
700 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000701
Hal Finkelbf45efd2013-11-16 23:59:05 +0000702 if (L->contains(User) && !Exclude.count(User)) {
703 Queue.push_back(User);
704 }
705 }
706
707 // We also want to collect single-user "feeder" values.
708 for (User::op_iterator OI = I->op_begin(),
709 OIE = I->op_end(); OI != OIE; ++OI) {
710 if (Instruction *Op = dyn_cast<Instruction>(*OI))
711 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
712 !Final.count(Op))
713 Queue.push_back(Op);
714 }
715 }
716}
717
718// Collect all of the users of all of the provided root instructions (combined
719// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000720void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000721 const SmallInstructionVector &Roots,
722 const SmallInstructionSet &Exclude,
723 const SmallInstructionSet &Final,
724 DenseSet<Instruction *> &Users) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000725 for (Instruction *Root : Roots)
726 collectInLoopUserSet(Root, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000727}
728
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000729static bool isUnorderedLoadStore(Instruction *I) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000730 if (LoadInst *LI = dyn_cast<LoadInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000731 return LI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000732 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Sanjoy Dasab73c9d2016-07-19 00:23:54 +0000733 return SI->isUnordered();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000734 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
735 return !MI->isVolatile();
736 return false;
737}
738
James Molloyf1473592015-02-11 09:19:47 +0000739/// Return true if IVU is a "simple" arithmetic operation.
740/// This is used for narrowing the search space for DAGRoots; only arithmetic
741/// and GEPs can be part of a DAGRoot.
742static bool isSimpleArithmeticOp(User *IVU) {
743 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
744 switch (I->getOpcode()) {
745 default: return false;
746 case Instruction::Add:
747 case Instruction::Sub:
748 case Instruction::Mul:
749 case Instruction::Shl:
750 case Instruction::AShr:
751 case Instruction::LShr:
752 case Instruction::GetElementPtr:
753 case Instruction::Trunc:
754 case Instruction::ZExt:
755 case Instruction::SExt:
756 return true;
757 }
758 }
759 return false;
760}
761
762static bool isLoopIncrement(User *U, Instruction *IV) {
763 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hud3d51062016-01-25 19:43:45 +0000764
765 if ((BO && BO->getOpcode() != Instruction::Add) ||
766 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000767 return false;
768
Lawrence Hud3d51062016-01-25 19:43:45 +0000769 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000770 PHINode *PN = dyn_cast<PHINode>(UU);
771 if (PN && PN == IV)
772 return true;
773 }
774 return false;
775}
776
777bool LoopReroll::DAGRootTracker::
778collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
779 SmallInstructionVector BaseUsers;
780
781 for (auto *I : Base->users()) {
782 ConstantInt *CI = nullptr;
783
784 if (isLoopIncrement(I, IV)) {
785 LoopIncs.push_back(cast<Instruction>(I));
786 continue;
787 }
788
789 // The root nodes must be either GEPs, ORs or ADDs.
790 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
791 if (BO->getOpcode() == Instruction::Add ||
792 BO->getOpcode() == Instruction::Or)
793 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
794 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
795 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
796 CI = dyn_cast<ConstantInt>(LastOperand);
797 }
798
799 if (!CI) {
800 if (Instruction *II = dyn_cast<Instruction>(I)) {
801 BaseUsers.push_back(II);
802 continue;
803 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000804 LLVM_DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I
805 << "\n");
James Molloyf1473592015-02-11 09:19:47 +0000806 return false;
807 }
808 }
809
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000810 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000811 if (Roots.find(V) != Roots.end())
812 // No duplicates, please.
813 return false;
814
James Molloyf1473592015-02-11 09:19:47 +0000815 Roots[V] = cast<Instruction>(I);
816 }
817
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000818 // Make sure we have at least two roots.
819 if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
James Molloyf1473592015-02-11 09:19:47 +0000820 return false;
James Molloyf1473592015-02-11 09:19:47 +0000821
822 // If we found non-loop-inc, non-root users of Base, assume they are
823 // for the zeroth root index. This is because "add %a, 0" gets optimized
824 // away.
James Molloye32d8062015-02-16 17:02:00 +0000825 if (BaseUsers.size()) {
826 if (Roots.find(0) != Roots.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000827 LLVM_DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
James Molloye32d8062015-02-16 17:02:00 +0000828 return false;
829 }
James Molloyf1473592015-02-11 09:19:47 +0000830 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000831 }
James Molloyf1473592015-02-11 09:19:47 +0000832
833 // Calculate the number of users of the base, or lowest indexed, iteration.
834 unsigned NumBaseUses = BaseUsers.size();
835 if (NumBaseUses == 0)
836 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000837
James Molloyf1473592015-02-11 09:19:47 +0000838 // Check that every node has the same number of users.
839 for (auto &KV : Roots) {
840 if (KV.first == 0)
841 continue;
Davide Italiano80fe9872017-04-18 21:42:21 +0000842 if (!KV.second->hasNUses(NumBaseUses)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000843 LLVM_DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
844 << "#Base=" << NumBaseUses
845 << ", #Root=" << KV.second->getNumUses() << "\n");
James Molloyf1473592015-02-11 09:19:47 +0000846 return false;
847 }
848 }
849
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000850 return true;
James Molloyf1473592015-02-11 09:19:47 +0000851}
852
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000853void LoopReroll::DAGRootTracker::
James Molloyf1473592015-02-11 09:19:47 +0000854findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
855 // Does the user look like it could be part of a root set?
856 // All its users must be simple arithmetic ops.
Davide Italiano80fe9872017-04-18 21:42:21 +0000857 if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000858 return;
James Molloyf1473592015-02-11 09:19:47 +0000859
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000860 if (I != IV && findRootsBase(I, SubsumedInsts))
861 return;
James Molloyf1473592015-02-11 09:19:47 +0000862
863 SubsumedInsts.insert(I);
864
865 for (User *V : I->users()) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000866 Instruction *I = cast<Instruction>(V);
David Majnemer0d955d02016-08-11 22:21:41 +0000867 if (is_contained(LoopIncs, I))
James Molloyf1473592015-02-11 09:19:47 +0000868 continue;
869
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000870 if (!isSimpleArithmeticOp(I))
871 continue;
872
873 // The recursive call makes a copy of SubsumedInsts.
874 findRootsRecursive(I, SubsumedInsts);
James Molloyf1473592015-02-11 09:19:47 +0000875 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000876}
877
878bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
879 if (DRS.Roots.empty())
880 return false;
881
882 // Consider a DAGRootSet with N-1 roots (so N different values including
883 // BaseInst).
884 // Define d = Roots[0] - BaseInst, which should be the same as
885 // Roots[I] - Roots[I-1] for all I in [1..N).
886 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
887 // loop iteration J.
888 //
889 // Now, For the loop iterations to be consecutive:
890 // D = d * N
891 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
892 if (!ADR)
893 return false;
Eli Friedman806136f2019-02-12 00:33:25 +0000894
895 // Check that the first root is evenly spaced.
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000896 unsigned N = DRS.Roots.size() + 1;
897 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
898 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
899 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
900 return false;
901
Eli Friedman806136f2019-02-12 00:33:25 +0000902 // Check that the remainling roots are evenly spaced.
903 for (unsigned i = 1; i < N - 1; ++i) {
904 const SCEV *NewStepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[i]),
905 SE->getSCEV(DRS.Roots[i-1]));
906 if (NewStepSCEV != StepSCEV)
907 return false;
908 }
909
James Molloyf1473592015-02-11 09:19:47 +0000910 return true;
911}
912
913bool LoopReroll::DAGRootTracker::
914findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000915 // The base of a RootSet must be an AddRec, so it can be erased.
916 const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
917 if (!IVU_ADR || IVU_ADR->getLoop() != L)
James Molloyf1473592015-02-11 09:19:47 +0000918 return false;
919
920 std::map<int64_t, Instruction*> V;
921 if (!collectPossibleRoots(IVU, V))
922 return false;
923
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000924 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000925 // subsumed.
926 if (V.find(0) == V.end())
927 SubsumedInsts.insert(IVU);
928
929 // Partition the vector into monotonically increasing indexes.
930 DAGRootSet DRS;
931 DRS.BaseInst = nullptr;
932
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000933 SmallVector<DAGRootSet, 16> PotentialRootSets;
934
James Molloyf1473592015-02-11 09:19:47 +0000935 for (auto &KV : V) {
936 if (!DRS.BaseInst) {
937 DRS.BaseInst = KV.second;
938 DRS.SubsumedInsts = SubsumedInsts;
939 } else if (DRS.Roots.empty()) {
940 DRS.Roots.push_back(KV.second);
941 } else if (V.find(KV.first - 1) != V.end()) {
942 DRS.Roots.push_back(KV.second);
943 } else {
944 // Linear sequence terminated.
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000945 if (!validateRootSet(DRS))
946 return false;
947
948 // Construct a new DAGRootSet with the next sequence.
949 PotentialRootSets.push_back(DRS);
James Molloyf1473592015-02-11 09:19:47 +0000950 DRS.BaseInst = KV.second;
James Molloyf1473592015-02-11 09:19:47 +0000951 DRS.Roots.clear();
952 }
953 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000954
955 if (!validateRootSet(DRS))
956 return false;
957
958 PotentialRootSets.push_back(DRS);
959
960 RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
James Molloyf1473592015-02-11 09:19:47 +0000961
962 return true;
963}
964
James Molloy5f255eb2015-01-29 13:48:05 +0000965bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000966 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +0000967
James Molloyf1473592015-02-11 09:19:47 +0000968 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000969 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +0000970 for (auto *IVU : IV->users()) {
971 if (isLoopIncrement(IVU, IV))
972 LoopIncs.push_back(cast<Instruction>(IVU));
973 }
Eli Friedmanc0bba1a2016-11-21 22:35:34 +0000974 findRootsRecursive(IV, SmallInstructionSet());
James Molloyf1473592015-02-11 09:19:47 +0000975 LoopIncs.push_back(IV);
976 } else {
977 if (!findRootsBase(IV, SmallInstructionSet()))
978 return false;
979 }
James Molloy5f255eb2015-01-29 13:48:05 +0000980
James Molloyf1473592015-02-11 09:19:47 +0000981 // Ensure all sets have the same size.
982 if (RootSets.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000983 LLVM_DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000984 return false;
James Molloyf1473592015-02-11 09:19:47 +0000985 }
986 for (auto &V : RootSets) {
987 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000988 LLVM_DEBUG(
989 dbgs()
990 << "LRR: Aborting because not all root sets have the same size\n");
James Molloyf1473592015-02-11 09:19:47 +0000991 return false;
992 }
993 }
James Molloy5f255eb2015-01-29 13:48:05 +0000994
James Molloyf1473592015-02-11 09:19:47 +0000995 Scale = RootSets[0].Roots.size() + 1;
996
997 if (Scale > IL_MaxRerollIterations) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000998 LLVM_DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
999 << "#Found=" << Scale
1000 << ", #Max=" << IL_MaxRerollIterations << "\n");
James Molloy64419d42015-01-29 21:52:03 +00001001 return false;
1002 }
1003
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001004 LLVM_DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale
1005 << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001006
1007 return true;
1008}
1009
James Molloy64419d42015-01-29 21:52:03 +00001010bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1011 // Populate the MapVector with all instructions in the block, in order first,
1012 // so we can iterate over the contents later in perfect order.
1013 for (auto &I : *L->getHeader()) {
1014 Uses[&I].resize(IL_End);
1015 }
James Molloy5f255eb2015-01-29 13:48:05 +00001016
James Molloy64419d42015-01-29 21:52:03 +00001017 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +00001018 for (auto &DRS : RootSets) {
1019 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1020 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1021 Exclude.insert(DRS.BaseInst);
1022 }
James Molloy64419d42015-01-29 21:52:03 +00001023 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1024
James Molloyf1473592015-02-11 09:19:47 +00001025 for (auto &DRS : RootSets) {
1026 DenseSet<Instruction*> VBase;
1027 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1028 for (auto *I : VBase) {
1029 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +00001030 }
1031
James Molloyf1473592015-02-11 09:19:47 +00001032 unsigned Idx = 1;
1033 for (auto *Root : DRS.Roots) {
1034 DenseSet<Instruction*> V;
1035 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1036
1037 // While we're here, check the use sets are the same size.
1038 if (V.size() != VBase.size()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001039 LLVM_DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
James Molloyf1473592015-02-11 09:19:47 +00001040 return false;
1041 }
1042
1043 for (auto *I : V) {
1044 Uses[I].set(Idx);
1045 }
1046 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +00001047 }
James Molloyf1473592015-02-11 09:19:47 +00001048
1049 // Make sure our subsumed instructions are remembered too.
1050 for (auto *I : DRS.SubsumedInsts) {
1051 Uses[I].set(IL_All);
1052 }
James Molloy64419d42015-01-29 21:52:03 +00001053 }
1054
1055 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +00001056
James Molloy64419d42015-01-29 21:52:03 +00001057 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +00001058 for (auto &DRS : RootSets) {
1059 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1060 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1061 Exclude.insert(DRS.BaseInst);
1062 }
James Molloy64419d42015-01-29 21:52:03 +00001063
1064 DenseSet<Instruction*> V;
1065 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1066 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +00001067 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001068 }
James Molloy64419d42015-01-29 21:52:03 +00001069
1070 return true;
James Molloy64419d42015-01-29 21:52:03 +00001071}
1072
James Molloye805ad92015-02-12 15:54:14 +00001073/// Get the next instruction in "In" that is a member of set Val.
1074/// Start searching from StartI, and do not return anything in Exclude.
1075/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +00001076LoopReroll::DAGRootTracker::UsesTy::iterator
1077LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +00001078 const SmallInstructionSet &Exclude,
1079 UsesTy::iterator *StartI) {
1080 UsesTy::iterator I = StartI ? *StartI : In.begin();
1081 while (I != In.end() && (I->second.test(Val) == 0 ||
1082 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +00001083 ++I;
1084 return I;
1085}
1086
James Molloyf1473592015-02-11 09:19:47 +00001087bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1088 for (auto &DRS : RootSets) {
1089 if (DRS.BaseInst == I)
1090 return true;
1091 }
1092 return false;
1093}
1094
1095bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1096 for (auto &DRS : RootSets) {
David Majnemer0d955d02016-08-11 22:21:41 +00001097 if (is_contained(DRS.Roots, I))
James Molloyf1473592015-02-11 09:19:47 +00001098 return true;
1099 }
1100 return false;
1101}
1102
James Molloye805ad92015-02-12 15:54:14 +00001103/// Return true if instruction I depends on any instruction between
1104/// Start and End.
1105bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1106 UsesTy::iterator Start,
1107 UsesTy::iterator End) {
1108 for (auto *U : I->users()) {
1109 for (auto It = Start; It != End; ++It)
1110 if (U == It->first)
1111 return true;
1112 }
1113 return false;
1114}
1115
Weiming Zhao310770a2015-09-28 17:03:23 +00001116static bool isIgnorableInst(const Instruction *I) {
1117 if (isa<DbgInfoIntrinsic>(I))
1118 return true;
1119 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1120 if (!II)
1121 return false;
1122 switch (II->getIntrinsicID()) {
1123 default:
1124 return false;
Eugene Zelenko306d2992017-10-18 21:46:47 +00001125 case Intrinsic::annotation:
Weiming Zhao310770a2015-09-28 17:03:23 +00001126 case Intrinsic::ptr_annotation:
1127 case Intrinsic::var_annotation:
1128 // TODO: the following intrinsics may also be whitelisted:
1129 // lifetime_start, lifetime_end, invariant_start, invariant_end
1130 return true;
1131 }
1132 return false;
1133}
1134
James Molloy64419d42015-01-29 21:52:03 +00001135bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001136 // We now need to check for equivalence of the use graph of each root with
1137 // that of the primary induction variable (excluding the roots). Our goal
1138 // here is not to solve the full graph isomorphism problem, but rather to
1139 // catch common cases without a lot of work. As a result, we will assume
1140 // that the relative order of the instructions in each unrolled iteration
1141 // is the same (although we will not make an assumption about how the
1142 // different iterations are intermixed). Note that while the order must be
1143 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001144
1145 // An array of just the possible reductions for this scale factor. When we
1146 // collect the set of all users of some root instructions, these reduction
1147 // instructions are treated as 'final' (their uses are not considered).
1148 // This is important because we don't want the root use set to search down
1149 // the reduction chain.
1150 SmallInstructionSet PossibleRedSet;
1151 SmallInstructionSet PossibleRedLastSet;
1152 SmallInstructionSet PossibleRedPHISet;
1153 Reductions.restrictToScale(Scale, PossibleRedSet,
1154 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001155
James Molloy64419d42015-01-29 21:52:03 +00001156 // Populate "Uses" with where each instruction is used.
1157 if (!collectUsedInstructions(PossibleRedSet))
1158 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001159
James Molloy64419d42015-01-29 21:52:03 +00001160 // Make sure we mark the reduction PHIs as used in all iterations.
1161 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001162 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001163 }
James Molloy5f255eb2015-01-29 13:48:05 +00001164
Lawrence Hu1befea22016-04-30 00:51:22 +00001165 // Make sure we mark loop-control-only PHIs as used in all iterations. See
1166 // comment above LoopReroll::isLoopControlIV for more information.
1167 BasicBlock *Header = L->getHeader();
1168 if (LoopControlIV && LoopControlIV != IV) {
1169 for (auto *U : LoopControlIV->users()) {
1170 Instruction *IVUser = dyn_cast<Instruction>(U);
1171 // IVUser could be loop increment or compare
1172 Uses[IVUser].set(IL_All);
1173 for (auto *UU : IVUser->users()) {
1174 Instruction *UUser = dyn_cast<Instruction>(UU);
1175 // UUser could be compare, PHI or branch
1176 Uses[UUser].set(IL_All);
Lawrence Hue58a8142016-05-10 21:16:49 +00001177 // Skip SExt
1178 if (isa<SExtInst>(UUser)) {
1179 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1180 Uses[UUser].set(IL_All);
1181 }
Lawrence Hu1befea22016-04-30 00:51:22 +00001182 // Is UUser a compare instruction?
1183 if (UU->hasOneUse()) {
1184 Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1185 if (BI == cast<BranchInst>(Header->getTerminator()))
1186 Uses[BI].set(IL_All);
1187 }
1188 }
1189 }
1190 }
1191
James Molloy64419d42015-01-29 21:52:03 +00001192 // Make sure all instructions in the loop are in one and only one
1193 // set.
1194 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001195 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001196 LLVM_DEBUG(
1197 dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1198 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
James Molloy64419d42015-01-29 21:52:03 +00001199 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001200 }
James Molloy64419d42015-01-29 21:52:03 +00001201 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001202
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001203 LLVM_DEBUG(for (auto &KV
1204 : Uses) {
1205 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1206 });
James Molloy64419d42015-01-29 21:52:03 +00001207
1208 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001209 // In addition to regular aliasing information, we need to look for
1210 // instructions from later (future) iterations that have side effects
1211 // preventing us from reordering them past other instructions with side
1212 // effects.
1213 bool FutureSideEffects = false;
1214 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001215 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1216 DenseMap<Value *, Value *> BaseMap;
1217
James Molloy64419d42015-01-29 21:52:03 +00001218 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001219 SmallInstructionSet Visited;
1220 auto BaseIt = nextInstr(0, Uses, Visited);
1221 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001222 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001223
James Molloy64419d42015-01-29 21:52:03 +00001224 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1225 Instruction *BaseInst = BaseIt->first;
1226 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001227
James Molloy64419d42015-01-29 21:52:03 +00001228 // Skip over the IV or root instructions; only match their users.
1229 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001230 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001231 Visited.insert(BaseInst);
1232 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001233 Continue = true;
1234 }
James Molloyf1473592015-02-11 09:19:47 +00001235 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001236 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001237 Visited.insert(RootInst);
1238 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001239 Continue = true;
1240 }
1241 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001242
James Molloye805ad92015-02-12 15:54:14 +00001243 if (!BaseInst->isSameOperationAs(RootInst)) {
1244 // Last chance saloon. We don't try and solve the full isomorphism
1245 // problem, but try and at least catch the case where two instructions
1246 // *of different types* are round the wrong way. We won't be able to
1247 // efficiently tell, given two ADD instructions, which way around we
1248 // should match them, but given an ADD and a SUB, we can at least infer
1249 // which one is which.
1250 //
1251 // This should allow us to deal with a greater subset of the isomorphism
1252 // problem. It does however change a linear algorithm into a quadratic
1253 // one, so limit the number of probes we do.
1254 auto TryIt = RootIt;
1255 unsigned N = NumToleratedFailedMatches;
1256 while (TryIt != Uses.end() &&
1257 !BaseInst->isSameOperationAs(TryIt->first) &&
1258 N--) {
1259 ++TryIt;
1260 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1261 }
1262
1263 if (TryIt == Uses.end() || TryIt == RootIt ||
1264 instrDependsOn(TryIt->first, RootIt, TryIt)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001265 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1266 << *BaseInst << " vs. " << *RootInst << "\n");
James Molloye805ad92015-02-12 15:54:14 +00001267 return false;
1268 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001269
James Molloye805ad92015-02-12 15:54:14 +00001270 RootIt = TryIt;
1271 RootInst = TryIt->first;
1272 }
1273
James Molloy64419d42015-01-29 21:52:03 +00001274 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001275 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001276 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001277 //
James Molloye805ad92015-02-12 15:54:14 +00001278 // Note that because we allow a limited amount of flexibility in the order
1279 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1280 // case we've already checked this set of instructions so we shouldn't
1281 // do anything.
1282 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001283 Instruction *I = LastRootIt->first;
1284 if (LastRootIt->second.find_first() < (int)Iter)
1285 continue;
1286 if (I->mayWriteToMemory())
1287 AST.add(I);
1288 // Note: This is specifically guarded by a check on isa<PHINode>,
1289 // which while a valid (somewhat arbitrary) micro-optimization, is
1290 // needed because otherwise isSafeToSpeculativelyExecute returns
1291 // false on PHI nodes.
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001292 if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001293 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001294 // Intervening instructions cause side effects.
1295 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001296 }
1297
James Molloy5f255eb2015-01-29 13:48:05 +00001298 // Make sure that this instruction, which is in the use set of this
1299 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001300 // some other root instruction.
1301 if (RootIt->second.count() > 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001302 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1303 << " vs. " << *RootInst << " (prev. case overlap)\n");
James Molloy64419d42015-01-29 21:52:03 +00001304 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001305 }
1306
1307 // Make sure that we don't alias with any instruction in the alias set
1308 // tracker. If we do, then we depend on a future iteration, and we
1309 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001310 if (RootInst->mayReadFromMemory())
1311 for (auto &K : AST) {
1312 if (K.aliasesUnknownInst(RootInst, *AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001313 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1314 << *BaseInst << " vs. " << *RootInst
1315 << " (depends on future store)\n");
James Molloy64419d42015-01-29 21:52:03 +00001316 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001317 }
1318 }
James Molloy5f255eb2015-01-29 13:48:05 +00001319
1320 // If we've past an instruction from a future iteration that may have
1321 // side effects, and this instruction might also, then we can't reorder
1322 // them, and this matching fails. As an exception, we allow the alias
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001323 // set tracker to handle regular (unordered) load/store dependencies.
1324 if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001325 !isSafeToSpeculativelyExecute(BaseInst)) ||
Sanjoy Dasab73c9d2016-07-19 00:23:54 +00001326 (!isUnorderedLoadStore(RootInst) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001327 !isSafeToSpeculativelyExecute(RootInst)))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001328 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1329 << " vs. " << *RootInst
1330 << " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001331 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001332 }
1333
1334 // For instructions that are part of a reduction, if the operation is
1335 // associative, then don't bother matching the operands (because we
1336 // already know that the instructions are isomorphic, and the order
1337 // within the iteration does not matter). For non-associative reductions,
1338 // we do need to match the operands, because we need to reject
1339 // out-of-order instructions within an iteration!
1340 // For example (assume floating-point addition), we need to reject this:
1341 // x += a[i]; x += b[i];
1342 // x += a[i+1]; x += b[i+1];
1343 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001344 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001345
James Molloy64419d42015-01-29 21:52:03 +00001346 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001347 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001348 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1349 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001350
1351 // If this is part of a reduction (and the operation is not
1352 // associatve), then we match all operands, but not those that are
1353 // part of the reduction.
1354 if (InReduction)
1355 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001356 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001357 continue;
1358
1359 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001360 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001361 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001362 } else {
1363 for (auto &DRS : RootSets) {
1364 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1365 Op2 = DRS.BaseInst;
1366 break;
1367 }
1368 }
1369 }
James Molloy5f255eb2015-01-29 13:48:05 +00001370
James Molloy64419d42015-01-29 21:52:03 +00001371 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001372 // If we've not already decided to swap the matched operands, and
1373 // we've not already matched our first operand (note that we could
1374 // have skipped matching the first operand because it is part of a
1375 // reduction above), and the instruction is commutative, then try
1376 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001377 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1378 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001379 Swapped = true;
1380 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001381 LLVM_DEBUG(dbgs()
1382 << "LRR: iteration root match failed at " << *BaseInst
1383 << " vs. " << *RootInst << " (operand " << j << ")\n");
James Molloy64419d42015-01-29 21:52:03 +00001384 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001385 }
1386 }
1387
1388 SomeOpMatched = true;
1389 }
1390 }
1391
James Molloy64419d42015-01-29 21:52:03 +00001392 if ((!PossibleRedLastSet.count(BaseInst) &&
1393 hasUsesOutsideLoop(BaseInst, L)) ||
1394 (!PossibleRedLastSet.count(RootInst) &&
1395 hasUsesOutsideLoop(RootInst, L))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001396 LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1397 << " vs. " << *RootInst << " (uses outside loop)\n");
James Molloy64419d42015-01-29 21:52:03 +00001398 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001399 }
1400
James Molloy64419d42015-01-29 21:52:03 +00001401 Reductions.recordPair(BaseInst, RootInst, Iter);
1402 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001403
James Molloy64419d42015-01-29 21:52:03 +00001404 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001405 Visited.insert(BaseInst);
1406 Visited.insert(RootInst);
1407 BaseIt = nextInstr(0, Uses, Visited);
1408 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001409 }
Eugene Zelenko306d2992017-10-18 21:46:47 +00001410 assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
1411 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001412 }
1413
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001414 LLVM_DEBUG(dbgs() << "LRR: Matched all iteration increments for " << *IV
1415 << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001416
Hal Finkelbf45efd2013-11-16 23:59:05 +00001417 return true;
1418}
1419
Eli Friedman203eaaf2018-06-22 22:58:55 +00001420void LoopReroll::DAGRootTracker::replace(const SCEV *BackedgeTakenCount) {
James Molloy5f255eb2015-01-29 13:48:05 +00001421 BasicBlock *Header = L->getHeader();
Eli Friedman203eaaf2018-06-22 22:58:55 +00001422
1423 // Compute the start and increment for each BaseInst before we start erasing
1424 // instructions.
1425 SmallVector<const SCEV *, 8> StartExprs;
1426 SmallVector<const SCEV *, 8> IncrExprs;
1427 for (auto &DRS : RootSets) {
1428 const SCEVAddRecExpr *IVSCEV =
1429 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1430 StartExprs.push_back(IVSCEV->getStart());
1431 IncrExprs.push_back(SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), IVSCEV));
1432 }
1433
James Molloy5f255eb2015-01-29 13:48:05 +00001434 // Remove instructions associated with non-base iterations.
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001435 for (BasicBlock::reverse_iterator J = Header->rbegin(), JE = Header->rend();
1436 J != JE;) {
James Molloy64419d42015-01-29 21:52:03 +00001437 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001438 if (I > 0 && I < IL_All) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001439 LLVM_DEBUG(dbgs() << "LRR: removing: " << *J << "\n");
Duncan P. N. Exon Smith5c001c32016-08-30 00:13:12 +00001440 J++->eraseFromParent();
James Molloy5f255eb2015-01-29 13:48:05 +00001441 continue;
1442 }
1443
1444 ++J;
1445 }
1446
Eli Friedman203eaaf2018-06-22 22:58:55 +00001447 // Rewrite each BaseInst using SCEV.
1448 for (size_t i = 0, e = RootSets.size(); i != e; ++i)
1449 // Insert the new induction variable.
1450 replaceIV(RootSets[i], StartExprs[i], IncrExprs[i]);
Lawrence Hu1befea22016-04-30 00:51:22 +00001451
Eli Friedman203eaaf2018-06-22 22:58:55 +00001452 { // Limit the lifetime of SCEVExpander.
1453 BranchInst *BI = cast<BranchInst>(Header->getTerminator());
1454 const DataLayout &DL = Header->getModule()->getDataLayout();
1455 SCEVExpander Expander(*SE, DL, "reroll");
1456 auto Zero = SE->getZero(BackedgeTakenCount->getType());
1457 auto One = SE->getOne(BackedgeTakenCount->getType());
1458 auto NewIVSCEV = SE->getAddRecExpr(Zero, One, L, SCEV::FlagAnyWrap);
1459 Value *NewIV =
1460 Expander.expandCodeFor(NewIVSCEV, BackedgeTakenCount->getType(),
1461 Header->getFirstNonPHIOrDbg());
1462 // FIXME: This arithmetic can overflow.
1463 auto TripCount = SE->getAddExpr(BackedgeTakenCount, One);
1464 auto ScaledTripCount = SE->getMulExpr(
1465 TripCount, SE->getConstant(BackedgeTakenCount->getType(), Scale));
1466 auto ScaledBECount = SE->getMinusSCEV(ScaledTripCount, One);
1467 Value *TakenCount =
1468 Expander.expandCodeFor(ScaledBECount, BackedgeTakenCount->getType(),
1469 Header->getFirstNonPHIOrDbg());
1470 Value *Cond =
1471 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, TakenCount, "exitcond");
1472 BI->setCondition(Cond);
1473
1474 if (BI->getSuccessor(1) != Header)
1475 BI->swapSuccessors();
1476 }
Lawrence Hub917cd92016-01-25 19:36:30 +00001477
1478 SimplifyInstructionsInBlock(Header, TLI);
1479 DeleteDeadPHIs(Header, TLI);
Lawrence Hu84b61952016-01-25 18:53:39 +00001480}
1481
Eli Friedman203eaaf2018-06-22 22:58:55 +00001482void LoopReroll::DAGRootTracker::replaceIV(DAGRootSet &DRS,
1483 const SCEV *Start,
1484 const SCEV *IncrExpr) {
Lawrence Hud3d51062016-01-25 19:43:45 +00001485 BasicBlock *Header = L->getHeader();
Eli Friedman203eaaf2018-06-22 22:58:55 +00001486 Instruction *Inst = DRS.BaseInst;
Lawrence Hud3d51062016-01-25 19:43:45 +00001487
Lawrence Hud3d51062016-01-25 19:43:45 +00001488 const SCEV *NewIVSCEV =
1489 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1490
1491 { // Limit the lifetime of SCEVExpander.
1492 const DataLayout &DL = Header->getModule()->getDataLayout();
1493 SCEVExpander Expander(*SE, DL, "reroll");
Eli Friedmanc0bba1a2016-11-21 22:35:34 +00001494 Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
1495 Header->getFirstNonPHIOrDbg());
Lawrence Hud3d51062016-01-25 19:43:45 +00001496
1497 for (auto &KV : Uses)
1498 if (KV.second.find_first() == 0)
1499 KV.first->replaceUsesOfWith(Inst, NewIV);
Lawrence Hud3d51062016-01-25 19:43:45 +00001500 }
1501}
1502
Hal Finkelbf45efd2013-11-16 23:59:05 +00001503// Validate the selected reductions. All iterations must have an isomorphic
1504// part of the reduction chain and, for non-associative reductions, the chain
1505// entries must appear in order.
1506bool LoopReroll::ReductionTracker::validateSelected() {
1507 // For a non-associative reduction, the chain entries must appear in order.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001508 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001509 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001510 for (Instruction *J : PossibleReds[i]) {
1511 // Note that all instructions in the chain must have been found because
1512 // all instructions in the function must have been assigned to some
1513 // iteration.
1514 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001515 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1516 !PossibleReds[i].getReducedValue()->isAssociative()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001517 LLVM_DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: "
1518 << J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001519 return false;
1520 }
1521
1522 if (Iter != PrevIter) {
1523 if (Count != BaseCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001524 LLVM_DEBUG(dbgs()
1525 << "LRR: Iteration " << PrevIter << " reduction use count "
1526 << Count << " is not equal to the base use count "
1527 << BaseCount << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001528 return false;
1529 }
1530
1531 Count = 0;
1532 }
1533
1534 ++Count;
1535 if (Iter == 0)
1536 ++BaseCount;
1537
1538 PrevIter = Iter;
1539 }
1540 }
1541
1542 return true;
1543}
1544
1545// For all selected reductions, remove all parts except those in the first
1546// iteration (and the PHI). Replace outside uses of the reduced value with uses
1547// of the first-iteration reduced value (in other words, reroll the selected
1548// reductions).
1549void LoopReroll::ReductionTracker::replaceSelected() {
1550 // Fixup reductions to refer to the last instruction associated with the
1551 // first iteration (not the last).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001552 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001553 int j = 0;
1554 for (int e = PossibleReds[i].size(); j != e; ++j)
1555 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1556 --j;
1557 break;
1558 }
1559
1560 // Replace users with the new end-of-chain value.
1561 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001562 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001563 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001564 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001565
Benjamin Kramer135f7352016-06-26 12:28:59 +00001566 for (Instruction *User : Users)
1567 User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
Hal Finkelbf45efd2013-11-16 23:59:05 +00001568 PossibleReds[i][j]);
1569 }
1570}
1571
1572// Reroll the provided loop with respect to the provided induction variable.
1573// Generally, we're looking for a loop like this:
1574//
1575// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1576// f(%iv)
1577// %iv.1 = add %iv, 1 <-- a root increment
1578// f(%iv.1)
1579// %iv.2 = add %iv, 2 <-- a root increment
1580// f(%iv.2)
1581// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1582// f(%iv.scale_m_1)
1583// ...
1584// %iv.next = add %iv, scale
1585// %cmp = icmp(%iv, ...)
1586// br %cmp, header, exit
1587//
1588// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1589// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1590// be intermixed with eachother. The restriction imposed by this algorithm is
1591// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1592// etc. be the same.
1593//
1594// First, we collect the use set of %iv, excluding the other increment roots.
1595// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1596// times, having collected the use set of f(%iv.(i+1)), during which we:
1597// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1598// the next unmatched instruction in f(%iv.(i+1)).
1599// - Ensure that both matched instructions don't have any external users
1600// (with the exception of last-in-chain reduction instructions).
1601// - Track the (aliasing) write set, and other side effects, of all
1602// instructions that belong to future iterations that come before the matched
1603// instructions. If the matched instructions read from that write set, then
1604// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1605// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1606// if any of these future instructions had side effects (could not be
1607// speculatively executed), and so do the matched instructions, when we
1608// cannot reorder those side-effect-producing instructions, and rerolling
1609// fails.
1610//
1611// Finally, we make sure that all loop instructions are either loop increment
1612// roots, belong to simple latch code, parts of validated reductions, part of
1613// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1614// have been validated), then we reroll the loop.
1615bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
Eli Friedman203eaaf2018-06-22 22:58:55 +00001616 const SCEV *BackedgeTakenCount,
Hal Finkelbf45efd2013-11-16 23:59:05 +00001617 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001618 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +00001619 IVToIncMap, LoopControlIV);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001620
James Molloy5f255eb2015-01-29 13:48:05 +00001621 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001622 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001623 LLVM_DEBUG(dbgs() << "LRR: Found all root induction increments for: " << *IV
1624 << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001625
James Molloy5f255eb2015-01-29 13:48:05 +00001626 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001627 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001628 if (!Reductions.validateSelected())
1629 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001630 // At this point, we've validated the rerolling, and we're committed to
1631 // making changes!
1632
1633 Reductions.replaceSelected();
Eli Friedman203eaaf2018-06-22 22:58:55 +00001634 DAGRoots.replace(BackedgeTakenCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001635
Hal Finkelbf45efd2013-11-16 23:59:05 +00001636 ++NumRerolledLoops;
1637 return true;
1638}
1639
1640bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001641 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001642 return false;
1643
Chandler Carruth7b560d42015-09-09 17:55:00 +00001644 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001645 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001646 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001647 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001648 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001649 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001650
1651 BasicBlock *Header = L->getHeader();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001652 LLVM_DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << "] Loop %"
1653 << Header->getName() << " (" << L->getNumBlocks()
1654 << " block(s))\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001655
Hal Finkelbf45efd2013-11-16 23:59:05 +00001656 // For now, we'll handle only single BB loops.
1657 if (L->getNumBlocks() > 1)
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001658 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001659
1660 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001661 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001662
Eli Friedman203eaaf2018-06-22 22:58:55 +00001663 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001664 LLVM_DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
Eli Friedman203eaaf2018-06-22 22:58:55 +00001665 LLVM_DEBUG(dbgs() << "LRR: backedge-taken count = " << *BackedgeTakenCount
1666 << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001667
1668 // First, we need to find the induction variable with respect to which we can
1669 // reroll (there may be several possible options).
1670 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001671 IVToIncMap.clear();
Lawrence Hu1befea22016-04-30 00:51:22 +00001672 LoopControlIV = nullptr;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001673 collectPossibleIVs(L, PossibleIVs);
1674
1675 if (PossibleIVs.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001676 LLVM_DEBUG(dbgs() << "LRR: No possible IVs found\n");
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001677 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001678 }
1679
1680 ReductionTracker Reductions;
1681 collectPossibleReductions(L, Reductions);
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001682 bool Changed = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001683
1684 // For each possible IV, collect the associated possible set of 'root' nodes
1685 // (i+1, i+2, etc.).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001686 for (Instruction *PossibleIV : PossibleIVs)
Eli Friedman203eaaf2018-06-22 22:58:55 +00001687 if (reroll(PossibleIV, L, Header, BackedgeTakenCount, Reductions)) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001688 Changed = true;
1689 break;
1690 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001691 LLVM_DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001692
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001693 // Trip count of L has changed so SE must be re-evaluated.
1694 if (Changed)
1695 SE->forgetLoop(L);
1696
Hal Finkelbf45efd2013-11-16 23:59:05 +00001697 return Changed;
1698}