eliminate uses of cerr()
[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 "ScheduleDAGSDNodes.h"
23 #include "llvm/CodeGen/LatencyPriorityQueue.h"
24 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/PriorityQueue.h"
35 #include "llvm/ADT/Statistic.h"
36 #include <climits>
37 using namespace llvm;
38
39 STATISTIC(NumNoops , "Number of noops inserted");
40 STATISTIC(NumStalls, "Number of pipeline stalls");
41
42 static RegisterScheduler
43   tdListDAGScheduler("list-td", "Top-down list scheduler",
44                      createTDListDAGScheduler);
45    
46 namespace {
47 //===----------------------------------------------------------------------===//
48 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
49 /// top-down scheduling.
50 ///
51 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAGSDNodes {
52 private:
53   /// AvailableQueue - The priority queue to use for the available SUnits.
54   ///
55   SchedulingPriorityQueue *AvailableQueue;
56   
57   /// PendingQueue - This contains all of the instructions whose operands have
58   /// been issued, but their results are not ready yet (due to the latency of
59   /// the operation).  Once the operands become available, the instruction is
60   /// added to the AvailableQueue.
61   std::vector<SUnit*> PendingQueue;
62
63   /// HazardRec - The hazard recognizer to use.
64   ScheduleHazardRecognizer *HazardRec;
65
66 public:
67   ScheduleDAGList(MachineFunction &mf,
68                   SchedulingPriorityQueue *availqueue,
69                   ScheduleHazardRecognizer *HR)
70     : ScheduleDAGSDNodes(mf),
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 *SU, const SDep &D);
83   void ReleaseSuccessors(SUnit *SU);
84   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
85   void ListScheduleTopDown();
86 };
87 }  // end anonymous namespace
88
89 /// Schedule - Schedule the DAG using list scheduling.
90 void ScheduleDAGList::Schedule() {
91   DEBUG(errs() << "********** List Scheduling **********\n");
92   
93   // Build the scheduling graph.
94   BuildSchedGraph();
95
96   AvailableQueue->initNodes(SUnits);
97   
98   ListScheduleTopDown();
99   
100   AvailableQueue->releaseState();
101 }
102
103 //===----------------------------------------------------------------------===//
104 //  Top-Down Scheduling
105 //===----------------------------------------------------------------------===//
106
107 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
108 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
109 void ScheduleDAGList::ReleaseSucc(SUnit *SU, const SDep &D) {
110   SUnit *SuccSU = D.getSUnit();
111   --SuccSU->NumPredsLeft;
112   
113 #ifndef NDEBUG
114   if (SuccSU->NumPredsLeft < 0) {
115     errs() << "*** Scheduling failed! ***\n";
116     SuccSU->dump(this);
117     errs() << " has been released too many times!\n";
118     llvm_unreachable(0);
119   }
120 #endif
121   
122   SuccSU->setDepthToAtLeast(SU->getDepth() + D.getLatency());
123   
124   // If all the node's predecessors are scheduled, this node is ready
125   // to be scheduled. Ignore the special ExitSU node.
126   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
127     PendingQueue.push_back(SuccSU);
128 }
129
130 void ScheduleDAGList::ReleaseSuccessors(SUnit *SU) {
131   // Top down: release successors.
132   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
133        I != E; ++I) {
134     assert(!I->isAssignedRegDep() &&
135            "The list-td scheduler doesn't yet support physreg dependencies!");
136
137     ReleaseSucc(SU, *I);
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   DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
146   DEBUG(SU->dump(this));
147   
148   Sequence.push_back(SU);
149   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
150   SU->setDepthToAtLeast(CurCycle);
151
152   ReleaseSuccessors(SU);
153   SU->isScheduled = true;
154   AvailableQueue->ScheduledNode(SU);
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   // Release any successors of the special Entry node.
163   ReleaseSuccessors(&EntrySU);
164
165   // All leaves to Available queue.
166   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
167     // It is available if it has no predecessors.
168     if (SUnits[i].Preds.empty()) {
169       AvailableQueue->push(&SUnits[i]);
170       SUnits[i].isAvailable = true;
171     }
172   }
173   
174   // While Available queue is not empty, grab the node with the highest
175   // priority. If it is not ready put it back.  Schedule the node.
176   std::vector<SUnit*> NotReady;
177   Sequence.reserve(SUnits.size());
178   while (!AvailableQueue->empty() || !PendingQueue.empty()) {
179     // Check to see if any of the pending instructions are ready to issue.  If
180     // so, add them to the available queue.
181     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
182       if (PendingQueue[i]->getDepth() == CurCycle) {
183         AvailableQueue->push(PendingQueue[i]);
184         PendingQueue[i]->isAvailable = true;
185         PendingQueue[i] = PendingQueue.back();
186         PendingQueue.pop_back();
187         --i; --e;
188       } else {
189         assert(PendingQueue[i]->getDepth() > CurCycle && "Negative latency?");
190       }
191     }
192     
193     // If there are no instructions available, don't try to issue anything, and
194     // don't advance the hazard recognizer.
195     if (AvailableQueue->empty()) {
196       ++CurCycle;
197       continue;
198     }
199
200     SUnit *FoundSUnit = 0;
201     
202     bool HasNoopHazards = false;
203     while (!AvailableQueue->empty()) {
204       SUnit *CurSUnit = AvailableQueue->pop();
205       
206       ScheduleHazardRecognizer::HazardType HT =
207         HazardRec->getHazardType(CurSUnit);
208       if (HT == ScheduleHazardRecognizer::NoHazard) {
209         FoundSUnit = CurSUnit;
210         break;
211       }
212     
213       // Remember if this is a noop hazard.
214       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
215       
216       NotReady.push_back(CurSUnit);
217     }
218     
219     // Add the nodes that aren't ready back onto the available list.
220     if (!NotReady.empty()) {
221       AvailableQueue->push_all(NotReady);
222       NotReady.clear();
223     }
224
225     // If we found a node to schedule, do it now.
226     if (FoundSUnit) {
227       ScheduleNodeTopDown(FoundSUnit, CurCycle);
228       HazardRec->EmitInstruction(FoundSUnit);
229
230       // If this is a pseudo-op node, we don't want to increment the current
231       // cycle.
232       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
233         ++CurCycle;        
234     } else if (!HasNoopHazards) {
235       // Otherwise, we have a pipeline stall, but no other problem, just advance
236       // the current cycle and try again.
237       DEBUG(errs() << "*** Advancing cycle, no work to do\n");
238       HazardRec->AdvanceCycle();
239       ++NumStalls;
240       ++CurCycle;
241     } else {
242       // Otherwise, we have no instructions to issue and we have instructions
243       // that will fault if we don't do this right.  This is the case for
244       // processors without pipeline interlocks and other cases.
245       DEBUG(errs() << "*** Emitting noop\n");
246       HazardRec->EmitNoop();
247       Sequence.push_back(0);   // NULL here means noop
248       ++NumNoops;
249       ++CurCycle;
250     }
251   }
252
253 #ifndef NDEBUG
254   VerifySchedule(/*isBottomUp=*/false);
255 #endif
256 }
257
258 //===----------------------------------------------------------------------===//
259 //                         Public Constructor Functions
260 //===----------------------------------------------------------------------===//
261
262 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
263 /// new hazard recognizer. This scheduler takes ownership of the hazard
264 /// recognizer and deletes it when done.
265 ScheduleDAGSDNodes *
266 llvm::createTDListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
267   return new ScheduleDAGList(*IS->MF,
268                              new LatencyPriorityQueue(),
269                              IS->CreateTargetHazardRecognizer());
270 }