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