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