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