ModuloSchedule.h 16 KB

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