50331788ec15e5a7b030ff581ec1664a8daa2eb2
[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 <climits>
34 using namespace llvm;
35
36 STATISTIC(NumNoops , "Number of noops inserted");
37 STATISTIC(NumStalls, "Number of pipeline stalls");
38
39 static RegisterScheduler
40   tdListDAGScheduler("list-td", "  Top-down list scheduler",
41                      createTDListDAGScheduler);
42    
43 namespace {
44 //===----------------------------------------------------------------------===//
45 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
46 /// top-down scheduling.
47 ///
48 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
49 private:
50   /// AvailableQueue - The priority queue to use for the available SUnits.
51   ///
52   SchedulingPriorityQueue *AvailableQueue;
53   
54   /// PendingQueue - This contains all of the instructions whose operands have
55   /// been issued, but their results are not ready yet (due to the latency of
56   /// the operation).  Once the operands becomes available, the instruction is
57   /// added to the AvailableQueue.  This keeps track of each SUnit and the
58   /// number of cycles left to execute before the operation is available.
59   std::vector<std::pair<unsigned, 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 *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   DOUT << "*** Final schedule ***\n";
104   DEBUG(dumpSchedule());
105   DOUT << "\n";
106 }
107
108 //===----------------------------------------------------------------------===//
109 //  Top-Down Scheduling
110 //===----------------------------------------------------------------------===//
111
112 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
113 /// the PendingQueue if the count reaches zero.
114 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
115   SuccSU->NumPredsLeft--;
116   
117   assert(SuccSU->NumPredsLeft >= 0 &&
118          "List scheduling internal error");
119   
120   if (SuccSU->NumPredsLeft == 0) {
121     // Compute how many cycles it will be before this actually becomes
122     // available.  This is the max of the start time of all predecessors plus
123     // their latencies.
124     unsigned AvailableCycle = 0;
125     for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
126          E = SuccSU->Preds.end(); I != E; ++I) {
127       // If this is a token edge, we don't need to wait for the latency of the
128       // preceeding instruction (e.g. a long-latency load) unless there is also
129       // some other data dependence.
130       SUnit &Pred = *I->Dep;
131       unsigned PredDoneCycle = Pred.Cycle;
132       if (!I->isCtrl)
133         PredDoneCycle += Pred.Latency;
134       else if (Pred.Latency)
135         PredDoneCycle += 1;
136
137       AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
138     }
139     
140     PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
141   }
142 }
143
144 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
145 /// count of its successors. If a successor pending count is zero, add it to
146 /// the Available queue.
147 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
148   DOUT << "*** Scheduling [" << CurCycle << "]: ";
149   DEBUG(SU->dump(&DAG));
150   
151   Sequence.push_back(SU);
152   SU->Cycle = CurCycle;
153   
154   // Bottom up: release successors.
155   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
156        I != E; ++I)
157     ReleaseSucc(I->Dep, I->isCtrl);
158 }
159
160 /// ListScheduleTopDown - The main loop of list scheduling for top-down
161 /// schedulers.
162 void ScheduleDAGList::ListScheduleTopDown() {
163   unsigned CurCycle = 0;
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 = SUnits[i].isPending = 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].first == CurCycle) {
183         AvailableQueue->push(PendingQueue[i].second);
184         PendingQueue[i].second->isAvailable = true;
185         PendingQueue[i] = PendingQueue.back();
186         PendingQueue.pop_back();
187         --i; --e;
188       } else {
189         assert(PendingQueue[i].first > 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     SDNode *FoundNode = 0;
202     
203     bool HasNoopHazards = false;
204     while (!AvailableQueue->empty()) {
205       SUnit *CurSUnit = AvailableQueue->pop();
206       
207       // Get the node represented by this SUnit.
208       FoundNode = CurSUnit->Node;
209       
210       // If this is a pseudo op, like copyfromreg, look to see if there is a
211       // real target node flagged to it.  If so, use the target node.
212       for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size(); 
213            FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
214         FoundNode = CurSUnit->FlaggedNodes[i];
215       
216       HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
217       if (HT == HazardRecognizer::NoHazard) {
218         FoundSUnit = CurSUnit;
219         break;
220       }
221       
222       // Remember if this is a noop hazard.
223       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
224       
225       NotReady.push_back(CurSUnit);
226     }
227     
228     // Add the nodes that aren't ready back onto the available list.
229     if (!NotReady.empty()) {
230       AvailableQueue->push_all(NotReady);
231       NotReady.clear();
232     }
233
234     // If we found a node to schedule, do it now.
235     if (FoundSUnit) {
236       ScheduleNodeTopDown(FoundSUnit, CurCycle);
237       HazardRec->EmitInstruction(FoundNode);
238       FoundSUnit->isScheduled = true;
239       AvailableQueue->ScheduledNode(FoundSUnit);
240
241       // If this is a pseudo-op node, we don't want to increment the current
242       // cycle.
243       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
244         ++CurCycle;        
245     } else if (!HasNoopHazards) {
246       // Otherwise, we have a pipeline stall, but no other problem, just advance
247       // the current cycle and try again.
248       DOUT << "*** Advancing cycle, no work to do\n";
249       HazardRec->AdvanceCycle();
250       ++NumStalls;
251       ++CurCycle;
252     } else {
253       // Otherwise, we have no instructions to issue and we have instructions
254       // that will fault if we don't do this right.  This is the case for
255       // processors without pipeline interlocks and other cases.
256       DOUT << "*** Emitting noop\n";
257       HazardRec->EmitNoop();
258       Sequence.push_back(0);   // NULL SUnit* -> noop
259       ++NumNoops;
260       ++CurCycle;
261     }
262   }
263
264 #ifndef NDEBUG
265   // Verify that all SUnits were scheduled.
266   bool AnyNotSched = false;
267   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
268     if (SUnits[i].NumPredsLeft != 0) {
269       if (!AnyNotSched)
270         cerr << "*** List scheduling failed! ***\n";
271       SUnits[i].dump(&DAG);
272       cerr << "has not been scheduled!\n";
273       AnyNotSched = true;
274     }
275   }
276   assert(!AnyNotSched);
277 #endif
278 }
279
280 //===----------------------------------------------------------------------===//
281 //                    LatencyPriorityQueue Implementation
282 //===----------------------------------------------------------------------===//
283 //
284 // This is a SchedulingPriorityQueue that schedules using latency information to
285 // reduce the length of the critical path through the basic block.
286 // 
287 namespace {
288   class LatencyPriorityQueue;
289   
290   /// Sorting functions for the Available queue.
291   struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
292     LatencyPriorityQueue *PQ;
293     latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
294     latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
295     
296     bool operator()(const SUnit* left, const SUnit* right) const;
297   };
298 }  // end anonymous namespace
299
300 namespace {
301   class LatencyPriorityQueue : public SchedulingPriorityQueue {
302     // SUnits - The SUnits for the current graph.
303     std::vector<SUnit> *SUnits;
304     
305     // Latencies - The latency (max of latency from this node to the bb exit)
306     // for each node.
307     std::vector<int> Latencies;
308
309     /// NumNodesSolelyBlocking - This vector contains, for every node in the
310     /// Queue, the number of nodes that the node is the sole unscheduled
311     /// predecessor for.  This is used as a tie-breaker heuristic for better
312     /// mobility.
313     std::vector<unsigned> NumNodesSolelyBlocking;
314
315     PriorityQueue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
316 public:
317     LatencyPriorityQueue() : Queue(latency_sort(this)) {
318     }
319     
320     void initNodes(std::vector<SUnit> &sunits) {
321       SUnits = &sunits;
322       // Calculate node priorities.
323       CalculatePriorities();
324     }
325
326     void addNode(const SUnit *SU) {
327       Latencies.resize(SUnits->size(), -1);
328       NumNodesSolelyBlocking.resize(SUnits->size(), 0);
329       CalcLatency(*SU);
330     }
331
332     void updateNode(const SUnit *SU) {
333       Latencies[SU->NodeNum] = -1;
334       CalcLatency(*SU);
335     }
336
337     void releaseState() {
338       SUnits = 0;
339       Latencies.clear();
340     }
341     
342     unsigned getLatency(unsigned NodeNum) const {
343       assert(NodeNum < Latencies.size());
344       return Latencies[NodeNum];
345     }
346     
347     unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
348       assert(NodeNum < NumNodesSolelyBlocking.size());
349       return NumNodesSolelyBlocking[NodeNum];
350     }
351     
352     unsigned size() const { return Queue.size(); }
353
354     bool empty() const { return Queue.empty(); }
355     
356     virtual void push(SUnit *U) {
357       push_impl(U);
358     }
359     void push_impl(SUnit *U);
360     
361     void push_all(const std::vector<SUnit *> &Nodes) {
362       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
363         push_impl(Nodes[i]);
364     }
365     
366     SUnit *pop() {
367       if (empty()) return NULL;
368       SUnit *V = Queue.top();
369       Queue.pop();
370       return V;
371     }
372
373     void remove(SUnit *SU) {
374       assert(!Queue.empty() && "Not in queue!");
375       Queue.erase_one(SU);
376     }
377
378     // ScheduledNode - As nodes are scheduled, we look to see if there are any
379     // successor nodes that have a single unscheduled predecessor.  If so, that
380     // single predecessor has a higher priority, since scheduling it will make
381     // the node available.
382     void ScheduledNode(SUnit *Node);
383
384 private:
385     void CalculatePriorities();
386     int CalcLatency(const SUnit &SU);
387     void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
388     SUnit *getSingleUnscheduledPred(SUnit *SU);
389   };
390 }
391
392 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
393   unsigned LHSNum = LHS->NodeNum;
394   unsigned RHSNum = RHS->NodeNum;
395
396   // The most important heuristic is scheduling the critical path.
397   unsigned LHSLatency = PQ->getLatency(LHSNum);
398   unsigned RHSLatency = PQ->getLatency(RHSNum);
399   if (LHSLatency < RHSLatency) return true;
400   if (LHSLatency > RHSLatency) return false;
401   
402   // After that, if two nodes have identical latencies, look to see if one will
403   // unblock more other nodes than the other.
404   unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
405   unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
406   if (LHSBlocked < RHSBlocked) return true;
407   if (LHSBlocked > RHSBlocked) return false;
408   
409   // Finally, just to provide a stable ordering, use the node number as a
410   // deciding factor.
411   return LHSNum < RHSNum;
412 }
413
414
415 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
416 ///
417 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
418   int &Latency = Latencies[SU.NodeNum];
419   if (Latency != -1)
420     return Latency;
421
422   std::vector<const SUnit*> WorkList;
423   WorkList.push_back(&SU);
424   while (!WorkList.empty()) {
425     const SUnit *Cur = WorkList.back();
426     bool AllDone = true;
427     int MaxSuccLatency = 0;
428     for (SUnit::const_succ_iterator I = Cur->Succs.begin(),E = Cur->Succs.end();
429          I != E; ++I) {
430       int SuccLatency = Latencies[I->Dep->NodeNum];
431       if (SuccLatency == -1) {
432         AllDone = false;
433         WorkList.push_back(I->Dep);
434       } else {
435         MaxSuccLatency = std::max(MaxSuccLatency, SuccLatency);
436       }
437     }
438     if (AllDone) {
439       Latencies[Cur->NodeNum] = MaxSuccLatency + Cur->Latency;
440       WorkList.pop_back();
441     }
442   }
443
444   return Latency;
445 }
446
447 /// CalculatePriorities - Calculate priorities of all scheduling units.
448 void LatencyPriorityQueue::CalculatePriorities() {
449   Latencies.assign(SUnits->size(), -1);
450   NumNodesSolelyBlocking.assign(SUnits->size(), 0);
451
452   // For each node, calculate the maximal path from the node to the exit.
453   std::vector<std::pair<const SUnit*, unsigned> > WorkList;
454   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
455     const SUnit *SU = &(*SUnits)[i];
456     if (SU->Succs.empty())
457       WorkList.push_back(std::make_pair(SU, 0U));
458   }
459
460   while (!WorkList.empty()) {
461     const SUnit *SU = WorkList.back().first;
462     unsigned SuccLat = WorkList.back().second;
463     WorkList.pop_back();
464     int &Latency = Latencies[SU->NodeNum];
465     if (Latency == -1 || (SU->Latency + SuccLat) > (unsigned)Latency) {
466       Latency = SU->Latency + SuccLat;
467       for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
468            I != E; ++I)
469         WorkList.push_back(std::make_pair(I->Dep, Latency));
470     }
471   }
472 }
473
474 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
475 /// of SU, return it, otherwise return null.
476 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
477   SUnit *OnlyAvailablePred = 0;
478   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
479        I != E; ++I) {
480     SUnit &Pred = *I->Dep;
481     if (!Pred.isScheduled) {
482       // We found an available, but not scheduled, predecessor.  If it's the
483       // only one we have found, keep track of it... otherwise give up.
484       if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
485         return 0;
486       OnlyAvailablePred = &Pred;
487     }
488   }
489       
490   return OnlyAvailablePred;
491 }
492
493 void LatencyPriorityQueue::push_impl(SUnit *SU) {
494   // Look at all of the successors of this node.  Count the number of nodes that
495   // this node is the sole unscheduled node for.
496   unsigned NumNodesBlocking = 0;
497   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
498        I != E; ++I)
499     if (getSingleUnscheduledPred(I->Dep) == SU)
500       ++NumNodesBlocking;
501   NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
502   
503   Queue.push(SU);
504 }
505
506
507 // ScheduledNode - As nodes are scheduled, we look to see if there are any
508 // successor nodes that have a single unscheduled predecessor.  If so, that
509 // single predecessor has a higher priority, since scheduling it will make
510 // the node available.
511 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
512   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
513        I != E; ++I)
514     AdjustPriorityOfUnscheduledPreds(I->Dep);
515 }
516
517 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
518 /// scheduled.  If SU is not itself available, then there is at least one
519 /// predecessor node that has not been scheduled yet.  If SU has exactly ONE
520 /// unscheduled predecessor, we want to increase its priority: it getting
521 /// scheduled will make this node available, so it is better than some other
522 /// node of the same priority that will not make a node available.
523 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
524   if (SU->isPending) return;  // All preds scheduled.
525   
526   SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
527   if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
528   
529   // Okay, we found a single predecessor that is available, but not scheduled.
530   // Since it is available, it must be in the priority queue.  First remove it.
531   remove(OnlyAvailablePred);
532
533   // Reinsert the node into the priority queue, which recomputes its
534   // NumNodesSolelyBlocking value.
535   push(OnlyAvailablePred);
536 }
537
538
539 //===----------------------------------------------------------------------===//
540 //                         Public Constructor Functions
541 //===----------------------------------------------------------------------===//
542
543 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
544 /// new hazard recognizer. This scheduler takes ownership of the hazard
545 /// recognizer and deletes it when done.
546 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
547                                             SelectionDAG *DAG,
548                                             MachineBasicBlock *BB, bool Fast) {
549   return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
550                              new LatencyPriorityQueue(),
551                              IS->CreateTargetHazardRecognizer());
552 }