Port a shift-by-1 optimization from LegalizeDAG: it
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms.  The basic approach uses a priority
12 // queue of available nodes to schedule.  One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/PriorityQueue.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include <climits>
34 #include "llvm/Support/CommandLine.h"
35 using namespace llvm;
36
37 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
38 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
39 STATISTIC(NumDups,       "Number of duplicated nodes");
40 STATISTIC(NumCCCopies,   "Number of cross class copies");
41
42 static RegisterScheduler
43   burrListDAGScheduler("list-burr",
44                        "  Bottom-up register reduction list scheduling",
45                        createBURRListDAGScheduler);
46 static RegisterScheduler
47   tdrListrDAGScheduler("list-tdrr",
48                        "  Top-down register reduction list scheduling",
49                        createTDRRListDAGScheduler);
50
51 namespace {
52 //===----------------------------------------------------------------------===//
53 /// ScheduleDAGRRList - The actual register reduction list scheduler
54 /// implementation.  This supports both top-down and bottom-up scheduling.
55 ///
56 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
57 private:
58   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
59   /// it is top-down.
60   bool isBottomUp;
61
62   /// Fast - True if we are performing fast scheduling.
63   ///
64   bool Fast;
65   
66   /// AvailableQueue - The priority queue to use for the available SUnits.
67   SchedulingPriorityQueue *AvailableQueue;
68
69   /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
70   /// that are "live". These nodes must be scheduled before any other nodes that
71   /// modifies the registers can be scheduled.
72   SmallSet<unsigned, 4> LiveRegs;
73   std::vector<SUnit*> LiveRegDefs;
74   std::vector<unsigned> LiveRegCycles;
75
76 public:
77   ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
78                     const TargetMachine &tm, bool isbottomup, bool f,
79                     SchedulingPriorityQueue *availqueue)
80     : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup), Fast(f),
81       AvailableQueue(availqueue) {
82     }
83
84   ~ScheduleDAGRRList() {
85     delete AvailableQueue;
86   }
87
88   void Schedule();
89
90   /// IsReachable - Checks if SU is reachable from TargetSU.
91   bool IsReachable(SUnit *SU, SUnit *TargetSU);
92
93   /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
94   /// create a cycle.
95   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
96
97   /// AddPred - This adds the specified node X as a predecessor of 
98   /// the current node Y if not already.
99   /// This returns true if this is a new predecessor.
100   /// Updates the topological ordering if required.
101   bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
102                unsigned PhyReg = 0, int Cost = 1);
103
104   /// RemovePred - This removes the specified node N from the predecessors of 
105   /// the current node M. Updates the topological ordering if required.
106   bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
107
108 private:
109   void ReleasePred(SUnit*, bool, unsigned);
110   void ReleaseSucc(SUnit*, bool isChain, unsigned);
111   void CapturePred(SUnit*, SUnit*, bool);
112   void ScheduleNodeBottomUp(SUnit*, unsigned);
113   void ScheduleNodeTopDown(SUnit*, unsigned);
114   void UnscheduleNodeBottomUp(SUnit*);
115   void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
116   SUnit *CopyAndMoveSuccessors(SUnit*);
117   void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
118                                   const TargetRegisterClass*,
119                                   const TargetRegisterClass*,
120                                   SmallVector<SUnit*, 2>&);
121   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
122   void ListScheduleTopDown();
123   void ListScheduleBottomUp();
124   void CommuteNodesToReducePressure();
125
126
127   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
128   /// Updates the topological ordering if required.
129   SUnit *CreateNewSUnit(SDNode *N) {
130     SUnit *NewNode = NewSUnit(N);
131     // Update the topological ordering.
132     if (NewNode->NodeNum >= Node2Index.size())
133       InitDAGTopologicalSorting();
134     return NewNode;
135   }
136
137   /// CreateClone - Creates a new SUnit from an existing one.
138   /// Updates the topological ordering if required.
139   SUnit *CreateClone(SUnit *N) {
140     SUnit *NewNode = Clone(N);
141     // Update the topological ordering.
142     if (NewNode->NodeNum >= Node2Index.size())
143       InitDAGTopologicalSorting();
144     return NewNode;
145   }
146
147   /// Functions for preserving the topological ordering
148   /// even after dynamic insertions of new edges.
149   /// This allows a very fast implementation of IsReachable.
150
151   /// InitDAGTopologicalSorting - create the initial topological 
152   /// ordering from the DAG to be scheduled.
153   void InitDAGTopologicalSorting();
154
155   /// DFS - make a DFS traversal and mark all nodes affected by the 
156   /// edge insertion. These nodes will later get new topological indexes
157   /// by means of the Shift method.
158   void DFS(SUnit *SU, int UpperBound, bool& HasLoop);
159
160   /// Shift - reassign topological indexes for the nodes in the DAG
161   /// to preserve the topological ordering.
162   void Shift(BitVector& Visited, int LowerBound, int UpperBound);
163
164   /// Allocate - assign the topological index to the node n.
165   void Allocate(int n, int index);
166
167   /// Index2Node - Maps topological index to the node number.
168   std::vector<int> Index2Node;
169   /// Node2Index - Maps the node number to its topological index.
170   std::vector<int> Node2Index;
171   /// Visited - a set of nodes visited during a DFS traversal.
172   BitVector Visited;
173 };
174 }  // end anonymous namespace
175
176
177 /// Schedule - Schedule the DAG using list scheduling.
178 void ScheduleDAGRRList::Schedule() {
179   DOUT << "********** List Scheduling **********\n";
180
181   LiveRegDefs.resize(TRI->getNumRegs(), NULL);  
182   LiveRegCycles.resize(TRI->getNumRegs(), 0);
183
184   // Build scheduling units.
185   BuildSchedUnits();
186
187   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
188           SUnits[su].dumpAll(&DAG));
189   if (!Fast) {
190     CalculateDepths();
191     CalculateHeights();
192   }
193   InitDAGTopologicalSorting();
194
195   AvailableQueue->initNodes(SUnits);
196   
197   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
198   if (isBottomUp)
199     ListScheduleBottomUp();
200   else
201     ListScheduleTopDown();
202   
203   AvailableQueue->releaseState();
204
205   if (!Fast)
206     CommuteNodesToReducePressure();
207   
208   DOUT << "*** Final schedule ***\n";
209   DEBUG(dumpSchedule());
210   DOUT << "\n";
211   
212   // Emit in scheduled order
213   EmitSchedule();
214 }
215
216 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
217 /// it is not the last use of its first operand, add it to the CommuteSet if
218 /// possible. It will be commuted when it is translated to a MI.
219 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
220   SmallPtrSet<SUnit*, 4> OperandSeen;
221   for (unsigned i = Sequence.size(); i != 0; ) {
222     --i;
223     SUnit *SU = Sequence[i];
224     if (!SU || !SU->Node) continue;
225     if (SU->isCommutable) {
226       unsigned Opc = SU->Node->getTargetOpcode();
227       const TargetInstrDesc &TID = TII->get(Opc);
228       unsigned NumRes = TID.getNumDefs();
229       unsigned NumOps = TID.getNumOperands() - NumRes;
230       for (unsigned j = 0; j != NumOps; ++j) {
231         if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
232           continue;
233
234         SDNode *OpN = SU->Node->getOperand(j).Val;
235         SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
236         if (OpSU && OperandSeen.count(OpSU) == 1) {
237           // Ok, so SU is not the last use of OpSU, but SU is two-address so
238           // it will clobber OpSU. Try to commute SU if no other source operands
239           // are live below.
240           bool DoCommute = true;
241           for (unsigned k = 0; k < NumOps; ++k) {
242             if (k != j) {
243               OpN = SU->Node->getOperand(k).Val;
244               OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
245               if (OpSU && OperandSeen.count(OpSU) == 1) {
246                 DoCommute = false;
247                 break;
248               }
249             }
250           }
251           if (DoCommute)
252             CommuteSet.insert(SU->Node);
253         }
254
255         // Only look at the first use&def node for now.
256         break;
257       }
258     }
259
260     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
261          I != E; ++I) {
262       if (!I->isCtrl)
263         OperandSeen.insert(I->Dep->OrigNode);
264     }
265   }
266 }
267
268 //===----------------------------------------------------------------------===//
269 //  Bottom-Up Scheduling
270 //===----------------------------------------------------------------------===//
271
272 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
273 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
274 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain, 
275                                     unsigned CurCycle) {
276   // FIXME: the distance between two nodes is not always == the predecessor's
277   // latency. For example, the reader can very well read the register written
278   // by the predecessor later than the issue cycle. It also depends on the
279   // interrupt model (drain vs. freeze).
280   PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
281
282   --PredSU->NumSuccsLeft;
283   
284 #ifndef NDEBUG
285   if (PredSU->NumSuccsLeft < 0) {
286     cerr << "*** List scheduling failed! ***\n";
287     PredSU->dump(&DAG);
288     cerr << " has been released too many times!\n";
289     assert(0);
290   }
291 #endif
292   
293   if (PredSU->NumSuccsLeft == 0) {
294     PredSU->isAvailable = true;
295     AvailableQueue->push(PredSU);
296   }
297 }
298
299 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
300 /// count of its predecessors. If a predecessor pending count is zero, add it to
301 /// the Available queue.
302 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
303   DOUT << "*** Scheduling [" << CurCycle << "]: ";
304   DEBUG(SU->dump(&DAG));
305   SU->Cycle = CurCycle;
306
307   AvailableQueue->ScheduledNode(SU);
308
309   // Bottom up: release predecessors
310   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
311        I != E; ++I) {
312     ReleasePred(I->Dep, I->isCtrl, CurCycle);
313     if (I->Cost < 0)  {
314       // This is a physical register dependency and it's impossible or
315       // expensive to copy the register. Make sure nothing that can 
316       // clobber the register is scheduled between the predecessor and
317       // this node.
318       if (LiveRegs.insert(I->Reg)) {
319         LiveRegDefs[I->Reg] = I->Dep;
320         LiveRegCycles[I->Reg] = CurCycle;
321       }
322     }
323   }
324
325   // Release all the implicit physical register defs that are live.
326   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
327        I != E; ++I) {
328     if (I->Cost < 0)  {
329       if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
330         LiveRegs.erase(I->Reg);
331         assert(LiveRegDefs[I->Reg] == SU &&
332                "Physical register dependency violated?");
333         LiveRegDefs[I->Reg] = NULL;
334         LiveRegCycles[I->Reg] = 0;
335       }
336     }
337   }
338
339   SU->isScheduled = true;
340 }
341
342 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
343 /// unscheduled, incrcease the succ left count of its predecessors. Remove
344 /// them from AvailableQueue if necessary.
345 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {  
346   unsigned CycleBound = 0;
347   for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
348        I != E; ++I) {
349     if (I->Dep == SU)
350       continue;
351     CycleBound = std::max(CycleBound,
352                           I->Dep->Cycle + PredSU->Latency);
353   }
354
355   if (PredSU->isAvailable) {
356     PredSU->isAvailable = false;
357     if (!PredSU->isPending)
358       AvailableQueue->remove(PredSU);
359   }
360
361   PredSU->CycleBound = CycleBound;
362   ++PredSU->NumSuccsLeft;
363 }
364
365 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
366 /// its predecessor states to reflect the change.
367 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
368   DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
369   DEBUG(SU->dump(&DAG));
370
371   AvailableQueue->UnscheduledNode(SU);
372
373   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
374        I != E; ++I) {
375     CapturePred(I->Dep, SU, I->isCtrl);
376     if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg])  {
377       LiveRegs.erase(I->Reg);
378       assert(LiveRegDefs[I->Reg] == I->Dep &&
379              "Physical register dependency violated?");
380       LiveRegDefs[I->Reg] = NULL;
381       LiveRegCycles[I->Reg] = 0;
382     }
383   }
384
385   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
386        I != E; ++I) {
387     if (I->Cost < 0)  {
388       if (LiveRegs.insert(I->Reg)) {
389         assert(!LiveRegDefs[I->Reg] &&
390                "Physical register dependency violated?");
391         LiveRegDefs[I->Reg] = SU;
392       }
393       if (I->Dep->Cycle < LiveRegCycles[I->Reg])
394         LiveRegCycles[I->Reg] = I->Dep->Cycle;
395     }
396   }
397
398   SU->Cycle = 0;
399   SU->isScheduled = false;
400   SU->isAvailable = true;
401   AvailableQueue->push(SU);
402 }
403
404 /// IsReachable - Checks if SU is reachable from TargetSU.
405 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
406   // If insertion of the edge SU->TargetSU would create a cycle
407   // then there is a path from TargetSU to SU.
408   int UpperBound, LowerBound;
409   LowerBound = Node2Index[TargetSU->NodeNum];
410   UpperBound = Node2Index[SU->NodeNum];
411   bool HasLoop = false;
412   // Is Ord(TargetSU) < Ord(SU) ?
413   if (LowerBound < UpperBound) {
414     Visited.reset();
415     // There may be a path from TargetSU to SU. Check for it. 
416     DFS(TargetSU, UpperBound, HasLoop);
417   }
418   return HasLoop;
419 }
420
421 /// Allocate - assign the topological index to the node n.
422 inline void ScheduleDAGRRList::Allocate(int n, int index) {
423   Node2Index[n] = index;
424   Index2Node[index] = n;
425 }
426
427 /// InitDAGTopologicalSorting - create the initial topological 
428 /// ordering from the DAG to be scheduled.
429
430 /// The idea of the algorithm is taken from 
431 /// "Online algorithms for managing the topological order of
432 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
433 /// This is the MNR algorithm, which was first introduced by 
434 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
435 /// "Maintaining a topological order under edge insertions".
436 ///
437 /// Short description of the algorithm: 
438 ///
439 /// Topological ordering, ord, of a DAG maps each node to a topological
440 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
441 ///
442 /// This means that if there is a path from the node X to the node Z, 
443 /// then ord(X) < ord(Z).
444 ///
445 /// This property can be used to check for reachability of nodes:
446 /// if Z is reachable from X, then an insertion of the edge Z->X would 
447 /// create a cycle.
448 ///
449 /// The algorithm first computes a topological ordering for the DAG by
450 /// initializing the Index2Node and Node2Index arrays and then tries to keep
451 /// the ordering up-to-date after edge insertions by reordering the DAG.
452 ///
453 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
454 /// the nodes reachable from Y, and then shifts them using Shift to lie
455 /// immediately after X in Index2Node.
456 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
457   unsigned DAGSize = SUnits.size();
458   std::vector<unsigned> InDegree(DAGSize);
459   std::vector<SUnit*> WorkList;
460   WorkList.reserve(DAGSize);
461   std::vector<SUnit*> TopOrder;
462   TopOrder.reserve(DAGSize);
463
464   // Initialize the data structures.
465   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
466     SUnit *SU = &SUnits[i];
467     int NodeNum = SU->NodeNum;
468     unsigned Degree = SU->Succs.size();
469     InDegree[NodeNum] = Degree;
470
471     // Is it a node without dependencies?
472     if (Degree == 0) {
473         assert(SU->Succs.empty() && "SUnit should have no successors");
474         // Collect leaf nodes.
475         WorkList.push_back(SU);
476     }
477   }  
478
479   while (!WorkList.empty()) {
480     SUnit *SU = WorkList.back();
481     WorkList.pop_back();
482     TopOrder.push_back(SU);
483     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
484          I != E; ++I) {
485       SUnit *SU = I->Dep;
486       if (!--InDegree[SU->NodeNum])
487         // If all dependencies of the node are processed already,
488         // then the node can be computed now.
489         WorkList.push_back(SU);
490     }
491   }
492
493   // Second pass, assign the actual topological order as node ids.
494   int Id = 0;
495
496   Index2Node.clear();
497   Node2Index.clear();
498   Index2Node.resize(DAGSize);
499   Node2Index.resize(DAGSize);
500   Visited.resize(DAGSize);
501
502   for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
503        TE = TopOrder.rend();TI != TE; ++TI) {
504     Allocate((*TI)->NodeNum, Id);
505     Id++;
506   }
507
508 #ifndef NDEBUG
509   // Check correctness of the ordering
510   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
511     SUnit *SU = &SUnits[i];
512     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
513          I != E; ++I) {
514        assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] && 
515        "Wrong topological sorting");
516     }
517   }
518 #endif
519 }
520
521 /// AddPred - adds an edge from SUnit X to SUnit Y.
522 /// Updates the topological ordering if required.
523 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
524                  unsigned PhyReg, int Cost) {
525   int UpperBound, LowerBound;
526   LowerBound = Node2Index[Y->NodeNum];
527   UpperBound = Node2Index[X->NodeNum];
528   bool HasLoop = false;
529   // Is Ord(X) < Ord(Y) ?
530   if (LowerBound < UpperBound) {
531     // Update the topological order.
532     Visited.reset();
533     DFS(Y, UpperBound, HasLoop);
534     assert(!HasLoop && "Inserted edge creates a loop!");
535     // Recompute topological indexes.
536     Shift(Visited, LowerBound, UpperBound);
537   }
538   // Now really insert the edge.
539   return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
540 }
541
542 /// RemovePred - This removes the specified node N from the predecessors of 
543 /// the current node M. Updates the topological ordering if required.
544 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N, 
545                                    bool isCtrl, bool isSpecial) {
546   // InitDAGTopologicalSorting();
547   return M->removePred(N, isCtrl, isSpecial);
548 }
549
550 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
551 /// all nodes affected by the edge insertion. These nodes will later get new
552 /// topological indexes by means of the Shift method.
553 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
554   std::vector<SUnit*> WorkList;
555   WorkList.reserve(SUnits.size()); 
556
557   WorkList.push_back(SU);
558   while (!WorkList.empty()) {
559     SU = WorkList.back();
560     WorkList.pop_back();
561     Visited.set(SU->NodeNum);
562     for (int I = SU->Succs.size()-1; I >= 0; --I) {
563       int s = SU->Succs[I].Dep->NodeNum;
564       if (Node2Index[s] == UpperBound) {
565         HasLoop = true; 
566         return;
567       }
568       // Visit successors if not already and in affected region.
569       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
570         WorkList.push_back(SU->Succs[I].Dep);
571       } 
572     } 
573   }
574 }
575
576 /// Shift - Renumber the nodes so that the topological ordering is 
577 /// preserved.
578 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound, 
579                               int UpperBound) {
580   std::vector<int> L;
581   int shift = 0;
582   int i;
583
584   for (i = LowerBound; i <= UpperBound; ++i) {
585     // w is node at topological index i.
586     int w = Index2Node[i];
587     if (Visited.test(w)) {
588       // Unmark.
589       Visited.reset(w);
590       L.push_back(w);
591       shift = shift + 1;
592     } else {
593       Allocate(w, i - shift);
594     }
595   }
596
597   for (unsigned j = 0; j < L.size(); ++j) {
598     Allocate(L[j], i - shift);
599     i = i + 1;
600   }
601 }
602
603
604 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
605 /// create a cycle.
606 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
607   if (IsReachable(TargetSU, SU))
608     return true;
609   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
610        I != E; ++I)
611     if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
612       return true;
613   return false;
614 }
615
616 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
617 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
618 /// SUnit. Also returns if a successor is unscheduled in the process.
619 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
620                                           unsigned &CurCycle) {
621   SUnit *OldSU = NULL;
622   while (CurCycle > BtCycle) {
623     OldSU = Sequence.back();
624     Sequence.pop_back();
625     if (SU->isSucc(OldSU))
626       // Don't try to remove SU from AvailableQueue.
627       SU->isAvailable = false;
628     UnscheduleNodeBottomUp(OldSU);
629     --CurCycle;
630   }
631
632       
633   if (SU->isSucc(OldSU)) {
634     assert(false && "Something is wrong!");
635     abort();
636   }
637
638   ++NumBacktracks;
639 }
640
641 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
642 /// successors to the newly created node.
643 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
644   if (SU->FlaggedNodes.size())
645     return NULL;
646
647   SDNode *N = SU->Node;
648   if (!N)
649     return NULL;
650
651   SUnit *NewSU;
652   bool TryUnfold = false;
653   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
654     MVT VT = N->getValueType(i);
655     if (VT == MVT::Flag)
656       return NULL;
657     else if (VT == MVT::Other)
658       TryUnfold = true;
659   }
660   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
661     const SDOperand &Op = N->getOperand(i);
662     MVT VT = Op.Val->getValueType(Op.ResNo);
663     if (VT == MVT::Flag)
664       return NULL;
665   }
666
667   if (TryUnfold) {
668     SmallVector<SDNode*, 2> NewNodes;
669     if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
670       return NULL;
671
672     DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
673     assert(NewNodes.size() == 2 && "Expected a load folding node!");
674
675     N = NewNodes[1];
676     SDNode *LoadNode = NewNodes[0];
677     unsigned NumVals = N->getNumValues();
678     unsigned OldNumVals = SU->Node->getNumValues();
679     for (unsigned i = 0; i != NumVals; ++i)
680       DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
681     DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
682                                   SDOperand(LoadNode, 1));
683
684     SUnit *NewSU = CreateNewSUnit(N);
685     assert(N->getNodeId() == -1 && "Node already inserted!");
686     N->setNodeId(NewSU->NodeNum);
687       
688     const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
689     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
690       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
691         NewSU->isTwoAddress = true;
692         break;
693       }
694     }
695     if (TID.isCommutable())
696       NewSU->isCommutable = true;
697     // FIXME: Calculate height / depth and propagate the changes?
698     NewSU->Depth = SU->Depth;
699     NewSU->Height = SU->Height;
700     ComputeLatency(NewSU);
701
702     // LoadNode may already exist. This can happen when there is another
703     // load from the same location and producing the same type of value
704     // but it has different alignment or volatileness.
705     bool isNewLoad = true;
706     SUnit *LoadSU;
707     if (LoadNode->getNodeId() != -1) {
708       LoadSU = &SUnits[LoadNode->getNodeId()];
709       isNewLoad = false;
710     } else {
711       LoadSU = CreateNewSUnit(LoadNode);
712       LoadNode->setNodeId(LoadSU->NodeNum);
713
714       LoadSU->Depth = SU->Depth;
715       LoadSU->Height = SU->Height;
716       ComputeLatency(LoadSU);
717     }
718
719     SUnit *ChainPred = NULL;
720     SmallVector<SDep, 4> ChainSuccs;
721     SmallVector<SDep, 4> LoadPreds;
722     SmallVector<SDep, 4> NodePreds;
723     SmallVector<SDep, 4> NodeSuccs;
724     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
725          I != E; ++I) {
726       if (I->isCtrl)
727         ChainPred = I->Dep;
728       else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
729         LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
730       else
731         NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
732     }
733     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
734          I != E; ++I) {
735       if (I->isCtrl)
736         ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
737                                   I->isCtrl, I->isSpecial));
738       else
739         NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
740                                  I->isCtrl, I->isSpecial));
741     }
742
743     if (ChainPred) {
744       RemovePred(SU, ChainPred, true, false);
745       if (isNewLoad)
746         AddPred(LoadSU, ChainPred, true, false);
747     }
748     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
749       SDep *Pred = &LoadPreds[i];
750       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
751       if (isNewLoad) {
752         AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
753                 Pred->Reg, Pred->Cost);
754       }
755     }
756     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
757       SDep *Pred = &NodePreds[i];
758       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
759       AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
760               Pred->Reg, Pred->Cost);
761     }
762     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
763       SDep *Succ = &NodeSuccs[i];
764       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
765       AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
766               Succ->Reg, Succ->Cost);
767     }
768     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
769       SDep *Succ = &ChainSuccs[i];
770       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
771       if (isNewLoad) {
772         AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
773                 Succ->Reg, Succ->Cost);
774       }
775     } 
776     if (isNewLoad) {
777       AddPred(NewSU, LoadSU, false, false);
778     }
779
780     if (isNewLoad)
781       AvailableQueue->addNode(LoadSU);
782     AvailableQueue->addNode(NewSU);
783
784     ++NumUnfolds;
785
786     if (NewSU->NumSuccsLeft == 0) {
787       NewSU->isAvailable = true;
788       return NewSU;
789     }
790     SU = NewSU;
791   }
792
793   DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
794   NewSU = CreateClone(SU);
795
796   // New SUnit has the exact same predecessors.
797   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
798        I != E; ++I)
799     if (!I->isSpecial) {
800       AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
801       NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
802     }
803
804   // Only copy scheduled successors. Cut them from old node's successor
805   // list and move them over.
806   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
807   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
808        I != E; ++I) {
809     if (I->isSpecial)
810       continue;
811     if (I->Dep->isScheduled) {
812       NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
813       AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
814       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
815     }
816   }
817   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
818     SUnit *Succ = DelDeps[i].first;
819     bool isCtrl = DelDeps[i].second;
820     RemovePred(Succ, SU, isCtrl, false);
821   }
822
823   AvailableQueue->updateNode(SU);
824   AvailableQueue->addNode(NewSU);
825
826   ++NumDups;
827   return NewSU;
828 }
829
830 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
831 /// and move all scheduled successors of the given SUnit to the last copy.
832 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
833                                               const TargetRegisterClass *DestRC,
834                                               const TargetRegisterClass *SrcRC,
835                                                SmallVector<SUnit*, 2> &Copies) {
836   SUnit *CopyFromSU = CreateNewSUnit(NULL);
837   CopyFromSU->CopySrcRC = SrcRC;
838   CopyFromSU->CopyDstRC = DestRC;
839   CopyFromSU->Depth = SU->Depth;
840   CopyFromSU->Height = SU->Height;
841
842   SUnit *CopyToSU = CreateNewSUnit(NULL);
843   CopyToSU->CopySrcRC = DestRC;
844   CopyToSU->CopyDstRC = SrcRC;
845
846   // Only copy scheduled successors. Cut them from old node's successor
847   // list and move them over.
848   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
849   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
850        I != E; ++I) {
851     if (I->isSpecial)
852       continue;
853     if (I->Dep->isScheduled) {
854       CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
855       AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
856       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
857     }
858   }
859   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
860     SUnit *Succ = DelDeps[i].first;
861     bool isCtrl = DelDeps[i].second;
862     RemovePred(Succ, SU, isCtrl, false);
863   }
864
865   AddPred(CopyFromSU, SU, false, false, Reg, -1);
866   AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
867
868   AvailableQueue->updateNode(SU);
869   AvailableQueue->addNode(CopyFromSU);
870   AvailableQueue->addNode(CopyToSU);
871   Copies.push_back(CopyFromSU);
872   Copies.push_back(CopyToSU);
873
874   ++NumCCCopies;
875 }
876
877 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
878 /// definition of the specified node.
879 /// FIXME: Move to SelectionDAG?
880 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
881                                  const TargetInstrInfo *TII) {
882   const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
883   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
884   unsigned NumRes = TID.getNumDefs();
885   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
886     if (Reg == *ImpDef)
887       break;
888     ++NumRes;
889   }
890   return N->getValueType(NumRes);
891 }
892
893 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
894 /// scheduling of the given node to satisfy live physical register dependencies.
895 /// If the specific node is the last one that's available to schedule, do
896 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
897 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
898                                                  SmallVector<unsigned, 4> &LRegs){
899   if (LiveRegs.empty())
900     return false;
901
902   SmallSet<unsigned, 4> RegAdded;
903   // If this node would clobber any "live" register, then it's not ready.
904   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
905        I != E; ++I) {
906     if (I->Cost < 0)  {
907       unsigned Reg = I->Reg;
908       if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
909         if (RegAdded.insert(Reg))
910           LRegs.push_back(Reg);
911       }
912       for (const unsigned *Alias = TRI->getAliasSet(Reg);
913            *Alias; ++Alias)
914         if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
915           if (RegAdded.insert(*Alias))
916             LRegs.push_back(*Alias);
917         }
918     }
919   }
920
921   for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
922     SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
923     if (!Node || !Node->isTargetOpcode())
924       continue;
925     const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
926     if (!TID.ImplicitDefs)
927       continue;
928     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
929       if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
930         if (RegAdded.insert(*Reg))
931           LRegs.push_back(*Reg);
932       }
933       for (const unsigned *Alias = TRI->getAliasSet(*Reg);
934            *Alias; ++Alias)
935         if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
936           if (RegAdded.insert(*Alias))
937             LRegs.push_back(*Alias);
938         }
939     }
940   }
941   return !LRegs.empty();
942 }
943
944
945 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
946 /// schedulers.
947 void ScheduleDAGRRList::ListScheduleBottomUp() {
948   unsigned CurCycle = 0;
949   // Add root to Available queue.
950   if (!SUnits.empty()) {
951     SUnit *RootSU = &SUnits[DAG.getRoot().Val->getNodeId()];
952     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
953     RootSU->isAvailable = true;
954     AvailableQueue->push(RootSU);
955   }
956
957   // While Available queue is not empty, grab the node with the highest
958   // priority. If it is not ready put it back.  Schedule the node.
959   SmallVector<SUnit*, 4> NotReady;
960   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
961   Sequence.reserve(SUnits.size());
962   while (!AvailableQueue->empty()) {
963     bool Delayed = false;
964     LRegsMap.clear();
965     SUnit *CurSU = AvailableQueue->pop();
966     while (CurSU) {
967       if (CurSU->CycleBound <= CurCycle) {
968         SmallVector<unsigned, 4> LRegs;
969         if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
970           break;
971         Delayed = true;
972         LRegsMap.insert(std::make_pair(CurSU, LRegs));
973       }
974
975       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
976       NotReady.push_back(CurSU);
977       CurSU = AvailableQueue->pop();
978     }
979
980     // All candidates are delayed due to live physical reg dependencies.
981     // Try backtracking, code duplication, or inserting cross class copies
982     // to resolve it.
983     if (Delayed && !CurSU) {
984       for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
985         SUnit *TrySU = NotReady[i];
986         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
987
988         // Try unscheduling up to the point where it's safe to schedule
989         // this node.
990         unsigned LiveCycle = CurCycle;
991         for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
992           unsigned Reg = LRegs[j];
993           unsigned LCycle = LiveRegCycles[Reg];
994           LiveCycle = std::min(LiveCycle, LCycle);
995         }
996         SUnit *OldSU = Sequence[LiveCycle];
997         if (!WillCreateCycle(TrySU, OldSU))  {
998           BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
999           // Force the current node to be scheduled before the node that
1000           // requires the physical reg dep.
1001           if (OldSU->isAvailable) {
1002             OldSU->isAvailable = false;
1003             AvailableQueue->remove(OldSU);
1004           }
1005           AddPred(TrySU, OldSU, true, true);
1006           // If one or more successors has been unscheduled, then the current
1007           // node is no longer avaialable. Schedule a successor that's now
1008           // available instead.
1009           if (!TrySU->isAvailable)
1010             CurSU = AvailableQueue->pop();
1011           else {
1012             CurSU = TrySU;
1013             TrySU->isPending = false;
1014             NotReady.erase(NotReady.begin()+i);
1015           }
1016           break;
1017         }
1018       }
1019
1020       if (!CurSU) {
1021         // Can't backtrack. Try duplicating the nodes that produces these
1022         // "expensive to copy" values to break the dependency. In case even
1023         // that doesn't work, insert cross class copies.
1024         SUnit *TrySU = NotReady[0];
1025         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1026         assert(LRegs.size() == 1 && "Can't handle this yet!");
1027         unsigned Reg = LRegs[0];
1028         SUnit *LRDef = LiveRegDefs[Reg];
1029         SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1030         if (!NewDef) {
1031           // Issue expensive cross register class copies.
1032           MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1033           const TargetRegisterClass *RC =
1034             TRI->getPhysicalRegisterRegClass(Reg, VT);
1035           const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1036           if (!DestRC) {
1037             assert(false && "Don't know how to copy this physical register!");
1038             abort();
1039           }
1040           SmallVector<SUnit*, 2> Copies;
1041           InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1042           DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1043                << " to SU #" << Copies.front()->NodeNum << "\n";
1044           AddPred(TrySU, Copies.front(), true, true);
1045           NewDef = Copies.back();
1046         }
1047
1048         DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1049              << " to SU #" << TrySU->NodeNum << "\n";
1050         LiveRegDefs[Reg] = NewDef;
1051         AddPred(NewDef, TrySU, true, true);
1052         TrySU->isAvailable = false;
1053         CurSU = NewDef;
1054       }
1055
1056       if (!CurSU) {
1057         assert(false && "Unable to resolve live physical register dependencies!");
1058         abort();
1059       }
1060     }
1061
1062     // Add the nodes that aren't ready back onto the available list.
1063     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1064       NotReady[i]->isPending = false;
1065       // May no longer be available due to backtracking.
1066       if (NotReady[i]->isAvailable)
1067         AvailableQueue->push(NotReady[i]);
1068     }
1069     NotReady.clear();
1070
1071     if (!CurSU)
1072       Sequence.push_back(0);
1073     else {
1074       ScheduleNodeBottomUp(CurSU, CurCycle);
1075       Sequence.push_back(CurSU);
1076     }
1077     ++CurCycle;
1078   }
1079
1080   // Reverse the order if it is bottom up.
1081   std::reverse(Sequence.begin(), Sequence.end());
1082   
1083   
1084 #ifndef NDEBUG
1085   // Verify that all SUnits were scheduled.
1086   bool AnyNotSched = false;
1087   unsigned DeadNodes = 0;
1088   unsigned Noops = 0;
1089   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1090     if (!SUnits[i].isScheduled) {
1091       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1092         ++DeadNodes;
1093         continue;
1094       }
1095       if (!AnyNotSched)
1096         cerr << "*** List scheduling failed! ***\n";
1097       SUnits[i].dump(&DAG);
1098       cerr << "has not been scheduled!\n";
1099       AnyNotSched = true;
1100     }
1101     if (SUnits[i].NumSuccsLeft != 0) {
1102       if (!AnyNotSched)
1103         cerr << "*** List scheduling failed! ***\n";
1104       SUnits[i].dump(&DAG);
1105       cerr << "has successors left!\n";
1106       AnyNotSched = true;
1107     }
1108   }
1109   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1110     if (!Sequence[i])
1111       ++Noops;
1112   assert(!AnyNotSched);
1113   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1114          "The number of nodes scheduled doesn't match the expected number!");
1115 #endif
1116 }
1117
1118 //===----------------------------------------------------------------------===//
1119 //  Top-Down Scheduling
1120 //===----------------------------------------------------------------------===//
1121
1122 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1123 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1124 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain, 
1125                                     unsigned CurCycle) {
1126   // FIXME: the distance between two nodes is not always == the predecessor's
1127   // latency. For example, the reader can very well read the register written
1128   // by the predecessor later than the issue cycle. It also depends on the
1129   // interrupt model (drain vs. freeze).
1130   SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1131
1132   --SuccSU->NumPredsLeft;
1133   
1134 #ifndef NDEBUG
1135   if (SuccSU->NumPredsLeft < 0) {
1136     cerr << "*** List scheduling failed! ***\n";
1137     SuccSU->dump(&DAG);
1138     cerr << " has been released too many times!\n";
1139     assert(0);
1140   }
1141 #endif
1142   
1143   if (SuccSU->NumPredsLeft == 0) {
1144     SuccSU->isAvailable = true;
1145     AvailableQueue->push(SuccSU);
1146   }
1147 }
1148
1149
1150 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1151 /// count of its successors. If a successor pending count is zero, add it to
1152 /// the Available queue.
1153 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1154   DOUT << "*** Scheduling [" << CurCycle << "]: ";
1155   DEBUG(SU->dump(&DAG));
1156   SU->Cycle = CurCycle;
1157
1158   AvailableQueue->ScheduledNode(SU);
1159
1160   // Top down: release successors
1161   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1162        I != E; ++I)
1163     ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1164   SU->isScheduled = true;
1165 }
1166
1167 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1168 /// schedulers.
1169 void ScheduleDAGRRList::ListScheduleTopDown() {
1170   unsigned CurCycle = 0;
1171
1172   // All leaves to Available queue.
1173   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1174     // It is available if it has no predecessors.
1175     if (SUnits[i].Preds.empty()) {
1176       AvailableQueue->push(&SUnits[i]);
1177       SUnits[i].isAvailable = true;
1178     }
1179   }
1180   
1181   // While Available queue is not empty, grab the node with the highest
1182   // priority. If it is not ready put it back.  Schedule the node.
1183   std::vector<SUnit*> NotReady;
1184   Sequence.reserve(SUnits.size());
1185   while (!AvailableQueue->empty()) {
1186     SUnit *CurSU = AvailableQueue->pop();
1187     while (CurSU && CurSU->CycleBound > CurCycle) {
1188       NotReady.push_back(CurSU);
1189       CurSU = AvailableQueue->pop();
1190     }
1191     
1192     // Add the nodes that aren't ready back onto the available list.
1193     AvailableQueue->push_all(NotReady);
1194     NotReady.clear();
1195
1196     if (!CurSU)
1197       Sequence.push_back(0);
1198     else {
1199       ScheduleNodeTopDown(CurSU, CurCycle);
1200       Sequence.push_back(CurSU);
1201     }
1202     ++CurCycle;
1203   }
1204   
1205   
1206 #ifndef NDEBUG
1207   // Verify that all SUnits were scheduled.
1208   bool AnyNotSched = false;
1209   unsigned DeadNodes = 0;
1210   unsigned Noops = 0;
1211   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1212     if (!SUnits[i].isScheduled) {
1213       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1214         ++DeadNodes;
1215         continue;
1216       }
1217       if (!AnyNotSched)
1218         cerr << "*** List scheduling failed! ***\n";
1219       SUnits[i].dump(&DAG);
1220       cerr << "has not been scheduled!\n";
1221       AnyNotSched = true;
1222     }
1223     if (SUnits[i].NumPredsLeft != 0) {
1224       if (!AnyNotSched)
1225         cerr << "*** List scheduling failed! ***\n";
1226       SUnits[i].dump(&DAG);
1227       cerr << "has predecessors left!\n";
1228       AnyNotSched = true;
1229     }
1230   }
1231   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1232     if (!Sequence[i])
1233       ++Noops;
1234   assert(!AnyNotSched);
1235   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
1236          "The number of nodes scheduled doesn't match the expected number!");
1237 #endif
1238 }
1239
1240
1241
1242 //===----------------------------------------------------------------------===//
1243 //                RegReductionPriorityQueue Implementation
1244 //===----------------------------------------------------------------------===//
1245 //
1246 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1247 // to reduce register pressure.
1248 // 
1249 namespace {
1250   template<class SF>
1251   class RegReductionPriorityQueue;
1252   
1253   /// Sorting functions for the Available queue.
1254   struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1255     RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1256     bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1257     bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1258     
1259     bool operator()(const SUnit* left, const SUnit* right) const;
1260   };
1261
1262   struct bu_ls_rr_fast_sort : public std::binary_function<SUnit*, SUnit*, bool>{
1263     RegReductionPriorityQueue<bu_ls_rr_fast_sort> *SPQ;
1264     bu_ls_rr_fast_sort(RegReductionPriorityQueue<bu_ls_rr_fast_sort> *spq)
1265       : SPQ(spq) {}
1266     bu_ls_rr_fast_sort(const bu_ls_rr_fast_sort &RHS) : SPQ(RHS.SPQ) {}
1267     
1268     bool operator()(const SUnit* left, const SUnit* right) const;
1269   };
1270
1271   struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1272     RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1273     td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1274     td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1275     
1276     bool operator()(const SUnit* left, const SUnit* right) const;
1277   };
1278 }  // end anonymous namespace
1279
1280 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1281   SDNode *N = SU->Node;
1282   return N && N->getOpcode() == ISD::CopyFromReg &&
1283     N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1284 }
1285
1286 /// CalcNodeBUSethiUllmanNumber - Compute Sethi Ullman number for bottom up
1287 /// scheduling. Smaller number is the higher priority.
1288 static unsigned
1289 CalcNodeBUSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1290   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1291   if (SethiUllmanNumber != 0)
1292     return SethiUllmanNumber;
1293
1294   unsigned Extra = 0;
1295   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1296        I != E; ++I) {
1297     if (I->isCtrl) continue;  // ignore chain preds
1298     SUnit *PredSU = I->Dep;
1299     unsigned PredSethiUllman = CalcNodeBUSethiUllmanNumber(PredSU, SUNumbers);
1300     if (PredSethiUllman > SethiUllmanNumber) {
1301       SethiUllmanNumber = PredSethiUllman;
1302       Extra = 0;
1303     } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1304       ++Extra;
1305   }
1306
1307   SethiUllmanNumber += Extra;
1308
1309   if (SethiUllmanNumber == 0)
1310     SethiUllmanNumber = 1;
1311   
1312   return SethiUllmanNumber;
1313 }
1314
1315 /// CalcNodeTDSethiUllmanNumber - Compute Sethi Ullman number for top down
1316 /// scheduling. Smaller number is the higher priority.
1317 static unsigned
1318 CalcNodeTDSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1319   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1320   if (SethiUllmanNumber != 0)
1321     return SethiUllmanNumber;
1322
1323   unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1324   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1325     SethiUllmanNumber = 0xffff;
1326   else if (SU->NumSuccsLeft == 0)
1327     // If SU does not have a use, i.e. it doesn't produce a value that would
1328     // be consumed (e.g. store), then it terminates a chain of computation.
1329     // Give it a small SethiUllman number so it will be scheduled right before
1330     // its predecessors that it doesn't lengthen their live ranges.
1331     SethiUllmanNumber = 0;
1332   else if (SU->NumPredsLeft == 0 &&
1333            (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1334     SethiUllmanNumber = 0xffff;
1335   else {
1336     int Extra = 0;
1337     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1338          I != E; ++I) {
1339       if (I->isCtrl) continue;  // ignore chain preds
1340       SUnit *PredSU = I->Dep;
1341       unsigned PredSethiUllman = CalcNodeTDSethiUllmanNumber(PredSU, SUNumbers);
1342       if (PredSethiUllman > SethiUllmanNumber) {
1343         SethiUllmanNumber = PredSethiUllman;
1344         Extra = 0;
1345       } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1346         ++Extra;
1347     }
1348
1349     SethiUllmanNumber += Extra;
1350   }
1351   
1352   return SethiUllmanNumber;
1353 }
1354
1355
1356 namespace {
1357   template<class SF>
1358   class VISIBILITY_HIDDEN RegReductionPriorityQueue
1359    : public SchedulingPriorityQueue {
1360     PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1361     unsigned currentQueueId;
1362
1363   public:
1364     RegReductionPriorityQueue() :
1365     Queue(SF(this)), currentQueueId(0) {}
1366     
1367     virtual void initNodes(std::vector<SUnit> &sunits) {}
1368
1369     virtual void addNode(const SUnit *SU) {}
1370
1371     virtual void updateNode(const SUnit *SU) {}
1372
1373     virtual void releaseState() {}
1374     
1375     virtual unsigned getNodePriority(const SUnit *SU) const {
1376       return 0;
1377     }
1378     
1379     unsigned size() const { return Queue.size(); }
1380
1381     bool empty() const { return Queue.empty(); }
1382     
1383     void push(SUnit *U) {
1384       assert(!U->NodeQueueId && "Node in the queue already");
1385       U->NodeQueueId = ++currentQueueId;
1386       Queue.push(U);
1387     }
1388
1389     void push_all(const std::vector<SUnit *> &Nodes) {
1390       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1391         push(Nodes[i]);
1392     }
1393     
1394     SUnit *pop() {
1395       if (empty()) return NULL;
1396       SUnit *V = Queue.top();
1397       Queue.pop();
1398       V->NodeQueueId = 0;
1399       return V;
1400     }
1401
1402     void remove(SUnit *SU) {
1403       assert(!Queue.empty() && "Queue is empty!");
1404       assert(SU->NodeQueueId != 0 && "Not in queue!");
1405       Queue.erase_one(SU);
1406       SU->NodeQueueId = 0;
1407     }
1408   };
1409
1410   class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1411    : public RegReductionPriorityQueue<bu_ls_rr_sort> {
1412     // SUnits - The SUnits for the current graph.
1413     const std::vector<SUnit> *SUnits;
1414     
1415     // SethiUllmanNumbers - The SethiUllman number for each node.
1416     std::vector<unsigned> SethiUllmanNumbers;
1417
1418     const TargetInstrInfo *TII;
1419     const TargetRegisterInfo *TRI;
1420     ScheduleDAGRRList *scheduleDAG;
1421
1422   public:
1423     explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1424                                          const TargetRegisterInfo *tri)
1425       : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1426
1427     void initNodes(std::vector<SUnit> &sunits) {
1428       SUnits = &sunits;
1429       // Add pseudo dependency edges for two-address nodes.
1430       AddPseudoTwoAddrDeps();
1431       // Calculate node priorities.
1432       CalculateSethiUllmanNumbers();
1433     }
1434
1435     void addNode(const SUnit *SU) {
1436       unsigned SUSize = SethiUllmanNumbers.size();
1437       if (SUnits->size() > SUSize)
1438         SethiUllmanNumbers.resize(SUSize*2, 0);
1439       CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1440     }
1441
1442     void updateNode(const SUnit *SU) {
1443       SethiUllmanNumbers[SU->NodeNum] = 0;
1444       CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1445     }
1446
1447     void releaseState() {
1448       SUnits = 0;
1449       SethiUllmanNumbers.clear();
1450     }
1451
1452     unsigned getNodePriority(const SUnit *SU) const {
1453       assert(SU->NodeNum < SethiUllmanNumbers.size());
1454       unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1455       if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1456         // CopyFromReg should be close to its def because it restricts
1457         // allocation choices. But if it is a livein then perhaps we want it
1458         // closer to its uses so it can be coalesced.
1459         return 0xffff;
1460       else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1461         // CopyToReg should be close to its uses to facilitate coalescing and
1462         // avoid spilling.
1463         return 0;
1464       else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1465                Opc == TargetInstrInfo::INSERT_SUBREG)
1466         // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1467         // facilitate coalescing.
1468         return 0;
1469       else if (SU->NumSuccs == 0)
1470         // If SU does not have a use, i.e. it doesn't produce a value that would
1471         // be consumed (e.g. store), then it terminates a chain of computation.
1472         // Give it a large SethiUllman number so it will be scheduled right
1473         // before its predecessors that it doesn't lengthen their live ranges.
1474         return 0xffff;
1475       else if (SU->NumPreds == 0)
1476         // If SU does not have a def, schedule it close to its uses because it
1477         // does not lengthen any live ranges.
1478         return 0;
1479       else
1480         return SethiUllmanNumbers[SU->NodeNum];
1481     }
1482
1483     void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 
1484       scheduleDAG = scheduleDag; 
1485     }
1486
1487   private:
1488     bool canClobber(const SUnit *SU, const SUnit *Op);
1489     void AddPseudoTwoAddrDeps();
1490     void CalculateSethiUllmanNumbers();
1491   };
1492
1493
1494   class VISIBILITY_HIDDEN BURegReductionFastPriorityQueue
1495    : public RegReductionPriorityQueue<bu_ls_rr_fast_sort> {
1496     // SUnits - The SUnits for the current graph.
1497     const std::vector<SUnit> *SUnits;
1498     
1499     // SethiUllmanNumbers - The SethiUllman number for each node.
1500     std::vector<unsigned> SethiUllmanNumbers;
1501   public:
1502     explicit BURegReductionFastPriorityQueue() {}
1503
1504     void initNodes(std::vector<SUnit> &sunits) {
1505       SUnits = &sunits;
1506       // Calculate node priorities.
1507       CalculateSethiUllmanNumbers();
1508     }
1509
1510     void addNode(const SUnit *SU) {
1511       unsigned SUSize = SethiUllmanNumbers.size();
1512       if (SUnits->size() > SUSize)
1513         SethiUllmanNumbers.resize(SUSize*2, 0);
1514       CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1515     }
1516
1517     void updateNode(const SUnit *SU) {
1518       SethiUllmanNumbers[SU->NodeNum] = 0;
1519       CalcNodeBUSethiUllmanNumber(SU, SethiUllmanNumbers);
1520     }
1521
1522     void releaseState() {
1523       SUnits = 0;
1524       SethiUllmanNumbers.clear();
1525     }
1526
1527     unsigned getNodePriority(const SUnit *SU) const {
1528       return SethiUllmanNumbers[SU->NodeNum];
1529     }
1530
1531   private:
1532     void CalculateSethiUllmanNumbers();
1533   };
1534
1535
1536   class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1537    : public RegReductionPriorityQueue<td_ls_rr_sort> {
1538     // SUnits - The SUnits for the current graph.
1539     const std::vector<SUnit> *SUnits;
1540     
1541     // SethiUllmanNumbers - The SethiUllman number for each node.
1542     std::vector<unsigned> SethiUllmanNumbers;
1543
1544   public:
1545     TDRegReductionPriorityQueue() {}
1546
1547     void initNodes(std::vector<SUnit> &sunits) {
1548       SUnits = &sunits;
1549       // Calculate node priorities.
1550       CalculateSethiUllmanNumbers();
1551     }
1552
1553     void addNode(const SUnit *SU) {
1554       unsigned SUSize = SethiUllmanNumbers.size();
1555       if (SUnits->size() > SUSize)
1556         SethiUllmanNumbers.resize(SUSize*2, 0);
1557       CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1558     }
1559
1560     void updateNode(const SUnit *SU) {
1561       SethiUllmanNumbers[SU->NodeNum] = 0;
1562       CalcNodeTDSethiUllmanNumber(SU, SethiUllmanNumbers);
1563     }
1564
1565     void releaseState() {
1566       SUnits = 0;
1567       SethiUllmanNumbers.clear();
1568     }
1569
1570     unsigned getNodePriority(const SUnit *SU) const {
1571       assert(SU->NodeNum < SethiUllmanNumbers.size());
1572       return SethiUllmanNumbers[SU->NodeNum];
1573     }
1574
1575   private:
1576     void CalculateSethiUllmanNumbers();
1577   };
1578 }
1579
1580 /// closestSucc - Returns the scheduled cycle of the successor which is
1581 /// closet to the current cycle.
1582 static unsigned closestSucc(const SUnit *SU) {
1583   unsigned MaxCycle = 0;
1584   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1585        I != E; ++I) {
1586     unsigned Cycle = I->Dep->Cycle;
1587     // If there are bunch of CopyToRegs stacked up, they should be considered
1588     // to be at the same position.
1589     if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1590       Cycle = closestSucc(I->Dep)+1;
1591     if (Cycle > MaxCycle)
1592       MaxCycle = Cycle;
1593   }
1594   return MaxCycle;
1595 }
1596
1597 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1598 /// for scratch registers. Live-in operands and live-out results don't count
1599 /// since they are "fixed".
1600 static unsigned calcMaxScratches(const SUnit *SU) {
1601   unsigned Scratches = 0;
1602   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1603        I != E; ++I) {
1604     if (I->isCtrl) continue;  // ignore chain preds
1605     if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1606       Scratches++;
1607   }
1608   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1609        I != E; ++I) {
1610     if (I->isCtrl) continue;  // ignore chain succs
1611     if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1612       Scratches += 10;
1613   }
1614   return Scratches;
1615 }
1616
1617 // Bottom up
1618 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1619   unsigned LPriority = SPQ->getNodePriority(left);
1620   unsigned RPriority = SPQ->getNodePriority(right);
1621   if (LPriority != RPriority)
1622     return LPriority > RPriority;
1623
1624   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1625   // e.g.
1626   // t1 = op t2, c1
1627   // t3 = op t4, c2
1628   //
1629   // and the following instructions are both ready.
1630   // t2 = op c3
1631   // t4 = op c4
1632   //
1633   // Then schedule t2 = op first.
1634   // i.e.
1635   // t4 = op c4
1636   // t2 = op c3
1637   // t1 = op t2, c1
1638   // t3 = op t4, c2
1639   //
1640   // This creates more short live intervals.
1641   unsigned LDist = closestSucc(left);
1642   unsigned RDist = closestSucc(right);
1643   if (LDist != RDist)
1644     return LDist < RDist;
1645
1646   // Intuitively, it's good to push down instructions whose results are
1647   // liveout so their long live ranges won't conflict with other values
1648   // which are needed inside the BB. Further prioritize liveout instructions
1649   // by the number of operands which are calculated within the BB.
1650   unsigned LScratch = calcMaxScratches(left);
1651   unsigned RScratch = calcMaxScratches(right);
1652   if (LScratch != RScratch)
1653     return LScratch > RScratch;
1654
1655   if (left->Height != right->Height)
1656     return left->Height > right->Height;
1657   
1658   if (left->Depth != right->Depth)
1659     return left->Depth < right->Depth;
1660
1661   if (left->CycleBound != right->CycleBound)
1662     return left->CycleBound > right->CycleBound;
1663
1664   assert(left->NodeQueueId && right->NodeQueueId && 
1665          "NodeQueueId cannot be zero");
1666   return (left->NodeQueueId > right->NodeQueueId);
1667 }
1668
1669 bool
1670 bu_ls_rr_fast_sort::operator()(const SUnit *left, const SUnit *right) const {
1671   unsigned LPriority = SPQ->getNodePriority(left);
1672   unsigned RPriority = SPQ->getNodePriority(right);
1673   if (LPriority != RPriority)
1674     return LPriority > RPriority;
1675   assert(left->NodeQueueId && right->NodeQueueId && 
1676          "NodeQueueId cannot be zero");
1677   return (left->NodeQueueId > right->NodeQueueId);
1678 }
1679
1680 bool
1681 BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
1682   if (SU->isTwoAddress) {
1683     unsigned Opc = SU->Node->getTargetOpcode();
1684     const TargetInstrDesc &TID = TII->get(Opc);
1685     unsigned NumRes = TID.getNumDefs();
1686     unsigned NumOps = TID.getNumOperands() - NumRes;
1687     for (unsigned i = 0; i != NumOps; ++i) {
1688       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1689         SDNode *DU = SU->Node->getOperand(i).Val;
1690         if (DU->getNodeId() != -1 &&
1691             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1692           return true;
1693       }
1694     }
1695   }
1696   return false;
1697 }
1698
1699
1700 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1701 /// CopyToReg node.
1702 static bool hasCopyToRegUse(SUnit *SU) {
1703   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1704        I != E; ++I) {
1705     if (I->isCtrl) continue;
1706     SUnit *SuccSU = I->Dep;
1707     if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1708       return true;
1709   }
1710   return false;
1711 }
1712
1713 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1714 /// physical register defs.
1715 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1716                                   const TargetInstrInfo *TII,
1717                                   const TargetRegisterInfo *TRI) {
1718   SDNode *N = SuccSU->Node;
1719   unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1720   const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1721   assert(ImpDefs && "Caller should check hasPhysRegDefs");
1722   const unsigned *SUImpDefs =
1723     TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1724   if (!SUImpDefs)
1725     return false;
1726   for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1727     MVT VT = N->getValueType(i);
1728     if (VT == MVT::Flag || VT == MVT::Other)
1729       continue;
1730     unsigned Reg = ImpDefs[i - NumDefs];
1731     for (;*SUImpDefs; ++SUImpDefs) {
1732       unsigned SUReg = *SUImpDefs;
1733       if (TRI->regsOverlap(Reg, SUReg))
1734         return true;
1735     }
1736   }
1737   return false;
1738 }
1739
1740 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1741 /// it as a def&use operand. Add a pseudo control edge from it to the other
1742 /// node (if it won't create a cycle) so the two-address one will be scheduled
1743 /// first (lower in the schedule). If both nodes are two-address, favor the
1744 /// one that has a CopyToReg use (more likely to be a loop induction update).
1745 /// If both are two-address, but one is commutable while the other is not
1746 /// commutable, favor the one that's not commutable.
1747 void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
1748   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1749     SUnit *SU = (SUnit *)&((*SUnits)[i]);
1750     if (!SU->isTwoAddress)
1751       continue;
1752
1753     SDNode *Node = SU->Node;
1754     if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1755       continue;
1756
1757     unsigned Opc = Node->getTargetOpcode();
1758     const TargetInstrDesc &TID = TII->get(Opc);
1759     unsigned NumRes = TID.getNumDefs();
1760     unsigned NumOps = TID.getNumOperands() - NumRes;
1761     for (unsigned j = 0; j != NumOps; ++j) {
1762       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1763         SDNode *DU = SU->Node->getOperand(j).Val;
1764         if (DU->getNodeId() == -1)
1765           continue;
1766         const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1767         if (!DUSU) continue;
1768         for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1769              E = DUSU->Succs.end(); I != E; ++I) {
1770           if (I->isCtrl) continue;
1771           SUnit *SuccSU = I->Dep;
1772           if (SuccSU == SU)
1773             continue;
1774           // Be conservative. Ignore if nodes aren't at roughly the same
1775           // depth and height.
1776           if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1777             continue;
1778           if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1779             continue;
1780           // Don't constrain nodes with physical register defs if the
1781           // predecessor can clobber them.
1782           if (SuccSU->hasPhysRegDefs) {
1783             if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1784               continue;
1785           }
1786           // Don't constraint extract_subreg / insert_subreg these may be
1787           // coalesced away. We don't them close to their uses.
1788           unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1789           if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1790               SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1791             continue;
1792           if ((!canClobber(SuccSU, DUSU) ||
1793                (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1794                (!SU->isCommutable && SuccSU->isCommutable)) &&
1795               !scheduleDAG->IsReachable(SuccSU, SU)) {
1796             DOUT << "Adding an edge from SU # " << SU->NodeNum
1797                  << " to SU #" << SuccSU->NodeNum << "\n";
1798             scheduleDAG->AddPred(SU, SuccSU, true, true);
1799           }
1800         }
1801       }
1802     }
1803   }
1804 }
1805
1806 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1807 /// scheduling units.
1808 void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1809   SethiUllmanNumbers.assign(SUnits->size(), 0);
1810   
1811   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1812     CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1813 }
1814 void BURegReductionFastPriorityQueue::CalculateSethiUllmanNumbers() {
1815   SethiUllmanNumbers.assign(SUnits->size(), 0);
1816   
1817   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1818     CalcNodeBUSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1819 }
1820
1821 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1822 /// predecessors of the successors of the SUnit SU. Stop when the provided
1823 /// limit is exceeded.
1824 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU, 
1825                                                     unsigned Limit) {
1826   unsigned Sum = 0;
1827   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1828        I != E; ++I) {
1829     SUnit *SuccSU = I->Dep;
1830     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1831          EE = SuccSU->Preds.end(); II != EE; ++II) {
1832       SUnit *PredSU = II->Dep;
1833       if (!PredSU->isScheduled)
1834         if (++Sum > Limit)
1835           return Sum;
1836     }
1837   }
1838   return Sum;
1839 }
1840
1841
1842 // Top down
1843 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1844   unsigned LPriority = SPQ->getNodePriority(left);
1845   unsigned RPriority = SPQ->getNodePriority(right);
1846   bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1847   bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1848   bool LIsFloater = LIsTarget && left->NumPreds == 0;
1849   bool RIsFloater = RIsTarget && right->NumPreds == 0;
1850   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1851   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1852
1853   if (left->NumSuccs == 0 && right->NumSuccs != 0)
1854     return false;
1855   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1856     return true;
1857
1858   if (LIsFloater)
1859     LBonus -= 2;
1860   if (RIsFloater)
1861     RBonus -= 2;
1862   if (left->NumSuccs == 1)
1863     LBonus += 2;
1864   if (right->NumSuccs == 1)
1865     RBonus += 2;
1866
1867   if (LPriority+LBonus != RPriority+RBonus)
1868     return LPriority+LBonus < RPriority+RBonus;
1869
1870   if (left->Depth != right->Depth)
1871     return left->Depth < right->Depth;
1872
1873   if (left->NumSuccsLeft != right->NumSuccsLeft)
1874     return left->NumSuccsLeft > right->NumSuccsLeft;
1875
1876   if (left->CycleBound != right->CycleBound)
1877     return left->CycleBound > right->CycleBound;
1878
1879   assert(left->NodeQueueId && right->NodeQueueId && 
1880          "NodeQueueId cannot be zero");
1881   return (left->NodeQueueId > right->NodeQueueId);
1882 }
1883
1884 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1885 /// scheduling units.
1886 void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
1887   SethiUllmanNumbers.assign(SUnits->size(), 0);
1888   
1889   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1890     CalcNodeTDSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1891 }
1892
1893 //===----------------------------------------------------------------------===//
1894 //                         Public Constructor Functions
1895 //===----------------------------------------------------------------------===//
1896
1897 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1898                                                     SelectionDAG *DAG,
1899                                                     MachineBasicBlock *BB,
1900                                                     bool Fast) {
1901   if (Fast)
1902     return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, true,
1903                                  new BURegReductionFastPriorityQueue());
1904
1905   const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1906   const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1907   
1908   BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1909
1910   ScheduleDAGRRList *SD =
1911     new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(),true,false, PQ);
1912   PQ->setScheduleDAG(SD);
1913   return SD;  
1914 }
1915
1916 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1917                                                     SelectionDAG *DAG,
1918                                                     MachineBasicBlock *BB,
1919                                                     bool Fast) {
1920   return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false, Fast,
1921                                new TDRegReductionPriorityQueue());
1922 }