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