[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-complete.git] / include / llvm / CodeGen / ModuloSchedule.h
blob530cefd1c81a72ad0474a6a7ddc1126f6b98148d
1 //===- ModuloSchedule.h - Software pipeline schedule expansion ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Software pipelining (SWP) is an instruction scheduling technique for loops
10 // that overlaps loop iterations and exploits ILP via compiler transformations.
12 // There are multiple methods for analyzing a loop and creating a schedule.
13 // An example algorithm is Swing Modulo Scheduling (implemented by the
14 // MachinePipeliner). The details of how a schedule is arrived at are irrelevant
15 // for the task of actually rewriting a loop to adhere to the schedule, which
16 // is what this file does.
18 // A schedule is, for every instruction in a block, a Cycle and a Stage. Note
19 // that we only support single-block loops, so "block" and "loop" can be used
20 // interchangably.
22 // The Cycle of an instruction defines a partial order of the instructions in
23 // the remapped loop. Instructions within a cycle must not consume the output
24 // of any instruction in the same cycle. Cycle information is assumed to have
25 // been calculated such that the processor will execute instructions in
26 // lock-step (for example in a VLIW ISA).
28 // The Stage of an instruction defines the mapping between logical loop
29 // iterations and pipelined loop iterations. An example (unrolled) pipeline
30 // may look something like:
32 // I0[0] Execute instruction I0 of iteration 0
33 // I1[0], I0[1] Execute I0 of iteration 1 and I1 of iteration 1
34 // I1[1], I0[2]
35 // I1[2], I0[3]
37 // In the schedule for this unrolled sequence we would say that I0 was scheduled
38 // in stage 0 and I1 in stage 1:
40 // loop:
41 // [stage 0] x = I0
42 // [stage 1] I1 x (from stage 0)
44 // And to actually generate valid code we must insert a phi:
46 // loop:
47 // x' = phi(x)
48 // x = I0
49 // I1 x'
51 // This is a simple example; the rules for how to generate correct code given
52 // an arbitrary schedule containing loop-carried values are complex.
54 // Note that these examples only mention the steady-state kernel of the
55 // generated loop; prologs and epilogs must be generated also that prime and
56 // flush the pipeline. Doing so is nontrivial.
58 //===----------------------------------------------------------------------===//
60 #ifndef LLVM_LIB_CODEGEN_MODULOSCHEDULE_H
61 #define LLVM_LIB_CODEGEN_MODULOSCHEDULE_H
63 #include "llvm/CodeGen/MachineFunction.h"
64 #include "llvm/CodeGen/MachineLoopInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include <vector>
68 namespace llvm {
69 class MachineBasicBlock;
70 class MachineInstr;
71 class LiveIntervals;
73 /// Represents a schedule for a single-block loop. For every instruction we
74 /// maintain a Cycle and Stage.
75 class ModuloSchedule {
76 private:
77 /// The block containing the loop instructions.
78 MachineLoop *Loop;
80 /// The instructions to be generated, in total order. Cycle provides a partial
81 /// order; the total order within cycles has been decided by the schedule
82 /// producer.
83 std::vector<MachineInstr *> ScheduledInstrs;
85 /// The cycle for each instruction.
86 DenseMap<MachineInstr *, int> Cycle;
88 /// The stage for each instruction.
89 DenseMap<MachineInstr *, int> Stage;
91 /// The number of stages in this schedule (Max(Stage) + 1).
92 int NumStages;
94 public:
95 /// Create a new ModuloSchedule.
96 /// \arg ScheduledInstrs The new loop instructions, in total resequenced
97 /// order.
98 /// \arg Cycle Cycle index for all instructions in ScheduledInstrs. Cycle does
99 /// not need to start at zero. ScheduledInstrs must be partially ordered by
100 /// Cycle.
101 /// \arg Stage Stage index for all instructions in ScheduleInstrs.
102 ModuloSchedule(MachineFunction &MF, MachineLoop *Loop,
103 std::vector<MachineInstr *> ScheduledInstrs,
104 DenseMap<MachineInstr *, int> Cycle,
105 DenseMap<MachineInstr *, int> Stage)
106 : Loop(Loop), ScheduledInstrs(ScheduledInstrs), Cycle(std::move(Cycle)),
107 Stage(std::move(Stage)) {
108 NumStages = 0;
109 for (auto &KV : this->Stage)
110 NumStages = std::max(NumStages, KV.second);
111 ++NumStages;
114 /// Return the single-block loop being scheduled.
115 MachineLoop *getLoop() const { return Loop; }
117 /// Return the number of stages contained in this schedule, which is the
118 /// largest stage index + 1.
119 int getNumStages() const { return NumStages; }
121 /// Return the first cycle in the schedule, which is the cycle index of the
122 /// first instruction.
123 int getFirstCycle() { return Cycle[ScheduledInstrs.front()]; }
125 /// Return the final cycle in the schedule, which is the cycle index of the
126 /// last instruction.
127 int getFinalCycle() { return Cycle[ScheduledInstrs.back()]; }
129 /// Return the stage that MI is scheduled in, or -1.
130 int getStage(MachineInstr *MI) {
131 auto I = Stage.find(MI);
132 return I == Stage.end() ? -1 : I->second;
135 /// Return the cycle that MI is scheduled at, or -1.
136 int getCycle(MachineInstr *MI) {
137 auto I = Cycle.find(MI);
138 return I == Cycle.end() ? -1 : I->second;
141 /// Return the rescheduled instructions in order.
142 ArrayRef<MachineInstr *> getInstructions() { return ScheduledInstrs; }
144 void dump() {
145 print(dbgs());
147 void print(raw_ostream &OS);
150 /// The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place,
151 /// rewriting the old loop and inserting prologs and epilogs as required.
152 class ModuloScheduleExpander {
153 public:
154 using InstrChangesTy = DenseMap<MachineInstr *, std::pair<unsigned, int64_t>>;
156 private:
157 using ValueMapTy = DenseMap<unsigned, unsigned>;
158 using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
159 using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
161 ModuloSchedule &Schedule;
162 MachineFunction &MF;
163 const TargetSubtargetInfo &ST;
164 MachineRegisterInfo &MRI;
165 const TargetInstrInfo *TII;
166 LiveIntervals &LIS;
168 MachineBasicBlock *BB;
169 MachineBasicBlock *Preheader;
170 MachineBasicBlock *NewKernel = nullptr;
172 /// Map for each register and the max difference between its uses and def.
173 /// The first element in the pair is the max difference in stages. The
174 /// second is true if the register defines a Phi value and loop value is
175 /// scheduled before the Phi.
176 std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
178 /// Instructions to change when emitting the final schedule.
179 InstrChangesTy InstrChanges;
181 void generatePipelinedLoop();
182 void generateProlog(unsigned LastStage, MachineBasicBlock *KernelBB,
183 ValueMapTy *VRMap, MBBVectorTy &PrologBBs);
184 void generateEpilog(unsigned LastStage, MachineBasicBlock *KernelBB,
185 ValueMapTy *VRMap, MBBVectorTy &EpilogBBs,
186 MBBVectorTy &PrologBBs);
187 void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
188 MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
189 ValueMapTy *VRMap, InstrMapTy &InstrMap,
190 unsigned LastStageNum, unsigned CurStageNum,
191 bool IsLast);
192 void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
193 MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
194 ValueMapTy *VRMap, InstrMapTy &InstrMap,
195 unsigned LastStageNum, unsigned CurStageNum, bool IsLast);
196 void removeDeadInstructions(MachineBasicBlock *KernelBB,
197 MBBVectorTy &EpilogBBs);
198 void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs);
199 void addBranches(MachineBasicBlock &PreheaderBB, MBBVectorTy &PrologBBs,
200 MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
201 ValueMapTy *VRMap);
202 bool computeDelta(MachineInstr &MI, unsigned &Delta);
203 void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
204 unsigned Num);
205 MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
206 unsigned InstStageNum);
207 MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
208 unsigned InstStageNum);
209 void updateInstruction(MachineInstr *NewMI, bool LastDef,
210 unsigned CurStageNum, unsigned InstrStageNum,
211 ValueMapTy *VRMap);
212 MachineInstr *findDefInLoop(unsigned Reg);
213 unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
214 unsigned LoopStage, ValueMapTy *VRMap,
215 MachineBasicBlock *BB);
216 void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
217 ValueMapTy *VRMap, InstrMapTy &InstrMap);
218 void rewriteScheduledInstr(MachineBasicBlock *BB, InstrMapTy &InstrMap,
219 unsigned CurStageNum, unsigned PhiNum,
220 MachineInstr *Phi, unsigned OldReg,
221 unsigned NewReg, unsigned PrevReg = 0);
222 bool isLoopCarried(MachineInstr &Phi);
224 /// Return the max. number of stages/iterations that can occur between a
225 /// register definition and its uses.
226 unsigned getStagesForReg(int Reg, unsigned CurStage) {
227 std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
228 if ((int)CurStage > Schedule.getNumStages() - 1 && Stages.first == 0 &&
229 Stages.second)
230 return 1;
231 return Stages.first;
234 /// The number of stages for a Phi is a little different than other
235 /// instructions. The minimum value computed in RegToStageDiff is 1
236 /// because we assume the Phi is needed for at least 1 iteration.
237 /// This is not the case if the loop value is scheduled prior to the
238 /// Phi in the same stage. This function returns the number of stages
239 /// or iterations needed between the Phi definition and any uses.
240 unsigned getStagesForPhi(int Reg) {
241 std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
242 if (Stages.second)
243 return Stages.first;
244 return Stages.first - 1;
247 public:
248 /// Create a new ModuloScheduleExpander.
249 /// \arg InstrChanges Modifications to make to instructions with memory
250 /// operands.
251 /// FIXME: InstrChanges is opaque and is an implementation detail of an
252 /// optimization in MachinePipeliner that crosses abstraction boundaries.
253 ModuloScheduleExpander(MachineFunction &MF, ModuloSchedule &S,
254 LiveIntervals &LIS, InstrChangesTy InstrChanges)
255 : Schedule(S), MF(MF), ST(MF.getSubtarget()), MRI(MF.getRegInfo()),
256 TII(ST.getInstrInfo()), LIS(LIS),
257 InstrChanges(std::move(InstrChanges)) {}
259 /// Performs the actual expansion.
260 void expand();
261 /// Performs final cleanup after expansion.
262 void cleanup();
264 /// Returns the newly rewritten kernel block, or nullptr if this was
265 /// optimized away.
266 MachineBasicBlock *getRewrittenKernel() { return NewKernel; }
269 /// A reimplementation of ModuloScheduleExpander. It works by generating a
270 /// standalone kernel loop and peeling out the prologs and epilogs.
272 /// FIXME: This implementation cannot yet generate valid code. It can generate
273 /// a correct kernel but cannot peel out prologs and epilogs.
274 class PeelingModuloScheduleExpander {
275 ModuloSchedule &Schedule;
276 MachineFunction &MF;
277 const TargetSubtargetInfo &ST;
278 MachineRegisterInfo &MRI;
279 const TargetInstrInfo *TII;
280 LiveIntervals *LIS;
282 MachineBasicBlock *BB;
283 MachineBasicBlock *Preheader;
284 public:
285 PeelingModuloScheduleExpander(MachineFunction &MF, ModuloSchedule &S,
286 LiveIntervals *LIS)
287 : Schedule(S), MF(MF), ST(MF.getSubtarget()), MRI(MF.getRegInfo()),
288 TII(ST.getInstrInfo()), LIS(LIS) {}
290 /// Runs ModuloScheduleExpander and treats it as a golden input to validate
291 /// aspects of the code generated by PeelingModuloScheduleExpander.
292 void validateAgainstModuloScheduleExpander();
295 /// Expander that simply annotates each scheduled instruction with a post-instr
296 /// symbol that can be consumed by the ModuloScheduleTest pass.
298 /// The post-instr symbol is a way of annotating an instruction that can be
299 /// roundtripped in MIR. The syntax is:
300 /// MYINST %0, post-instr-symbol <mcsymbol Stage-1_Cycle-5>
301 class ModuloScheduleTestAnnotater {
302 MachineFunction &MF;
303 ModuloSchedule &S;
305 public:
306 ModuloScheduleTestAnnotater(MachineFunction &MF, ModuloSchedule &S)
307 : MF(MF), S(S) {}
309 /// Performs the annotation.
310 void annotate();
313 } // end namespace llvm
315 #endif // LLVM_LIB_CODEGEN_MODULOSCHEDULE_H