02cc2855d0e67dde5b2dc0728bccbc3afbad44bb
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGRRList.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/ScheduleDAGSDNodes.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 ScheduleDAGSDNodes {
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   /// AvailableQueue - The priority queue to use for the available SUnits.
63   SchedulingPriorityQueue *AvailableQueue;
64
65   /// LiveRegDefs - A set of physical registers and their definition
66   /// that are "live". These nodes must be scheduled before any other nodes that
67   /// modifies the registers can be scheduled.
68   unsigned NumLiveRegs;
69   std::vector<SUnit*> LiveRegDefs;
70   std::vector<unsigned> LiveRegCycles;
71
72   /// Topo - A topological ordering for SUnits which permits fast IsReachable
73   /// and similar queries.
74   ScheduleDAGTopologicalSort Topo;
75
76 public:
77   ScheduleDAGRRList(SelectionDAG *dag, MachineBasicBlock *bb,
78                     const TargetMachine &tm, bool isbottomup,
79                     SchedulingPriorityQueue *availqueue)
80     : ScheduleDAGSDNodes(dag, bb, tm), isBottomUp(isbottomup),
81       AvailableQueue(availqueue), Topo(SUnits) {
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(const SUnit *SU, const SUnit *TargetSU) {
92     return Topo.IsReachable(SU, TargetSU);
93   }
94
95   /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
96   /// create a cycle.
97   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
98     return Topo.WillCreateCycle(SU, TargetSU);
99   }
100
101   /// AddPred - This adds the specified node X as a predecessor of 
102   /// the current node Y if not already.
103   /// This returns true if this is a new predecessor.
104   /// Updates the topological ordering if required.
105   bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isArtificial,
106                unsigned PhyReg = 0, int Cost = 1) {
107     Topo.AddPred(Y, X);
108     return Y->addPred(X, isCtrl, isArtificial, PhyReg, Cost);
109   }
110
111   /// RemovePred - This removes the specified node N from the predecessors of 
112   /// the current node M. Updates the topological ordering if required.
113   bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isArtificial) {
114     Topo.RemovePred(M, N);
115     return M->removePred(N, isCtrl, isArtificial, false);
116   }
117
118 private:
119   void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
120   void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
121   void CapturePred(SUnit*, SUnit*, bool);
122   void ScheduleNodeBottomUp(SUnit*, unsigned);
123   void ScheduleNodeTopDown(SUnit*, unsigned);
124   void UnscheduleNodeBottomUp(SUnit*);
125   void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
126   SUnit *CopyAndMoveSuccessors(SUnit*);
127   void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
128                                   const TargetRegisterClass*,
129                                   const TargetRegisterClass*,
130                                   SmallVector<SUnit*, 2>&);
131   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
132   void ListScheduleTopDown();
133   void ListScheduleBottomUp();
134   void CommuteNodesToReducePressure();
135
136
137   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
138   /// Updates the topological ordering if required.
139   SUnit *CreateNewSUnit(SDNode *N) {
140     unsigned NumSUnits = SUnits.size();
141     SUnit *NewNode = NewSUnit(N);
142     // Update the topological ordering.
143     if (NewNode->NodeNum >= NumSUnits)
144       Topo.InitDAGTopologicalSorting();
145     return NewNode;
146   }
147
148   /// CreateClone - Creates a new SUnit from an existing one.
149   /// Updates the topological ordering if required.
150   SUnit *CreateClone(SUnit *N) {
151     unsigned NumSUnits = SUnits.size();
152     SUnit *NewNode = Clone(N);
153     // Update the topological ordering.
154     if (NewNode->NodeNum >= NumSUnits)
155       Topo.InitDAGTopologicalSorting();
156     return NewNode;
157   }
158 };
159 }  // end anonymous namespace
160
161
162 /// Schedule - Schedule the DAG using list scheduling.
163 void ScheduleDAGRRList::Schedule() {
164   DOUT << "********** List Scheduling **********\n";
165
166   NumLiveRegs = 0;
167   LiveRegDefs.resize(TRI->getNumRegs(), NULL);  
168   LiveRegCycles.resize(TRI->getNumRegs(), 0);
169
170   // Build scheduling units.
171   BuildSchedUnits();
172
173   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
174           SUnits[su].dumpAll(this));
175   CalculateDepths();
176   CalculateHeights();
177   Topo.InitDAGTopologicalSorting();
178
179   AvailableQueue->initNodes(SUnits);
180   
181   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
182   if (isBottomUp)
183     ListScheduleBottomUp();
184   else
185     ListScheduleTopDown();
186   
187   AvailableQueue->releaseState();
188
189   CommuteNodesToReducePressure();
190 }
191
192 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
193 /// it is not the last use of its first operand, add it to the CommuteSet if
194 /// possible. It will be commuted when it is translated to a MI.
195 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
196   SmallPtrSet<SUnit*, 4> OperandSeen;
197   for (unsigned i = Sequence.size(); i != 0; ) {
198     --i;
199     SUnit *SU = Sequence[i];
200     if (!SU || !SU->getNode()) continue;
201     if (SU->isCommutable) {
202       unsigned Opc = SU->getNode()->getMachineOpcode();
203       const TargetInstrDesc &TID = TII->get(Opc);
204       unsigned NumRes = TID.getNumDefs();
205       unsigned NumOps = TID.getNumOperands() - NumRes;
206       for (unsigned j = 0; j != NumOps; ++j) {
207         if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
208           continue;
209
210         SDNode *OpN = SU->getNode()->getOperand(j).getNode();
211         SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
212         if (OpSU && OperandSeen.count(OpSU) == 1) {
213           // Ok, so SU is not the last use of OpSU, but SU is two-address so
214           // it will clobber OpSU. Try to commute SU if no other source operands
215           // are live below.
216           bool DoCommute = true;
217           for (unsigned k = 0; k < NumOps; ++k) {
218             if (k != j) {
219               OpN = SU->getNode()->getOperand(k).getNode();
220               OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
221               if (OpSU && OperandSeen.count(OpSU) == 1) {
222                 DoCommute = false;
223                 break;
224               }
225             }
226           }
227           if (DoCommute)
228             CommuteSet.insert(SU->getNode());
229         }
230
231         // Only look at the first use&def node for now.
232         break;
233       }
234     }
235
236     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
237          I != E; ++I) {
238       if (!I->isCtrl)
239         OperandSeen.insert(I->Dep->OrigNode);
240     }
241   }
242 }
243
244 //===----------------------------------------------------------------------===//
245 //  Bottom-Up Scheduling
246 //===----------------------------------------------------------------------===//
247
248 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
249 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
250 void ScheduleDAGRRList::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
251   --PredSU->NumSuccsLeft;
252   
253 #ifndef NDEBUG
254   if (PredSU->NumSuccsLeft < 0) {
255     cerr << "*** Scheduling failed! ***\n";
256     PredSU->dump(this);
257     cerr << " has been released too many times!\n";
258     assert(0);
259   }
260 #endif
261   
262   if (PredSU->NumSuccsLeft == 0) {
263     PredSU->isAvailable = true;
264     AvailableQueue->push(PredSU);
265   }
266 }
267
268 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
269 /// count of its predecessors. If a predecessor pending count is zero, add it to
270 /// the Available queue.
271 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
272   DOUT << "*** Scheduling [" << CurCycle << "]: ";
273   DEBUG(SU->dump(this));
274
275   SU->Cycle = CurCycle;
276   Sequence.push_back(SU);
277
278   // Bottom up: release predecessors
279   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
280        I != E; ++I) {
281     ReleasePred(SU, I->Dep, I->isCtrl);
282     if (I->Cost < 0)  {
283       // This is a physical register dependency and it's impossible or
284       // expensive to copy the register. Make sure nothing that can 
285       // clobber the register is scheduled between the predecessor and
286       // this node.
287       if (!LiveRegDefs[I->Reg]) {
288         ++NumLiveRegs;
289         LiveRegDefs[I->Reg] = I->Dep;
290         LiveRegCycles[I->Reg] = CurCycle;
291       }
292     }
293   }
294
295   // Release all the implicit physical register defs that are live.
296   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
297        I != E; ++I) {
298     if (I->Cost < 0)  {
299       if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
300         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
301         assert(LiveRegDefs[I->Reg] == SU &&
302                "Physical register dependency violated?");
303         --NumLiveRegs;
304         LiveRegDefs[I->Reg] = NULL;
305         LiveRegCycles[I->Reg] = 0;
306       }
307     }
308   }
309
310   SU->isScheduled = true;
311   AvailableQueue->ScheduledNode(SU);
312 }
313
314 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
315 /// unscheduled, incrcease the succ left count of its predecessors. Remove
316 /// them from AvailableQueue if necessary.
317 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {  
318   if (PredSU->isAvailable) {
319     PredSU->isAvailable = false;
320     if (!PredSU->isPending)
321       AvailableQueue->remove(PredSU);
322   }
323
324   ++PredSU->NumSuccsLeft;
325 }
326
327 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
328 /// its predecessor states to reflect the change.
329 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
330   DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
331   DEBUG(SU->dump(this));
332
333   AvailableQueue->UnscheduledNode(SU);
334
335   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
336        I != E; ++I) {
337     CapturePred(I->Dep, SU, I->isCtrl);
338     if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg])  {
339       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
340       assert(LiveRegDefs[I->Reg] == I->Dep &&
341              "Physical register dependency violated?");
342       --NumLiveRegs;
343       LiveRegDefs[I->Reg] = NULL;
344       LiveRegCycles[I->Reg] = 0;
345     }
346   }
347
348   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
349        I != E; ++I) {
350     if (I->Cost < 0)  {
351       if (!LiveRegDefs[I->Reg]) {
352         LiveRegDefs[I->Reg] = SU;
353         ++NumLiveRegs;
354       }
355       if (I->Dep->Cycle < LiveRegCycles[I->Reg])
356         LiveRegCycles[I->Reg] = I->Dep->Cycle;
357     }
358   }
359
360   SU->Cycle = 0;
361   SU->isScheduled = false;
362   SU->isAvailable = true;
363   AvailableQueue->push(SU);
364 }
365
366 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
367 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
368 /// SUnit. Also returns if a successor is unscheduled in the process.
369 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
370                                           unsigned &CurCycle) {
371   SUnit *OldSU = NULL;
372   while (CurCycle > BtCycle) {
373     OldSU = Sequence.back();
374     Sequence.pop_back();
375     if (SU->isSucc(OldSU))
376       // Don't try to remove SU from AvailableQueue.
377       SU->isAvailable = false;
378     UnscheduleNodeBottomUp(OldSU);
379     --CurCycle;
380   }
381
382       
383   if (SU->isSucc(OldSU)) {
384     assert(false && "Something is wrong!");
385     abort();
386   }
387
388   ++NumBacktracks;
389 }
390
391 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
392 /// successors to the newly created node.
393 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
394   if (SU->getNode()->getFlaggedNode())
395     return NULL;
396
397   SDNode *N = SU->getNode();
398   if (!N)
399     return NULL;
400
401   SUnit *NewSU;
402   bool TryUnfold = false;
403   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
404     MVT VT = N->getValueType(i);
405     if (VT == MVT::Flag)
406       return NULL;
407     else if (VT == MVT::Other)
408       TryUnfold = true;
409   }
410   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
411     const SDValue &Op = N->getOperand(i);
412     MVT VT = Op.getNode()->getValueType(Op.getResNo());
413     if (VT == MVT::Flag)
414       return NULL;
415   }
416
417   if (TryUnfold) {
418     SmallVector<SDNode*, 2> NewNodes;
419     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
420       return NULL;
421
422     DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
423     assert(NewNodes.size() == 2 && "Expected a load folding node!");
424
425     N = NewNodes[1];
426     SDNode *LoadNode = NewNodes[0];
427     unsigned NumVals = N->getNumValues();
428     unsigned OldNumVals = SU->getNode()->getNumValues();
429     for (unsigned i = 0; i != NumVals; ++i)
430       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
431     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
432                                    SDValue(LoadNode, 1));
433
434     // LoadNode may already exist. This can happen when there is another
435     // load from the same location and producing the same type of value
436     // but it has different alignment or volatileness.
437     bool isNewLoad = true;
438     SUnit *LoadSU;
439     if (LoadNode->getNodeId() != -1) {
440       LoadSU = &SUnits[LoadNode->getNodeId()];
441       isNewLoad = false;
442     } else {
443       LoadSU = CreateNewSUnit(LoadNode);
444       LoadNode->setNodeId(LoadSU->NodeNum);
445
446       LoadSU->Depth = SU->Depth;
447       LoadSU->Height = SU->Height;
448       ComputeLatency(LoadSU);
449     }
450
451     SUnit *NewSU = CreateNewSUnit(N);
452     assert(N->getNodeId() == -1 && "Node already inserted!");
453     N->setNodeId(NewSU->NodeNum);
454       
455     const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
456     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
457       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
458         NewSU->isTwoAddress = true;
459         break;
460       }
461     }
462     if (TID.isCommutable())
463       NewSU->isCommutable = true;
464     // FIXME: Calculate height / depth and propagate the changes?
465     NewSU->Depth = SU->Depth;
466     NewSU->Height = SU->Height;
467     ComputeLatency(NewSU);
468
469     SUnit *ChainPred = NULL;
470     SmallVector<SDep, 4> ChainSuccs;
471     SmallVector<SDep, 4> LoadPreds;
472     SmallVector<SDep, 4> NodePreds;
473     SmallVector<SDep, 4> NodeSuccs;
474     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
475          I != E; ++I) {
476       if (I->isCtrl)
477         ChainPred = I->Dep;
478       else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
479         LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
480       else
481         NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
482     }
483     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
484          I != E; ++I) {
485       if (I->isCtrl)
486         ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
487                                   I->isCtrl, I->isArtificial, I->isAntiDep));
488       else
489         NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
490                                  I->isCtrl, I->isArtificial, I->isAntiDep));
491     }
492
493     if (ChainPred) {
494       RemovePred(SU, ChainPred, true, false);
495       if (isNewLoad)
496         AddPred(LoadSU, ChainPred, true, false);
497     }
498     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
499       SDep *Pred = &LoadPreds[i];
500       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
501       if (isNewLoad) {
502         AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
503                 Pred->Reg, Pred->Cost);
504       }
505     }
506     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
507       SDep *Pred = &NodePreds[i];
508       RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
509       AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
510               Pred->Reg, Pred->Cost);
511     }
512     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
513       SDep *Succ = &NodeSuccs[i];
514       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
515       AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isArtificial,
516               Succ->Reg, Succ->Cost);
517     }
518     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
519       SDep *Succ = &ChainSuccs[i];
520       RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
521       if (isNewLoad) {
522         AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isArtificial,
523                 Succ->Reg, Succ->Cost);
524       }
525     } 
526     if (isNewLoad) {
527       AddPred(NewSU, LoadSU, false, false);
528     }
529
530     if (isNewLoad)
531       AvailableQueue->addNode(LoadSU);
532     AvailableQueue->addNode(NewSU);
533
534     ++NumUnfolds;
535
536     if (NewSU->NumSuccsLeft == 0) {
537       NewSU->isAvailable = true;
538       return NewSU;
539     }
540     SU = NewSU;
541   }
542
543   DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
544   NewSU = CreateClone(SU);
545
546   // New SUnit has the exact same predecessors.
547   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
548        I != E; ++I)
549     if (!I->isArtificial) {
550       AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
551       NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
552     }
553
554   // Only copy scheduled successors. Cut them from old node's successor
555   // list and move them over.
556   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
557   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
558        I != E; ++I) {
559     if (I->isArtificial)
560       continue;
561     if (I->Dep->isScheduled) {
562       NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
563       AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
564       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
565     }
566   }
567   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
568     SUnit *Succ = DelDeps[i].first;
569     bool isCtrl = DelDeps[i].second;
570     RemovePred(Succ, SU, isCtrl, false);
571   }
572
573   AvailableQueue->updateNode(SU);
574   AvailableQueue->addNode(NewSU);
575
576   ++NumDups;
577   return NewSU;
578 }
579
580 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
581 /// and move all scheduled successors of the given SUnit to the last copy.
582 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
583                                               const TargetRegisterClass *DestRC,
584                                               const TargetRegisterClass *SrcRC,
585                                                SmallVector<SUnit*, 2> &Copies) {
586   SUnit *CopyFromSU = CreateNewSUnit(NULL);
587   CopyFromSU->CopySrcRC = SrcRC;
588   CopyFromSU->CopyDstRC = DestRC;
589   CopyFromSU->Depth = SU->Depth;
590   CopyFromSU->Height = SU->Height;
591
592   SUnit *CopyToSU = CreateNewSUnit(NULL);
593   CopyToSU->CopySrcRC = DestRC;
594   CopyToSU->CopyDstRC = SrcRC;
595
596   // Only copy scheduled successors. Cut them from old node's successor
597   // list and move them over.
598   SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
599   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
600        I != E; ++I) {
601     if (I->isArtificial)
602       continue;
603     if (I->Dep->isScheduled) {
604       CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
605       AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
606       DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
607     }
608   }
609   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
610     SUnit *Succ = DelDeps[i].first;
611     bool isCtrl = DelDeps[i].second;
612     RemovePred(Succ, SU, isCtrl, false);
613   }
614
615   AddPred(CopyFromSU, SU, false, false, Reg, -1);
616   AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
617
618   AvailableQueue->updateNode(SU);
619   AvailableQueue->addNode(CopyFromSU);
620   AvailableQueue->addNode(CopyToSU);
621   Copies.push_back(CopyFromSU);
622   Copies.push_back(CopyToSU);
623
624   ++NumCCCopies;
625 }
626
627 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
628 /// definition of the specified node.
629 /// FIXME: Move to SelectionDAG?
630 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
631                                  const TargetInstrInfo *TII) {
632   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
633   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
634   unsigned NumRes = TID.getNumDefs();
635   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
636     if (Reg == *ImpDef)
637       break;
638     ++NumRes;
639   }
640   return N->getValueType(NumRes);
641 }
642
643 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
644 /// scheduling of the given node to satisfy live physical register dependencies.
645 /// If the specific node is the last one that's available to schedule, do
646 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
647 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
648                                                  SmallVector<unsigned, 4> &LRegs){
649   if (NumLiveRegs == 0)
650     return false;
651
652   SmallSet<unsigned, 4> RegAdded;
653   // If this node would clobber any "live" register, then it's not ready.
654   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
655        I != E; ++I) {
656     if (I->Cost < 0)  {
657       unsigned Reg = I->Reg;
658       if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
659         if (RegAdded.insert(Reg))
660           LRegs.push_back(Reg);
661       }
662       for (const unsigned *Alias = TRI->getAliasSet(Reg);
663            *Alias; ++Alias)
664         if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
665           if (RegAdded.insert(*Alias))
666             LRegs.push_back(*Alias);
667         }
668     }
669   }
670
671   for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
672     if (!Node->isMachineOpcode())
673       continue;
674     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
675     if (!TID.ImplicitDefs)
676       continue;
677     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
678       if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
679         if (RegAdded.insert(*Reg))
680           LRegs.push_back(*Reg);
681       }
682       for (const unsigned *Alias = TRI->getAliasSet(*Reg);
683            *Alias; ++Alias)
684         if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
685           if (RegAdded.insert(*Alias))
686             LRegs.push_back(*Alias);
687         }
688     }
689   }
690   return !LRegs.empty();
691 }
692
693
694 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
695 /// schedulers.
696 void ScheduleDAGRRList::ListScheduleBottomUp() {
697   unsigned CurCycle = 0;
698   // Add root to Available queue.
699   if (!SUnits.empty()) {
700     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
701     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
702     RootSU->isAvailable = true;
703     AvailableQueue->push(RootSU);
704   }
705
706   // While Available queue is not empty, grab the node with the highest
707   // priority. If it is not ready put it back.  Schedule the node.
708   SmallVector<SUnit*, 4> NotReady;
709   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
710   Sequence.reserve(SUnits.size());
711   while (!AvailableQueue->empty()) {
712     bool Delayed = false;
713     LRegsMap.clear();
714     SUnit *CurSU = AvailableQueue->pop();
715     while (CurSU) {
716       SmallVector<unsigned, 4> LRegs;
717       if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
718         break;
719       Delayed = true;
720       LRegsMap.insert(std::make_pair(CurSU, LRegs));
721
722       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
723       NotReady.push_back(CurSU);
724       CurSU = AvailableQueue->pop();
725     }
726
727     // All candidates are delayed due to live physical reg dependencies.
728     // Try backtracking, code duplication, or inserting cross class copies
729     // to resolve it.
730     if (Delayed && !CurSU) {
731       for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
732         SUnit *TrySU = NotReady[i];
733         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
734
735         // Try unscheduling up to the point where it's safe to schedule
736         // this node.
737         unsigned LiveCycle = CurCycle;
738         for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
739           unsigned Reg = LRegs[j];
740           unsigned LCycle = LiveRegCycles[Reg];
741           LiveCycle = std::min(LiveCycle, LCycle);
742         }
743         SUnit *OldSU = Sequence[LiveCycle];
744         if (!WillCreateCycle(TrySU, OldSU))  {
745           BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
746           // Force the current node to be scheduled before the node that
747           // requires the physical reg dep.
748           if (OldSU->isAvailable) {
749             OldSU->isAvailable = false;
750             AvailableQueue->remove(OldSU);
751           }
752           AddPred(TrySU, OldSU, true, true);
753           // If one or more successors has been unscheduled, then the current
754           // node is no longer avaialable. Schedule a successor that's now
755           // available instead.
756           if (!TrySU->isAvailable)
757             CurSU = AvailableQueue->pop();
758           else {
759             CurSU = TrySU;
760             TrySU->isPending = false;
761             NotReady.erase(NotReady.begin()+i);
762           }
763           break;
764         }
765       }
766
767       if (!CurSU) {
768         // Can't backtrack. Try duplicating the nodes that produces these
769         // "expensive to copy" values to break the dependency. In case even
770         // that doesn't work, insert cross class copies.
771         SUnit *TrySU = NotReady[0];
772         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
773         assert(LRegs.size() == 1 && "Can't handle this yet!");
774         unsigned Reg = LRegs[0];
775         SUnit *LRDef = LiveRegDefs[Reg];
776         SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
777         if (!NewDef) {
778           // Issue expensive cross register class copies.
779           MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
780           const TargetRegisterClass *RC =
781             TRI->getPhysicalRegisterRegClass(Reg, VT);
782           const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
783           if (!DestRC) {
784             assert(false && "Don't know how to copy this physical register!");
785             abort();
786           }
787           SmallVector<SUnit*, 2> Copies;
788           InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
789           DOUT << "Adding an edge from SU # " << TrySU->NodeNum
790                << " to SU #" << Copies.front()->NodeNum << "\n";
791           AddPred(TrySU, Copies.front(), true, true);
792           NewDef = Copies.back();
793         }
794
795         DOUT << "Adding an edge from SU # " << NewDef->NodeNum
796              << " to SU #" << TrySU->NodeNum << "\n";
797         LiveRegDefs[Reg] = NewDef;
798         AddPred(NewDef, TrySU, true, true);
799         TrySU->isAvailable = false;
800         CurSU = NewDef;
801       }
802
803       if (!CurSU) {
804         assert(false && "Unable to resolve live physical register dependencies!");
805         abort();
806       }
807     }
808
809     // Add the nodes that aren't ready back onto the available list.
810     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
811       NotReady[i]->isPending = false;
812       // May no longer be available due to backtracking.
813       if (NotReady[i]->isAvailable)
814         AvailableQueue->push(NotReady[i]);
815     }
816     NotReady.clear();
817
818     if (CurSU)
819       ScheduleNodeBottomUp(CurSU, CurCycle);
820     ++CurCycle;
821   }
822
823   // Reverse the order if it is bottom up.
824   std::reverse(Sequence.begin(), Sequence.end());
825   
826 #ifndef NDEBUG
827   VerifySchedule(isBottomUp);
828 #endif
829 }
830
831 //===----------------------------------------------------------------------===//
832 //  Top-Down Scheduling
833 //===----------------------------------------------------------------------===//
834
835 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
836 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
837 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
838   --SuccSU->NumPredsLeft;
839   
840 #ifndef NDEBUG
841   if (SuccSU->NumPredsLeft < 0) {
842     cerr << "*** Scheduling failed! ***\n";
843     SuccSU->dump(this);
844     cerr << " has been released too many times!\n";
845     assert(0);
846   }
847 #endif
848   
849   if (SuccSU->NumPredsLeft == 0) {
850     SuccSU->isAvailable = true;
851     AvailableQueue->push(SuccSU);
852   }
853 }
854
855 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
856 /// count of its successors. If a successor pending count is zero, add it to
857 /// the Available queue.
858 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
859   DOUT << "*** Scheduling [" << CurCycle << "]: ";
860   DEBUG(SU->dump(this));
861
862   SU->Cycle = CurCycle;
863   Sequence.push_back(SU);
864
865   // Top down: release successors
866   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
867        I != E; ++I)
868     ReleaseSucc(SU, I->Dep, I->isCtrl);
869
870   SU->isScheduled = true;
871   AvailableQueue->ScheduledNode(SU);
872 }
873
874 /// ListScheduleTopDown - The main loop of list scheduling for top-down
875 /// schedulers.
876 void ScheduleDAGRRList::ListScheduleTopDown() {
877   unsigned CurCycle = 0;
878
879   // All leaves to Available queue.
880   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
881     // It is available if it has no predecessors.
882     if (SUnits[i].Preds.empty()) {
883       AvailableQueue->push(&SUnits[i]);
884       SUnits[i].isAvailable = true;
885     }
886   }
887   
888   // While Available queue is not empty, grab the node with the highest
889   // priority. If it is not ready put it back.  Schedule the node.
890   Sequence.reserve(SUnits.size());
891   while (!AvailableQueue->empty()) {
892     SUnit *CurSU = AvailableQueue->pop();
893     
894     if (CurSU)
895       ScheduleNodeTopDown(CurSU, CurCycle);
896     ++CurCycle;
897   }
898   
899 #ifndef NDEBUG
900   VerifySchedule(isBottomUp);
901 #endif
902 }
903
904
905 //===----------------------------------------------------------------------===//
906 //                RegReductionPriorityQueue Implementation
907 //===----------------------------------------------------------------------===//
908 //
909 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
910 // to reduce register pressure.
911 // 
912 namespace {
913   template<class SF>
914   class RegReductionPriorityQueue;
915   
916   /// Sorting functions for the Available queue.
917   struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
918     RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
919     bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
920     bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
921     
922     bool operator()(const SUnit* left, const SUnit* right) const;
923   };
924
925   struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
926     RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
927     td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
928     td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
929     
930     bool operator()(const SUnit* left, const SUnit* right) const;
931   };
932 }  // end anonymous namespace
933
934 static inline bool isCopyFromLiveIn(const SUnit *SU) {
935   SDNode *N = SU->getNode();
936   return N && N->getOpcode() == ISD::CopyFromReg &&
937     N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
938 }
939
940 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
941 /// Smaller number is the higher priority.
942 static unsigned
943 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
944   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
945   if (SethiUllmanNumber != 0)
946     return SethiUllmanNumber;
947
948   unsigned Extra = 0;
949   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
950        I != E; ++I) {
951     if (I->isCtrl) continue;  // ignore chain preds
952     SUnit *PredSU = I->Dep;
953     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
954     if (PredSethiUllman > SethiUllmanNumber) {
955       SethiUllmanNumber = PredSethiUllman;
956       Extra = 0;
957     } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
958       ++Extra;
959   }
960
961   SethiUllmanNumber += Extra;
962
963   if (SethiUllmanNumber == 0)
964     SethiUllmanNumber = 1;
965   
966   return SethiUllmanNumber;
967 }
968
969 namespace {
970   template<class SF>
971   class VISIBILITY_HIDDEN RegReductionPriorityQueue
972    : public SchedulingPriorityQueue {
973     PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
974     unsigned currentQueueId;
975
976   protected:
977     // SUnits - The SUnits for the current graph.
978     std::vector<SUnit> *SUnits;
979     
980     const TargetInstrInfo *TII;
981     const TargetRegisterInfo *TRI;
982     ScheduleDAGRRList *scheduleDAG;
983
984     // SethiUllmanNumbers - The SethiUllman number for each node.
985     std::vector<unsigned> SethiUllmanNumbers;
986
987   public:
988     RegReductionPriorityQueue(const TargetInstrInfo *tii,
989                               const TargetRegisterInfo *tri) :
990     Queue(SF(this)), currentQueueId(0),
991     TII(tii), TRI(tri), scheduleDAG(NULL) {}
992     
993     void initNodes(std::vector<SUnit> &sunits) {
994       SUnits = &sunits;
995       // Add pseudo dependency edges for two-address nodes.
996       AddPseudoTwoAddrDeps();
997       // Calculate node priorities.
998       CalculateSethiUllmanNumbers();
999     }
1000
1001     void addNode(const SUnit *SU) {
1002       unsigned SUSize = SethiUllmanNumbers.size();
1003       if (SUnits->size() > SUSize)
1004         SethiUllmanNumbers.resize(SUSize*2, 0);
1005       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1006     }
1007
1008     void updateNode(const SUnit *SU) {
1009       SethiUllmanNumbers[SU->NodeNum] = 0;
1010       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1011     }
1012
1013     void releaseState() {
1014       SUnits = 0;
1015       SethiUllmanNumbers.clear();
1016     }
1017
1018     unsigned getNodePriority(const SUnit *SU) const {
1019       assert(SU->NodeNum < SethiUllmanNumbers.size());
1020       unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1021       if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1022         // CopyFromReg should be close to its def because it restricts
1023         // allocation choices. But if it is a livein then perhaps we want it
1024         // closer to its uses so it can be coalesced.
1025         return 0xffff;
1026       else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1027         // CopyToReg should be close to its uses to facilitate coalescing and
1028         // avoid spilling.
1029         return 0;
1030       else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1031                Opc == TargetInstrInfo::INSERT_SUBREG)
1032         // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1033         // facilitate coalescing.
1034         return 0;
1035       else if (SU->NumSuccs == 0)
1036         // If SU does not have a use, i.e. it doesn't produce a value that would
1037         // be consumed (e.g. store), then it terminates a chain of computation.
1038         // Give it a large SethiUllman number so it will be scheduled right
1039         // before its predecessors that it doesn't lengthen their live ranges.
1040         return 0xffff;
1041       else if (SU->NumPreds == 0)
1042         // If SU does not have a def, schedule it close to its uses because it
1043         // does not lengthen any live ranges.
1044         return 0;
1045       else
1046         return SethiUllmanNumbers[SU->NodeNum];
1047     }
1048     
1049     unsigned size() const { return Queue.size(); }
1050
1051     bool empty() const { return Queue.empty(); }
1052     
1053     void push(SUnit *U) {
1054       assert(!U->NodeQueueId && "Node in the queue already");
1055       U->NodeQueueId = ++currentQueueId;
1056       Queue.push(U);
1057     }
1058
1059     void push_all(const std::vector<SUnit *> &Nodes) {
1060       for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1061         push(Nodes[i]);
1062     }
1063     
1064     SUnit *pop() {
1065       if (empty()) return NULL;
1066       SUnit *V = Queue.top();
1067       Queue.pop();
1068       V->NodeQueueId = 0;
1069       return V;
1070     }
1071
1072     void remove(SUnit *SU) {
1073       assert(!Queue.empty() && "Queue is empty!");
1074       assert(SU->NodeQueueId != 0 && "Not in queue!");
1075       Queue.erase_one(SU);
1076       SU->NodeQueueId = 0;
1077     }
1078
1079     void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 
1080       scheduleDAG = scheduleDag; 
1081     }
1082
1083   protected:
1084     bool canClobber(const SUnit *SU, const SUnit *Op);
1085     void AddPseudoTwoAddrDeps();
1086     void CalculateSethiUllmanNumbers();
1087   };
1088
1089   typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1090     BURegReductionPriorityQueue;
1091
1092   typedef RegReductionPriorityQueue<td_ls_rr_sort>
1093     TDRegReductionPriorityQueue;
1094 }
1095
1096 /// closestSucc - Returns the scheduled cycle of the successor which is
1097 /// closet to the current cycle.
1098 static unsigned closestSucc(const SUnit *SU) {
1099   unsigned MaxCycle = 0;
1100   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1101        I != E; ++I) {
1102     unsigned Cycle = I->Dep->Cycle;
1103     // If there are bunch of CopyToRegs stacked up, they should be considered
1104     // to be at the same position.
1105     if (I->Dep->getNode() && I->Dep->getNode()->getOpcode() == ISD::CopyToReg)
1106       Cycle = closestSucc(I->Dep)+1;
1107     if (Cycle > MaxCycle)
1108       MaxCycle = Cycle;
1109   }
1110   return MaxCycle;
1111 }
1112
1113 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1114 /// for scratch registers. Live-in operands and live-out results don't count
1115 /// since they are "fixed".
1116 static unsigned calcMaxScratches(const SUnit *SU) {
1117   unsigned Scratches = 0;
1118   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1119        I != E; ++I) {
1120     if (I->isCtrl) continue;  // ignore chain preds
1121     if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyFromReg)
1122       Scratches++;
1123   }
1124   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1125        I != E; ++I) {
1126     if (I->isCtrl) continue;  // ignore chain succs
1127     if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyToReg)
1128       Scratches += 10;
1129   }
1130   return Scratches;
1131 }
1132
1133 // Bottom up
1134 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1135   unsigned LPriority = SPQ->getNodePriority(left);
1136   unsigned RPriority = SPQ->getNodePriority(right);
1137   if (LPriority != RPriority)
1138     return LPriority > RPriority;
1139
1140   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1141   // e.g.
1142   // t1 = op t2, c1
1143   // t3 = op t4, c2
1144   //
1145   // and the following instructions are both ready.
1146   // t2 = op c3
1147   // t4 = op c4
1148   //
1149   // Then schedule t2 = op first.
1150   // i.e.
1151   // t4 = op c4
1152   // t2 = op c3
1153   // t1 = op t2, c1
1154   // t3 = op t4, c2
1155   //
1156   // This creates more short live intervals.
1157   unsigned LDist = closestSucc(left);
1158   unsigned RDist = closestSucc(right);
1159   if (LDist != RDist)
1160     return LDist < RDist;
1161
1162   // Intuitively, it's good to push down instructions whose results are
1163   // liveout so their long live ranges won't conflict with other values
1164   // which are needed inside the BB. Further prioritize liveout instructions
1165   // by the number of operands which are calculated within the BB.
1166   unsigned LScratch = calcMaxScratches(left);
1167   unsigned RScratch = calcMaxScratches(right);
1168   if (LScratch != RScratch)
1169     return LScratch > RScratch;
1170
1171   if (left->Height != right->Height)
1172     return left->Height > right->Height;
1173   
1174   if (left->Depth != right->Depth)
1175     return left->Depth < right->Depth;
1176
1177   assert(left->NodeQueueId && right->NodeQueueId && 
1178          "NodeQueueId cannot be zero");
1179   return (left->NodeQueueId > right->NodeQueueId);
1180 }
1181
1182 template<class SF>
1183 bool
1184 RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1185   if (SU->isTwoAddress) {
1186     unsigned Opc = SU->getNode()->getMachineOpcode();
1187     const TargetInstrDesc &TID = TII->get(Opc);
1188     unsigned NumRes = TID.getNumDefs();
1189     unsigned NumOps = TID.getNumOperands() - NumRes;
1190     for (unsigned i = 0; i != NumOps; ++i) {
1191       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1192         SDNode *DU = SU->getNode()->getOperand(i).getNode();
1193         if (DU->getNodeId() != -1 &&
1194             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1195           return true;
1196       }
1197     }
1198   }
1199   return false;
1200 }
1201
1202
1203 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1204 /// CopyToReg node.
1205 static bool hasCopyToRegUse(const SUnit *SU) {
1206   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1207        I != E; ++I) {
1208     if (I->isCtrl) continue;
1209     const SUnit *SuccSU = I->Dep;
1210     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg)
1211       return true;
1212   }
1213   return false;
1214 }
1215
1216 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1217 /// physical register defs.
1218 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1219                                   const TargetInstrInfo *TII,
1220                                   const TargetRegisterInfo *TRI) {
1221   SDNode *N = SuccSU->getNode();
1222   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1223   const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1224   assert(ImpDefs && "Caller should check hasPhysRegDefs");
1225   const unsigned *SUImpDefs =
1226     TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
1227   if (!SUImpDefs)
1228     return false;
1229   for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1230     MVT VT = N->getValueType(i);
1231     if (VT == MVT::Flag || VT == MVT::Other)
1232       continue;
1233     if (!N->hasAnyUseOfValue(i))
1234       continue;
1235     unsigned Reg = ImpDefs[i - NumDefs];
1236     for (;*SUImpDefs; ++SUImpDefs) {
1237       unsigned SUReg = *SUImpDefs;
1238       if (TRI->regsOverlap(Reg, SUReg))
1239         return true;
1240     }
1241   }
1242   return false;
1243 }
1244
1245 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1246 /// it as a def&use operand. Add a pseudo control edge from it to the other
1247 /// node (if it won't create a cycle) so the two-address one will be scheduled
1248 /// first (lower in the schedule). If both nodes are two-address, favor the
1249 /// one that has a CopyToReg use (more likely to be a loop induction update).
1250 /// If both are two-address, but one is commutable while the other is not
1251 /// commutable, favor the one that's not commutable.
1252 template<class SF>
1253 void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1254   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1255     SUnit *SU = &(*SUnits)[i];
1256     if (!SU->isTwoAddress)
1257       continue;
1258
1259     SDNode *Node = SU->getNode();
1260     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1261       continue;
1262
1263     unsigned Opc = Node->getMachineOpcode();
1264     const TargetInstrDesc &TID = TII->get(Opc);
1265     unsigned NumRes = TID.getNumDefs();
1266     unsigned NumOps = TID.getNumOperands() - NumRes;
1267     for (unsigned j = 0; j != NumOps; ++j) {
1268       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1269         continue;
1270       SDNode *DU = SU->getNode()->getOperand(j).getNode();
1271       if (DU->getNodeId() == -1)
1272         continue;
1273       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1274       if (!DUSU) continue;
1275       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1276            E = DUSU->Succs.end(); I != E; ++I) {
1277         if (I->isCtrl) continue;
1278         SUnit *SuccSU = I->Dep;
1279         if (SuccSU == SU)
1280           continue;
1281         // Be conservative. Ignore if nodes aren't at roughly the same
1282         // depth and height.
1283         if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1284           continue;
1285         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1286           continue;
1287         // Don't constrain nodes with physical register defs if the
1288         // predecessor can clobber them.
1289         if (SuccSU->hasPhysRegDefs) {
1290           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1291             continue;
1292         }
1293         // Don't constraint extract_subreg / insert_subreg these may be
1294         // coalesced away. We don't them close to their uses.
1295         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1296         if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1297             SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1298           continue;
1299         if ((!canClobber(SuccSU, DUSU) ||
1300              (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1301              (!SU->isCommutable && SuccSU->isCommutable)) &&
1302             !scheduleDAG->IsReachable(SuccSU, SU)) {
1303           DOUT << "Adding a pseudo-two-addr edge from SU # " << SU->NodeNum
1304                << " to SU #" << SuccSU->NodeNum << "\n";
1305           scheduleDAG->AddPred(SU, SuccSU, true, true);
1306         }
1307       }
1308     }
1309   }
1310 }
1311
1312 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1313 /// scheduling units.
1314 template<class SF>
1315 void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1316   SethiUllmanNumbers.assign(SUnits->size(), 0);
1317   
1318   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1319     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1320 }
1321
1322 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1323 /// predecessors of the successors of the SUnit SU. Stop when the provided
1324 /// limit is exceeded.
1325 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU, 
1326                                                     unsigned Limit) {
1327   unsigned Sum = 0;
1328   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1329        I != E; ++I) {
1330     const SUnit *SuccSU = I->Dep;
1331     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1332          EE = SuccSU->Preds.end(); II != EE; ++II) {
1333       SUnit *PredSU = II->Dep;
1334       if (!PredSU->isScheduled)
1335         if (++Sum > Limit)
1336           return Sum;
1337     }
1338   }
1339   return Sum;
1340 }
1341
1342
1343 // Top down
1344 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1345   unsigned LPriority = SPQ->getNodePriority(left);
1346   unsigned RPriority = SPQ->getNodePriority(right);
1347   bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1348   bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1349   bool LIsFloater = LIsTarget && left->NumPreds == 0;
1350   bool RIsFloater = RIsTarget && right->NumPreds == 0;
1351   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1352   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1353
1354   if (left->NumSuccs == 0 && right->NumSuccs != 0)
1355     return false;
1356   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1357     return true;
1358
1359   if (LIsFloater)
1360     LBonus -= 2;
1361   if (RIsFloater)
1362     RBonus -= 2;
1363   if (left->NumSuccs == 1)
1364     LBonus += 2;
1365   if (right->NumSuccs == 1)
1366     RBonus += 2;
1367
1368   if (LPriority+LBonus != RPriority+RBonus)
1369     return LPriority+LBonus < RPriority+RBonus;
1370
1371   if (left->Depth != right->Depth)
1372     return left->Depth < right->Depth;
1373
1374   if (left->NumSuccsLeft != right->NumSuccsLeft)
1375     return left->NumSuccsLeft > right->NumSuccsLeft;
1376
1377   assert(left->NodeQueueId && right->NodeQueueId && 
1378          "NodeQueueId cannot be zero");
1379   return (left->NodeQueueId > right->NodeQueueId);
1380 }
1381
1382 //===----------------------------------------------------------------------===//
1383 //                         Public Constructor Functions
1384 //===----------------------------------------------------------------------===//
1385
1386 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1387                                                     SelectionDAG *DAG,
1388                                                     const TargetMachine *TM,
1389                                                     MachineBasicBlock *BB,
1390                                                     bool) {
1391   const TargetInstrInfo *TII = TM->getInstrInfo();
1392   const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1393   
1394   BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1395
1396   ScheduleDAGRRList *SD =
1397     new ScheduleDAGRRList(DAG, BB, *TM, true, PQ);
1398   PQ->setScheduleDAG(SD);
1399   return SD;  
1400 }
1401
1402 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1403                                                     SelectionDAG *DAG,
1404                                                     const TargetMachine *TM,
1405                                                     MachineBasicBlock *BB,
1406                                                     bool) {
1407   const TargetInstrInfo *TII = TM->getInstrInfo();
1408   const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1409   
1410   TDRegReductionPriorityQueue *PQ = new TDRegReductionPriorityQueue(TII, TRI);
1411
1412   ScheduleDAGRRList *SD = new ScheduleDAGRRList(DAG, BB, *TM, false, PQ);
1413   PQ->setScheduleDAG(SD);
1414   return SD;
1415 }