Correct a comment.
[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.  This keeps track of each SUnit and the
59   /// number of cycles left to execute before the operation is available.
60   std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
61
62   /// HazardRec - The hazard recognizer to use.
63   HazardRecognizer *HazardRec;
64
65 public:
66   ScheduleDAGList(SelectionDAG *dag, MachineBasicBlock *bb,
67                   const TargetMachine &tm,
68                   SchedulingPriorityQueue *availqueue,
69                   HazardRecognizer *HR)
70     : ScheduleDAG(dag, bb, tm),
71       AvailableQueue(availqueue), HazardRec(HR) {
72     }
73
74   ~ScheduleDAGList() {
75     delete HazardRec;
76     delete AvailableQueue;
77   }
78
79   void Schedule();
80
81 private:
82   void ReleaseSucc(SUnit *SuccSU, bool isChain);
83   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
84   void ListScheduleTopDown();
85 };
86 }  // end anonymous namespace
87
88 HazardRecognizer::~HazardRecognizer() {}
89
90
91 /// Schedule - Schedule the DAG using list scheduling.
92 void ScheduleDAGList::Schedule() {
93   DOUT << "********** List Scheduling **********\n";
94   
95   // Build scheduling units.
96   BuildSchedUnits();
97
98   AvailableQueue->initNodes(SUnits);
99   
100   ListScheduleTopDown();
101   
102   AvailableQueue->releaseState();
103 }
104
105 //===----------------------------------------------------------------------===//
106 //  Top-Down Scheduling
107 //===----------------------------------------------------------------------===//
108
109 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
110 /// the PendingQueue if the count reaches zero.
111 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
112   SuccSU->NumPredsLeft--;
113   
114   assert(SuccSU->NumPredsLeft >= 0 &&
115          "List scheduling internal error");
116   
117   if (SuccSU->NumPredsLeft == 0) {
118     // Compute how many cycles it will be before this actually becomes
119     // available.  This is the max of the start time of all predecessors plus
120     // their latencies.
121     unsigned AvailableCycle = 0;
122     for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
123          E = SuccSU->Preds.end(); I != E; ++I) {
124       // If this is a token edge, we don't need to wait for the latency of the
125       // preceeding instruction (e.g. a long-latency load) unless there is also
126       // some other data dependence.
127       SUnit &Pred = *I->Dep;
128       unsigned PredDoneCycle = Pred.Cycle;
129       if (!I->isCtrl)
130         PredDoneCycle += Pred.Latency;
131       else if (Pred.Latency)
132         PredDoneCycle += 1;
133
134       AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
135     }
136     
137     PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
138   }
139 }
140
141 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
142 /// count of its successors. If a successor pending count is zero, add it to
143 /// the Available queue.
144 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
145   DOUT << "*** Scheduling [" << CurCycle << "]: ";
146   DEBUG(SU->dump(DAG));
147   
148   Sequence.push_back(SU);
149   SU->Cycle = CurCycle;
150   
151   // Top down: release successors.
152   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
153        I != E; ++I)
154     ReleaseSucc(I->Dep, I->isCtrl);
155 }
156
157 /// ListScheduleTopDown - The main loop of list scheduling for top-down
158 /// schedulers.
159 void ScheduleDAGList::ListScheduleTopDown() {
160   unsigned CurCycle = 0;
161
162   // All leaves to Available queue.
163   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
164     // It is available if it has no predecessors.
165     if (SUnits[i].Preds.empty()) {
166       AvailableQueue->push(&SUnits[i]);
167       SUnits[i].isAvailable = SUnits[i].isPending = true;
168     }
169   }
170   
171   // While Available queue is not empty, grab the node with the highest
172   // priority. If it is not ready put it back.  Schedule the node.
173   std::vector<SUnit*> NotReady;
174   Sequence.reserve(SUnits.size());
175   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
176     // Check to see if any of the pending instructions are ready to issue.  If
177     // so, add them to the available queue.
178     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
179       if (PendingQueue[i].first == CurCycle) {
180         AvailableQueue->push(PendingQueue[i].second);
181         PendingQueue[i].second->isAvailable = true;
182         PendingQueue[i] = PendingQueue.back();
183         PendingQueue.pop_back();
184         --i; --e;
185       } else {
186         assert(PendingQueue[i].first > CurCycle && "Negative latency?");
187       }
188     }
189     
190     // If there are no instructions available, don't try to issue anything, and
191     // don't advance the hazard recognizer.
192     if (AvailableQueue->empty()) {
193       ++CurCycle;
194       continue;
195     }
196
197     SUnit *FoundSUnit = 0;
198     SDNode *FoundNode = 0;
199     
200     bool HasNoopHazards = false;
201     while (!AvailableQueue->empty()) {
202       SUnit *CurSUnit = AvailableQueue->pop();
203       
204       // Get the node represented by this SUnit.
205       FoundNode = CurSUnit->getNode();
206       
207       // If this is a pseudo op, like copyfromreg, look to see if there is a
208       // real target node flagged to it.  If so, use the target node.
209       while (!FoundNode->isMachineOpcode()) {
210         SDNode *N = FoundNode->getFlaggedNode();
211         if (!N) break;
212         FoundNode = N;
213       }
214       
215       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
216       if (HT == HazardRecognizer::NoHazard) {
217         FoundSUnit = CurSUnit;
218         break;
219       }
220       
221       // Remember if this is a noop hazard.
222       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
223       
224       NotReady.push_back(CurSUnit);
225     }
226     
227     // Add the nodes that aren't ready back onto the available list.
228     if (!NotReady.empty()) {
229       AvailableQueue->push_all(NotReady);
230       NotReady.clear();
231     }
232
233     // If we found a node to schedule, do it now.
234     if (FoundSUnit) {
235       ScheduleNodeTopDown(FoundSUnit, CurCycle);
236       HazardRec->EmitInstruction(FoundNode);
237       FoundSUnit->isScheduled = true;
238       AvailableQueue->ScheduledNode(FoundSUnit);
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(DAG);
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 }