Change SUnit's dump method to take a ScheduleDAG* instead of
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGList.cpp
1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
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 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "pre-RA-sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/CodeGen/SchedulerRegistry.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/ADT/PriorityQueue.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "LatencyPriorityQueue.h"
34 #include <climits>
35 using namespace llvm;
36
37 STATISTIC(NumNoops , "Number of noops inserted");
38 STATISTIC(NumStalls, "Number of pipeline stalls");
39
40 static RegisterScheduler
41   tdListDAGScheduler("list-td", "Top-down list scheduler",
42                      createTDListDAGScheduler);
43    
44 namespace {
45 //===----------------------------------------------------------------------===//
46 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
47 /// top-down scheduling.
48 ///
49 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
50 private:
51   /// AvailableQueue - The priority queue to use for the available SUnits.
52   ///
53   SchedulingPriorityQueue *AvailableQueue;
54   
55   /// PendingQueue - This contains all of the instructions whose operands have
56   /// been issued, but their results are not ready yet (due to the latency of
57   /// the operation).  Once the operands becomes available, the instruction is
58   /// added to the AvailableQueue.
59   std::vector<SUnit*> PendingQueue;
60
61   /// HazardRec - The hazard recognizer to use.
62   HazardRecognizer *HazardRec;
63
64 public:
65   ScheduleDAGList(SelectionDAG *dag, MachineBasicBlock *bb,
66                   const TargetMachine &tm,
67                   SchedulingPriorityQueue *availqueue,
68                   HazardRecognizer *HR)
69     : ScheduleDAG(dag, bb, tm),
70       AvailableQueue(availqueue), HazardRec(HR) {
71     }
72
73   ~ScheduleDAGList() {
74     delete HazardRec;
75     delete AvailableQueue;
76   }
77
78   void Schedule();
79
80 private:
81   void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
82   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
83   void ListScheduleTopDown();
84 };
85 }  // end anonymous namespace
86
87 HazardRecognizer::~HazardRecognizer() {}
88
89
90 /// Schedule - Schedule the DAG using list scheduling.
91 void ScheduleDAGList::Schedule() {
92   DOUT << "********** List Scheduling **********\n";
93   
94   // Build scheduling units.
95   BuildSchedUnits();
96
97   AvailableQueue->initNodes(SUnits);
98   
99   ListScheduleTopDown();
100   
101   AvailableQueue->releaseState();
102 }
103
104 //===----------------------------------------------------------------------===//
105 //  Top-Down Scheduling
106 //===----------------------------------------------------------------------===//
107
108 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
109 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
110 void ScheduleDAGList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
111   --SuccSU->NumPredsLeft;
112   
113 #ifndef NDEBUG
114   if (SuccSU->NumPredsLeft < 0) {
115     cerr << "*** Scheduling failed! ***\n";
116     SuccSU->dump(this);
117     cerr << " has been released too many times!\n";
118     assert(0);
119   }
120 #endif
121   
122   // Compute how many cycles it will be before this actually becomes
123   // available.  This is the max of the start time of all predecessors plus
124   // their latencies.
125   // If this is a token edge, we don't need to wait for the latency of the
126   // preceeding instruction (e.g. a long-latency load) unless there is also
127   // some other data dependence.
128   unsigned PredDoneCycle = SU->Cycle;
129   if (!isChain)
130     PredDoneCycle += SU->Latency;
131   else if (SU->Latency)
132     PredDoneCycle += 1;
133   SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
134   
135   if (SuccSU->NumPredsLeft == 0) {
136     PendingQueue.push_back(SuccSU);
137   }
138 }
139
140 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
141 /// count of its successors. If a successor pending count is zero, add it to
142 /// the Available queue.
143 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
144   DOUT << "*** Scheduling [" << CurCycle << "]: ";
145   DEBUG(SU->dump(this));
146   
147   Sequence.push_back(SU);
148   SU->Cycle = CurCycle;
149
150   // Top down: release successors.
151   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
152        I != E; ++I)
153     ReleaseSucc(SU, I->Dep, I->isCtrl);
154
155   SU->isScheduled = true;
156   AvailableQueue->ScheduledNode(SU);
157 }
158
159 /// ListScheduleTopDown - The main loop of list scheduling for top-down
160 /// schedulers.
161 void ScheduleDAGList::ListScheduleTopDown() {
162   unsigned CurCycle = 0;
163
164   // All leaves to Available queue.
165   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
166     // It is available if it has no predecessors.
167     if (SUnits[i].Preds.empty()) {
168       AvailableQueue->push(&SUnits[i]);
169       SUnits[i].isAvailable = true;
170     }
171   }
172   
173   // While Available queue is not empty, grab the node with the highest
174   // priority. If it is not ready put it back.  Schedule the node.
175   std::vector<SUnit*> NotReady;
176   Sequence.reserve(SUnits.size());
177   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
178     // Check to see if any of the pending instructions are ready to issue.  If
179     // so, add them to the available queue.
180     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
181       if (PendingQueue[i]->CycleBound == CurCycle) {
182         AvailableQueue->push(PendingQueue[i]);
183         PendingQueue[i]->isAvailable = true;
184         PendingQueue[i] = PendingQueue.back();
185         PendingQueue.pop_back();
186         --i; --e;
187       } else {
188         assert(PendingQueue[i]->CycleBound > CurCycle && "Negative latency?");
189       }
190     }
191     
192     // If there are no instructions available, don't try to issue anything, and
193     // don't advance the hazard recognizer.
194     if (AvailableQueue->empty()) {
195       ++CurCycle;
196       continue;
197     }
198
199     SUnit *FoundSUnit = 0;
200     SDNode *FoundNode = 0;
201     
202     bool HasNoopHazards = false;
203     while (!AvailableQueue->empty()) {
204       SUnit *CurSUnit = AvailableQueue->pop();
205       
206       // Get the node represented by this SUnit.
207       FoundNode = CurSUnit->getNode();
208       
209       // If this is a pseudo op, like copyfromreg, look to see if there is a
210       // real target node flagged to it.  If so, use the target node.
211       while (!FoundNode->isMachineOpcode()) {
212         SDNode *N = FoundNode->getFlaggedNode();
213         if (!N) break;
214         FoundNode = N;
215       }
216       
217       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
218       if (HT == HazardRecognizer::NoHazard) {
219         FoundSUnit = CurSUnit;
220         break;
221       }
222       
223       // Remember if this is a noop hazard.
224       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
225       
226       NotReady.push_back(CurSUnit);
227     }
228     
229     // Add the nodes that aren't ready back onto the available list.
230     if (!NotReady.empty()) {
231       AvailableQueue->push_all(NotReady);
232       NotReady.clear();
233     }
234
235     // If we found a node to schedule, do it now.
236     if (FoundSUnit) {
237       ScheduleNodeTopDown(FoundSUnit, CurCycle);
238       HazardRec->EmitInstruction(FoundNode);
239
240       // If this is a pseudo-op node, we don't want to increment the current
241       // cycle.
242       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
243         ++CurCycle;        
244     } else if (!HasNoopHazards) {
245       // Otherwise, we have a pipeline stall, but no other problem, just advance
246       // the current cycle and try again.
247       DOUT << "*** Advancing cycle, no work to do\n";
248       HazardRec->AdvanceCycle();
249       ++NumStalls;
250       ++CurCycle;
251     } else {
252       // Otherwise, we have no instructions to issue and we have instructions
253       // that will fault if we don't do this right.  This is the case for
254       // processors without pipeline interlocks and other cases.
255       DOUT << "*** Emitting noop\n";
256       HazardRec->EmitNoop();
257       Sequence.push_back(0);   // NULL SUnit* -> noop
258       ++NumNoops;
259       ++CurCycle;
260     }
261   }
262
263 #ifndef NDEBUG
264   // Verify that all SUnits were scheduled.
265   bool AnyNotSched = false;
266   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
267     if (SUnits[i].NumPredsLeft != 0) {
268       if (!AnyNotSched)
269         cerr << "*** List scheduling failed! ***\n";
270       SUnits[i].dump(this);
271       cerr << "has not been scheduled!\n";
272       AnyNotSched = true;
273     }
274   }
275   assert(!AnyNotSched);
276 #endif
277 }
278
279 //===----------------------------------------------------------------------===//
280 //                         Public Constructor Functions
281 //===----------------------------------------------------------------------===//
282
283 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
284 /// new hazard recognizer. This scheduler takes ownership of the hazard
285 /// recognizer and deletes it when done.
286 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
287                                             SelectionDAG *DAG,
288                                             const TargetMachine *TM,
289                                             MachineBasicBlock *BB, bool Fast) {
290   return new ScheduleDAGList(DAG, BB, *TM,
291                              new LatencyPriorityQueue(),
292                              IS->CreateTargetHazardRecognizer());
293 }