1306d2997SEugene Zelenko //===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
2bf45efdeSHal Finkel //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bf45efdeSHal Finkel //
7bf45efdeSHal Finkel //===----------------------------------------------------------------------===//
8bf45efdeSHal Finkel //
9bf45efdeSHal Finkel // This pass implements a simple loop reroller.
10bf45efdeSHal Finkel //
11bf45efdeSHal Finkel //===----------------------------------------------------------------------===//
12bf45efdeSHal Finkel
13306d2997SEugene Zelenko #include "llvm/ADT/APInt.h"
146bda14b3SChandler Carruth #include "llvm/ADT/BitVector.h"
15306d2997SEugene Zelenko #include "llvm/ADT/DenseMap.h"
16306d2997SEugene Zelenko #include "llvm/ADT/DenseSet.h"
1764419d41SJames Molloy #include "llvm/ADT/MapVector.h"
188a8cd2baSChandler Carruth #include "llvm/ADT/STLExtras.h"
19a1cc8483SFlorian Hahn #include "llvm/ADT/SmallPtrSet.h"
20306d2997SEugene Zelenko #include "llvm/ADT/SmallVector.h"
21bf45efdeSHal Finkel #include "llvm/ADT/Statistic.h"
22bf45efdeSHal Finkel #include "llvm/Analysis/AliasAnalysis.h"
23bf45efdeSHal Finkel #include "llvm/Analysis/AliasSetTracker.h"
24306d2997SEugene Zelenko #include "llvm/Analysis/LoopInfo.h"
25bf45efdeSHal Finkel #include "llvm/Analysis/LoopPass.h"
26bf45efdeSHal Finkel #include "llvm/Analysis/ScalarEvolution.h"
27bf45efdeSHal Finkel #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28799003bfSBenjamin Kramer #include "llvm/Analysis/TargetLibraryInfo.h"
29bf45efdeSHal Finkel #include "llvm/Analysis/ValueTracking.h"
30306d2997SEugene Zelenko #include "llvm/IR/BasicBlock.h"
31306d2997SEugene Zelenko #include "llvm/IR/Constants.h"
325ad5f15cSChandler Carruth #include "llvm/IR/Dominators.h"
33306d2997SEugene Zelenko #include "llvm/IR/InstrTypes.h"
34306d2997SEugene Zelenko #include "llvm/IR/Instruction.h"
35306d2997SEugene Zelenko #include "llvm/IR/Instructions.h"
36bf45efdeSHal Finkel #include "llvm/IR/IntrinsicInst.h"
37306d2997SEugene Zelenko #include "llvm/IR/Module.h"
38306d2997SEugene Zelenko #include "llvm/IR/Type.h"
39306d2997SEugene Zelenko #include "llvm/IR/Use.h"
40306d2997SEugene Zelenko #include "llvm/IR/User.h"
41306d2997SEugene Zelenko #include "llvm/IR/Value.h"
4205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
43306d2997SEugene Zelenko #include "llvm/Pass.h"
44306d2997SEugene Zelenko #include "llvm/Support/Casting.h"
45bf45efdeSHal Finkel #include "llvm/Support/CommandLine.h"
46bf45efdeSHal Finkel #include "llvm/Support/Debug.h"
47bf45efdeSHal Finkel #include "llvm/Support/raw_ostream.h"
486bda14b3SChandler Carruth #include "llvm/Transforms/Scalar.h"
49d3f6972aSArthur Eubanks #include "llvm/Transforms/Scalar/LoopReroll.h"
50a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h"
51bf45efdeSHal Finkel #include "llvm/Transforms/Utils/BasicBlockUtils.h"
5205da2fe5SReid Kleckner #include "llvm/Transforms/Utils/Local.h"
53bf45efdeSHal Finkel #include "llvm/Transforms/Utils/LoopUtils.h"
54bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
55306d2997SEugene Zelenko #include <cassert>
56306d2997SEugene Zelenko #include <cstddef>
57306d2997SEugene Zelenko #include <cstdint>
58306d2997SEugene Zelenko #include <iterator>
59306d2997SEugene Zelenko #include <map>
60306d2997SEugene Zelenko #include <utility>
61bf45efdeSHal Finkel
62bf45efdeSHal Finkel using namespace llvm;
63bf45efdeSHal Finkel
64964daaafSChandler Carruth #define DEBUG_TYPE "loop-reroll"
65964daaafSChandler Carruth
66bf45efdeSHal Finkel STATISTIC(NumRerolledLoops, "Number of rerolled loops");
67bf45efdeSHal Finkel
68bf45efdeSHal Finkel static cl::opt<unsigned>
69e805ad95SJames Molloy NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
70e805ad95SJames Molloy cl::Hidden,
71e805ad95SJames Molloy cl::desc("The maximum number of failures to tolerate"
72e805ad95SJames Molloy " during fuzzy matching. (default: 400)"));
73e805ad95SJames Molloy
74bf45efdeSHal Finkel // This loop re-rolling transformation aims to transform loops like this:
75bf45efdeSHal Finkel //
76bf45efdeSHal Finkel // int foo(int a);
77bf45efdeSHal Finkel // void bar(int *x) {
78bf45efdeSHal Finkel // for (int i = 0; i < 500; i += 3) {
79bf45efdeSHal Finkel // foo(i);
80bf45efdeSHal Finkel // foo(i+1);
81bf45efdeSHal Finkel // foo(i+2);
82bf45efdeSHal Finkel // }
83bf45efdeSHal Finkel // }
84bf45efdeSHal Finkel //
85bf45efdeSHal Finkel // into a loop like this:
86bf45efdeSHal Finkel //
87bf45efdeSHal Finkel // void bar(int *x) {
88bf45efdeSHal Finkel // for (int i = 0; i < 500; ++i)
89bf45efdeSHal Finkel // foo(i);
90bf45efdeSHal Finkel // }
91bf45efdeSHal Finkel //
92bf45efdeSHal Finkel // It does this by looking for loops that, besides the latch code, are composed
93bf45efdeSHal Finkel // of isomorphic DAGs of instructions, with each DAG rooted at some increment
94bf45efdeSHal Finkel // to the induction variable, and where each DAG is isomorphic to the DAG
95bf45efdeSHal Finkel // rooted at the induction variable (excepting the sub-DAGs which root the
96bf45efdeSHal Finkel // other induction-variable increments). In other words, we're looking for loop
97bf45efdeSHal Finkel // bodies of the form:
98bf45efdeSHal Finkel //
99bf45efdeSHal Finkel // %iv = phi [ (preheader, ...), (body, %iv.next) ]
100bf45efdeSHal Finkel // f(%iv)
101bf45efdeSHal Finkel // %iv.1 = add %iv, 1 <-- a root increment
102bf45efdeSHal Finkel // f(%iv.1)
103bf45efdeSHal Finkel // %iv.2 = add %iv, 2 <-- a root increment
104bf45efdeSHal Finkel // f(%iv.2)
105bf45efdeSHal Finkel // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
106bf45efdeSHal Finkel // f(%iv.scale_m_1)
107bf45efdeSHal Finkel // ...
108bf45efdeSHal Finkel // %iv.next = add %iv, scale
109bf45efdeSHal Finkel // %cmp = icmp(%iv, ...)
110bf45efdeSHal Finkel // br %cmp, header, exit
111bf45efdeSHal Finkel //
112bf45efdeSHal Finkel // where each f(i) is a set of instructions that, collectively, are a function
113bf45efdeSHal Finkel // only of i (and other loop-invariant values).
114bf45efdeSHal Finkel //
115bf45efdeSHal Finkel // As a special case, we can also reroll loops like this:
116bf45efdeSHal Finkel //
117bf45efdeSHal Finkel // int foo(int);
118bf45efdeSHal Finkel // void bar(int *x) {
119bf45efdeSHal Finkel // for (int i = 0; i < 500; ++i) {
120bf45efdeSHal Finkel // x[3*i] = foo(0);
121bf45efdeSHal Finkel // x[3*i+1] = foo(0);
122bf45efdeSHal Finkel // x[3*i+2] = foo(0);
123bf45efdeSHal Finkel // }
124bf45efdeSHal Finkel // }
125bf45efdeSHal Finkel //
126bf45efdeSHal Finkel // into this:
127bf45efdeSHal Finkel //
128bf45efdeSHal Finkel // void bar(int *x) {
129bf45efdeSHal Finkel // for (int i = 0; i < 1500; ++i)
130bf45efdeSHal Finkel // x[i] = foo(0);
131bf45efdeSHal Finkel // }
132bf45efdeSHal Finkel //
133bf45efdeSHal Finkel // in which case, we're looking for inputs like this:
134bf45efdeSHal Finkel //
135bf45efdeSHal Finkel // %iv = phi [ (preheader, ...), (body, %iv.next) ]
136bf45efdeSHal Finkel // %scaled.iv = mul %iv, scale
137bf45efdeSHal Finkel // f(%scaled.iv)
138bf45efdeSHal Finkel // %scaled.iv.1 = add %scaled.iv, 1
139bf45efdeSHal Finkel // f(%scaled.iv.1)
140bf45efdeSHal Finkel // %scaled.iv.2 = add %scaled.iv, 2
141bf45efdeSHal Finkel // f(%scaled.iv.2)
142bf45efdeSHal Finkel // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
143bf45efdeSHal Finkel // f(%scaled.iv.scale_m_1)
144bf45efdeSHal Finkel // ...
145bf45efdeSHal Finkel // %iv.next = add %iv, 1
146bf45efdeSHal Finkel // %cmp = icmp(%iv, ...)
147bf45efdeSHal Finkel // br %cmp, header, exit
148bf45efdeSHal Finkel
149bf45efdeSHal Finkel namespace {
150306d2997SEugene Zelenko
15164419d41SJames Molloy enum IterationLimits {
1529914dbd1SElena Demikhovsky /// The maximum number of iterations that we'll try and reroll.
1539914dbd1SElena Demikhovsky IL_MaxRerollIterations = 32,
15464419d41SJames Molloy /// The bitvector index used by loop induction variables and other
155f1473593SJames Molloy /// instructions that belong to all iterations.
156f1473593SJames Molloy IL_All,
15764419d41SJames Molloy IL_End
15864419d41SJames Molloy };
15964419d41SJames Molloy
160d3f6972aSArthur Eubanks class LoopRerollLegacyPass : public LoopPass {
161bf45efdeSHal Finkel public:
162bf45efdeSHal Finkel static char ID; // Pass ID, replacement for typeid
163306d2997SEugene Zelenko
LoopRerollLegacyPass()164d3f6972aSArthur Eubanks LoopRerollLegacyPass() : LoopPass(ID) {
165d3f6972aSArthur Eubanks initializeLoopRerollLegacyPassPass(*PassRegistry::getPassRegistry());
166bf45efdeSHal Finkel }
167bf45efdeSHal Finkel
1683e4c697cSCraig Topper bool runOnLoop(Loop *L, LPPassManager &LPM) override;
169bf45efdeSHal Finkel
getAnalysisUsage(AnalysisUsage & AU) const1703e4c697cSCraig Topper void getAnalysisUsage(AnalysisUsage &AU) const override {
171b98f63dbSChandler Carruth AU.addRequired<TargetLibraryInfoWrapperPass>();
17231088a9dSChandler Carruth getLoopAnalysisUsage(AU);
173bf45efdeSHal Finkel }
174d3f6972aSArthur Eubanks };
175d3f6972aSArthur Eubanks
176d3f6972aSArthur Eubanks class LoopReroll {
177d3f6972aSArthur Eubanks public:
LoopReroll(AliasAnalysis * AA,LoopInfo * LI,ScalarEvolution * SE,TargetLibraryInfo * TLI,DominatorTree * DT,bool PreserveLCSSA)178d3f6972aSArthur Eubanks LoopReroll(AliasAnalysis *AA, LoopInfo *LI, ScalarEvolution *SE,
179d3f6972aSArthur Eubanks TargetLibraryInfo *TLI, DominatorTree *DT, bool PreserveLCSSA)
180d3f6972aSArthur Eubanks : AA(AA), LI(LI), SE(SE), TLI(TLI), DT(DT),
181d3f6972aSArthur Eubanks PreserveLCSSA(PreserveLCSSA) {}
182d3f6972aSArthur Eubanks bool runOnLoop(Loop *L);
183bf45efdeSHal Finkel
184bf45efdeSHal Finkel protected:
185bf45efdeSHal Finkel AliasAnalysis *AA;
186bf45efdeSHal Finkel LoopInfo *LI;
187bf45efdeSHal Finkel ScalarEvolution *SE;
188bf45efdeSHal Finkel TargetLibraryInfo *TLI;
189bf45efdeSHal Finkel DominatorTree *DT;
190843fb204SJustin Bogner bool PreserveLCSSA;
191bf45efdeSHal Finkel
192306d2997SEugene Zelenko using SmallInstructionVector = SmallVector<Instruction *, 16>;
19361998289SCraig Topper using SmallInstructionSet = SmallPtrSet<Instruction *, 16>;
194bf45efdeSHal Finkel
195dc8a83b5SLawrence Hu // Map between induction variable and its increment
196dc8a83b5SLawrence Hu DenseMap<Instruction *, int64_t> IVToIncMap;
197306d2997SEugene Zelenko
1981befea2bSLawrence Hu // For loop with multiple induction variable, remember the one used only to
1991befea2bSLawrence Hu // control the loop.
2001befea2bSLawrence Hu Instruction *LoopControlIV;
201dc8a83b5SLawrence Hu
202dc8a83b5SLawrence Hu // A chain of isomorphic instructions, identified by a single-use PHI
203bf45efdeSHal Finkel // representing a reduction. Only the last value may be used outside the
204bf45efdeSHal Finkel // loop.
205bf45efdeSHal Finkel struct SimpleLoopReduction {
SimpleLoopReduction__anon25f666240111::LoopReroll::SimpleLoopReduction206306d2997SEugene Zelenko SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
207bf45efdeSHal Finkel assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
208bf45efdeSHal Finkel add(L);
209bf45efdeSHal Finkel }
210bf45efdeSHal Finkel
valid__anon25f666240111::LoopReroll::SimpleLoopReduction211bf45efdeSHal Finkel bool valid() const {
212bf45efdeSHal Finkel return Valid;
213bf45efdeSHal Finkel }
214bf45efdeSHal Finkel
getPHI__anon25f666240111::LoopReroll::SimpleLoopReduction215bf45efdeSHal Finkel Instruction *getPHI() const {
216bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
217bf45efdeSHal Finkel return Instructions.front();
218bf45efdeSHal Finkel }
219bf45efdeSHal Finkel
getReducedValue__anon25f666240111::LoopReroll::SimpleLoopReduction220bf45efdeSHal Finkel Instruction *getReducedValue() const {
221bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
222bf45efdeSHal Finkel return Instructions.back();
223bf45efdeSHal Finkel }
224bf45efdeSHal Finkel
get__anon25f666240111::LoopReroll::SimpleLoopReduction225bf45efdeSHal Finkel Instruction *get(size_t i) const {
226bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
227bf45efdeSHal Finkel return Instructions[i+1];
228bf45efdeSHal Finkel }
229bf45efdeSHal Finkel
operator []__anon25f666240111::LoopReroll::SimpleLoopReduction230bf45efdeSHal Finkel Instruction *operator [] (size_t i) const { return get(i); }
231bf45efdeSHal Finkel
232bf45efdeSHal Finkel // The size, ignoring the initial PHI.
size__anon25f666240111::LoopReroll::SimpleLoopReduction233bf45efdeSHal Finkel size_t size() const {
234bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
235bf45efdeSHal Finkel return Instructions.size()-1;
236bf45efdeSHal Finkel }
237bf45efdeSHal Finkel
238306d2997SEugene Zelenko using iterator = SmallInstructionVector::iterator;
239306d2997SEugene Zelenko using const_iterator = SmallInstructionVector::const_iterator;
240bf45efdeSHal Finkel
begin__anon25f666240111::LoopReroll::SimpleLoopReduction241bf45efdeSHal Finkel iterator begin() {
242bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
243b6d0bd48SBenjamin Kramer return std::next(Instructions.begin());
244bf45efdeSHal Finkel }
245bf45efdeSHal Finkel
begin__anon25f666240111::LoopReroll::SimpleLoopReduction246bf45efdeSHal Finkel const_iterator begin() const {
247bf45efdeSHal Finkel assert(Valid && "Using invalid reduction");
248b6d0bd48SBenjamin Kramer return std::next(Instructions.begin());
249bf45efdeSHal Finkel }
250bf45efdeSHal Finkel
end__anon25f666240111::LoopReroll::SimpleLoopReduction251bf45efdeSHal Finkel iterator end() { return Instructions.end(); }
end__anon25f666240111::LoopReroll::SimpleLoopReduction252bf45efdeSHal Finkel const_iterator end() const { return Instructions.end(); }
253bf45efdeSHal Finkel
254bf45efdeSHal Finkel protected:
255306d2997SEugene Zelenko bool Valid = false;
256bf45efdeSHal Finkel SmallInstructionVector Instructions;
257bf45efdeSHal Finkel
258bf45efdeSHal Finkel void add(Loop *L);
259bf45efdeSHal Finkel };
260bf45efdeSHal Finkel
261bf45efdeSHal Finkel // The set of all reductions, and state tracking of possible reductions
262bf45efdeSHal Finkel // during loop instruction processing.
263bf45efdeSHal Finkel struct ReductionTracker {
264306d2997SEugene Zelenko using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
265bf45efdeSHal Finkel
266bf45efdeSHal Finkel // Add a new possible reduction.
addSLR__anon25f666240111::LoopReroll::ReductionTracker267d0e13af2SNAKAMURA Takumi void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
268bf45efdeSHal Finkel
269bf45efdeSHal Finkel // Setup to track possible reductions corresponding to the provided
270bf45efdeSHal Finkel // rerolling scale. Only reductions with a number of non-PHI instructions
271bf45efdeSHal Finkel // that is divisible by the scale are considered. Three instructions sets
272bf45efdeSHal Finkel // are filled in:
273bf45efdeSHal Finkel // - A set of all possible instructions in eligible reductions.
274bf45efdeSHal Finkel // - A set of all PHIs in eligible reductions
275d0e13af2SNAKAMURA Takumi // - A set of all reduced values (last instructions) in eligible
276d0e13af2SNAKAMURA Takumi // reductions.
restrictToScale__anon25f666240111::LoopReroll::ReductionTracker277bf45efdeSHal Finkel void restrictToScale(uint64_t Scale,
278bf45efdeSHal Finkel SmallInstructionSet &PossibleRedSet,
279bf45efdeSHal Finkel SmallInstructionSet &PossibleRedPHISet,
280bf45efdeSHal Finkel SmallInstructionSet &PossibleRedLastSet) {
281bf45efdeSHal Finkel PossibleRedIdx.clear();
282bf45efdeSHal Finkel PossibleRedIter.clear();
283bf45efdeSHal Finkel Reds.clear();
284bf45efdeSHal Finkel
285bf45efdeSHal Finkel for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
286bf45efdeSHal Finkel if (PossibleReds[i].size() % Scale == 0) {
287bf45efdeSHal Finkel PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
288bf45efdeSHal Finkel PossibleRedPHISet.insert(PossibleReds[i].getPHI());
289bf45efdeSHal Finkel
290bf45efdeSHal Finkel PossibleRedSet.insert(PossibleReds[i].getPHI());
291bf45efdeSHal Finkel PossibleRedIdx[PossibleReds[i].getPHI()] = i;
2925af50a54SNAKAMURA Takumi for (Instruction *J : PossibleReds[i]) {
2935af50a54SNAKAMURA Takumi PossibleRedSet.insert(J);
2945af50a54SNAKAMURA Takumi PossibleRedIdx[J] = i;
295bf45efdeSHal Finkel }
296bf45efdeSHal Finkel }
297bf45efdeSHal Finkel }
298bf45efdeSHal Finkel
299bf45efdeSHal Finkel // The functions below are used while processing the loop instructions.
300bf45efdeSHal Finkel
301bf45efdeSHal Finkel // Are the two instructions both from reductions, and furthermore, from
302bf45efdeSHal Finkel // the same reduction?
isPairInSame__anon25f666240111::LoopReroll::ReductionTracker303bf45efdeSHal Finkel bool isPairInSame(Instruction *J1, Instruction *J2) {
304bf45efdeSHal Finkel DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
305bf45efdeSHal Finkel if (J1I != PossibleRedIdx.end()) {
306bf45efdeSHal Finkel DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
307bf45efdeSHal Finkel if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
308bf45efdeSHal Finkel return true;
309bf45efdeSHal Finkel }
310bf45efdeSHal Finkel
311bf45efdeSHal Finkel return false;
312bf45efdeSHal Finkel }
313bf45efdeSHal Finkel
314bf45efdeSHal Finkel // The two provided instructions, the first from the base iteration, and
315bf45efdeSHal Finkel // the second from iteration i, form a matched pair. If these are part of
316bf45efdeSHal Finkel // a reduction, record that fact.
recordPair__anon25f666240111::LoopReroll::ReductionTracker317bf45efdeSHal Finkel void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
318bf45efdeSHal Finkel if (PossibleRedIdx.count(J1)) {
319bf45efdeSHal Finkel assert(PossibleRedIdx.count(J2) &&
320bf45efdeSHal Finkel "Recording reduction vs. non-reduction instruction?");
321bf45efdeSHal Finkel
322bf45efdeSHal Finkel PossibleRedIter[J1] = 0;
323bf45efdeSHal Finkel PossibleRedIter[J2] = i;
324bf45efdeSHal Finkel
325bf45efdeSHal Finkel int Idx = PossibleRedIdx[J1];
326bf45efdeSHal Finkel assert(Idx == PossibleRedIdx[J2] &&
327bf45efdeSHal Finkel "Recording pair from different reductions?");
32867107ea1SHal Finkel Reds.insert(Idx);
329bf45efdeSHal Finkel }
330bf45efdeSHal Finkel }
331bf45efdeSHal Finkel
332bf45efdeSHal Finkel // The functions below can be called after we've finished processing all
333bf45efdeSHal Finkel // instructions in the loop, and we know which reductions were selected.
334bf45efdeSHal Finkel
335bf45efdeSHal Finkel bool validateSelected();
336bf45efdeSHal Finkel void replaceSelected();
337bf45efdeSHal Finkel
338bf45efdeSHal Finkel protected:
339bf45efdeSHal Finkel // The vector of all possible reductions (for any scale).
340bf45efdeSHal Finkel SmallReductionVector PossibleReds;
341bf45efdeSHal Finkel
342bf45efdeSHal Finkel DenseMap<Instruction *, int> PossibleRedIdx;
343bf45efdeSHal Finkel DenseMap<Instruction *, int> PossibleRedIter;
344bf45efdeSHal Finkel DenseSet<int> Reds;
345bf45efdeSHal Finkel };
346bf45efdeSHal Finkel
347f1473593SJames Molloy // A DAGRootSet models an induction variable being used in a rerollable
348f1473593SJames Molloy // loop. For example,
349f1473593SJames Molloy //
350f1473593SJames Molloy // x[i*3+0] = y1
351f1473593SJames Molloy // x[i*3+1] = y2
352f1473593SJames Molloy // x[i*3+2] = y3
353f1473593SJames Molloy //
354f1473593SJames Molloy // Base instruction -> i*3
355f1473593SJames Molloy // +---+----+
356f1473593SJames Molloy // / | \
357f1473593SJames Molloy // ST[y1] +1 +2 <-- Roots
358f1473593SJames Molloy // | |
359f1473593SJames Molloy // ST[y2] ST[y3]
360f1473593SJames Molloy //
361f1473593SJames Molloy // There may be multiple DAGRoots, for example:
362f1473593SJames Molloy //
363f1473593SJames Molloy // x[i*2+0] = ... (1)
364f1473593SJames Molloy // x[i*2+1] = ... (1)
365f1473593SJames Molloy // x[i*2+4] = ... (2)
366f1473593SJames Molloy // x[i*2+5] = ... (2)
367f1473593SJames Molloy // x[(i+1234)*2+5678] = ... (3)
368f1473593SJames Molloy // x[(i+1234)*2+5679] = ... (3)
369f1473593SJames Molloy //
370f1473593SJames Molloy // The loop will be rerolled by adding a new loop induction variable,
371f1473593SJames Molloy // one for the Base instruction in each DAGRootSet.
372f1473593SJames Molloy //
373f1473593SJames Molloy struct DAGRootSet {
374f1473593SJames Molloy Instruction *BaseInst;
375f1473593SJames Molloy SmallInstructionVector Roots;
376306d2997SEugene Zelenko
377f1473593SJames Molloy // The instructions between IV and BaseInst (but not including BaseInst).
378f1473593SJames Molloy SmallInstructionSet SubsumedInsts;
379f1473593SJames Molloy };
380f1473593SJames Molloy
3815f255eb4SJames Molloy // The set of all DAG roots, and state tracking of all roots
3825f255eb4SJames Molloy // for a particular induction variable.
3835f255eb4SJames Molloy struct DAGRootTracker {
DAGRootTracker__anon25f666240111::LoopReroll::DAGRootTracker3845f255eb4SJames Molloy DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
3855f255eb4SJames Molloy ScalarEvolution *SE, AliasAnalysis *AA,
386843fb204SJustin Bogner TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
387843fb204SJustin Bogner bool PreserveLCSSA,
3881befea2bSLawrence Hu DenseMap<Instruction *, int64_t> &IncrMap,
3891befea2bSLawrence Hu Instruction *LoopCtrlIV)
390843fb204SJustin Bogner : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
3911befea2bSLawrence Hu PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
3921befea2bSLawrence Hu LoopControlIV(LoopCtrlIV) {}
3935f255eb4SJames Molloy
3945f255eb4SJames Molloy /// Stage 1: Find all the DAG roots for the induction variable.
3955f255eb4SJames Molloy bool findRoots();
396306d2997SEugene Zelenko
3975f255eb4SJames Molloy /// Stage 2: Validate if the found roots are valid.
3985f255eb4SJames Molloy bool validate(ReductionTracker &Reductions);
399306d2997SEugene Zelenko
4005f255eb4SJames Molloy /// Stage 3: Assuming validate() returned true, perform the
4015f255eb4SJames Molloy /// replacement.
402203eaaf5SEli Friedman /// @param BackedgeTakenCount The backedge-taken count of L.
403203eaaf5SEli Friedman void replace(const SCEV *BackedgeTakenCount);
4045f255eb4SJames Molloy
4055f255eb4SJames Molloy protected:
406306d2997SEugene Zelenko using UsesTy = MapVector<Instruction *, BitVector>;
40764419d41SJames Molloy
408c0bba1a9SEli Friedman void findRootsRecursive(Instruction *IVU,
409f1473593SJames Molloy SmallInstructionSet SubsumedInsts);
410f1473593SJames Molloy bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
411f1473593SJames Molloy bool collectPossibleRoots(Instruction *Base,
412f1473593SJames Molloy std::map<int64_t,Instruction*> &Roots);
413c0bba1a9SEli Friedman bool validateRootSet(DAGRootSet &DRS);
4145f255eb4SJames Molloy
41564419d41SJames Molloy bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
4165f255eb4SJames Molloy void collectInLoopUserSet(const SmallInstructionVector &Roots,
4175f255eb4SJames Molloy const SmallInstructionSet &Exclude,
4185f255eb4SJames Molloy const SmallInstructionSet &Final,
4195f255eb4SJames Molloy DenseSet<Instruction *> &Users);
4205f255eb4SJames Molloy void collectInLoopUserSet(Instruction *Root,
4215f255eb4SJames Molloy const SmallInstructionSet &Exclude,
4225f255eb4SJames Molloy const SmallInstructionSet &Final,
4235f255eb4SJames Molloy DenseSet<Instruction *> &Users);
4245f255eb4SJames Molloy
425e805ad95SJames Molloy UsesTy::iterator nextInstr(int Val, UsesTy &In,
426e805ad95SJames Molloy const SmallInstructionSet &Exclude,
427e805ad95SJames Molloy UsesTy::iterator *StartI=nullptr);
428f1473593SJames Molloy bool isBaseInst(Instruction *I);
429f1473593SJames Molloy bool isRootInst(Instruction *I);
430e805ad95SJames Molloy bool instrDependsOn(Instruction *I,
431e805ad95SJames Molloy UsesTy::iterator Start,
432e805ad95SJames Molloy UsesTy::iterator End);
433203eaaf5SEli Friedman void replaceIV(DAGRootSet &DRS, const SCEV *Start, const SCEV *IncrExpr);
43464419d41SJames Molloy
4355f255eb4SJames Molloy LoopReroll *Parent;
4365f255eb4SJames Molloy
4375f255eb4SJames Molloy // Members of Parent, replicated here for brevity.
4385f255eb4SJames Molloy Loop *L;
4395f255eb4SJames Molloy ScalarEvolution *SE;
4405f255eb4SJames Molloy AliasAnalysis *AA;
4415f255eb4SJames Molloy TargetLibraryInfo *TLI;
442843fb204SJustin Bogner DominatorTree *DT;
443843fb204SJustin Bogner LoopInfo *LI;
444843fb204SJustin Bogner bool PreserveLCSSA;
4455f255eb4SJames Molloy
4465f255eb4SJames Molloy // The loop induction variable.
4475f255eb4SJames Molloy Instruction *IV;
448306d2997SEugene Zelenko
4495f255eb4SJames Molloy // Loop step amount.
450dc8a83b5SLawrence Hu int64_t Inc;
451306d2997SEugene Zelenko
4525f255eb4SJames Molloy // Loop reroll count; if Inc == 1, this records the scaling applied
4535f255eb4SJames Molloy // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
4545f255eb4SJames Molloy // If Inc is not 1, Scale = Inc.
4555f255eb4SJames Molloy uint64_t Scale;
456306d2997SEugene Zelenko
4575f255eb4SJames Molloy // The roots themselves.
458f1473593SJames Molloy SmallVector<DAGRootSet,16> RootSets;
459306d2997SEugene Zelenko
4605f255eb4SJames Molloy // All increment instructions for IV.
4615f255eb4SJames Molloy SmallInstructionVector LoopIncs;
462306d2997SEugene Zelenko
46364419d41SJames Molloy // Map of all instructions in the loop (in order) to the iterations
464f1473593SJames Molloy // they are used in (or specially, IL_All for instructions
46564419d41SJames Molloy // used in the loop increment mechanism).
46664419d41SJames Molloy UsesTy Uses;
467306d2997SEugene Zelenko
468dc8a83b5SLawrence Hu // Map between induction variable and its increment
469dc8a83b5SLawrence Hu DenseMap<Instruction *, int64_t> &IVToIncMap;
470306d2997SEugene Zelenko
4711befea2bSLawrence Hu Instruction *LoopControlIV;
4725f255eb4SJames Molloy };
4735f255eb4SJames Molloy
4741befea2bSLawrence Hu // Check if it is a compare-like instruction whose user is a branch
isCompareUsedByBranch(Instruction * I)4751befea2bSLawrence Hu bool isCompareUsedByBranch(Instruction *I) {
4761befea2bSLawrence Hu auto *TI = I->getParent()->getTerminator();
4771befea2bSLawrence Hu if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
4781befea2bSLawrence Hu return false;
4791befea2bSLawrence Hu return I->hasOneUse() && TI->getOperand(0) == I;
4801befea2bSLawrence Hu };
4811befea2bSLawrence Hu
4821befea2bSLawrence Hu bool isLoopControlIV(Loop *L, Instruction *IV);
483bf45efdeSHal Finkel void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
484bf45efdeSHal Finkel void collectPossibleReductions(Loop *L,
485bf45efdeSHal Finkel ReductionTracker &Reductions);
486203eaaf5SEli Friedman bool reroll(Instruction *IV, Loop *L, BasicBlock *Header,
487203eaaf5SEli Friedman const SCEV *BackedgeTakenCount, ReductionTracker &Reductions);
488bf45efdeSHal Finkel };
489306d2997SEugene Zelenko
490306d2997SEugene Zelenko } // end anonymous namespace
491bf45efdeSHal Finkel
492d3f6972aSArthur Eubanks char LoopRerollLegacyPass::ID = 0;
493306d2997SEugene Zelenko
494d3f6972aSArthur Eubanks INITIALIZE_PASS_BEGIN(LoopRerollLegacyPass, "loop-reroll", "Reroll loops",
495d3f6972aSArthur Eubanks false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)49631088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
497b98f63dbSChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
498d3f6972aSArthur Eubanks INITIALIZE_PASS_END(LoopRerollLegacyPass, "loop-reroll", "Reroll loops", false,
499d3f6972aSArthur Eubanks false)
500bf45efdeSHal Finkel
501d3f6972aSArthur Eubanks Pass *llvm::createLoopRerollPass() { return new LoopRerollLegacyPass; }
502bf45efdeSHal Finkel
503bf45efdeSHal Finkel // Returns true if the provided instruction is used outside the given loop.
504bf45efdeSHal Finkel // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
505bf45efdeSHal Finkel // non-loop blocks to be outside the loop.
hasUsesOutsideLoop(Instruction * I,Loop * L)506bf45efdeSHal Finkel static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
50764419d41SJames Molloy for (User *U : I->users()) {
508cdf47884SChandler Carruth if (!L->contains(cast<Instruction>(U)))
509bf45efdeSHal Finkel return true;
51064419d41SJames Molloy }
511bf45efdeSHal Finkel return false;
512bf45efdeSHal Finkel }
513bf45efdeSHal Finkel
5141befea2bSLawrence Hu // Check if an IV is only used to control the loop. There are two cases:
5151befea2bSLawrence Hu // 1. It only has one use which is loop increment, and the increment is only
516e58a814cSLawrence Hu // used by comparison and the PHI (could has sext with nsw in between), and the
517e58a814cSLawrence Hu // comparison is only used by branch.
5181befea2bSLawrence Hu // 2. It is used by loop increment and the comparison, the loop increment is
5191befea2bSLawrence Hu // only used by the PHI, and the comparison is used only by the branch.
isLoopControlIV(Loop * L,Instruction * IV)5201befea2bSLawrence Hu bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
5211befea2bSLawrence Hu unsigned IVUses = IV->getNumUses();
5221befea2bSLawrence Hu if (IVUses != 2 && IVUses != 1)
5231befea2bSLawrence Hu return false;
5241befea2bSLawrence Hu
5251befea2bSLawrence Hu for (auto *User : IV->users()) {
5261befea2bSLawrence Hu int32_t IncOrCmpUses = User->getNumUses();
5271befea2bSLawrence Hu bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
5281befea2bSLawrence Hu
5291befea2bSLawrence Hu // User can only have one or two uses.
5301befea2bSLawrence Hu if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
5311befea2bSLawrence Hu return false;
5321befea2bSLawrence Hu
5331befea2bSLawrence Hu // Case 1
5341befea2bSLawrence Hu if (IVUses == 1) {
5351befea2bSLawrence Hu // The only user must be the loop increment.
5361befea2bSLawrence Hu // The loop increment must have two uses.
5371befea2bSLawrence Hu if (IsCompInst || IncOrCmpUses != 2)
5381befea2bSLawrence Hu return false;
5391befea2bSLawrence Hu }
5401befea2bSLawrence Hu
5411befea2bSLawrence Hu // Case 2
5421befea2bSLawrence Hu if (IVUses == 2 && IncOrCmpUses != 1)
5431befea2bSLawrence Hu return false;
5441befea2bSLawrence Hu
5451befea2bSLawrence Hu // The users of the IV must be a binary operation or a comparison
5461befea2bSLawrence Hu if (auto *BO = dyn_cast<BinaryOperator>(User)) {
5471befea2bSLawrence Hu if (BO->getOpcode() == Instruction::Add) {
5481befea2bSLawrence Hu // Loop Increment
5491befea2bSLawrence Hu // User of Loop Increment should be either PHI or CMP
5501befea2bSLawrence Hu for (auto *UU : User->users()) {
5511befea2bSLawrence Hu if (PHINode *PN = dyn_cast<PHINode>(UU)) {
5521befea2bSLawrence Hu if (PN != IV)
5531befea2bSLawrence Hu return false;
5541befea2bSLawrence Hu }
555e58a814cSLawrence Hu // Must be a CMP or an ext (of a value with nsw) then CMP
556e58a814cSLawrence Hu else {
557*a5d68514SSimon Pilgrim auto *UUser = cast<Instruction>(UU);
558e58a814cSLawrence Hu // Skip SExt if we are extending an nsw value
559e58a814cSLawrence Hu // TODO: Allow ZExt too
560*a5d68514SSimon Pilgrim if (BO->hasNoSignedWrap() && UUser->hasOneUse() &&
561e58a814cSLawrence Hu isa<SExtInst>(UUser))
562*a5d68514SSimon Pilgrim UUser = cast<Instruction>(*(UUser->user_begin()));
563e58a814cSLawrence Hu if (!isCompareUsedByBranch(UUser))
5641befea2bSLawrence Hu return false;
5651befea2bSLawrence Hu }
566e58a814cSLawrence Hu }
5671befea2bSLawrence Hu } else
5681befea2bSLawrence Hu return false;
5691befea2bSLawrence Hu // Compare : can only have one use, and must be branch
5701befea2bSLawrence Hu } else if (!IsCompInst)
5711befea2bSLawrence Hu return false;
5721befea2bSLawrence Hu }
5731befea2bSLawrence Hu return true;
5741befea2bSLawrence Hu }
5751befea2bSLawrence Hu
576bf45efdeSHal Finkel // Collect the list of loop induction variables with respect to which it might
577bf45efdeSHal Finkel // be possible to reroll the loop.
collectPossibleIVs(Loop * L,SmallInstructionVector & PossibleIVs)578bf45efdeSHal Finkel void LoopReroll::collectPossibleIVs(Loop *L,
579bf45efdeSHal Finkel SmallInstructionVector &PossibleIVs) {
580bf45efdeSHal Finkel BasicBlock *Header = L->getHeader();
581bf45efdeSHal Finkel for (BasicBlock::iterator I = Header->begin(),
582bf45efdeSHal Finkel IE = Header->getFirstInsertionPt(); I != IE; ++I) {
583bf45efdeSHal Finkel if (!isa<PHINode>(I))
584bf45efdeSHal Finkel continue;
585d3d51061SLawrence Hu if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
586bf45efdeSHal Finkel continue;
587bf45efdeSHal Finkel
588bf45efdeSHal Finkel if (const SCEVAddRecExpr *PHISCEV =
589be4d8cbaSDuncan P. N. Exon Smith dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
590bf45efdeSHal Finkel if (PHISCEV->getLoop() != L)
591bf45efdeSHal Finkel continue;
592bf45efdeSHal Finkel if (!PHISCEV->isAffine())
593bf45efdeSHal Finkel continue;
594203eaaf5SEli Friedman auto IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
595d3d51061SLawrence Hu if (IncSCEV) {
596be4d8cbaSDuncan P. N. Exon Smith IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
597d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
598dc8a83b5SLawrence Hu << "\n");
5991befea2bSLawrence Hu
6001befea2bSLawrence Hu if (isLoopControlIV(L, &*I)) {
6011befea2bSLawrence Hu assert(!LoopControlIV && "Found two loop control only IV");
6021befea2bSLawrence Hu LoopControlIV = &(*I);
603d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I
604d34e60caSNicola Zaghen << " = " << *PHISCEV << "\n");
6051befea2bSLawrence Hu } else
606be4d8cbaSDuncan P. N. Exon Smith PossibleIVs.push_back(&*I);
607bf45efdeSHal Finkel }
608bf45efdeSHal Finkel }
609bf45efdeSHal Finkel }
610bf45efdeSHal Finkel }
611bf45efdeSHal Finkel
612bf45efdeSHal Finkel // Add the remainder of the reduction-variable chain to the instruction vector
613bf45efdeSHal Finkel // (the initial PHINode has already been added). If successful, the object is
614bf45efdeSHal Finkel // marked as valid.
add(Loop * L)615bf45efdeSHal Finkel void LoopReroll::SimpleLoopReduction::add(Loop *L) {
616bf45efdeSHal Finkel assert(!Valid && "Cannot add to an already-valid chain");
617bf45efdeSHal Finkel
618bf45efdeSHal Finkel // The reduction variable must be a chain of single-use instructions
619bf45efdeSHal Finkel // (including the PHI), except for the last value (which is used by the PHI
620bf45efdeSHal Finkel // and also outside the loop).
621bf45efdeSHal Finkel Instruction *C = Instructions.front();
6224c7deb22SJames Molloy if (C->user_empty())
6234c7deb22SJames Molloy return;
624bf45efdeSHal Finkel
625bf45efdeSHal Finkel do {
626cdf47884SChandler Carruth C = cast<Instruction>(*C->user_begin());
627bf45efdeSHal Finkel if (C->hasOneUse()) {
628bf45efdeSHal Finkel if (!C->isBinaryOp())
629bf45efdeSHal Finkel return;
630bf45efdeSHal Finkel
631bf45efdeSHal Finkel if (!(isa<PHINode>(Instructions.back()) ||
632bf45efdeSHal Finkel C->isSameOperationAs(Instructions.back())))
633bf45efdeSHal Finkel return;
634bf45efdeSHal Finkel
635bf45efdeSHal Finkel Instructions.push_back(C);
636bf45efdeSHal Finkel }
637bf45efdeSHal Finkel } while (C->hasOneUse());
638bf45efdeSHal Finkel
639bf45efdeSHal Finkel if (Instructions.size() < 2 ||
640bf45efdeSHal Finkel !C->isSameOperationAs(Instructions.back()) ||
641cdf47884SChandler Carruth C->use_empty())
642bf45efdeSHal Finkel return;
643bf45efdeSHal Finkel
644bf45efdeSHal Finkel // C is now the (potential) last instruction in the reduction chain.
64564419d41SJames Molloy for (User *U : C->users()) {
646bf45efdeSHal Finkel // The only in-loop user can be the initial PHI.
647cdf47884SChandler Carruth if (L->contains(cast<Instruction>(U)))
648cdf47884SChandler Carruth if (cast<Instruction>(U) != Instructions.front())
649bf45efdeSHal Finkel return;
65064419d41SJames Molloy }
651bf45efdeSHal Finkel
652bf45efdeSHal Finkel Instructions.push_back(C);
653bf45efdeSHal Finkel Valid = true;
654bf45efdeSHal Finkel }
655bf45efdeSHal Finkel
656bf45efdeSHal Finkel // Collect the vector of possible reduction variables.
collectPossibleReductions(Loop * L,ReductionTracker & Reductions)657bf45efdeSHal Finkel void LoopReroll::collectPossibleReductions(Loop *L,
658bf45efdeSHal Finkel ReductionTracker &Reductions) {
659bf45efdeSHal Finkel BasicBlock *Header = L->getHeader();
660bf45efdeSHal Finkel for (BasicBlock::iterator I = Header->begin(),
661bf45efdeSHal Finkel IE = Header->getFirstInsertionPt(); I != IE; ++I) {
662bf45efdeSHal Finkel if (!isa<PHINode>(I))
663bf45efdeSHal Finkel continue;
664bf45efdeSHal Finkel if (!I->getType()->isSingleValueType())
665bf45efdeSHal Finkel continue;
666bf45efdeSHal Finkel
667be4d8cbaSDuncan P. N. Exon Smith SimpleLoopReduction SLR(&*I, L);
668bf45efdeSHal Finkel if (!SLR.valid())
669bf45efdeSHal Finkel continue;
670bf45efdeSHal Finkel
671d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with "
672d34e60caSNicola Zaghen << SLR.size() << " chained instructions)\n");
673bf45efdeSHal Finkel Reductions.addSLR(SLR);
674bf45efdeSHal Finkel }
675bf45efdeSHal Finkel }
676bf45efdeSHal Finkel
677bf45efdeSHal Finkel // Collect the set of all users of the provided root instruction. This set of
678bf45efdeSHal Finkel // users contains not only the direct users of the root instruction, but also
679bf45efdeSHal Finkel // all users of those users, and so on. There are two exceptions:
680bf45efdeSHal Finkel //
681bf45efdeSHal Finkel // 1. Instructions in the set of excluded instructions are never added to the
682bf45efdeSHal Finkel // use set (even if they are users). This is used, for example, to exclude
683bf45efdeSHal Finkel // including root increments in the use set of the primary IV.
684bf45efdeSHal Finkel //
685bf45efdeSHal Finkel // 2. Instructions in the set of final instructions are added to the use set
686bf45efdeSHal Finkel // if they are users, but their users are not added. This is used, for
687bf45efdeSHal Finkel // example, to prevent a reduction update from forcing all later reduction
688bf45efdeSHal Finkel // updates into the use set.
collectInLoopUserSet(Instruction * Root,const SmallInstructionSet & Exclude,const SmallInstructionSet & Final,DenseSet<Instruction * > & Users)6895f255eb4SJames Molloy void LoopReroll::DAGRootTracker::collectInLoopUserSet(
690bf45efdeSHal Finkel Instruction *Root, const SmallInstructionSet &Exclude,
691bf45efdeSHal Finkel const SmallInstructionSet &Final,
692bf45efdeSHal Finkel DenseSet<Instruction *> &Users) {
693bf45efdeSHal Finkel SmallInstructionVector Queue(1, Root);
694bf45efdeSHal Finkel while (!Queue.empty()) {
695bf45efdeSHal Finkel Instruction *I = Queue.pop_back_val();
696bf45efdeSHal Finkel if (!Users.insert(I).second)
697bf45efdeSHal Finkel continue;
698bf45efdeSHal Finkel
699bf45efdeSHal Finkel if (!Final.count(I))
700cdf47884SChandler Carruth for (Use &U : I->uses()) {
701cdf47884SChandler Carruth Instruction *User = cast<Instruction>(U.getUser());
702bf45efdeSHal Finkel if (PHINode *PN = dyn_cast<PHINode>(User)) {
703bf45efdeSHal Finkel // Ignore "wrap-around" uses to PHIs of this loop's header.
704cdf47884SChandler Carruth if (PN->getIncomingBlock(U) == L->getHeader())
705bf45efdeSHal Finkel continue;
706bf45efdeSHal Finkel }
707bf45efdeSHal Finkel
708bf45efdeSHal Finkel if (L->contains(User) && !Exclude.count(User)) {
709bf45efdeSHal Finkel Queue.push_back(User);
710bf45efdeSHal Finkel }
711bf45efdeSHal Finkel }
712bf45efdeSHal Finkel
713bf45efdeSHal Finkel // We also want to collect single-user "feeder" values.
7145fc9e309SKazu Hirata for (Use &U : I->operands()) {
7155fc9e309SKazu Hirata if (Instruction *Op = dyn_cast<Instruction>(U))
716bf45efdeSHal Finkel if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
717bf45efdeSHal Finkel !Final.count(Op))
718bf45efdeSHal Finkel Queue.push_back(Op);
719bf45efdeSHal Finkel }
720bf45efdeSHal Finkel }
721bf45efdeSHal Finkel }
722bf45efdeSHal Finkel
723bf45efdeSHal Finkel // Collect all of the users of all of the provided root instructions (combined
724bf45efdeSHal Finkel // into a single set).
collectInLoopUserSet(const SmallInstructionVector & Roots,const SmallInstructionSet & Exclude,const SmallInstructionSet & Final,DenseSet<Instruction * > & Users)7255f255eb4SJames Molloy void LoopReroll::DAGRootTracker::collectInLoopUserSet(
726bf45efdeSHal Finkel const SmallInstructionVector &Roots,
727bf45efdeSHal Finkel const SmallInstructionSet &Exclude,
728bf45efdeSHal Finkel const SmallInstructionSet &Final,
729bf45efdeSHal Finkel DenseSet<Instruction *> &Users) {
730135f735aSBenjamin Kramer for (Instruction *Root : Roots)
731135f735aSBenjamin Kramer collectInLoopUserSet(Root, Exclude, Final, Users);
732bf45efdeSHal Finkel }
733bf45efdeSHal Finkel
isUnorderedLoadStore(Instruction * I)734ab73c9d8SSanjoy Das static bool isUnorderedLoadStore(Instruction *I) {
735bf45efdeSHal Finkel if (LoadInst *LI = dyn_cast<LoadInst>(I))
736ab73c9d8SSanjoy Das return LI->isUnordered();
737bf45efdeSHal Finkel if (StoreInst *SI = dyn_cast<StoreInst>(I))
738ab73c9d8SSanjoy Das return SI->isUnordered();
739bf45efdeSHal Finkel if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
740bf45efdeSHal Finkel return !MI->isVolatile();
741bf45efdeSHal Finkel return false;
742bf45efdeSHal Finkel }
743bf45efdeSHal Finkel
744f1473593SJames Molloy /// Return true if IVU is a "simple" arithmetic operation.
745f1473593SJames Molloy /// This is used for narrowing the search space for DAGRoots; only arithmetic
746f1473593SJames Molloy /// and GEPs can be part of a DAGRoot.
isSimpleArithmeticOp(User * IVU)747f1473593SJames Molloy static bool isSimpleArithmeticOp(User *IVU) {
748f1473593SJames Molloy if (Instruction *I = dyn_cast<Instruction>(IVU)) {
749f1473593SJames Molloy switch (I->getOpcode()) {
750f1473593SJames Molloy default: return false;
751f1473593SJames Molloy case Instruction::Add:
752f1473593SJames Molloy case Instruction::Sub:
753f1473593SJames Molloy case Instruction::Mul:
754f1473593SJames Molloy case Instruction::Shl:
755f1473593SJames Molloy case Instruction::AShr:
756f1473593SJames Molloy case Instruction::LShr:
757f1473593SJames Molloy case Instruction::GetElementPtr:
758f1473593SJames Molloy case Instruction::Trunc:
759f1473593SJames Molloy case Instruction::ZExt:
760f1473593SJames Molloy case Instruction::SExt:
761f1473593SJames Molloy return true;
762f1473593SJames Molloy }
763f1473593SJames Molloy }
764f1473593SJames Molloy return false;
765f1473593SJames Molloy }
766f1473593SJames Molloy
isLoopIncrement(User * U,Instruction * IV)767f1473593SJames Molloy static bool isLoopIncrement(User *U, Instruction *IV) {
768f1473593SJames Molloy BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
769d3d51061SLawrence Hu
770d3d51061SLawrence Hu if ((BO && BO->getOpcode() != Instruction::Add) ||
771d3d51061SLawrence Hu (!BO && !isa<GetElementPtrInst>(U)))
772f1473593SJames Molloy return false;
773f1473593SJames Molloy
774d3d51061SLawrence Hu for (auto *UU : U->users()) {
775f1473593SJames Molloy PHINode *PN = dyn_cast<PHINode>(UU);
776f1473593SJames Molloy if (PN && PN == IV)
777f1473593SJames Molloy return true;
778f1473593SJames Molloy }
779f1473593SJames Molloy return false;
780f1473593SJames Molloy }
781f1473593SJames Molloy
782f1473593SJames Molloy bool LoopReroll::DAGRootTracker::
collectPossibleRoots(Instruction * Base,std::map<int64_t,Instruction * > & Roots)783f1473593SJames Molloy collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
784f1473593SJames Molloy SmallInstructionVector BaseUsers;
785f1473593SJames Molloy
786f1473593SJames Molloy for (auto *I : Base->users()) {
787f1473593SJames Molloy ConstantInt *CI = nullptr;
788f1473593SJames Molloy
789f1473593SJames Molloy if (isLoopIncrement(I, IV)) {
790f1473593SJames Molloy LoopIncs.push_back(cast<Instruction>(I));
791f1473593SJames Molloy continue;
792f1473593SJames Molloy }
793f1473593SJames Molloy
794f1473593SJames Molloy // The root nodes must be either GEPs, ORs or ADDs.
795f1473593SJames Molloy if (auto *BO = dyn_cast<BinaryOperator>(I)) {
796f1473593SJames Molloy if (BO->getOpcode() == Instruction::Add ||
797f1473593SJames Molloy BO->getOpcode() == Instruction::Or)
798f1473593SJames Molloy CI = dyn_cast<ConstantInt>(BO->getOperand(1));
799f1473593SJames Molloy } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
800f1473593SJames Molloy Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
801f1473593SJames Molloy CI = dyn_cast<ConstantInt>(LastOperand);
802f1473593SJames Molloy }
803f1473593SJames Molloy
804f1473593SJames Molloy if (!CI) {
805f1473593SJames Molloy if (Instruction *II = dyn_cast<Instruction>(I)) {
806f1473593SJames Molloy BaseUsers.push_back(II);
807f1473593SJames Molloy continue;
808f1473593SJames Molloy } else {
809d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I
810d34e60caSNicola Zaghen << "\n");
811f1473593SJames Molloy return false;
812f1473593SJames Molloy }
813f1473593SJames Molloy }
814f1473593SJames Molloy
815dc8a83b5SLawrence Hu int64_t V = std::abs(CI->getValue().getSExtValue());
816f1473593SJames Molloy if (Roots.find(V) != Roots.end())
817f1473593SJames Molloy // No duplicates, please.
818f1473593SJames Molloy return false;
819f1473593SJames Molloy
820f1473593SJames Molloy Roots[V] = cast<Instruction>(I);
821f1473593SJames Molloy }
822f1473593SJames Molloy
823c0bba1a9SEli Friedman // Make sure we have at least two roots.
824c0bba1a9SEli Friedman if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
825f1473593SJames Molloy return false;
826f1473593SJames Molloy
827f1473593SJames Molloy // If we found non-loop-inc, non-root users of Base, assume they are
828f1473593SJames Molloy // for the zeroth root index. This is because "add %a, 0" gets optimized
829f1473593SJames Molloy // away.
830e32d806bSJames Molloy if (BaseUsers.size()) {
831e32d806bSJames Molloy if (Roots.find(0) != Roots.end()) {
832d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
833e32d806bSJames Molloy return false;
834e32d806bSJames Molloy }
835f1473593SJames Molloy Roots[0] = Base;
836e32d806bSJames Molloy }
837f1473593SJames Molloy
838f1473593SJames Molloy // Calculate the number of users of the base, or lowest indexed, iteration.
839f1473593SJames Molloy unsigned NumBaseUses = BaseUsers.size();
840f1473593SJames Molloy if (NumBaseUses == 0)
841f1473593SJames Molloy NumBaseUses = Roots.begin()->second->getNumUses();
842f1473593SJames Molloy
843f1473593SJames Molloy // Check that every node has the same number of users.
844f1473593SJames Molloy for (auto &KV : Roots) {
845f1473593SJames Molloy if (KV.first == 0)
846f1473593SJames Molloy continue;
84780fe987bSDavide Italiano if (!KV.second->hasNUses(NumBaseUses)) {
848d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
849d34e60caSNicola Zaghen << "#Base=" << NumBaseUses
850d34e60caSNicola Zaghen << ", #Root=" << KV.second->getNumUses() << "\n");
851f1473593SJames Molloy return false;
852f1473593SJames Molloy }
853f1473593SJames Molloy }
854f1473593SJames Molloy
855f1473593SJames Molloy return true;
856f1473593SJames Molloy }
857f1473593SJames Molloy
858c0bba1a9SEli Friedman void LoopReroll::DAGRootTracker::
findRootsRecursive(Instruction * I,SmallInstructionSet SubsumedInsts)859f1473593SJames Molloy findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
860f1473593SJames Molloy // Does the user look like it could be part of a root set?
861f1473593SJames Molloy // All its users must be simple arithmetic ops.
86280fe987bSDavide Italiano if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
863c0bba1a9SEli Friedman return;
864f1473593SJames Molloy
865c0bba1a9SEli Friedman if (I != IV && findRootsBase(I, SubsumedInsts))
866c0bba1a9SEli Friedman return;
867f1473593SJames Molloy
868f1473593SJames Molloy SubsumedInsts.insert(I);
869f1473593SJames Molloy
870f1473593SJames Molloy for (User *V : I->users()) {
871c0bba1a9SEli Friedman Instruction *I = cast<Instruction>(V);
8720d955d0bSDavid Majnemer if (is_contained(LoopIncs, I))
873f1473593SJames Molloy continue;
874f1473593SJames Molloy
875c0bba1a9SEli Friedman if (!isSimpleArithmeticOp(I))
876c0bba1a9SEli Friedman continue;
877c0bba1a9SEli Friedman
878c0bba1a9SEli Friedman // The recursive call makes a copy of SubsumedInsts.
879c0bba1a9SEli Friedman findRootsRecursive(I, SubsumedInsts);
880f1473593SJames Molloy }
881c0bba1a9SEli Friedman }
882c0bba1a9SEli Friedman
validateRootSet(DAGRootSet & DRS)883c0bba1a9SEli Friedman bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
884c0bba1a9SEli Friedman if (DRS.Roots.empty())
885c0bba1a9SEli Friedman return false;
886c0bba1a9SEli Friedman
887272bc25bSKAWASHIMA Takahiro // If the value of the base instruction is used outside the loop, we cannot
888272bc25bSKAWASHIMA Takahiro // reroll the loop. Check for other root instructions is unnecessary because
889272bc25bSKAWASHIMA Takahiro // they don't match any base instructions if their values are used outside.
890272bc25bSKAWASHIMA Takahiro if (hasUsesOutsideLoop(DRS.BaseInst, L))
891272bc25bSKAWASHIMA Takahiro return false;
892272bc25bSKAWASHIMA Takahiro
893c0bba1a9SEli Friedman // Consider a DAGRootSet with N-1 roots (so N different values including
894c0bba1a9SEli Friedman // BaseInst).
895c0bba1a9SEli Friedman // Define d = Roots[0] - BaseInst, which should be the same as
896c0bba1a9SEli Friedman // Roots[I] - Roots[I-1] for all I in [1..N).
897c0bba1a9SEli Friedman // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
898c0bba1a9SEli Friedman // loop iteration J.
899c0bba1a9SEli Friedman //
900c0bba1a9SEli Friedman // Now, For the loop iterations to be consecutive:
901c0bba1a9SEli Friedman // D = d * N
902c0bba1a9SEli Friedman const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
903c0bba1a9SEli Friedman if (!ADR)
904c0bba1a9SEli Friedman return false;
905806136f8SEli Friedman
906806136f8SEli Friedman // Check that the first root is evenly spaced.
907c0bba1a9SEli Friedman unsigned N = DRS.Roots.size() + 1;
908c0bba1a9SEli Friedman const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
9095d1ba534SEli Friedman if (isa<SCEVCouldNotCompute>(StepSCEV) || StepSCEV->getType()->isPointerTy())
9107ac1c7beSEli Friedman return false;
911c0bba1a9SEli Friedman const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
912c0bba1a9SEli Friedman if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
913c0bba1a9SEli Friedman return false;
914c0bba1a9SEli Friedman
915806136f8SEli Friedman // Check that the remainling roots are evenly spaced.
916806136f8SEli Friedman for (unsigned i = 1; i < N - 1; ++i) {
917806136f8SEli Friedman const SCEV *NewStepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[i]),
918806136f8SEli Friedman SE->getSCEV(DRS.Roots[i-1]));
919806136f8SEli Friedman if (NewStepSCEV != StepSCEV)
920806136f8SEli Friedman return false;
921806136f8SEli Friedman }
922806136f8SEli Friedman
923f1473593SJames Molloy return true;
924f1473593SJames Molloy }
925f1473593SJames Molloy
926f1473593SJames Molloy bool LoopReroll::DAGRootTracker::
findRootsBase(Instruction * IVU,SmallInstructionSet SubsumedInsts)927f1473593SJames Molloy findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
928c0bba1a9SEli Friedman // The base of a RootSet must be an AddRec, so it can be erased.
929c0bba1a9SEli Friedman const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
930c0bba1a9SEli Friedman if (!IVU_ADR || IVU_ADR->getLoop() != L)
931f1473593SJames Molloy return false;
932f1473593SJames Molloy
933f1473593SJames Molloy std::map<int64_t, Instruction*> V;
934f1473593SJames Molloy if (!collectPossibleRoots(IVU, V))
935f1473593SJames Molloy return false;
936f1473593SJames Molloy
937f1473593SJames Molloy // If we didn't get a root for index zero, then IVU must be
938f1473593SJames Molloy // subsumed.
939f1473593SJames Molloy if (V.find(0) == V.end())
940f1473593SJames Molloy SubsumedInsts.insert(IVU);
941f1473593SJames Molloy
942f1473593SJames Molloy // Partition the vector into monotonically increasing indexes.
943f1473593SJames Molloy DAGRootSet DRS;
944f1473593SJames Molloy DRS.BaseInst = nullptr;
945f1473593SJames Molloy
946c0bba1a9SEli Friedman SmallVector<DAGRootSet, 16> PotentialRootSets;
947c0bba1a9SEli Friedman
948f1473593SJames Molloy for (auto &KV : V) {
949f1473593SJames Molloy if (!DRS.BaseInst) {
950f1473593SJames Molloy DRS.BaseInst = KV.second;
951f1473593SJames Molloy DRS.SubsumedInsts = SubsumedInsts;
952f1473593SJames Molloy } else if (DRS.Roots.empty()) {
953f1473593SJames Molloy DRS.Roots.push_back(KV.second);
954f1473593SJames Molloy } else if (V.find(KV.first - 1) != V.end()) {
955f1473593SJames Molloy DRS.Roots.push_back(KV.second);
956f1473593SJames Molloy } else {
957f1473593SJames Molloy // Linear sequence terminated.
958c0bba1a9SEli Friedman if (!validateRootSet(DRS))
959c0bba1a9SEli Friedman return false;
960c0bba1a9SEli Friedman
961c0bba1a9SEli Friedman // Construct a new DAGRootSet with the next sequence.
962c0bba1a9SEli Friedman PotentialRootSets.push_back(DRS);
963f1473593SJames Molloy DRS.BaseInst = KV.second;
964f1473593SJames Molloy DRS.Roots.clear();
965f1473593SJames Molloy }
966f1473593SJames Molloy }
967c0bba1a9SEli Friedman
968c0bba1a9SEli Friedman if (!validateRootSet(DRS))
969c0bba1a9SEli Friedman return false;
970c0bba1a9SEli Friedman
971c0bba1a9SEli Friedman PotentialRootSets.push_back(DRS);
972c0bba1a9SEli Friedman
973c0bba1a9SEli Friedman RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
974f1473593SJames Molloy
975f1473593SJames Molloy return true;
976f1473593SJames Molloy }
977f1473593SJames Molloy
findRoots()9785f255eb4SJames Molloy bool LoopReroll::DAGRootTracker::findRoots() {
979dc8a83b5SLawrence Hu Inc = IVToIncMap[IV];
9805f255eb4SJames Molloy
981f1473593SJames Molloy assert(RootSets.empty() && "Unclean state!");
982dc8a83b5SLawrence Hu if (std::abs(Inc) == 1) {
983f1473593SJames Molloy for (auto *IVU : IV->users()) {
984f1473593SJames Molloy if (isLoopIncrement(IVU, IV))
985f1473593SJames Molloy LoopIncs.push_back(cast<Instruction>(IVU));
986f1473593SJames Molloy }
987c0bba1a9SEli Friedman findRootsRecursive(IV, SmallInstructionSet());
988f1473593SJames Molloy LoopIncs.push_back(IV);
989f1473593SJames Molloy } else {
990f1473593SJames Molloy if (!findRootsBase(IV, SmallInstructionSet()))
991f1473593SJames Molloy return false;
992f1473593SJames Molloy }
993f1473593SJames Molloy
994f1473593SJames Molloy // Ensure all sets have the same size.
995f1473593SJames Molloy if (RootSets.empty()) {
996d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
997f1473593SJames Molloy return false;
998f1473593SJames Molloy }
999f1473593SJames Molloy for (auto &V : RootSets) {
1000f1473593SJames Molloy if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
1001d34e60caSNicola Zaghen LLVM_DEBUG(
1002d34e60caSNicola Zaghen dbgs()
1003f1473593SJames Molloy << "LRR: Aborting because not all root sets have the same size\n");
1004f1473593SJames Molloy return false;
1005f1473593SJames Molloy }
1006f1473593SJames Molloy }
1007f1473593SJames Molloy
1008f1473593SJames Molloy Scale = RootSets[0].Roots.size() + 1;
1009f1473593SJames Molloy
1010f1473593SJames Molloy if (Scale > IL_MaxRerollIterations) {
1011d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
1012d34e60caSNicola Zaghen << "#Found=" << Scale
1013d34e60caSNicola Zaghen << ", #Max=" << IL_MaxRerollIterations << "\n");
101464419d41SJames Molloy return false;
101564419d41SJames Molloy }
101664419d41SJames Molloy
1017d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale
1018d34e60caSNicola Zaghen << "\n");
10195f255eb4SJames Molloy
10205f255eb4SJames Molloy return true;
10215f255eb4SJames Molloy }
10225f255eb4SJames Molloy
collectUsedInstructions(SmallInstructionSet & PossibleRedSet)102364419d41SJames Molloy bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
102464419d41SJames Molloy // Populate the MapVector with all instructions in the block, in order first,
102564419d41SJames Molloy // so we can iterate over the contents later in perfect order.
102664419d41SJames Molloy for (auto &I : *L->getHeader()) {
102764419d41SJames Molloy Uses[&I].resize(IL_End);
102864419d41SJames Molloy }
10295f255eb4SJames Molloy
103064419d41SJames Molloy SmallInstructionSet Exclude;
1031f1473593SJames Molloy for (auto &DRS : RootSets) {
1032f1473593SJames Molloy Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1033f1473593SJames Molloy Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1034f1473593SJames Molloy Exclude.insert(DRS.BaseInst);
1035f1473593SJames Molloy }
103664419d41SJames Molloy Exclude.insert(LoopIncs.begin(), LoopIncs.end());
103764419d41SJames Molloy
1038f1473593SJames Molloy for (auto &DRS : RootSets) {
103964419d41SJames Molloy DenseSet<Instruction*> VBase;
1040f1473593SJames Molloy collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
104164419d41SJames Molloy for (auto *I : VBase) {
104264419d41SJames Molloy Uses[I].set(0);
104364419d41SJames Molloy }
104464419d41SJames Molloy
104564419d41SJames Molloy unsigned Idx = 1;
1046f1473593SJames Molloy for (auto *Root : DRS.Roots) {
104764419d41SJames Molloy DenseSet<Instruction*> V;
104864419d41SJames Molloy collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
104964419d41SJames Molloy
105064419d41SJames Molloy // While we're here, check the use sets are the same size.
105164419d41SJames Molloy if (V.size() != VBase.size()) {
1052d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
105364419d41SJames Molloy return false;
105464419d41SJames Molloy }
105564419d41SJames Molloy
105664419d41SJames Molloy for (auto *I : V) {
105764419d41SJames Molloy Uses[I].set(Idx);
105864419d41SJames Molloy }
105964419d41SJames Molloy ++Idx;
106064419d41SJames Molloy }
106164419d41SJames Molloy
1062f1473593SJames Molloy // Make sure our subsumed instructions are remembered too.
1063f1473593SJames Molloy for (auto *I : DRS.SubsumedInsts) {
1064f1473593SJames Molloy Uses[I].set(IL_All);
1065f1473593SJames Molloy }
1066f1473593SJames Molloy }
1067f1473593SJames Molloy
106864419d41SJames Molloy // Make sure the loop increments are also accounted for.
1069f1473593SJames Molloy
107064419d41SJames Molloy Exclude.clear();
1071f1473593SJames Molloy for (auto &DRS : RootSets) {
1072f1473593SJames Molloy Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1073f1473593SJames Molloy Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1074f1473593SJames Molloy Exclude.insert(DRS.BaseInst);
1075f1473593SJames Molloy }
107664419d41SJames Molloy
107764419d41SJames Molloy DenseSet<Instruction*> V;
107864419d41SJames Molloy collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
107964419d41SJames Molloy for (auto *I : V) {
1080d9a9c992SKAWASHIMA Takahiro if (I->mayHaveSideEffects()) {
1081d9a9c992SKAWASHIMA Takahiro LLVM_DEBUG(dbgs() << "LRR: Aborting - "
1082d9a9c992SKAWASHIMA Takahiro << "An instruction which does not belong to any root "
1083d9a9c992SKAWASHIMA Takahiro << "sets must not have side effects: " << *I);
1084d9a9c992SKAWASHIMA Takahiro return false;
1085d9a9c992SKAWASHIMA Takahiro }
1086f1473593SJames Molloy Uses[I].set(IL_All);
108764419d41SJames Molloy }
108864419d41SJames Molloy
108964419d41SJames Molloy return true;
109064419d41SJames Molloy }
109164419d41SJames Molloy
1092e805ad95SJames Molloy /// Get the next instruction in "In" that is a member of set Val.
1093e805ad95SJames Molloy /// Start searching from StartI, and do not return anything in Exclude.
1094e805ad95SJames Molloy /// If StartI is not given, start from In.begin().
109564419d41SJames Molloy LoopReroll::DAGRootTracker::UsesTy::iterator
nextInstr(int Val,UsesTy & In,const SmallInstructionSet & Exclude,UsesTy::iterator * StartI)109664419d41SJames Molloy LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
1097e805ad95SJames Molloy const SmallInstructionSet &Exclude,
1098e805ad95SJames Molloy UsesTy::iterator *StartI) {
1099e805ad95SJames Molloy UsesTy::iterator I = StartI ? *StartI : In.begin();
1100e805ad95SJames Molloy while (I != In.end() && (I->second.test(Val) == 0 ||
110133bf1cadSKazu Hirata Exclude.contains(I->first)))
110264419d41SJames Molloy ++I;
110364419d41SJames Molloy return I;
110464419d41SJames Molloy }
110564419d41SJames Molloy
isBaseInst(Instruction * I)1106f1473593SJames Molloy bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1107f1473593SJames Molloy for (auto &DRS : RootSets) {
1108f1473593SJames Molloy if (DRS.BaseInst == I)
1109f1473593SJames Molloy return true;
1110f1473593SJames Molloy }
1111f1473593SJames Molloy return false;
1112f1473593SJames Molloy }
1113f1473593SJames Molloy
isRootInst(Instruction * I)1114f1473593SJames Molloy bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1115f1473593SJames Molloy for (auto &DRS : RootSets) {
11160d955d0bSDavid Majnemer if (is_contained(DRS.Roots, I))
1117f1473593SJames Molloy return true;
1118f1473593SJames Molloy }
1119f1473593SJames Molloy return false;
1120f1473593SJames Molloy }
1121f1473593SJames Molloy
1122e805ad95SJames Molloy /// Return true if instruction I depends on any instruction between
1123e805ad95SJames Molloy /// Start and End.
instrDependsOn(Instruction * I,UsesTy::iterator Start,UsesTy::iterator End)1124e805ad95SJames Molloy bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1125e805ad95SJames Molloy UsesTy::iterator Start,
1126e805ad95SJames Molloy UsesTy::iterator End) {
1127e805ad95SJames Molloy for (auto *U : I->users()) {
1128e805ad95SJames Molloy for (auto It = Start; It != End; ++It)
1129e805ad95SJames Molloy if (U == It->first)
1130e805ad95SJames Molloy return true;
1131e805ad95SJames Molloy }
1132e805ad95SJames Molloy return false;
1133e805ad95SJames Molloy }
1134e805ad95SJames Molloy
isIgnorableInst(const Instruction * I)1135310770a9SWeiming Zhao static bool isIgnorableInst(const Instruction *I) {
1136310770a9SWeiming Zhao if (isa<DbgInfoIntrinsic>(I))
1137310770a9SWeiming Zhao return true;
1138310770a9SWeiming Zhao const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1139310770a9SWeiming Zhao if (!II)
1140310770a9SWeiming Zhao return false;
1141310770a9SWeiming Zhao switch (II->getIntrinsicID()) {
1142310770a9SWeiming Zhao default:
1143310770a9SWeiming Zhao return false;
1144306d2997SEugene Zelenko case Intrinsic::annotation:
1145310770a9SWeiming Zhao case Intrinsic::ptr_annotation:
1146310770a9SWeiming Zhao case Intrinsic::var_annotation:
114710563e16SEric Christopher // TODO: the following intrinsics may also be allowed:
1148310770a9SWeiming Zhao // lifetime_start, lifetime_end, invariant_start, invariant_end
1149310770a9SWeiming Zhao return true;
1150310770a9SWeiming Zhao }
1151310770a9SWeiming Zhao return false;
1152310770a9SWeiming Zhao }
1153310770a9SWeiming Zhao
validate(ReductionTracker & Reductions)115464419d41SJames Molloy bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
11555f255eb4SJames Molloy // We now need to check for equivalence of the use graph of each root with
11565f255eb4SJames Molloy // that of the primary induction variable (excluding the roots). Our goal
11575f255eb4SJames Molloy // here is not to solve the full graph isomorphism problem, but rather to
11585f255eb4SJames Molloy // catch common cases without a lot of work. As a result, we will assume
11595f255eb4SJames Molloy // that the relative order of the instructions in each unrolled iteration
11605f255eb4SJames Molloy // is the same (although we will not make an assumption about how the
11615f255eb4SJames Molloy // different iterations are intermixed). Note that while the order must be
11625f255eb4SJames Molloy // the same, the instructions may not be in the same basic block.
11635f255eb4SJames Molloy
11645f255eb4SJames Molloy // An array of just the possible reductions for this scale factor. When we
11655f255eb4SJames Molloy // collect the set of all users of some root instructions, these reduction
11665f255eb4SJames Molloy // instructions are treated as 'final' (their uses are not considered).
11675f255eb4SJames Molloy // This is important because we don't want the root use set to search down
11685f255eb4SJames Molloy // the reduction chain.
11695f255eb4SJames Molloy SmallInstructionSet PossibleRedSet;
11705f255eb4SJames Molloy SmallInstructionSet PossibleRedLastSet;
11715f255eb4SJames Molloy SmallInstructionSet PossibleRedPHISet;
11725f255eb4SJames Molloy Reductions.restrictToScale(Scale, PossibleRedSet,
11735f255eb4SJames Molloy PossibleRedPHISet, PossibleRedLastSet);
11745f255eb4SJames Molloy
117564419d41SJames Molloy // Populate "Uses" with where each instruction is used.
117664419d41SJames Molloy if (!collectUsedInstructions(PossibleRedSet))
117764419d41SJames Molloy return false;
11785f255eb4SJames Molloy
117964419d41SJames Molloy // Make sure we mark the reduction PHIs as used in all iterations.
118064419d41SJames Molloy for (auto *I : PossibleRedPHISet) {
1181f1473593SJames Molloy Uses[I].set(IL_All);
1182bf45efdeSHal Finkel }
1183bf45efdeSHal Finkel
11841befea2bSLawrence Hu // Make sure we mark loop-control-only PHIs as used in all iterations. See
11851befea2bSLawrence Hu // comment above LoopReroll::isLoopControlIV for more information.
11861befea2bSLawrence Hu BasicBlock *Header = L->getHeader();
11871befea2bSLawrence Hu if (LoopControlIV && LoopControlIV != IV) {
11881befea2bSLawrence Hu for (auto *U : LoopControlIV->users()) {
11891befea2bSLawrence Hu Instruction *IVUser = dyn_cast<Instruction>(U);
11901befea2bSLawrence Hu // IVUser could be loop increment or compare
11911befea2bSLawrence Hu Uses[IVUser].set(IL_All);
11921befea2bSLawrence Hu for (auto *UU : IVUser->users()) {
11931befea2bSLawrence Hu Instruction *UUser = dyn_cast<Instruction>(UU);
11941befea2bSLawrence Hu // UUser could be compare, PHI or branch
11951befea2bSLawrence Hu Uses[UUser].set(IL_All);
1196e58a814cSLawrence Hu // Skip SExt
1197e58a814cSLawrence Hu if (isa<SExtInst>(UUser)) {
1198e58a814cSLawrence Hu UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1199e58a814cSLawrence Hu Uses[UUser].set(IL_All);
1200e58a814cSLawrence Hu }
12011befea2bSLawrence Hu // Is UUser a compare instruction?
12021befea2bSLawrence Hu if (UU->hasOneUse()) {
12031befea2bSLawrence Hu Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
12041befea2bSLawrence Hu if (BI == cast<BranchInst>(Header->getTerminator()))
12051befea2bSLawrence Hu Uses[BI].set(IL_All);
12061befea2bSLawrence Hu }
12071befea2bSLawrence Hu }
12081befea2bSLawrence Hu }
12091befea2bSLawrence Hu }
12101befea2bSLawrence Hu
121164419d41SJames Molloy // Make sure all instructions in the loop are in one and only one
121264419d41SJames Molloy // set.
121364419d41SJames Molloy for (auto &KV : Uses) {
1214310770a9SWeiming Zhao if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
1215d34e60caSNicola Zaghen LLVM_DEBUG(
1216d34e60caSNicola Zaghen dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
121764419d41SJames Molloy << *KV.first << " (#uses=" << KV.second.count() << ")\n");
121864419d41SJames Molloy return false;
121964419d41SJames Molloy }
122064419d41SJames Molloy }
122164419d41SJames Molloy
1222d34e60caSNicola Zaghen LLVM_DEBUG(for (auto &KV
1223d34e60caSNicola Zaghen : Uses) {
122464419d41SJames Molloy dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1225d34e60caSNicola Zaghen });
122664419d41SJames Molloy
122764419d41SJames Molloy for (unsigned Iter = 1; Iter < Scale; ++Iter) {
12285f255eb4SJames Molloy // In addition to regular aliasing information, we need to look for
12295f255eb4SJames Molloy // instructions from later (future) iterations that have side effects
12305f255eb4SJames Molloy // preventing us from reordering them past other instructions with side
12315f255eb4SJames Molloy // effects.
12325f255eb4SJames Molloy bool FutureSideEffects = false;
12335f255eb4SJames Molloy AliasSetTracker AST(*AA);
12345f255eb4SJames Molloy // The map between instructions in f(%iv.(i+1)) and f(%iv).
12355f255eb4SJames Molloy DenseMap<Value *, Value *> BaseMap;
12365f255eb4SJames Molloy
123764419d41SJames Molloy // Compare iteration Iter to the base.
1238e805ad95SJames Molloy SmallInstructionSet Visited;
1239e805ad95SJames Molloy auto BaseIt = nextInstr(0, Uses, Visited);
1240e805ad95SJames Molloy auto RootIt = nextInstr(Iter, Uses, Visited);
124164419d41SJames Molloy auto LastRootIt = Uses.begin();
12425f255eb4SJames Molloy
124364419d41SJames Molloy while (BaseIt != Uses.end() && RootIt != Uses.end()) {
124464419d41SJames Molloy Instruction *BaseInst = BaseIt->first;
124564419d41SJames Molloy Instruction *RootInst = RootIt->first;
12465f255eb4SJames Molloy
124764419d41SJames Molloy // Skip over the IV or root instructions; only match their users.
124864419d41SJames Molloy bool Continue = false;
1249f1473593SJames Molloy if (isBaseInst(BaseInst)) {
1250e805ad95SJames Molloy Visited.insert(BaseInst);
1251e805ad95SJames Molloy BaseIt = nextInstr(0, Uses, Visited);
125264419d41SJames Molloy Continue = true;
125364419d41SJames Molloy }
1254f1473593SJames Molloy if (isRootInst(RootInst)) {
125564419d41SJames Molloy LastRootIt = RootIt;
1256e805ad95SJames Molloy Visited.insert(RootInst);
1257e805ad95SJames Molloy RootIt = nextInstr(Iter, Uses, Visited);
125864419d41SJames Molloy Continue = true;
125964419d41SJames Molloy }
126064419d41SJames Molloy if (Continue) continue;
126164419d41SJames Molloy
1262e805ad95SJames Molloy if (!BaseInst->isSameOperationAs(RootInst)) {
1263e805ad95SJames Molloy // Last chance saloon. We don't try and solve the full isomorphism
1264e805ad95SJames Molloy // problem, but try and at least catch the case where two instructions
1265e805ad95SJames Molloy // *of different types* are round the wrong way. We won't be able to
1266e805ad95SJames Molloy // efficiently tell, given two ADD instructions, which way around we
1267e805ad95SJames Molloy // should match them, but given an ADD and a SUB, we can at least infer
1268e805ad95SJames Molloy // which one is which.
1269e805ad95SJames Molloy //
1270e805ad95SJames Molloy // This should allow us to deal with a greater subset of the isomorphism
1271e805ad95SJames Molloy // problem. It does however change a linear algorithm into a quadratic
1272e805ad95SJames Molloy // one, so limit the number of probes we do.
1273e805ad95SJames Molloy auto TryIt = RootIt;
1274e805ad95SJames Molloy unsigned N = NumToleratedFailedMatches;
1275e805ad95SJames Molloy while (TryIt != Uses.end() &&
1276e805ad95SJames Molloy !BaseInst->isSameOperationAs(TryIt->first) &&
1277e805ad95SJames Molloy N--) {
1278e805ad95SJames Molloy ++TryIt;
1279e805ad95SJames Molloy TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1280e805ad95SJames Molloy }
1281e805ad95SJames Molloy
1282e805ad95SJames Molloy if (TryIt == Uses.end() || TryIt == RootIt ||
1283e805ad95SJames Molloy instrDependsOn(TryIt->first, RootIt, TryIt)) {
1284d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1285d34e60caSNicola Zaghen << *BaseInst << " vs. " << *RootInst << "\n");
1286e805ad95SJames Molloy return false;
1287e805ad95SJames Molloy }
1288e805ad95SJames Molloy
1289e805ad95SJames Molloy RootIt = TryIt;
1290e805ad95SJames Molloy RootInst = TryIt->first;
1291e805ad95SJames Molloy }
1292e805ad95SJames Molloy
129364419d41SJames Molloy // All instructions between the last root and this root
1294e805ad95SJames Molloy // may belong to some other iteration. If they belong to a
129564419d41SJames Molloy // future iteration, then they're dangerous to alias with.
1296e805ad95SJames Molloy //
1297e805ad95SJames Molloy // Note that because we allow a limited amount of flexibility in the order
1298e805ad95SJames Molloy // that we visit nodes, LastRootIt might be *before* RootIt, in which
1299e805ad95SJames Molloy // case we've already checked this set of instructions so we shouldn't
1300e805ad95SJames Molloy // do anything.
1301e805ad95SJames Molloy for (; LastRootIt < RootIt; ++LastRootIt) {
130264419d41SJames Molloy Instruction *I = LastRootIt->first;
130364419d41SJames Molloy if (LastRootIt->second.find_first() < (int)Iter)
130464419d41SJames Molloy continue;
130564419d41SJames Molloy if (I->mayWriteToMemory())
130664419d41SJames Molloy AST.add(I);
13075f255eb4SJames Molloy // Note: This is specifically guarded by a check on isa<PHINode>,
13085f255eb4SJames Molloy // which while a valid (somewhat arbitrary) micro-optimization, is
13095f255eb4SJames Molloy // needed because otherwise isSafeToSpeculativelyExecute returns
13105f255eb4SJames Molloy // false on PHI nodes.
1311ab73c9d8SSanjoy Das if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
1312a28d91d8SMehdi Amini !isSafeToSpeculativelyExecute(I))
131364419d41SJames Molloy // Intervening instructions cause side effects.
13145f255eb4SJames Molloy FutureSideEffects = true;
13155f255eb4SJames Molloy }
13165f255eb4SJames Molloy
13175f255eb4SJames Molloy // Make sure that this instruction, which is in the use set of this
13185f255eb4SJames Molloy // root instruction, does not also belong to the base set or the set of
131964419d41SJames Molloy // some other root instruction.
132064419d41SJames Molloy if (RootIt->second.count() > 1) {
1321d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1322d34e60caSNicola Zaghen << " vs. " << *RootInst << " (prev. case overlap)\n");
132364419d41SJames Molloy return false;
13245f255eb4SJames Molloy }
13255f255eb4SJames Molloy
13265f255eb4SJames Molloy // Make sure that we don't alias with any instruction in the alias set
13275f255eb4SJames Molloy // tracker. If we do, then we depend on a future iteration, and we
13285f255eb4SJames Molloy // can't reroll.
132964419d41SJames Molloy if (RootInst->mayReadFromMemory())
133064419d41SJames Molloy for (auto &K : AST) {
133164419d41SJames Molloy if (K.aliasesUnknownInst(RootInst, *AA)) {
1332d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
1333d34e60caSNicola Zaghen << *BaseInst << " vs. " << *RootInst
1334d34e60caSNicola Zaghen << " (depends on future store)\n");
133564419d41SJames Molloy return false;
13365f255eb4SJames Molloy }
13375f255eb4SJames Molloy }
13385f255eb4SJames Molloy
13395f255eb4SJames Molloy // If we've past an instruction from a future iteration that may have
13405f255eb4SJames Molloy // side effects, and this instruction might also, then we can't reorder
13415f255eb4SJames Molloy // them, and this matching fails. As an exception, we allow the alias
1342ab73c9d8SSanjoy Das // set tracker to handle regular (unordered) load/store dependencies.
1343ab73c9d8SSanjoy Das if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
1344a28d91d8SMehdi Amini !isSafeToSpeculativelyExecute(BaseInst)) ||
1345ab73c9d8SSanjoy Das (!isUnorderedLoadStore(RootInst) &&
1346a28d91d8SMehdi Amini !isSafeToSpeculativelyExecute(RootInst)))) {
1347d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1348d34e60caSNicola Zaghen << " vs. " << *RootInst
1349d34e60caSNicola Zaghen << " (side effects prevent reordering)\n");
135064419d41SJames Molloy return false;
13515f255eb4SJames Molloy }
13525f255eb4SJames Molloy
13535f255eb4SJames Molloy // For instructions that are part of a reduction, if the operation is
13545f255eb4SJames Molloy // associative, then don't bother matching the operands (because we
13555f255eb4SJames Molloy // already know that the instructions are isomorphic, and the order
13565f255eb4SJames Molloy // within the iteration does not matter). For non-associative reductions,
13575f255eb4SJames Molloy // we do need to match the operands, because we need to reject
13585f255eb4SJames Molloy // out-of-order instructions within an iteration!
13595f255eb4SJames Molloy // For example (assume floating-point addition), we need to reject this:
13605f255eb4SJames Molloy // x += a[i]; x += b[i];
13615f255eb4SJames Molloy // x += a[i+1]; x += b[i+1];
13625f255eb4SJames Molloy // x += b[i+2]; x += a[i+2];
136364419d41SJames Molloy bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
13645f255eb4SJames Molloy
136564419d41SJames Molloy if (!(InReduction && BaseInst->isAssociative())) {
13665f255eb4SJames Molloy bool Swapped = false, SomeOpMatched = false;
136764419d41SJames Molloy for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
136864419d41SJames Molloy Value *Op2 = RootInst->getOperand(j);
13695f255eb4SJames Molloy
13705f255eb4SJames Molloy // If this is part of a reduction (and the operation is not
13715f255eb4SJames Molloy // associatve), then we match all operands, but not those that are
13725f255eb4SJames Molloy // part of the reduction.
13735f255eb4SJames Molloy if (InReduction)
13745f255eb4SJames Molloy if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
137564419d41SJames Molloy if (Reductions.isPairInSame(RootInst, Op2I))
13765f255eb4SJames Molloy continue;
13775f255eb4SJames Molloy
13785f255eb4SJames Molloy DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1379f1473593SJames Molloy if (BMI != BaseMap.end()) {
13805f255eb4SJames Molloy Op2 = BMI->second;
1381f1473593SJames Molloy } else {
1382f1473593SJames Molloy for (auto &DRS : RootSets) {
1383f1473593SJames Molloy if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1384f1473593SJames Molloy Op2 = DRS.BaseInst;
1385f1473593SJames Molloy break;
1386f1473593SJames Molloy }
1387f1473593SJames Molloy }
1388f1473593SJames Molloy }
13895f255eb4SJames Molloy
139064419d41SJames Molloy if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
13915f255eb4SJames Molloy // If we've not already decided to swap the matched operands, and
13925f255eb4SJames Molloy // we've not already matched our first operand (note that we could
13935f255eb4SJames Molloy // have skipped matching the first operand because it is part of a
13945f255eb4SJames Molloy // reduction above), and the instruction is commutative, then try
13955f255eb4SJames Molloy // the swapped match.
139664419d41SJames Molloy if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
139764419d41SJames Molloy BaseInst->getOperand(!j) == Op2) {
13985f255eb4SJames Molloy Swapped = true;
13995f255eb4SJames Molloy } else {
1400d34e60caSNicola Zaghen LLVM_DEBUG(dbgs()
1401d34e60caSNicola Zaghen << "LRR: iteration root match failed at " << *BaseInst
140264419d41SJames Molloy << " vs. " << *RootInst << " (operand " << j << ")\n");
140364419d41SJames Molloy return false;
14045f255eb4SJames Molloy }
14055f255eb4SJames Molloy }
14065f255eb4SJames Molloy
14075f255eb4SJames Molloy SomeOpMatched = true;
14085f255eb4SJames Molloy }
14095f255eb4SJames Molloy }
14105f255eb4SJames Molloy
141164419d41SJames Molloy if ((!PossibleRedLastSet.count(BaseInst) &&
141264419d41SJames Molloy hasUsesOutsideLoop(BaseInst, L)) ||
141364419d41SJames Molloy (!PossibleRedLastSet.count(RootInst) &&
141464419d41SJames Molloy hasUsesOutsideLoop(RootInst, L))) {
1415d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1416d34e60caSNicola Zaghen << " vs. " << *RootInst << " (uses outside loop)\n");
1417bf45efdeSHal Finkel return false;
141864419d41SJames Molloy }
141964419d41SJames Molloy
142064419d41SJames Molloy Reductions.recordPair(BaseInst, RootInst, Iter);
142164419d41SJames Molloy BaseMap.insert(std::make_pair(RootInst, BaseInst));
142264419d41SJames Molloy
142364419d41SJames Molloy LastRootIt = RootIt;
1424e805ad95SJames Molloy Visited.insert(BaseInst);
1425e805ad95SJames Molloy Visited.insert(RootInst);
1426e805ad95SJames Molloy BaseIt = nextInstr(0, Uses, Visited);
1427e805ad95SJames Molloy RootIt = nextInstr(Iter, Uses, Visited);
142864419d41SJames Molloy }
142964419d41SJames Molloy assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
143064419d41SJames Molloy "Mismatched set sizes!");
143164419d41SJames Molloy }
1432bf45efdeSHal Finkel
1433d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Matched all iteration increments for " << *IV
1434d34e60caSNicola Zaghen << "\n");
14355f255eb4SJames Molloy
1436bf45efdeSHal Finkel return true;
1437bf45efdeSHal Finkel }
1438bf45efdeSHal Finkel
replace(const SCEV * BackedgeTakenCount)1439203eaaf5SEli Friedman void LoopReroll::DAGRootTracker::replace(const SCEV *BackedgeTakenCount) {
14405f255eb4SJames Molloy BasicBlock *Header = L->getHeader();
1441203eaaf5SEli Friedman
1442203eaaf5SEli Friedman // Compute the start and increment for each BaseInst before we start erasing
1443203eaaf5SEli Friedman // instructions.
1444203eaaf5SEli Friedman SmallVector<const SCEV *, 8> StartExprs;
1445203eaaf5SEli Friedman SmallVector<const SCEV *, 8> IncrExprs;
1446203eaaf5SEli Friedman for (auto &DRS : RootSets) {
1447203eaaf5SEli Friedman const SCEVAddRecExpr *IVSCEV =
1448203eaaf5SEli Friedman cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1449203eaaf5SEli Friedman StartExprs.push_back(IVSCEV->getStart());
1450203eaaf5SEli Friedman IncrExprs.push_back(SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), IVSCEV));
1451203eaaf5SEli Friedman }
1452203eaaf5SEli Friedman
14535f255eb4SJames Molloy // Remove instructions associated with non-base iterations.
14547787a8f1SKazu Hirata for (Instruction &Inst : llvm::make_early_inc_range(llvm::reverse(*Header))) {
14557787a8f1SKazu Hirata unsigned I = Uses[&Inst].find_first();
1456f1473593SJames Molloy if (I > 0 && I < IL_All) {
14577787a8f1SKazu Hirata LLVM_DEBUG(dbgs() << "LRR: removing: " << Inst << "\n");
14587787a8f1SKazu Hirata Inst.eraseFromParent();
14595f255eb4SJames Molloy }
14605f255eb4SJames Molloy }
14615f255eb4SJames Molloy
1462203eaaf5SEli Friedman // Rewrite each BaseInst using SCEV.
1463203eaaf5SEli Friedman for (size_t i = 0, e = RootSets.size(); i != e; ++i)
14645f255eb4SJames Molloy // Insert the new induction variable.
1465203eaaf5SEli Friedman replaceIV(RootSets[i], StartExprs[i], IncrExprs[i]);
1466203eaaf5SEli Friedman
1467203eaaf5SEli Friedman { // Limit the lifetime of SCEVExpander.
1468203eaaf5SEli Friedman BranchInst *BI = cast<BranchInst>(Header->getTerminator());
1469203eaaf5SEli Friedman const DataLayout &DL = Header->getModule()->getDataLayout();
1470203eaaf5SEli Friedman SCEVExpander Expander(*SE, DL, "reroll");
1471203eaaf5SEli Friedman auto Zero = SE->getZero(BackedgeTakenCount->getType());
1472203eaaf5SEli Friedman auto One = SE->getOne(BackedgeTakenCount->getType());
1473203eaaf5SEli Friedman auto NewIVSCEV = SE->getAddRecExpr(Zero, One, L, SCEV::FlagAnyWrap);
1474203eaaf5SEli Friedman Value *NewIV =
1475203eaaf5SEli Friedman Expander.expandCodeFor(NewIVSCEV, BackedgeTakenCount->getType(),
1476203eaaf5SEli Friedman Header->getFirstNonPHIOrDbg());
1477203eaaf5SEli Friedman // FIXME: This arithmetic can overflow.
1478203eaaf5SEli Friedman auto TripCount = SE->getAddExpr(BackedgeTakenCount, One);
1479203eaaf5SEli Friedman auto ScaledTripCount = SE->getMulExpr(
1480203eaaf5SEli Friedman TripCount, SE->getConstant(BackedgeTakenCount->getType(), Scale));
1481203eaaf5SEli Friedman auto ScaledBECount = SE->getMinusSCEV(ScaledTripCount, One);
1482203eaaf5SEli Friedman Value *TakenCount =
1483203eaaf5SEli Friedman Expander.expandCodeFor(ScaledBECount, BackedgeTakenCount->getType(),
1484203eaaf5SEli Friedman Header->getFirstNonPHIOrDbg());
1485203eaaf5SEli Friedman Value *Cond =
1486203eaaf5SEli Friedman new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, TakenCount, "exitcond");
1487203eaaf5SEli Friedman BI->setCondition(Cond);
1488203eaaf5SEli Friedman
1489203eaaf5SEli Friedman if (BI->getSuccessor(1) != Header)
1490203eaaf5SEli Friedman BI->swapSuccessors();
1491203eaaf5SEli Friedman }
149284b6195eSLawrence Hu
1493d3d51061SLawrence Hu SimplifyInstructionsInBlock(Header, TLI);
1494d3d51061SLawrence Hu DeleteDeadPHIs(Header, TLI);
1495b917cd9fSLawrence Hu }
149684b6195eSLawrence Hu
replaceIV(DAGRootSet & DRS,const SCEV * Start,const SCEV * IncrExpr)1497203eaaf5SEli Friedman void LoopReroll::DAGRootTracker::replaceIV(DAGRootSet &DRS,
1498203eaaf5SEli Friedman const SCEV *Start,
1499203eaaf5SEli Friedman const SCEV *IncrExpr) {
1500d3d51061SLawrence Hu BasicBlock *Header = L->getHeader();
1501203eaaf5SEli Friedman Instruction *Inst = DRS.BaseInst;
1502d3d51061SLawrence Hu
1503d3d51061SLawrence Hu const SCEV *NewIVSCEV =
1504d3d51061SLawrence Hu SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1505d3d51061SLawrence Hu
1506d3d51061SLawrence Hu { // Limit the lifetime of SCEVExpander.
1507d3d51061SLawrence Hu const DataLayout &DL = Header->getModule()->getDataLayout();
1508d3d51061SLawrence Hu SCEVExpander Expander(*SE, DL, "reroll");
1509c0bba1a9SEli Friedman Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
1510c0bba1a9SEli Friedman Header->getFirstNonPHIOrDbg());
1511d3d51061SLawrence Hu
1512d3d51061SLawrence Hu for (auto &KV : Uses)
1513d3d51061SLawrence Hu if (KV.second.find_first() == 0)
1514d3d51061SLawrence Hu KV.first->replaceUsesOfWith(Inst, NewIV);
15155f255eb4SJames Molloy }
1516f1473593SJames Molloy }
15175f255eb4SJames Molloy
1518bf45efdeSHal Finkel // Validate the selected reductions. All iterations must have an isomorphic
1519bf45efdeSHal Finkel // part of the reduction chain and, for non-associative reductions, the chain
1520bf45efdeSHal Finkel // entries must appear in order.
validateSelected()1521bf45efdeSHal Finkel bool LoopReroll::ReductionTracker::validateSelected() {
1522bf45efdeSHal Finkel // For a non-associative reduction, the chain entries must appear in order.
1523135f735aSBenjamin Kramer for (int i : Reds) {
1524bf45efdeSHal Finkel int PrevIter = 0, BaseCount = 0, Count = 0;
15255af50a54SNAKAMURA Takumi for (Instruction *J : PossibleReds[i]) {
1526bf45efdeSHal Finkel // Note that all instructions in the chain must have been found because
1527bf45efdeSHal Finkel // all instructions in the function must have been assigned to some
1528bf45efdeSHal Finkel // iteration.
15295af50a54SNAKAMURA Takumi int Iter = PossibleRedIter[J];
1530bf45efdeSHal Finkel if (Iter != PrevIter && Iter != PrevIter + 1 &&
1531bf45efdeSHal Finkel !PossibleReds[i].getReducedValue()->isAssociative()) {
1532d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: "
1533d34e60caSNicola Zaghen << J << "\n");
1534bf45efdeSHal Finkel return false;
1535bf45efdeSHal Finkel }
1536bf45efdeSHal Finkel
1537bf45efdeSHal Finkel if (Iter != PrevIter) {
1538bf45efdeSHal Finkel if (Count != BaseCount) {
1539d34e60caSNicola Zaghen LLVM_DEBUG(dbgs()
1540d34e60caSNicola Zaghen << "LRR: Iteration " << PrevIter << " reduction use count "
1541d34e60caSNicola Zaghen << Count << " is not equal to the base use count "
1542d34e60caSNicola Zaghen << BaseCount << "\n");
1543bf45efdeSHal Finkel return false;
1544bf45efdeSHal Finkel }
1545bf45efdeSHal Finkel
1546bf45efdeSHal Finkel Count = 0;
1547bf45efdeSHal Finkel }
1548bf45efdeSHal Finkel
1549bf45efdeSHal Finkel ++Count;
1550bf45efdeSHal Finkel if (Iter == 0)
1551bf45efdeSHal Finkel ++BaseCount;
1552bf45efdeSHal Finkel
1553bf45efdeSHal Finkel PrevIter = Iter;
1554bf45efdeSHal Finkel }
1555bf45efdeSHal Finkel }
1556bf45efdeSHal Finkel
1557bf45efdeSHal Finkel return true;
1558bf45efdeSHal Finkel }
1559bf45efdeSHal Finkel
1560bf45efdeSHal Finkel // For all selected reductions, remove all parts except those in the first
1561bf45efdeSHal Finkel // iteration (and the PHI). Replace outside uses of the reduced value with uses
1562bf45efdeSHal Finkel // of the first-iteration reduced value (in other words, reroll the selected
1563bf45efdeSHal Finkel // reductions).
replaceSelected()1564bf45efdeSHal Finkel void LoopReroll::ReductionTracker::replaceSelected() {
1565bf45efdeSHal Finkel // Fixup reductions to refer to the last instruction associated with the
1566bf45efdeSHal Finkel // first iteration (not the last).
1567135f735aSBenjamin Kramer for (int i : Reds) {
1568bf45efdeSHal Finkel int j = 0;
1569bf45efdeSHal Finkel for (int e = PossibleReds[i].size(); j != e; ++j)
1570bf45efdeSHal Finkel if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1571bf45efdeSHal Finkel --j;
1572bf45efdeSHal Finkel break;
1573bf45efdeSHal Finkel }
1574bf45efdeSHal Finkel
1575bf45efdeSHal Finkel // Replace users with the new end-of-chain value.
1576bf45efdeSHal Finkel SmallInstructionVector Users;
157764419d41SJames Molloy for (User *U : PossibleReds[i].getReducedValue()->users()) {
1578cdf47884SChandler Carruth Users.push_back(cast<Instruction>(U));
157964419d41SJames Molloy }
1580bf45efdeSHal Finkel
1581135f735aSBenjamin Kramer for (Instruction *User : Users)
1582135f735aSBenjamin Kramer User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1583bf45efdeSHal Finkel PossibleReds[i][j]);
1584bf45efdeSHal Finkel }
1585bf45efdeSHal Finkel }
1586bf45efdeSHal Finkel
1587bf45efdeSHal Finkel // Reroll the provided loop with respect to the provided induction variable.
1588bf45efdeSHal Finkel // Generally, we're looking for a loop like this:
1589bf45efdeSHal Finkel //
1590bf45efdeSHal Finkel // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1591bf45efdeSHal Finkel // f(%iv)
1592bf45efdeSHal Finkel // %iv.1 = add %iv, 1 <-- a root increment
1593bf45efdeSHal Finkel // f(%iv.1)
1594bf45efdeSHal Finkel // %iv.2 = add %iv, 2 <-- a root increment
1595bf45efdeSHal Finkel // f(%iv.2)
1596bf45efdeSHal Finkel // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1597bf45efdeSHal Finkel // f(%iv.scale_m_1)
1598bf45efdeSHal Finkel // ...
1599bf45efdeSHal Finkel // %iv.next = add %iv, scale
1600bf45efdeSHal Finkel // %cmp = icmp(%iv, ...)
1601bf45efdeSHal Finkel // br %cmp, header, exit
1602bf45efdeSHal Finkel //
1603bf45efdeSHal Finkel // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1604bf45efdeSHal Finkel // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1605bf45efdeSHal Finkel // be intermixed with eachother. The restriction imposed by this algorithm is
1606bf45efdeSHal Finkel // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1607bf45efdeSHal Finkel // etc. be the same.
1608bf45efdeSHal Finkel //
1609bf45efdeSHal Finkel // First, we collect the use set of %iv, excluding the other increment roots.
1610bf45efdeSHal Finkel // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1611bf45efdeSHal Finkel // times, having collected the use set of f(%iv.(i+1)), during which we:
1612bf45efdeSHal Finkel // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1613bf45efdeSHal Finkel // the next unmatched instruction in f(%iv.(i+1)).
1614bf45efdeSHal Finkel // - Ensure that both matched instructions don't have any external users
1615bf45efdeSHal Finkel // (with the exception of last-in-chain reduction instructions).
1616bf45efdeSHal Finkel // - Track the (aliasing) write set, and other side effects, of all
1617bf45efdeSHal Finkel // instructions that belong to future iterations that come before the matched
1618bf45efdeSHal Finkel // instructions. If the matched instructions read from that write set, then
1619bf45efdeSHal Finkel // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1620bf45efdeSHal Finkel // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1621bf45efdeSHal Finkel // if any of these future instructions had side effects (could not be
1622bf45efdeSHal Finkel // speculatively executed), and so do the matched instructions, when we
1623bf45efdeSHal Finkel // cannot reorder those side-effect-producing instructions, and rerolling
1624bf45efdeSHal Finkel // fails.
1625bf45efdeSHal Finkel //
1626bf45efdeSHal Finkel // Finally, we make sure that all loop instructions are either loop increment
1627bf45efdeSHal Finkel // roots, belong to simple latch code, parts of validated reductions, part of
1628bf45efdeSHal Finkel // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1629bf45efdeSHal Finkel // have been validated), then we reroll the loop.
reroll(Instruction * IV,Loop * L,BasicBlock * Header,const SCEV * BackedgeTakenCount,ReductionTracker & Reductions)1630bf45efdeSHal Finkel bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1631203eaaf5SEli Friedman const SCEV *BackedgeTakenCount,
1632bf45efdeSHal Finkel ReductionTracker &Reductions) {
1633843fb204SJustin Bogner DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
16341befea2bSLawrence Hu IVToIncMap, LoopControlIV);
1635bf45efdeSHal Finkel
16365f255eb4SJames Molloy if (!DAGRoots.findRoots())
1637bf45efdeSHal Finkel return false;
1638d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: Found all root induction increments for: " << *IV
1639d34e60caSNicola Zaghen << "\n");
1640bf45efdeSHal Finkel
16415f255eb4SJames Molloy if (!DAGRoots.validate(Reductions))
1642bf45efdeSHal Finkel return false;
1643bf45efdeSHal Finkel if (!Reductions.validateSelected())
1644bf45efdeSHal Finkel return false;
1645bf45efdeSHal Finkel // At this point, we've validated the rerolling, and we're committed to
1646bf45efdeSHal Finkel // making changes!
1647bf45efdeSHal Finkel
1648bf45efdeSHal Finkel Reductions.replaceSelected();
1649203eaaf5SEli Friedman DAGRoots.replace(BackedgeTakenCount);
1650bf45efdeSHal Finkel
1651bf45efdeSHal Finkel ++NumRerolledLoops;
1652bf45efdeSHal Finkel return true;
1653bf45efdeSHal Finkel }
1654bf45efdeSHal Finkel
runOnLoop(Loop * L)1655d3f6972aSArthur Eubanks bool LoopReroll::runOnLoop(Loop *L) {
1656bf45efdeSHal Finkel BasicBlock *Header = L->getHeader();
1657d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << "] Loop %"
1658d34e60caSNicola Zaghen << Header->getName() << " (" << L->getNumBlocks()
1659d34e60caSNicola Zaghen << " block(s))\n");
1660bf45efdeSHal Finkel
1661bf45efdeSHal Finkel // For now, we'll handle only single BB loops.
1662bf45efdeSHal Finkel if (L->getNumBlocks() > 1)
166307ac2bd4SZinovy Nis return false;
1664bf45efdeSHal Finkel
1665bf45efdeSHal Finkel if (!SE->hasLoopInvariantBackedgeTakenCount(L))
166607ac2bd4SZinovy Nis return false;
1667bf45efdeSHal Finkel
1668203eaaf5SEli Friedman const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1669d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
1670203eaaf5SEli Friedman LLVM_DEBUG(dbgs() << "LRR: backedge-taken count = " << *BackedgeTakenCount
1671203eaaf5SEli Friedman << "\n");
1672bf45efdeSHal Finkel
1673bf45efdeSHal Finkel // First, we need to find the induction variable with respect to which we can
1674bf45efdeSHal Finkel // reroll (there may be several possible options).
1675bf45efdeSHal Finkel SmallInstructionVector PossibleIVs;
1676dc8a83b5SLawrence Hu IVToIncMap.clear();
16771befea2bSLawrence Hu LoopControlIV = nullptr;
1678bf45efdeSHal Finkel collectPossibleIVs(L, PossibleIVs);
1679bf45efdeSHal Finkel
1680bf45efdeSHal Finkel if (PossibleIVs.empty()) {
1681d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LRR: No possible IVs found\n");
168207ac2bd4SZinovy Nis return false;
1683bf45efdeSHal Finkel }
1684bf45efdeSHal Finkel
1685bf45efdeSHal Finkel ReductionTracker Reductions;
1686bf45efdeSHal Finkel collectPossibleReductions(L, Reductions);
168707ac2bd4SZinovy Nis bool Changed = false;
1688bf45efdeSHal Finkel
1689bf45efdeSHal Finkel // For each possible IV, collect the associated possible set of 'root' nodes
1690bf45efdeSHal Finkel // (i+1, i+2, etc.).
1691135f735aSBenjamin Kramer for (Instruction *PossibleIV : PossibleIVs)
1692203eaaf5SEli Friedman if (reroll(PossibleIV, L, Header, BackedgeTakenCount, Reductions)) {
1693bf45efdeSHal Finkel Changed = true;
1694bf45efdeSHal Finkel break;
1695bf45efdeSHal Finkel }
1696d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
1697bf45efdeSHal Finkel
169807ac2bd4SZinovy Nis // Trip count of L has changed so SE must be re-evaluated.
169907ac2bd4SZinovy Nis if (Changed)
170007ac2bd4SZinovy Nis SE->forgetLoop(L);
170107ac2bd4SZinovy Nis
1702bf45efdeSHal Finkel return Changed;
1703bf45efdeSHal Finkel }
1704d3f6972aSArthur Eubanks
runOnLoop(Loop * L,LPPassManager & LPM)1705d3f6972aSArthur Eubanks bool LoopRerollLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
1706d3f6972aSArthur Eubanks if (skipLoop(L))
1707d3f6972aSArthur Eubanks return false;
1708d3f6972aSArthur Eubanks
1709d3f6972aSArthur Eubanks auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1710d3f6972aSArthur Eubanks auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1711d3f6972aSArthur Eubanks auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1712d3f6972aSArthur Eubanks auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
1713d3f6972aSArthur Eubanks *L->getHeader()->getParent());
1714d3f6972aSArthur Eubanks auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1715d3f6972aSArthur Eubanks bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1716d3f6972aSArthur Eubanks
1717d3f6972aSArthur Eubanks return LoopReroll(AA, LI, SE, TLI, DT, PreserveLCSSA).runOnLoop(L);
1718d3f6972aSArthur Eubanks }
1719d3f6972aSArthur Eubanks
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)1720d3f6972aSArthur Eubanks PreservedAnalyses LoopRerollPass::run(Loop &L, LoopAnalysisManager &AM,
1721d3f6972aSArthur Eubanks LoopStandardAnalysisResults &AR,
1722d3f6972aSArthur Eubanks LPMUpdater &U) {
1723d3f6972aSArthur Eubanks return LoopReroll(&AR.AA, &AR.LI, &AR.SE, &AR.TLI, &AR.DT, true).runOnLoop(&L)
1724d3f6972aSArthur Eubanks ? getLoopPassPreservedAnalyses()
1725d3f6972aSArthur Eubanks : PreservedAnalyses::all();
1726d3f6972aSArthur Eubanks }
1727