ModuloSchedule.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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.
  11. //
  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.
  17. //
  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.
  21. //
  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).
  27. //
  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:
  31. //
  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]
  36. //
  37. // In the schedule for this unrolled sequence we would say that I0 was scheduled
  38. // in stage 0 and I1 in stage 1:
  39. //
  40. // loop:
  41. // [stage 0] x = I0
  42. // [stage 1] I1 x (from stage 0)
  43. //
  44. // And to actually generate valid code we must insert a phi:
  45. //
  46. // loop:
  47. // x' = phi(x)
  48. // x = I0
  49. // I1 x'
  50. //
  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.
  53. //
  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.
  57. //
  58. //===----------------------------------------------------------------------===//
  59. #ifndef LLVM_CODEGEN_MODULOSCHEDULE_H
  60. #define LLVM_CODEGEN_MODULOSCHEDULE_H
  61. #include "llvm/CodeGen/MachineFunction.h"
  62. #include "llvm/CodeGen/MachineLoopInfo.h"
  63. #include "llvm/CodeGen/MachineLoopUtils.h"
  64. #include "llvm/CodeGen/TargetInstrInfo.h"
  65. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  66. #include <deque>
  67. #include <vector>
  68. namespace llvm {
  69. class MachineBasicBlock;
  70. class MachineInstr;
  71. class LiveIntervals;
  72. /// Represents a schedule for a single-block loop. For every instruction we
  73. /// maintain a Cycle and Stage.
  74. class ModuloSchedule {
  75. private:
  76. /// The block containing the loop instructions.
  77. MachineLoop *Loop;
  78. /// The instructions to be generated, in total order. Cycle provides a partial
  79. /// order; the total order within cycles has been decided by the schedule
  80. /// producer.
  81. std::vector<MachineInstr *> ScheduledInstrs;
  82. /// The cycle for each instruction.
  83. DenseMap<MachineInstr *, int> Cycle;
  84. /// The stage for each instruction.
  85. DenseMap<MachineInstr *, int> Stage;
  86. /// The number of stages in this schedule (Max(Stage) + 1).
  87. int NumStages;
  88. public:
  89. /// Create a new ModuloSchedule.
  90. /// \arg ScheduledInstrs The new loop instructions, in total resequenced
  91. /// order.
  92. /// \arg Cycle Cycle index for all instructions in ScheduledInstrs. Cycle does
  93. /// not need to start at zero. ScheduledInstrs must be partially ordered by
  94. /// Cycle.
  95. /// \arg Stage Stage index for all instructions in ScheduleInstrs.
  96. ModuloSchedule(MachineFunction &MF, MachineLoop *Loop,
  97. std::vector<MachineInstr *> ScheduledInstrs,
  98. DenseMap<MachineInstr *, int> Cycle,
  99. DenseMap<MachineInstr *, int> Stage)
  100. : Loop(Loop), ScheduledInstrs(ScheduledInstrs), Cycle(std::move(Cycle)),
  101. Stage(std::move(Stage)) {
  102. NumStages = 0;
  103. for (auto &KV : this->Stage)
  104. NumStages = std::max(NumStages, KV.second);
  105. ++NumStages;
  106. }
  107. /// Return the single-block loop being scheduled.
  108. MachineLoop *getLoop() const { return Loop; }
  109. /// Return the number of stages contained in this schedule, which is the
  110. /// largest stage index + 1.
  111. int getNumStages() const { return NumStages; }
  112. /// Return the first cycle in the schedule, which is the cycle index of the
  113. /// first instruction.
  114. int getFirstCycle() { return Cycle[ScheduledInstrs.front()]; }
  115. /// Return the final cycle in the schedule, which is the cycle index of the
  116. /// last instruction.
  117. int getFinalCycle() { return Cycle[ScheduledInstrs.back()]; }
  118. /// Return the stage that MI is scheduled in, or -1.
  119. int getStage(MachineInstr *MI) {
  120. auto I = Stage.find(MI);
  121. return I == Stage.end() ? -1 : I->second;
  122. }
  123. /// Return the cycle that MI is scheduled at, or -1.
  124. int getCycle(MachineInstr *MI) {
  125. auto I = Cycle.find(MI);
  126. return I == Cycle.end() ? -1 : I->second;
  127. }
  128. /// Set the stage of a newly created instruction.
  129. void setStage(MachineInstr *MI, int MIStage) {
  130. assert(Stage.count(MI) == 0);
  131. Stage[MI] = MIStage;
  132. }
  133. /// Return the rescheduled instructions in order.
  134. ArrayRef<MachineInstr *> getInstructions() { return ScheduledInstrs; }
  135. void dump() { print(dbgs()); }
  136. void print(raw_ostream &OS);
  137. };
  138. /// The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place,
  139. /// rewriting the old loop and inserting prologs and epilogs as required.
  140. class ModuloScheduleExpander {
  141. public:
  142. using InstrChangesTy = DenseMap<MachineInstr *, std::pair<unsigned, int64_t>>;
  143. private:
  144. using ValueMapTy = DenseMap<unsigned, unsigned>;
  145. using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
  146. using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
  147. ModuloSchedule &Schedule;
  148. MachineFunction &MF;
  149. const TargetSubtargetInfo &ST;
  150. MachineRegisterInfo &MRI;
  151. const TargetInstrInfo *TII;
  152. LiveIntervals &LIS;
  153. MachineBasicBlock *BB;
  154. MachineBasicBlock *Preheader;
  155. MachineBasicBlock *NewKernel = nullptr;
  156. std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo> LoopInfo;
  157. /// Map for each register and the max difference between its uses and def.
  158. /// The first element in the pair is the max difference in stages. The
  159. /// second is true if the register defines a Phi value and loop value is
  160. /// scheduled before the Phi.
  161. std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
  162. /// Instructions to change when emitting the final schedule.
  163. InstrChangesTy InstrChanges;
  164. void generatePipelinedLoop();
  165. void generateProlog(unsigned LastStage, MachineBasicBlock *KernelBB,
  166. ValueMapTy *VRMap, MBBVectorTy &PrologBBs);
  167. void generateEpilog(unsigned LastStage, MachineBasicBlock *KernelBB,
  168. ValueMapTy *VRMap, MBBVectorTy &EpilogBBs,
  169. MBBVectorTy &PrologBBs);
  170. void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  171. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  172. ValueMapTy *VRMap, InstrMapTy &InstrMap,
  173. unsigned LastStageNum, unsigned CurStageNum,
  174. bool IsLast);
  175. void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  176. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  177. ValueMapTy *VRMap, InstrMapTy &InstrMap,
  178. unsigned LastStageNum, unsigned CurStageNum, bool IsLast);
  179. void removeDeadInstructions(MachineBasicBlock *KernelBB,
  180. MBBVectorTy &EpilogBBs);
  181. void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs);
  182. void addBranches(MachineBasicBlock &PreheaderBB, MBBVectorTy &PrologBBs,
  183. MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
  184. ValueMapTy *VRMap);
  185. bool computeDelta(MachineInstr &MI, unsigned &Delta);
  186. void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
  187. unsigned Num);
  188. MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
  189. unsigned InstStageNum);
  190. MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
  191. unsigned InstStageNum);
  192. void updateInstruction(MachineInstr *NewMI, bool LastDef,
  193. unsigned CurStageNum, unsigned InstrStageNum,
  194. ValueMapTy *VRMap);
  195. MachineInstr *findDefInLoop(unsigned Reg);
  196. unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
  197. unsigned LoopStage, ValueMapTy *VRMap,
  198. MachineBasicBlock *BB);
  199. void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
  200. ValueMapTy *VRMap, InstrMapTy &InstrMap);
  201. void rewriteScheduledInstr(MachineBasicBlock *BB, InstrMapTy &InstrMap,
  202. unsigned CurStageNum, unsigned PhiNum,
  203. MachineInstr *Phi, unsigned OldReg,
  204. unsigned NewReg, unsigned PrevReg = 0);
  205. bool isLoopCarried(MachineInstr &Phi);
  206. /// Return the max. number of stages/iterations that can occur between a
  207. /// register definition and its uses.
  208. unsigned getStagesForReg(int Reg, unsigned CurStage) {
  209. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  210. if ((int)CurStage > Schedule.getNumStages() - 1 && Stages.first == 0 &&
  211. Stages.second)
  212. return 1;
  213. return Stages.first;
  214. }
  215. /// The number of stages for a Phi is a little different than other
  216. /// instructions. The minimum value computed in RegToStageDiff is 1
  217. /// because we assume the Phi is needed for at least 1 iteration.
  218. /// This is not the case if the loop value is scheduled prior to the
  219. /// Phi in the same stage. This function returns the number of stages
  220. /// or iterations needed between the Phi definition and any uses.
  221. unsigned getStagesForPhi(int Reg) {
  222. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  223. if (Stages.second)
  224. return Stages.first;
  225. return Stages.first - 1;
  226. }
  227. public:
  228. /// Create a new ModuloScheduleExpander.
  229. /// \arg InstrChanges Modifications to make to instructions with memory
  230. /// operands.
  231. /// FIXME: InstrChanges is opaque and is an implementation detail of an
  232. /// optimization in MachinePipeliner that crosses abstraction boundaries.
  233. ModuloScheduleExpander(MachineFunction &MF, ModuloSchedule &S,
  234. LiveIntervals &LIS, InstrChangesTy InstrChanges)
  235. : Schedule(S), MF(MF), ST(MF.getSubtarget()), MRI(MF.getRegInfo()),
  236. TII(ST.getInstrInfo()), LIS(LIS),
  237. InstrChanges(std::move(InstrChanges)) {}
  238. /// Performs the actual expansion.
  239. void expand();
  240. /// Performs final cleanup after expansion.
  241. void cleanup();
  242. /// Returns the newly rewritten kernel block, or nullptr if this was
  243. /// optimized away.
  244. MachineBasicBlock *getRewrittenKernel() { return NewKernel; }
  245. };
  246. /// A reimplementation of ModuloScheduleExpander. It works by generating a
  247. /// standalone kernel loop and peeling out the prologs and epilogs.
  248. class PeelingModuloScheduleExpander {
  249. public:
  250. PeelingModuloScheduleExpander(MachineFunction &MF, ModuloSchedule &S,
  251. LiveIntervals *LIS)
  252. : Schedule(S), MF(MF), ST(MF.getSubtarget()), MRI(MF.getRegInfo()),
  253. TII(ST.getInstrInfo()), LIS(LIS) {}
  254. void expand();
  255. /// Runs ModuloScheduleExpander and treats it as a golden input to validate
  256. /// aspects of the code generated by PeelingModuloScheduleExpander.
  257. void validateAgainstModuloScheduleExpander();
  258. protected:
  259. ModuloSchedule &Schedule;
  260. MachineFunction &MF;
  261. const TargetSubtargetInfo &ST;
  262. MachineRegisterInfo &MRI;
  263. const TargetInstrInfo *TII;
  264. LiveIntervals *LIS;
  265. /// The original loop block that gets rewritten in-place.
  266. MachineBasicBlock *BB;
  267. /// The original loop preheader.
  268. MachineBasicBlock *Preheader;
  269. /// All prolog and epilog blocks.
  270. SmallVector<MachineBasicBlock *, 4> Prologs, Epilogs;
  271. /// For every block, the stages that are produced.
  272. DenseMap<MachineBasicBlock *, BitVector> LiveStages;
  273. /// For every block, the stages that are available. A stage can be available
  274. /// but not produced (in the epilog) or produced but not available (in the
  275. /// prolog).
  276. DenseMap<MachineBasicBlock *, BitVector> AvailableStages;
  277. /// When peeling the epilogue keep track of the distance between the phi
  278. /// nodes and the kernel.
  279. DenseMap<MachineInstr *, unsigned> PhiNodeLoopIteration;
  280. /// CanonicalMIs and BlockMIs form a bidirectional map between any of the
  281. /// loop kernel clones.
  282. DenseMap<MachineInstr *, MachineInstr *> CanonicalMIs;
  283. DenseMap<std::pair<MachineBasicBlock *, MachineInstr *>, MachineInstr *>
  284. BlockMIs;
  285. /// State passed from peelKernel to peelPrologAndEpilogs().
  286. std::deque<MachineBasicBlock *> PeeledFront, PeeledBack;
  287. /// Illegal phis that need to be deleted once we re-link stages.
  288. SmallVector<MachineInstr *, 4> IllegalPhisToDelete;
  289. /// Converts BB from the original loop body to the rewritten, pipelined
  290. /// steady-state.
  291. void rewriteKernel();
  292. /// Peels one iteration of the rewritten kernel (BB) in the specified
  293. /// direction.
  294. MachineBasicBlock *peelKernel(LoopPeelDirection LPD);
  295. // Delete instructions whose stage is less than MinStage in the given basic
  296. // block.
  297. void filterInstructions(MachineBasicBlock *MB, int MinStage);
  298. // Move instructions of the given stage from sourceBB to DestBB. Remap the phi
  299. // instructions to keep a valid IR.
  300. void moveStageBetweenBlocks(MachineBasicBlock *DestBB,
  301. MachineBasicBlock *SourceBB, unsigned Stage);
  302. /// Peel the kernel forwards and backwards to produce prologs and epilogs,
  303. /// and stitch them together.
  304. void peelPrologAndEpilogs();
  305. /// All prolog and epilog blocks are clones of the kernel, so any produced
  306. /// register in one block has an corollary in all other blocks.
  307. Register getEquivalentRegisterIn(Register Reg, MachineBasicBlock *BB);
  308. /// Change all users of MI, if MI is predicated out
  309. /// (LiveStages[MI->getParent()] == false).
  310. void rewriteUsesOf(MachineInstr *MI);
  311. /// Insert branches between prologs, kernel and epilogs.
  312. void fixupBranches();
  313. /// Create a poor-man's LCSSA by cloning only the PHIs from the kernel block
  314. /// to a block dominated by all prologs and epilogs. This allows us to treat
  315. /// the loop exiting block as any other kernel clone.
  316. MachineBasicBlock *CreateLCSSAExitingBlock();
  317. /// Helper to get the stage of an instruction in the schedule.
  318. unsigned getStage(MachineInstr *MI) {
  319. if (CanonicalMIs.count(MI))
  320. MI = CanonicalMIs[MI];
  321. return Schedule.getStage(MI);
  322. }
  323. /// Helper function to find the right canonical register for a phi instruction
  324. /// coming from a peeled out prologue.
  325. Register getPhiCanonicalReg(MachineInstr* CanonicalPhi, MachineInstr* Phi);
  326. /// Target loop info before kernel peeling.
  327. std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo> LoopInfo;
  328. };
  329. /// Expander that simply annotates each scheduled instruction with a post-instr
  330. /// symbol that can be consumed by the ModuloScheduleTest pass.
  331. ///
  332. /// The post-instr symbol is a way of annotating an instruction that can be
  333. /// roundtripped in MIR. The syntax is:
  334. /// MYINST %0, post-instr-symbol <mcsymbol Stage-1_Cycle-5>
  335. class ModuloScheduleTestAnnotater {
  336. MachineFunction &MF;
  337. ModuloSchedule &S;
  338. public:
  339. ModuloScheduleTestAnnotater(MachineFunction &MF, ModuloSchedule &S)
  340. : MF(MF), S(S) {}
  341. /// Performs the annotation.
  342. void annotate();
  343. };
  344. } // end namespace llvm
  345. #endif // LLVM_CODEGEN_MODULOSCHEDULE_H