30b8014eefe75f34c78bdd9eb1cfe6e5fb301814
[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 was developed by Evan Cheng and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements bottom-up and top-down list schedulers, using standard
11 // algorithms.  The basic approach uses a priority queue of available nodes to
12 // schedule.  One at a time, nodes are taken from the priority queue (thus in
13 // priority 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 "sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include <climits>
28 #include <iostream>
29 #include <queue>
30 #include <set>
31 #include <vector>
32 #include "llvm/Support/CommandLine.h"
33 using namespace llvm;
34
35 namespace {
36   Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37   Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
38
39   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40   /// a group of nodes flagged together.
41   struct SUnit {
42     SDNode *Node;                       // Representative node.
43     std::vector<SDNode*> FlaggedNodes;  // All nodes flagged to Node.
44     
45     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
46     // is true if the edge is a token chain edge, false if it is a value edge. 
47     std::set<std::pair<SUnit*,bool> > Preds;  // All sunit predecessors.
48     std::set<std::pair<SUnit*,bool> > Succs;  // All sunit successors.
49
50     short NumPredsLeft;                 // # of preds not scheduled.
51     short NumSuccsLeft;                 // # of succs not scheduled.
52     short NumChainPredsLeft;            // # of chain preds not scheduled.
53     short NumChainSuccsLeft;            // # of chain succs not scheduled.
54     bool isTwoAddress     : 1;          // Is a two-address instruction.
55     bool isDefNUseOperand : 1;          // Is a def&use operand.
56     bool isAvailable      : 1;          // True once available.
57     bool isScheduled      : 1;          // True once scheduled.
58     unsigned short Latency;             // Node latency.
59     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
60     unsigned NodeNum;                   // Entry # of node in the node vector.
61     
62     SUnit(SDNode *node, unsigned nodenum)
63       : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
64       NumChainPredsLeft(0), NumChainSuccsLeft(0),
65       isTwoAddress(false), isDefNUseOperand(false),
66       isAvailable(false), isScheduled(false), 
67       Latency(0), CycleBound(0), NodeNum(nodenum) {}
68     
69     void dump(const SelectionDAG *G) const;
70     void dumpAll(const SelectionDAG *G) const;
71   };
72 }
73
74 void SUnit::dump(const SelectionDAG *G) const {
75   std::cerr << "SU: ";
76   Node->dump(G);
77   std::cerr << "\n";
78   if (FlaggedNodes.size() != 0) {
79     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
80       std::cerr << "    ";
81       FlaggedNodes[i]->dump(G);
82       std::cerr << "\n";
83     }
84   }
85 }
86
87 void SUnit::dumpAll(const SelectionDAG *G) const {
88   dump(G);
89
90   std::cerr << "  # preds left       : " << NumPredsLeft << "\n";
91   std::cerr << "  # succs left       : " << NumSuccsLeft << "\n";
92   std::cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
93   std::cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
94   std::cerr << "  Latency            : " << Latency << "\n";
95
96   if (Preds.size() != 0) {
97     std::cerr << "  Predecessors:\n";
98     for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
99            E = Preds.end(); I != E; ++I) {
100       if (I->second)
101         std::cerr << "   ch  ";
102       else
103         std::cerr << "   val ";
104       I->first->dump(G);
105     }
106   }
107   if (Succs.size() != 0) {
108     std::cerr << "  Successors:\n";
109     for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
110            E = Succs.end(); I != E; ++I) {
111       if (I->second)
112         std::cerr << "   ch  ";
113       else
114         std::cerr << "   val ";
115       I->first->dump(G);
116     }
117   }
118   std::cerr << "\n";
119 }
120
121 //===----------------------------------------------------------------------===//
122 /// SchedulingPriorityQueue - This interface is used to plug different
123 /// priorities computation algorithms into the list scheduler. It implements the
124 /// interface of a standard priority queue, where nodes are inserted in 
125 /// arbitrary order and returned in priority order.  The computation of the
126 /// priority and the representation of the queue are totally up to the
127 /// implementation to decide.
128 /// 
129 namespace {
130 class SchedulingPriorityQueue {
131 public:
132   virtual ~SchedulingPriorityQueue() {}
133   
134   virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
135   virtual void releaseState() = 0;
136   
137   virtual bool empty() const = 0;
138   virtual void push(SUnit *U) = 0;
139   
140   virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
141   virtual SUnit *pop() = 0;
142   
143   /// ScheduledNode - As each node is scheduled, this method is invoked.  This
144   /// allows the priority function to adjust the priority of node that have
145   /// already been emitted.
146   virtual void ScheduledNode(SUnit *Node) {}
147 };
148 }
149
150
151
152 namespace {
153 //===----------------------------------------------------------------------===//
154 /// ScheduleDAGList - The actual list scheduler implementation.  This supports
155 /// both top-down and bottom-up scheduling.
156 ///
157 class ScheduleDAGList : public ScheduleDAG {
158 private:
159   // SDNode to SUnit mapping (many to one).
160   std::map<SDNode*, SUnit*> SUnitMap;
161   // The schedule.  Null SUnit*'s represent noop instructions.
162   std::vector<SUnit*> Sequence;
163   
164   // The scheduling units.
165   std::vector<SUnit> SUnits;
166
167   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
168   /// it is top-down.
169   bool isBottomUp;
170   
171   /// PriorityQueue - The priority queue to use.
172   SchedulingPriorityQueue *PriorityQueue;
173   
174   /// HazardRec - The hazard recognizer to use.
175   HazardRecognizer *HazardRec;
176   
177 public:
178   ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
179                   const TargetMachine &tm, bool isbottomup,
180                   SchedulingPriorityQueue *priorityqueue,
181                   HazardRecognizer *HR)
182     : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup), 
183       PriorityQueue(priorityqueue), HazardRec(HR) {
184     }
185
186   ~ScheduleDAGList() {
187     delete HazardRec;
188     delete PriorityQueue;
189   }
190
191   void Schedule();
192
193   void dumpSchedule() const;
194
195 private:
196   SUnit *NewSUnit(SDNode *N);
197   void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
198   void ReleaseSucc(SUnit *SuccSU, bool isChain, unsigned CurCycle);
199   void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
200   void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
201   void ListScheduleTopDown();
202   void ListScheduleBottomUp();
203   void BuildSchedUnits();
204   void EmitSchedule();
205 };
206 }  // end anonymous namespace
207
208 HazardRecognizer::~HazardRecognizer() {}
209
210
211 /// NewSUnit - Creates a new SUnit and return a ptr to it.
212 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
213   SUnits.push_back(SUnit(N, SUnits.size()));
214   return &SUnits.back();
215 }
216
217 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
218 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
219 /// together nodes with a single SUnit.
220 void ScheduleDAGList::BuildSchedUnits() {
221   // Reserve entries in the vector for each of the SUnits we are creating.  This
222   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
223   // invalidated.
224   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
225   
226   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
227   
228   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
229        E = DAG.allnodes_end(); NI != E; ++NI) {
230     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
231       continue;
232     
233     // If this node has already been processed, stop now.
234     if (SUnitMap[NI]) continue;
235     
236     SUnit *NodeSUnit = NewSUnit(NI);
237     
238     // See if anything is flagged to this node, if so, add them to flagged
239     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
240     // are required the be the last operand and result of a node.
241     
242     // Scan up, adding flagged preds to FlaggedNodes.
243     SDNode *N = NI;
244     while (N->getNumOperands() &&
245            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
246       N = N->getOperand(N->getNumOperands()-1).Val;
247       NodeSUnit->FlaggedNodes.push_back(N);
248       SUnitMap[N] = NodeSUnit;
249     }
250     
251     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
252     // have a user of the flag operand.
253     N = NI;
254     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
255       SDOperand FlagVal(N, N->getNumValues()-1);
256       
257       // There are either zero or one users of the Flag result.
258       bool HasFlagUse = false;
259       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
260            UI != E; ++UI)
261         if (FlagVal.isOperand(*UI)) {
262           HasFlagUse = true;
263           NodeSUnit->FlaggedNodes.push_back(N);
264           SUnitMap[N] = NodeSUnit;
265           N = *UI;
266           break;
267         }
268           if (!HasFlagUse) break;
269     }
270     
271     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
272     // Update the SUnit
273     NodeSUnit->Node = N;
274     SUnitMap[N] = NodeSUnit;
275     
276     // Compute the latency for the node.  We use the sum of the latencies for
277     // all nodes flagged together into this SUnit.
278     if (InstrItins.isEmpty()) {
279       // No latency information.
280       NodeSUnit->Latency = 1;
281     } else {
282       NodeSUnit->Latency = 0;
283       if (N->isTargetOpcode()) {
284         unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
285         InstrStage *S = InstrItins.begin(SchedClass);
286         InstrStage *E = InstrItins.end(SchedClass);
287         for (; S != E; ++S)
288           NodeSUnit->Latency += S->Cycles;
289       }
290       for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
291         SDNode *FNode = NodeSUnit->FlaggedNodes[i];
292         if (FNode->isTargetOpcode()) {
293           unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
294           InstrStage *S = InstrItins.begin(SchedClass);
295           InstrStage *E = InstrItins.end(SchedClass);
296           for (; S != E; ++S)
297             NodeSUnit->Latency += S->Cycles;
298         }
299       }
300     }
301   }
302   
303   // Pass 2: add the preds, succs, etc.
304   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
305     SUnit *SU = &SUnits[su];
306     SDNode *MainNode = SU->Node;
307     
308     if (MainNode->isTargetOpcode() &&
309         TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
310       SU->isTwoAddress = true;
311     
312     // Find all predecessors and successors of the group.
313     // Temporarily add N to make code simpler.
314     SU->FlaggedNodes.push_back(MainNode);
315     
316     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
317       SDNode *N = SU->FlaggedNodes[n];
318       
319       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
320         SDNode *OpN = N->getOperand(i).Val;
321         if (isPassiveNode(OpN)) continue;   // Not scheduled.
322         SUnit *OpSU = SUnitMap[OpN];
323         assert(OpSU && "Node has no SUnit!");
324         if (OpSU == SU) continue;           // In the same group.
325         
326         MVT::ValueType OpVT = N->getOperand(i).getValueType();
327         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
328         bool isChain = OpVT == MVT::Other;
329         
330         if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
331           if (!isChain) {
332             SU->NumPredsLeft++;
333           } else {
334             SU->NumChainPredsLeft++;
335           }
336         }
337         if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
338           if (!isChain) {
339             OpSU->NumSuccsLeft++;
340           } else {
341             OpSU->NumChainSuccsLeft++;
342           }
343         }
344       }
345     }
346     
347     // Remove MainNode from FlaggedNodes again.
348     SU->FlaggedNodes.pop_back();
349   }
350   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
351         SUnits[su].dumpAll(&DAG));
352 }
353
354 /// EmitSchedule - Emit the machine code in scheduled order.
355 void ScheduleDAGList::EmitSchedule() {
356   std::map<SDNode*, unsigned> VRBaseMap;
357   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
358     if (SUnit *SU = Sequence[i]) {
359       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
360         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
361       EmitNode(SU->Node, VRBaseMap);
362     } else {
363       // Null SUnit* is a noop.
364       EmitNoop();
365     }
366   }
367 }
368
369 /// dump - dump the schedule.
370 void ScheduleDAGList::dumpSchedule() const {
371   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
372     if (SUnit *SU = Sequence[i])
373       SU->dump(&DAG);
374     else
375       std::cerr << "**** NOOP ****\n";
376   }
377 }
378
379 /// Schedule - Schedule the DAG using list scheduling.
380 /// FIXME: Right now it only supports the burr (bottom up register reducing)
381 /// heuristic.
382 void ScheduleDAGList::Schedule() {
383   DEBUG(std::cerr << "********** List Scheduling **********\n");
384   
385   // Build scheduling units.
386   BuildSchedUnits();
387   
388   PriorityQueue->initNodes(SUnits);
389   
390   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
391   if (isBottomUp)
392     ListScheduleBottomUp();
393   else
394     ListScheduleTopDown();
395   
396   PriorityQueue->releaseState();
397   
398   DEBUG(std::cerr << "*** Final schedule ***\n");
399   DEBUG(dumpSchedule());
400   DEBUG(std::cerr << "\n");
401   
402   // Emit in scheduled order
403   EmitSchedule();
404 }
405
406 //===----------------------------------------------------------------------===//
407 //  Bottom-Up Scheduling
408 //===----------------------------------------------------------------------===//
409
410 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
411 /// the Available queue is the count reaches zero. Also update its cycle bound.
412 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain, 
413                                   unsigned CurrCycle) {
414   // FIXME: the distance between two nodes is not always == the predecessor's
415   // latency. For example, the reader can very well read the register written
416   // by the predecessor later than the issue cycle. It also depends on the
417   // interrupt model (drain vs. freeze).
418   PredSU->CycleBound = std::max(PredSU->CycleBound,CurrCycle + PredSU->Latency);
419
420   if (!isChain)
421     PredSU->NumSuccsLeft--;
422   else
423     PredSU->NumChainSuccsLeft--;
424   
425 #ifndef NDEBUG
426   if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
427     std::cerr << "*** List scheduling failed! ***\n";
428     PredSU->dump(&DAG);
429     std::cerr << " has been released too many times!\n";
430     assert(0);
431   }
432 #endif
433   
434   if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
435     // EntryToken has to go last!  Special case it here.
436     if (PredSU->Node->getOpcode() != ISD::EntryToken) {
437       PredSU->isAvailable = true;
438       PriorityQueue->push(PredSU);
439     }
440   }
441 }
442 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
443 /// count of its predecessors. If a predecessor pending count is zero, add it to
444 /// the Available queue.
445 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurrCycle) {
446   DEBUG(std::cerr << "*** Scheduling: ");
447   DEBUG(SU->dump(&DAG));
448
449   Sequence.push_back(SU);
450
451   // Bottom up: release predecessors
452   for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
453          E = SU->Preds.end(); I != E; ++I) {
454     ReleasePred(I->first, I->second, CurrCycle);
455     if (!I->second)
456       SU->NumPredsLeft--;
457   }
458 }
459
460 /// isReady - True if node's lower cycle bound is less or equal to the current
461 /// scheduling cycle. Always true if all nodes have uniform latency 1.
462 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
463   return SU->CycleBound <= CurrCycle;
464 }
465
466 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
467 /// schedulers.
468 void ScheduleDAGList::ListScheduleBottomUp() {
469   unsigned CurrCycle = 0;
470   // Add root to Available queue.
471   PriorityQueue->push(SUnitMap[DAG.getRoot().Val]);
472
473   // While Available queue is not empty, grab the node with the highest
474   // priority. If it is not ready put it back. Schedule the node.
475   std::vector<SUnit*> NotReady;
476   while (!PriorityQueue->empty()) {
477     SUnit *CurrNode = PriorityQueue->pop();
478
479     while (!isReady(CurrNode, CurrCycle)) {
480       NotReady.push_back(CurrNode);
481       CurrNode = PriorityQueue->pop();
482     }
483     
484     // Add the nodes that aren't ready back onto the available list.
485     PriorityQueue->push_all(NotReady);
486     NotReady.clear();
487
488     ScheduleNodeBottomUp(CurrNode, CurrCycle);
489     CurrCycle++;
490     CurrNode->isScheduled = true;
491     PriorityQueue->ScheduledNode(CurrNode);
492   }
493
494   // Add entry node last
495   if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
496     SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
497     Sequence.push_back(Entry);
498   }
499
500   // Reverse the order if it is bottom up.
501   std::reverse(Sequence.begin(), Sequence.end());
502   
503   
504 #ifndef NDEBUG
505   // Verify that all SUnits were scheduled.
506   bool AnyNotSched = false;
507   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
508     if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
509       if (!AnyNotSched)
510         std::cerr << "*** List scheduling failed! ***\n";
511       SUnits[i].dump(&DAG);
512       std::cerr << "has not been scheduled!\n";
513       AnyNotSched = true;
514     }
515   }
516   assert(!AnyNotSched);
517 #endif
518 }
519
520 //===----------------------------------------------------------------------===//
521 //  Top-Down Scheduling
522 //===----------------------------------------------------------------------===//
523
524 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
525 /// the Available queue is the count reaches zero. Also update its cycle bound.
526 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain,
527                                   unsigned CurrCycle) {
528   // FIXME: the distance between two nodes is not always == the predecessor's
529   // latency. For example, the reader can very well read the register written
530   // by the predecessor later than the issue cycle. It also depends on the
531   // interrupt model (drain vs. freeze).
532   SuccSU->CycleBound = std::max(SuccSU->CycleBound,CurrCycle + SuccSU->Latency);
533   
534   if (!isChain)
535     SuccSU->NumPredsLeft--;
536   else
537     SuccSU->NumChainPredsLeft--;
538   
539 #ifndef NDEBUG
540   if (SuccSU->NumPredsLeft < 0 || SuccSU->NumChainPredsLeft < 0) {
541     std::cerr << "*** List scheduling failed! ***\n";
542     SuccSU->dump(&DAG);
543     std::cerr << " has been released too many times!\n";
544     abort();
545   }
546 #endif
547   
548   if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
549     SuccSU->isAvailable = true;
550     PriorityQueue->push(SuccSU);
551   }
552 }
553
554 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
555 /// count of its successors. If a successor pending count is zero, add it to
556 /// the Available queue.
557 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurrCycle) {
558   DEBUG(std::cerr << "*** Scheduling: ");
559   DEBUG(SU->dump(&DAG));
560   
561   Sequence.push_back(SU);
562   
563   // Bottom up: release successors.
564   for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
565        E = SU->Succs.end(); I != E; ++I) {
566     ReleaseSucc(I->first, I->second, CurrCycle);
567     if (!I->second)
568       SU->NumSuccsLeft--;
569   }
570 }
571
572 /// ListScheduleTopDown - The main loop of list scheduling for top-down
573 /// schedulers.
574 void ScheduleDAGList::ListScheduleTopDown() {
575   unsigned CurrCycle = 0;
576   // Emit the entry node first.
577   SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
578   ScheduleNodeTopDown(Entry, CurrCycle);
579   HazardRec->EmitInstruction(Entry->Node);
580                       
581   // All leaves to Available queue.
582   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
583     // It is available if it has no predecessors.
584     if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry)
585       PriorityQueue->push(&SUnits[i]);
586   }
587   
588   // While Available queue is not empty, grab the node with the highest
589   // priority. If it is not ready put it back.  Schedule the node.
590   std::vector<SUnit*> NotReady;
591   while (!PriorityQueue->empty()) {
592     SUnit *FoundNode = 0;
593
594     bool HasNoopHazards = false;
595     do {
596       SUnit *CurNode = PriorityQueue->pop();
597       
598       // Get the node represented by this SUnit.
599       SDNode *N = CurNode->Node;
600       // If this is a pseudo op, like copyfromreg, look to see if there is a
601       // real target node flagged to it.  If so, use the target node.
602       for (unsigned i = 0, e = CurNode->FlaggedNodes.size(); 
603            N->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
604         N = CurNode->FlaggedNodes[i];
605       
606       HazardRecognizer::HazardType HT = HazardRec->getHazardType(N);
607       if (HT == HazardRecognizer::NoHazard) {
608         FoundNode = CurNode;
609         break;
610       }
611       
612       // Remember if this is a noop hazard.
613       HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
614       
615       NotReady.push_back(CurNode);
616     } while (!PriorityQueue->empty());
617     
618     // Add the nodes that aren't ready back onto the available list.
619     PriorityQueue->push_all(NotReady);
620     NotReady.clear();
621
622     // If we found a node to schedule, do it now.
623     if (FoundNode) {
624       ScheduleNodeTopDown(FoundNode, CurrCycle);
625       CurrCycle++;   // Fixme don't increment for pseudo-ops!
626       HazardRec->EmitInstruction(FoundNode->Node);
627       FoundNode->isScheduled = true;
628       PriorityQueue->ScheduledNode(FoundNode);
629     } else if (!HasNoopHazards) {
630       // Otherwise, we have a pipeline stall, but no other problem, just advance
631       // the current cycle and try again.
632       DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
633       HazardRec->AdvanceCycle();
634       ++NumStalls;
635     } else {
636       // Otherwise, we have no instructions to issue and we have instructions
637       // that will fault if we don't do this right.  This is the case for
638       // processors without pipeline interlocks and other cases.
639       DEBUG(std::cerr << "*** Emitting noop\n");
640       HazardRec->EmitNoop();
641       Sequence.push_back(0);   // NULL SUnit* -> noop
642       ++NumNoops;
643     }
644   }
645
646 #ifndef NDEBUG
647   // Verify that all SUnits were scheduled.
648   bool AnyNotSched = false;
649   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
650     if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
651       if (!AnyNotSched)
652         std::cerr << "*** List scheduling failed! ***\n";
653       SUnits[i].dump(&DAG);
654       std::cerr << "has not been scheduled!\n";
655       AnyNotSched = true;
656     }
657   }
658   assert(!AnyNotSched);
659 #endif
660 }
661
662 //===----------------------------------------------------------------------===//
663 //                RegReductionPriorityQueue Implementation
664 //===----------------------------------------------------------------------===//
665 //
666 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
667 // to reduce register pressure.
668 // 
669 namespace {
670   class RegReductionPriorityQueue;
671   
672   /// Sorting functions for the Available queue.
673   struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
674     RegReductionPriorityQueue *SPQ;
675     ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
676     ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
677     
678     bool operator()(const SUnit* left, const SUnit* right) const;
679   };
680 }  // end anonymous namespace
681
682 namespace {
683   class RegReductionPriorityQueue : public SchedulingPriorityQueue {
684     // SUnits - The SUnits for the current graph.
685     const std::vector<SUnit> *SUnits;
686     
687     // SethiUllmanNumbers - The SethiUllman number for each node.
688     std::vector<int> SethiUllmanNumbers;
689     
690     std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
691   public:
692     RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
693     }
694     
695     void initNodes(const std::vector<SUnit> &sunits) {
696       SUnits = &sunits;
697       // Calculate node priorities.
698       CalculatePriorities();
699     }
700     void releaseState() {
701       SUnits = 0;
702       SethiUllmanNumbers.clear();
703     }
704     
705     unsigned getSethiUllmanNumber(unsigned NodeNum) const {
706       assert(NodeNum < SethiUllmanNumbers.size());
707       return SethiUllmanNumbers[NodeNum];
708     }
709     
710     bool empty() const { return Queue.empty(); }
711     
712     void push(SUnit *U) {
713       Queue.push(U);
714     }
715     void push_all(const std::vector<SUnit *> &Nodes) {
716       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
717         Queue.push(Nodes[i]);
718     }
719     
720     SUnit *pop() {
721       SUnit *V = Queue.top();
722       Queue.pop();
723       return V;
724     }
725   private:
726     void CalculatePriorities();
727     int CalcNodePriority(const SUnit *SU);
728   };
729 }
730
731 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
732   unsigned LeftNum  = left->NodeNum;
733   unsigned RightNum = right->NodeNum;
734   
735   int LBonus = (int)left ->isDefNUseOperand;
736   int RBonus = (int)right->isDefNUseOperand;
737   
738   // Special tie breaker: if two nodes share a operand, the one that
739   // use it as a def&use operand is preferred.
740   if (left->isTwoAddress && !right->isTwoAddress) {
741     SDNode *DUNode = left->Node->getOperand(0).Val;
742     if (DUNode->isOperand(right->Node))
743       LBonus++;
744   }
745   if (!left->isTwoAddress && right->isTwoAddress) {
746     SDNode *DUNode = right->Node->getOperand(0).Val;
747     if (DUNode->isOperand(left->Node))
748       RBonus++;
749   }
750   
751   // Priority1 is just the number of live range genned.
752   int LPriority1 = left ->NumPredsLeft - LBonus;
753   int RPriority1 = right->NumPredsLeft - RBonus;
754   int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
755   int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
756   
757   if (LPriority1 > RPriority1)
758     return true;
759   else if (LPriority1 == RPriority1)
760     if (LPriority2 < RPriority2)
761       return true;
762     else if (LPriority2 == RPriority2)
763       if (left->CycleBound > right->CycleBound) 
764         return true;
765   
766   return false;
767 }
768
769
770 /// CalcNodePriority - Priority is the Sethi Ullman number. 
771 /// Smaller number is the higher priority.
772 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
773   int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
774   if (SethiUllmanNumber != INT_MIN)
775     return SethiUllmanNumber;
776   
777   if (SU->Preds.size() == 0) {
778     SethiUllmanNumber = 1;
779   } else {
780     int Extra = 0;
781     for (std::set<std::pair<SUnit*, bool> >::const_iterator
782          I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
783       if (I->second) continue;  // ignore chain preds.
784       SUnit *PredSU = I->first;
785       int PredSethiUllman = CalcNodePriority(PredSU);
786       if (PredSethiUllman > SethiUllmanNumber) {
787         SethiUllmanNumber = PredSethiUllman;
788         Extra = 0;
789       } else if (PredSethiUllman == SethiUllmanNumber)
790         Extra++;
791     }
792     
793     if (SU->Node->getOpcode() != ISD::TokenFactor)
794       SethiUllmanNumber += Extra;
795     else
796       SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
797   }
798   
799   return SethiUllmanNumber;
800 }
801
802 /// CalculatePriorities - Calculate priorities of all scheduling units.
803 void RegReductionPriorityQueue::CalculatePriorities() {
804   SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
805   
806   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
807     CalcNodePriority(&(*SUnits)[i]);
808 }
809
810 //===----------------------------------------------------------------------===//
811 //                    LatencyPriorityQueue Implementation
812 //===----------------------------------------------------------------------===//
813 //
814 // This is a SchedulingPriorityQueue that schedules using latency information to
815 // reduce the length of the critical path through the basic block.
816 // 
817 namespace {
818   class LatencyPriorityQueue;
819   
820   /// Sorting functions for the Available queue.
821   struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
822     LatencyPriorityQueue *PQ;
823     latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
824     latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
825     
826     bool operator()(const SUnit* left, const SUnit* right) const;
827   };
828 }  // end anonymous namespace
829
830 namespace {
831   class LatencyPriorityQueue : public SchedulingPriorityQueue {
832     // SUnits - The SUnits for the current graph.
833     const std::vector<SUnit> *SUnits;
834     
835     // Latencies - The latency (max of latency from this node to the bb exit)
836     // for each node.
837     std::vector<int> Latencies;
838
839     /// NumNodesSolelyBlocking - This vector contains, for every node in the
840     /// Queue, the number of nodes that the node is the sole unscheduled
841     /// predecessor for.  This is used as a tie-breaker heuristic for better
842     /// mobility.
843     std::vector<unsigned> NumNodesSolelyBlocking;
844
845     std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
846 public:
847     LatencyPriorityQueue() : Queue(latency_sort(this)) {
848     }
849     
850     void initNodes(const std::vector<SUnit> &sunits) {
851       SUnits = &sunits;
852       // Calculate node priorities.
853       CalculatePriorities();
854     }
855     void releaseState() {
856       SUnits = 0;
857       Latencies.clear();
858     }
859     
860     unsigned getLatency(unsigned NodeNum) const {
861       assert(NodeNum < Latencies.size());
862       return Latencies[NodeNum];
863     }
864     
865     unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
866       assert(NodeNum < NumNodesSolelyBlocking.size());
867       return NumNodesSolelyBlocking[NodeNum];
868     }
869     
870     bool empty() const { return Queue.empty(); }
871     
872     virtual void push(SUnit *U) {
873       push_impl(U);
874     }
875     void push_impl(SUnit *U);
876     
877     void push_all(const std::vector<SUnit *> &Nodes) {
878       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
879         push_impl(Nodes[i]);
880     }
881     
882     SUnit *pop() {
883       SUnit *V = Queue.top();
884       Queue.pop();
885       return V;
886     }
887     
888     // ScheduledNode - As nodes are scheduled, we look to see if there are any
889     // successor nodes that have a single unscheduled predecessor.  If so, that
890     // single predecessor has a higher priority, since scheduling it will make
891     // the node available.
892     void ScheduledNode(SUnit *Node);
893     
894 private:
895     void CalculatePriorities();
896     int CalcLatency(const SUnit &SU);
897     void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
898     
899     /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
900     /// node from a priority queue.  We should roll our own heap to make this
901     /// better or something.
902     void RemoveFromPriorityQueue(SUnit *SU) {
903       std::vector<SUnit*> Temp;
904       
905       assert(!Queue.empty() && "Not in queue!");
906       while (Queue.top() != SU) {
907         Temp.push_back(Queue.top());
908         Queue.pop();
909         assert(!Queue.empty() && "Not in queue!");
910       }
911
912       // Remove the node from the PQ.
913       Queue.pop();
914       
915       // Add all the other nodes back.
916       for (unsigned i = 0, e = Temp.size(); i != e; ++i)
917         Queue.push(Temp[i]);
918     }
919   };
920 }
921
922 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
923   unsigned LHSNum = LHS->NodeNum;
924   unsigned RHSNum = RHS->NodeNum;
925
926   // The most important heuristic is scheduling the critical path.
927   unsigned LHSLatency = PQ->getLatency(LHSNum);
928   unsigned RHSLatency = PQ->getLatency(RHSNum);
929   if (LHSLatency < RHSLatency) return true;
930   if (LHSLatency > RHSLatency) return false;
931   
932   // After that, if two nodes have identical latencies, look to see if one will
933   // unblock more other nodes than the other.
934   unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
935   unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
936   if (LHSBlocked < RHSBlocked) return true;
937   if (LHSBlocked > RHSBlocked) return false;
938   
939   // Finally, just to provide a stable ordering, use the node number as a
940   // deciding factor.
941   return LHSNum < RHSNum;
942 }
943
944
945 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
946 ///
947 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
948   int &Latency = Latencies[SU.NodeNum];
949   if (Latency != -1)
950     return Latency;
951   
952   int MaxSuccLatency = 0;
953   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
954        E = SU.Succs.end(); I != E; ++I)
955     MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
956
957   return Latency = MaxSuccLatency + SU.Latency;
958 }
959
960 /// CalculatePriorities - Calculate priorities of all scheduling units.
961 void LatencyPriorityQueue::CalculatePriorities() {
962   Latencies.assign(SUnits->size(), -1);
963   NumNodesSolelyBlocking.assign(SUnits->size(), 0);
964   
965   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
966     CalcLatency((*SUnits)[i]);
967 }
968
969 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
970 /// of SU, return it, otherwise return null.
971 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
972   SUnit *OnlyAvailablePred = 0;
973   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
974        E = SU->Preds.end(); I != E; ++I)
975     if (!I->first->isScheduled) {
976       // We found an available, but not scheduled, predecessor.  If it's the
977       // only one we have found, keep track of it... otherwise give up.
978       if (OnlyAvailablePred && OnlyAvailablePred != I->first)
979         return 0;
980       OnlyAvailablePred = I->first;
981     }
982       
983   return OnlyAvailablePred;
984 }
985
986 void LatencyPriorityQueue::push_impl(SUnit *SU) {
987   // Look at all of the successors of this node.  Count the number of nodes that
988   // this node is the sole unscheduled node for.
989   unsigned NumNodesBlocking = 0;
990   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
991        E = SU->Succs.end(); I != E; ++I)
992     if (getSingleUnscheduledPred(I->first) == SU)
993       ++NumNodesBlocking;
994   NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
995   
996   Queue.push(SU);
997 }
998
999
1000 // ScheduledNode - As nodes are scheduled, we look to see if there are any
1001 // successor nodes that have a single unscheduled predecessor.  If so, that
1002 // single predecessor has a higher priority, since scheduling it will make
1003 // the node available.
1004 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1005   for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1006        E = SU->Succs.end(); I != E; ++I)
1007     AdjustPriorityOfUnscheduledPreds(I->first);
1008 }
1009
1010 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1011 /// scheduled.  If SU is not itself available, then there is at least one
1012 /// predecessor node that has not been scheduled yet.  If SU has exactly ONE
1013 /// unscheduled predecessor, we want to increase its priority: it getting
1014 /// scheduled will make this node available, so it is better than some other
1015 /// node of the same priority that will not make a node available.
1016 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1017   if (SU->isAvailable) return;  // All preds scheduled.
1018   
1019   SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1020   if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1021   
1022   // Okay, we found a single predecessor that is available, but not scheduled.
1023   // Since it is available, it must be in the priority queue.  First remove it.
1024   RemoveFromPriorityQueue(OnlyAvailablePred);
1025
1026   // Reinsert the node into the priority queue, which recomputes its
1027   // NumNodesSolelyBlocking value.
1028   push(OnlyAvailablePred);
1029 }
1030
1031
1032 //===----------------------------------------------------------------------===//
1033 //                         Public Constructor Functions
1034 //===----------------------------------------------------------------------===//
1035
1036 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1037                                                     MachineBasicBlock *BB) {
1038   return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true, 
1039                              new RegReductionPriorityQueue(),
1040                              new HazardRecognizer());
1041 }
1042
1043 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1044 /// specified hazard recognizer.
1045 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1046                                             MachineBasicBlock *BB,
1047                                             HazardRecognizer *HR) {
1048   return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1049                              new LatencyPriorityQueue(),
1050                              HR);
1051 }