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