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