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