MachineScheduler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // MachineScheduler schedules machine instructions after phi elimination. It
  11. // preserves LiveIntervals so it can be invoked before register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "misched"
  15. #include "ScheduleDAGInstrs.h"
  16. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  17. #include "llvm/CodeGen/MachinePassRegistry.h"
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Target/TargetInstrInfo.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/ADT/OwningPtr.h"
  26. #include <queue>
  27. using namespace llvm;
  28. //===----------------------------------------------------------------------===//
  29. // Machine Instruction Scheduling Pass and Registry
  30. //===----------------------------------------------------------------------===//
  31. namespace {
  32. /// MachineScheduler runs after coalescing and before register allocation.
  33. class MachineScheduler : public MachineFunctionPass {
  34. public:
  35. MachineFunction *MF;
  36. const TargetInstrInfo *TII;
  37. const MachineLoopInfo *MLI;
  38. const MachineDominatorTree *MDT;
  39. LiveIntervals *LIS;
  40. MachineScheduler();
  41. virtual void getAnalysisUsage(AnalysisUsage &AU) const;
  42. virtual void releaseMemory() {}
  43. virtual bool runOnMachineFunction(MachineFunction&);
  44. virtual void print(raw_ostream &O, const Module* = 0) const;
  45. static char ID; // Class identification, replacement for typeinfo
  46. };
  47. } // namespace
  48. char MachineScheduler::ID = 0;
  49. char &llvm::MachineSchedulerID = MachineScheduler::ID;
  50. INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
  51. "Machine Instruction Scheduler", false, false)
  52. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  53. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  54. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  55. INITIALIZE_PASS_END(MachineScheduler, "misched",
  56. "Machine Instruction Scheduler", false, false)
  57. MachineScheduler::MachineScheduler()
  58. : MachineFunctionPass(ID), MF(0), MLI(0), MDT(0) {
  59. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  60. }
  61. void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  62. AU.setPreservesCFG();
  63. AU.addRequiredID(MachineDominatorsID);
  64. AU.addRequired<MachineLoopInfo>();
  65. AU.addRequired<AliasAnalysis>();
  66. AU.addPreserved<AliasAnalysis>();
  67. AU.addRequired<SlotIndexes>();
  68. AU.addPreserved<SlotIndexes>();
  69. AU.addRequired<LiveIntervals>();
  70. AU.addPreserved<LiveIntervals>();
  71. MachineFunctionPass::getAnalysisUsage(AU);
  72. }
  73. namespace {
  74. /// MachineSchedRegistry provides a selection of available machine instruction
  75. /// schedulers.
  76. class MachineSchedRegistry : public MachinePassRegistryNode {
  77. public:
  78. typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineScheduler *);
  79. // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
  80. typedef ScheduleDAGCtor FunctionPassCtor;
  81. static MachinePassRegistry Registry;
  82. MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
  83. : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
  84. Registry.Add(this);
  85. }
  86. ~MachineSchedRegistry() { Registry.Remove(this); }
  87. // Accessors.
  88. //
  89. MachineSchedRegistry *getNext() const {
  90. return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
  91. }
  92. static MachineSchedRegistry *getList() {
  93. return (MachineSchedRegistry *)Registry.getList();
  94. }
  95. static ScheduleDAGCtor getDefault() {
  96. return (ScheduleDAGCtor)Registry.getDefault();
  97. }
  98. static void setDefault(ScheduleDAGCtor C) {
  99. Registry.setDefault((MachinePassCtor)C);
  100. }
  101. static void setListener(MachinePassRegistryListener *L) {
  102. Registry.setListener(L);
  103. }
  104. };
  105. } // namespace
  106. MachinePassRegistry MachineSchedRegistry::Registry;
  107. static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P);
  108. /// MachineSchedOpt allows command line selection of the scheduler.
  109. static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
  110. RegisterPassParser<MachineSchedRegistry> >
  111. MachineSchedOpt("misched",
  112. cl::init(&createDefaultMachineSched), cl::Hidden,
  113. cl::desc("Machine instruction scheduler to use"));
  114. //===----------------------------------------------------------------------===//
  115. // Machine Instruction Scheduling Common Implementation
  116. //===----------------------------------------------------------------------===//
  117. namespace {
  118. /// ScheduleTopDownLive is an implementation of ScheduleDAGInstrs that schedules
  119. /// machine instructions while updating LiveIntervals.
  120. class ScheduleTopDownLive : public ScheduleDAGInstrs {
  121. protected:
  122. MachineScheduler *Pass;
  123. public:
  124. ScheduleTopDownLive(MachineScheduler *P):
  125. ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false, P->LIS),
  126. Pass(P) {}
  127. /// ScheduleDAGInstrs callback.
  128. void Schedule();
  129. /// Interface implemented by the selected top-down liveinterval scheduler.
  130. ///
  131. /// Pick the next node to schedule, or return NULL.
  132. virtual SUnit *pickNode() = 0;
  133. /// When all preceeding dependencies have been resolved, free this node for
  134. /// scheduling.
  135. virtual void releaseNode(SUnit *SU) = 0;
  136. protected:
  137. void releaseSucc(SUnit *SU, SDep *SuccEdge);
  138. void releaseSuccessors(SUnit *SU);
  139. };
  140. } // namespace
  141. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
  142. /// NumPredsLeft reaches zero, release the successor node.
  143. void ScheduleTopDownLive::releaseSucc(SUnit *SU, SDep *SuccEdge) {
  144. SUnit *SuccSU = SuccEdge->getSUnit();
  145. #ifndef NDEBUG
  146. if (SuccSU->NumPredsLeft == 0) {
  147. dbgs() << "*** Scheduling failed! ***\n";
  148. SuccSU->dump(this);
  149. dbgs() << " has been released too many times!\n";
  150. llvm_unreachable(0);
  151. }
  152. #endif
  153. --SuccSU->NumPredsLeft;
  154. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  155. releaseNode(SuccSU);
  156. }
  157. /// releaseSuccessors - Call releaseSucc on each of SU's successors.
  158. void ScheduleTopDownLive::releaseSuccessors(SUnit *SU) {
  159. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  160. I != E; ++I) {
  161. releaseSucc(SU, &*I);
  162. }
  163. }
  164. /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
  165. /// time to do some work.
  166. void ScheduleTopDownLive::Schedule() {
  167. BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
  168. DEBUG(dbgs() << "********** MI Scheduling **********\n");
  169. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  170. SUnits[su].dumpAll(this));
  171. // Release any successors of the special Entry node. It is currently unused,
  172. // but we keep up appearances.
  173. releaseSuccessors(&EntrySU);
  174. // Release all DAG roots for scheduling.
  175. for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
  176. I != E; ++I) {
  177. // A SUnit is ready to schedule if it has no predecessors.
  178. if (I->Preds.empty())
  179. releaseNode(&(*I));
  180. }
  181. InsertPos = Begin;
  182. while (SUnit *SU = pickNode()) {
  183. DEBUG(dbgs() << "*** Scheduling Instruction:\n"; SU->dump(this));
  184. // Move the instruction to its new location in the instruction stream.
  185. MachineInstr *MI = SU->getInstr();
  186. if (&*InsertPos == MI)
  187. ++InsertPos;
  188. else {
  189. BB->splice(InsertPos, BB, MI);
  190. Pass->LIS->handleMove(MI);
  191. if (Begin == InsertPos)
  192. Begin = MI;
  193. }
  194. // Release dependent instructions for scheduling.
  195. releaseSuccessors(SU);
  196. }
  197. }
  198. bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  199. // Initialize the context of the pass.
  200. MF = &mf;
  201. MLI = &getAnalysis<MachineLoopInfo>();
  202. MDT = &getAnalysis<MachineDominatorTree>();
  203. LIS = &getAnalysis<LiveIntervals>();
  204. TII = MF->getTarget().getInstrInfo();
  205. // Select the scheduler, or set the default.
  206. MachineSchedRegistry::ScheduleDAGCtor Ctor =
  207. MachineSchedRegistry::getDefault();
  208. if (!Ctor) {
  209. Ctor = MachineSchedOpt;
  210. MachineSchedRegistry::setDefault(Ctor);
  211. }
  212. // Instantiate the selected scheduler.
  213. OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
  214. // Visit all machine basic blocks.
  215. for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
  216. MBB != MBBEnd; ++MBB) {
  217. // Break the block into scheduling regions [I, RegionEnd), and schedule each
  218. // region as soon as it is discovered.
  219. unsigned RemainingCount = MBB->size();
  220. for(MachineBasicBlock::iterator RegionEnd = MBB->end();
  221. RegionEnd != MBB->begin();) {
  222. // The next region starts above the previous region. Look backward in the
  223. // instruction stream until we find the nearest boundary.
  224. MachineBasicBlock::iterator I = RegionEnd;
  225. for(;I != MBB->begin(); --I, --RemainingCount) {
  226. if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
  227. break;
  228. }
  229. if (I == RegionEnd) {
  230. // Skip empty scheduling regions.
  231. RegionEnd = llvm::prior(RegionEnd);
  232. --RemainingCount;
  233. continue;
  234. }
  235. // Skip regions with one instruction.
  236. if (I == llvm::prior(RegionEnd)) {
  237. RegionEnd = llvm::prior(RegionEnd);
  238. continue;
  239. }
  240. DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
  241. << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
  242. if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
  243. else dbgs() << "End";
  244. dbgs() << " Remaining: " << RemainingCount << "\n");
  245. // Inform ScheduleDAGInstrs of the region being scheduled. It calls back
  246. // to our Schedule() method.
  247. Scheduler->Run(MBB, I, RegionEnd, MBB->size());
  248. RegionEnd = Scheduler->Begin;
  249. }
  250. assert(RemainingCount == 0 && "Instruction count mismatch!");
  251. }
  252. return true;
  253. }
  254. void MachineScheduler::print(raw_ostream &O, const Module* m) const {
  255. // unimplemented
  256. }
  257. //===----------------------------------------------------------------------===//
  258. // Placeholder for extending the machine instruction scheduler.
  259. //===----------------------------------------------------------------------===//
  260. namespace {
  261. class DefaultMachineScheduler : public ScheduleDAGInstrs {
  262. MachineScheduler *Pass;
  263. public:
  264. DefaultMachineScheduler(MachineScheduler *P):
  265. ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false, P->LIS),
  266. Pass(P) {}
  267. /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
  268. /// time to do some work.
  269. void Schedule();
  270. };
  271. } // namespace
  272. static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P) {
  273. return new DefaultMachineScheduler(P);
  274. }
  275. static MachineSchedRegistry
  276. SchedDefaultRegistry("default", "Activate the scheduler pass, "
  277. "but don't reorder instructions",
  278. createDefaultMachineSched);
  279. /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
  280. /// time to do some work.
  281. void DefaultMachineScheduler::Schedule() {
  282. BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
  283. DEBUG(dbgs() << "********** MI Scheduling **********\n");
  284. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  285. SUnits[su].dumpAll(this));
  286. // TODO: Put interesting things here.
  287. //
  288. // When this is fully implemented, it will become a subclass of
  289. // ScheduleTopDownLive. So this driver will disappear.
  290. }
  291. //===----------------------------------------------------------------------===//
  292. // Machine Instruction Shuffler for Correctness Testing
  293. //===----------------------------------------------------------------------===//
  294. #ifndef NDEBUG
  295. namespace {
  296. // Nodes with a higher number have higher priority. This way we attempt to
  297. // schedule the latest instructions earliest.
  298. //
  299. // TODO: Relies on the property of the BuildSchedGraph that results in SUnits
  300. // being ordered in sequence top-down.
  301. struct ShuffleSUnitOrder {
  302. bool operator()(SUnit *A, SUnit *B) const {
  303. return A->NodeNum < B->NodeNum;
  304. }
  305. };
  306. /// Reorder instructions as much as possible.
  307. class InstructionShuffler : public ScheduleTopDownLive {
  308. std::priority_queue<SUnit*, std::vector<SUnit*>, ShuffleSUnitOrder> Queue;
  309. public:
  310. InstructionShuffler(MachineScheduler *P):
  311. ScheduleTopDownLive(P) {}
  312. /// ScheduleTopDownLive Interface
  313. virtual SUnit *pickNode() {
  314. if (Queue.empty()) return NULL;
  315. SUnit *SU = Queue.top();
  316. Queue.pop();
  317. return SU;
  318. }
  319. virtual void releaseNode(SUnit *SU) {
  320. Queue.push(SU);
  321. }
  322. };
  323. } // namespace
  324. static ScheduleDAGInstrs *createInstructionShuffler(MachineScheduler *P) {
  325. return new InstructionShuffler(P);
  326. }
  327. static MachineSchedRegistry ShufflerRegistry("shuffle",
  328. "Shuffle machine instructions",
  329. createInstructionShuffler);
  330. #endif // !NDEBUG