0f4d9c8267856b629fb28b4512020b8e4c41173e
[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 "ScheduleDAGSDNodes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <climits>
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(NumPRCopies,   "Number of physical register 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 static RegisterScheduler
51   sourceListDAGScheduler("source",
52                          "Similar to list-burr but schedules in source "
53                          "order when possible",
54                          createSourceListDAGScheduler);
55
56 static RegisterScheduler
57   hybridListDAGScheduler("list-hybrid",
58                          "Bottom-up register pressure aware list scheduling "
59                          "which tries to balance latency and register pressure",
60                          createHybridListDAGScheduler);
61
62 static RegisterScheduler
63   ILPListDAGScheduler("list-ilp",
64                       "Bottom-up register pressure aware list scheduling "
65                       "which tries to balance ILP and register pressure",
66                       createILPListDAGScheduler);
67
68 namespace {
69 //===----------------------------------------------------------------------===//
70 /// ScheduleDAGRRList - The actual register reduction list scheduler
71 /// implementation.  This supports both top-down and bottom-up scheduling.
72 ///
73 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
74 private:
75   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
76   /// it is top-down.
77   bool isBottomUp;
78
79   /// NeedLatency - True if the scheduler will make use of latency information.
80   ///
81   bool NeedLatency;
82
83   /// AvailableQueue - The priority queue to use for the available SUnits.
84   SchedulingPriorityQueue *AvailableQueue;
85
86   /// LiveRegDefs - A set of physical registers and their definition
87   /// that are "live". These nodes must be scheduled before any other nodes that
88   /// modifies the registers can be scheduled.
89   unsigned NumLiveRegs;
90   std::vector<SUnit*> LiveRegDefs;
91   std::vector<unsigned> LiveRegCycles;
92
93   /// Topo - A topological ordering for SUnits which permits fast IsReachable
94   /// and similar queries.
95   ScheduleDAGTopologicalSort Topo;
96
97 public:
98   ScheduleDAGRRList(MachineFunction &mf,
99                     bool isbottomup, bool needlatency,
100                     SchedulingPriorityQueue *availqueue)
101     : ScheduleDAGSDNodes(mf), isBottomUp(isbottomup), NeedLatency(needlatency),
102       AvailableQueue(availqueue), Topo(SUnits) {
103     }
104
105   ~ScheduleDAGRRList() {
106     delete AvailableQueue;
107   }
108
109   void Schedule();
110
111   /// IsReachable - Checks if SU is reachable from TargetSU.
112   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
113     return Topo.IsReachable(SU, TargetSU);
114   }
115
116   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
117   /// create a cycle.
118   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
119     return Topo.WillCreateCycle(SU, TargetSU);
120   }
121
122   /// AddPred - adds a predecessor edge to SUnit SU.
123   /// This returns true if this is a new predecessor.
124   /// Updates the topological ordering if required.
125   void AddPred(SUnit *SU, const SDep &D) {
126     Topo.AddPred(SU, D.getSUnit());
127     SU->addPred(D);
128   }
129
130   /// RemovePred - removes a predecessor edge from SUnit SU.
131   /// This returns true if an edge was removed.
132   /// Updates the topological ordering if required.
133   void RemovePred(SUnit *SU, const SDep &D) {
134     Topo.RemovePred(SU, D.getSUnit());
135     SU->removePred(D);
136   }
137
138 private:
139   void ReleasePred(SUnit *SU, const SDep *PredEdge);
140   void ReleasePredecessors(SUnit *SU, unsigned CurCycle);
141   void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
142   void ReleaseSuccessors(SUnit *SU);
143   void CapturePred(SDep *PredEdge);
144   void ScheduleNodeBottomUp(SUnit*, unsigned);
145   void ScheduleNodeTopDown(SUnit*, unsigned);
146   void UnscheduleNodeBottomUp(SUnit*);
147   void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
148   SUnit *CopyAndMoveSuccessors(SUnit*);
149   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
150                                 const TargetRegisterClass*,
151                                 const TargetRegisterClass*,
152                                 SmallVector<SUnit*, 2>&);
153   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
154   void ListScheduleTopDown();
155   void ListScheduleBottomUp();
156
157
158   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
159   /// Updates the topological ordering if required.
160   SUnit *CreateNewSUnit(SDNode *N) {
161     unsigned NumSUnits = SUnits.size();
162     SUnit *NewNode = NewSUnit(N);
163     // Update the topological ordering.
164     if (NewNode->NodeNum >= NumSUnits)
165       Topo.InitDAGTopologicalSorting();
166     return NewNode;
167   }
168
169   /// CreateClone - Creates a new SUnit from an existing one.
170   /// Updates the topological ordering if required.
171   SUnit *CreateClone(SUnit *N) {
172     unsigned NumSUnits = SUnits.size();
173     SUnit *NewNode = Clone(N);
174     // Update the topological ordering.
175     if (NewNode->NodeNum >= NumSUnits)
176       Topo.InitDAGTopologicalSorting();
177     return NewNode;
178   }
179
180   /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
181   /// need actual latency information but the hybrid scheduler does.
182   bool ForceUnitLatencies() const {
183     return !NeedLatency;
184   }
185 };
186 }  // end anonymous namespace
187
188
189 /// Schedule - Schedule the DAG using list scheduling.
190 void ScheduleDAGRRList::Schedule() {
191   DEBUG(dbgs()
192         << "********** List Scheduling BB#" << BB->getNumber()
193         << " '" << BB->getName() << "' **********\n");
194
195   NumLiveRegs = 0;
196   LiveRegDefs.resize(TRI->getNumRegs(), NULL);  
197   LiveRegCycles.resize(TRI->getNumRegs(), 0);
198
199   // Build the scheduling graph.
200   BuildSchedGraph(NULL);
201
202   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
203           SUnits[su].dumpAll(this));
204   Topo.InitDAGTopologicalSorting();
205
206   AvailableQueue->initNodes(SUnits);
207   
208   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
209   if (isBottomUp)
210     ListScheduleBottomUp();
211   else
212     ListScheduleTopDown();
213   
214   AvailableQueue->releaseState();
215 }
216
217 //===----------------------------------------------------------------------===//
218 //  Bottom-Up Scheduling
219 //===----------------------------------------------------------------------===//
220
221 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
222 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
223 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
224   SUnit *PredSU = PredEdge->getSUnit();
225
226 #ifndef NDEBUG
227   if (PredSU->NumSuccsLeft == 0) {
228     dbgs() << "*** Scheduling failed! ***\n";
229     PredSU->dump(this);
230     dbgs() << " has been released too many times!\n";
231     llvm_unreachable(0);
232   }
233 #endif
234   --PredSU->NumSuccsLeft;
235
236   if (!ForceUnitLatencies()) {
237     // Updating predecessor's height. This is now the cycle when the
238     // predecessor can be scheduled without causing a pipeline stall.
239     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
240   }
241
242   // If all the node's successors are scheduled, this node is ready
243   // to be scheduled. Ignore the special EntrySU node.
244   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
245     PredSU->isAvailable = true;
246     AvailableQueue->push(PredSU);
247   }
248 }
249
250 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU, unsigned CurCycle) {
251   // Bottom up: release predecessors
252   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
253        I != E; ++I) {
254     ReleasePred(SU, &*I);
255     if (I->isAssignedRegDep()) {
256       // This is a physical register dependency and it's impossible or
257       // expensive to copy the register. Make sure nothing that can 
258       // clobber the register is scheduled between the predecessor and
259       // this node.
260       if (!LiveRegDefs[I->getReg()]) {
261         ++NumLiveRegs;
262         LiveRegDefs[I->getReg()] = I->getSUnit();
263         LiveRegCycles[I->getReg()] = CurCycle;
264       }
265     }
266   }
267 }
268
269 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
270 /// count of its predecessors. If a predecessor pending count is zero, add it to
271 /// the Available queue.
272 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
273   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
274   DEBUG(SU->dump(this));
275
276 #ifndef NDEBUG
277   if (CurCycle < SU->getHeight())
278     DEBUG(dbgs() << "   Height [" << SU->getHeight() << "] pipeline stall!\n");
279 #endif
280
281   // FIXME: Handle noop hazard.
282   SU->setHeightToAtLeast(CurCycle);
283   Sequence.push_back(SU);
284
285   AvailableQueue->ScheduledNode(SU);
286   
287   ReleasePredecessors(SU, CurCycle);
288
289   // Release all the implicit physical register defs that are live.
290   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
291        I != E; ++I) {
292     if (I->isAssignedRegDep()) {
293       if (LiveRegCycles[I->getReg()] == I->getSUnit()->getHeight()) {
294         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
295         assert(LiveRegDefs[I->getReg()] == SU &&
296                "Physical register dependency violated?");
297         --NumLiveRegs;
298         LiveRegDefs[I->getReg()] = NULL;
299         LiveRegCycles[I->getReg()] = 0;
300       }
301     }
302   }
303
304   SU->isScheduled = true;
305 }
306
307 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
308 /// unscheduled, incrcease the succ left count of its predecessors. Remove
309 /// them from AvailableQueue if necessary.
310 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {  
311   SUnit *PredSU = PredEdge->getSUnit();
312   if (PredSU->isAvailable) {
313     PredSU->isAvailable = false;
314     if (!PredSU->isPending)
315       AvailableQueue->remove(PredSU);
316   }
317
318   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
319   ++PredSU->NumSuccsLeft;
320 }
321
322 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
323 /// its predecessor states to reflect the change.
324 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
325   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
326   DEBUG(SU->dump(this));
327
328   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
329        I != E; ++I) {
330     CapturePred(&*I);
331     if (I->isAssignedRegDep() && SU->getHeight() == LiveRegCycles[I->getReg()]){
332       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
333       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
334              "Physical register dependency violated?");
335       --NumLiveRegs;
336       LiveRegDefs[I->getReg()] = NULL;
337       LiveRegCycles[I->getReg()] = 0;
338     }
339   }
340
341   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
342        I != E; ++I) {
343     if (I->isAssignedRegDep()) {
344       if (!LiveRegDefs[I->getReg()]) {
345         LiveRegDefs[I->getReg()] = SU;
346         ++NumLiveRegs;
347       }
348       if (I->getSUnit()->getHeight() < LiveRegCycles[I->getReg()])
349         LiveRegCycles[I->getReg()] = I->getSUnit()->getHeight();
350     }
351   }
352
353   SU->setHeightDirty();
354   SU->isScheduled = false;
355   SU->isAvailable = true;
356   AvailableQueue->push(SU);
357   AvailableQueue->UnscheduledNode(SU);
358 }
359
360 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
361 /// BTCycle in order to schedule a specific node.
362 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
363                                           unsigned &CurCycle) {
364   SUnit *OldSU = NULL;
365   while (CurCycle > BtCycle) {
366     OldSU = Sequence.back();
367     Sequence.pop_back();
368     if (SU->isSucc(OldSU))
369       // Don't try to remove SU from AvailableQueue.
370       SU->isAvailable = false;
371     UnscheduleNodeBottomUp(OldSU);
372     --CurCycle;
373     AvailableQueue->setCurCycle(CurCycle);
374   }
375
376   assert(!SU->isSucc(OldSU) && "Something is wrong!");
377
378   ++NumBacktracks;
379 }
380
381 static bool isOperandOf(const SUnit *SU, SDNode *N) {
382   for (const SDNode *SUNode = SU->getNode(); SUNode;
383        SUNode = SUNode->getFlaggedNode()) {
384     if (SUNode->isOperandOf(N))
385       return true;
386   }
387   return false;
388 }
389
390 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
391 /// successors to the newly created node.
392 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
393   if (SU->getNode()->getFlaggedNode())
394     return NULL;
395
396   SDNode *N = SU->getNode();
397   if (!N)
398     return NULL;
399
400   SUnit *NewSU;
401   bool TryUnfold = false;
402   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
403     EVT VT = N->getValueType(i);
404     if (VT == MVT::Flag)
405       return NULL;
406     else if (VT == MVT::Other)
407       TryUnfold = true;
408   }
409   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
410     const SDValue &Op = N->getOperand(i);
411     EVT VT = Op.getNode()->getValueType(Op.getResNo());
412     if (VT == MVT::Flag)
413       return NULL;
414   }
415
416   if (TryUnfold) {
417     SmallVector<SDNode*, 2> NewNodes;
418     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
419       return NULL;
420
421     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
422     assert(NewNodes.size() == 2 && "Expected a load folding node!");
423
424     N = NewNodes[1];
425     SDNode *LoadNode = NewNodes[0];
426     unsigned NumVals = N->getNumValues();
427     unsigned OldNumVals = SU->getNode()->getNumValues();
428     for (unsigned i = 0; i != NumVals; ++i)
429       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
430     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
431                                    SDValue(LoadNode, 1));
432
433     // LoadNode may already exist. This can happen when there is another
434     // load from the same location and producing the same type of value
435     // but it has different alignment or volatileness.
436     bool isNewLoad = true;
437     SUnit *LoadSU;
438     if (LoadNode->getNodeId() != -1) {
439       LoadSU = &SUnits[LoadNode->getNodeId()];
440       isNewLoad = false;
441     } else {
442       LoadSU = CreateNewSUnit(LoadNode);
443       LoadNode->setNodeId(LoadSU->NodeNum);
444       ComputeLatency(LoadSU);
445     }
446
447     SUnit *NewSU = CreateNewSUnit(N);
448     assert(N->getNodeId() == -1 && "Node already inserted!");
449     N->setNodeId(NewSU->NodeNum);
450       
451     const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
452     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
453       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
454         NewSU->isTwoAddress = true;
455         break;
456       }
457     }
458     if (TID.isCommutable())
459       NewSU->isCommutable = true;
460     ComputeLatency(NewSU);
461
462     // Record all the edges to and from the old SU, by category.
463     SmallVector<SDep, 4> ChainPreds;
464     SmallVector<SDep, 4> ChainSuccs;
465     SmallVector<SDep, 4> LoadPreds;
466     SmallVector<SDep, 4> NodePreds;
467     SmallVector<SDep, 4> NodeSuccs;
468     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
469          I != E; ++I) {
470       if (I->isCtrl())
471         ChainPreds.push_back(*I);
472       else if (isOperandOf(I->getSUnit(), LoadNode))
473         LoadPreds.push_back(*I);
474       else
475         NodePreds.push_back(*I);
476     }
477     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
478          I != E; ++I) {
479       if (I->isCtrl())
480         ChainSuccs.push_back(*I);
481       else
482         NodeSuccs.push_back(*I);
483     }
484
485     // Now assign edges to the newly-created nodes.
486     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
487       const SDep &Pred = ChainPreds[i];
488       RemovePred(SU, Pred);
489       if (isNewLoad)
490         AddPred(LoadSU, Pred);
491     }
492     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
493       const SDep &Pred = LoadPreds[i];
494       RemovePred(SU, Pred);
495       if (isNewLoad)
496         AddPred(LoadSU, Pred);
497     }
498     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
499       const SDep &Pred = NodePreds[i];
500       RemovePred(SU, Pred);
501       AddPred(NewSU, Pred);
502     }
503     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
504       SDep D = NodeSuccs[i];
505       SUnit *SuccDep = D.getSUnit();
506       D.setSUnit(SU);
507       RemovePred(SuccDep, D);
508       D.setSUnit(NewSU);
509       AddPred(SuccDep, D);
510     }
511     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
512       SDep D = ChainSuccs[i];
513       SUnit *SuccDep = D.getSUnit();
514       D.setSUnit(SU);
515       RemovePred(SuccDep, D);
516       if (isNewLoad) {
517         D.setSUnit(LoadSU);
518         AddPred(SuccDep, D);
519       }
520     } 
521
522     // Add a data dependency to reflect that NewSU reads the value defined
523     // by LoadSU.
524     AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
525
526     if (isNewLoad)
527       AvailableQueue->addNode(LoadSU);
528     AvailableQueue->addNode(NewSU);
529
530     ++NumUnfolds;
531
532     if (NewSU->NumSuccsLeft == 0) {
533       NewSU->isAvailable = true;
534       return NewSU;
535     }
536     SU = NewSU;
537   }
538
539   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
540   NewSU = CreateClone(SU);
541
542   // New SUnit has the exact same predecessors.
543   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
544        I != E; ++I)
545     if (!I->isArtificial())
546       AddPred(NewSU, *I);
547
548   // Only copy scheduled successors. Cut them from old node's successor
549   // list and move them over.
550   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
551   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
552        I != E; ++I) {
553     if (I->isArtificial())
554       continue;
555     SUnit *SuccSU = I->getSUnit();
556     if (SuccSU->isScheduled) {
557       SDep D = *I;
558       D.setSUnit(NewSU);
559       AddPred(SuccSU, D);
560       D.setSUnit(SU);
561       DelDeps.push_back(std::make_pair(SuccSU, D));
562     }
563   }
564   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
565     RemovePred(DelDeps[i].first, DelDeps[i].second);
566
567   AvailableQueue->updateNode(SU);
568   AvailableQueue->addNode(NewSU);
569
570   ++NumDups;
571   return NewSU;
572 }
573
574 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
575 /// scheduled successors of the given SUnit to the last copy.
576 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
577                                                const TargetRegisterClass *DestRC,
578                                                const TargetRegisterClass *SrcRC,
579                                                SmallVector<SUnit*, 2> &Copies) {
580   SUnit *CopyFromSU = CreateNewSUnit(NULL);
581   CopyFromSU->CopySrcRC = SrcRC;
582   CopyFromSU->CopyDstRC = DestRC;
583
584   SUnit *CopyToSU = CreateNewSUnit(NULL);
585   CopyToSU->CopySrcRC = DestRC;
586   CopyToSU->CopyDstRC = SrcRC;
587
588   // Only copy scheduled successors. Cut them from old node's successor
589   // list and move them over.
590   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
591   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
592        I != E; ++I) {
593     if (I->isArtificial())
594       continue;
595     SUnit *SuccSU = I->getSUnit();
596     if (SuccSU->isScheduled) {
597       SDep D = *I;
598       D.setSUnit(CopyToSU);
599       AddPred(SuccSU, D);
600       DelDeps.push_back(std::make_pair(SuccSU, *I));
601     }
602   }
603   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
604     RemovePred(DelDeps[i].first, DelDeps[i].second);
605
606   AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
607   AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
608
609   AvailableQueue->updateNode(SU);
610   AvailableQueue->addNode(CopyFromSU);
611   AvailableQueue->addNode(CopyToSU);
612   Copies.push_back(CopyFromSU);
613   Copies.push_back(CopyToSU);
614
615   ++NumPRCopies;
616 }
617
618 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
619 /// definition of the specified node.
620 /// FIXME: Move to SelectionDAG?
621 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
622                                  const TargetInstrInfo *TII) {
623   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
624   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
625   unsigned NumRes = TID.getNumDefs();
626   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
627     if (Reg == *ImpDef)
628       break;
629     ++NumRes;
630   }
631   return N->getValueType(NumRes);
632 }
633
634 /// CheckForLiveRegDef - Return true and update live register vector if the
635 /// specified register def of the specified SUnit clobbers any "live" registers.
636 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
637                                std::vector<SUnit*> &LiveRegDefs,
638                                SmallSet<unsigned, 4> &RegAdded,
639                                SmallVector<unsigned, 4> &LRegs,
640                                const TargetRegisterInfo *TRI) {
641   if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != SU) {
642     if (RegAdded.insert(Reg))
643       LRegs.push_back(Reg);
644   }
645   for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
646     if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
647       if (RegAdded.insert(*Alias))
648         LRegs.push_back(*Alias);
649     }
650 }
651
652 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
653 /// scheduling of the given node to satisfy live physical register dependencies.
654 /// If the specific node is the last one that's available to schedule, do
655 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
656 bool ScheduleDAGRRList::
657 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
658   if (NumLiveRegs == 0)
659     return false;
660
661   SmallSet<unsigned, 4> RegAdded;
662   // If this node would clobber any "live" register, then it's not ready.
663   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
664        I != E; ++I) {
665     if (I->isAssignedRegDep())
666       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
667                          RegAdded, LRegs, TRI);
668   }
669
670   for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
671     if (Node->getOpcode() == ISD::INLINEASM) {
672       // Inline asm can clobber physical defs.
673       unsigned NumOps = Node->getNumOperands();
674       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
675         --NumOps;  // Ignore the flag operand.
676
677       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
678         unsigned Flags =
679           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
680         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
681
682         ++i; // Skip the ID value.
683         if (InlineAsm::isRegDefKind(Flags) ||
684             InlineAsm::isRegDefEarlyClobberKind(Flags)) {
685           // Check for def of register or earlyclobber register.
686           for (; NumVals; --NumVals, ++i) {
687             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
688             if (TargetRegisterInfo::isPhysicalRegister(Reg))
689               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
690           }
691         } else
692           i += NumVals;
693       }
694       continue;
695     }
696
697     if (!Node->isMachineOpcode())
698       continue;
699     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
700     if (!TID.ImplicitDefs)
701       continue;
702     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
703       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
704   }
705   
706   
707   return !LRegs.empty();
708 }
709
710
711 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
712 /// schedulers.
713 void ScheduleDAGRRList::ListScheduleBottomUp() {
714   unsigned CurCycle = 0;
715
716   // Release any predecessors of the special Exit node.
717   ReleasePredecessors(&ExitSU, CurCycle);
718
719   // Add root to Available queue.
720   if (!SUnits.empty()) {
721     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
722     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
723     RootSU->isAvailable = true;
724     AvailableQueue->push(RootSU);
725   }
726
727   // While Available queue is not empty, grab the node with the highest
728   // priority. If it is not ready put it back.  Schedule the node.
729   SmallVector<SUnit*, 4> NotReady;
730   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
731   Sequence.reserve(SUnits.size());
732   while (!AvailableQueue->empty()) {
733     bool Delayed = false;
734     LRegsMap.clear();
735     SUnit *CurSU = AvailableQueue->pop();
736     while (CurSU) {
737       SmallVector<unsigned, 4> LRegs;
738       if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
739         break;
740       Delayed = true;
741       LRegsMap.insert(std::make_pair(CurSU, LRegs));
742
743       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
744       NotReady.push_back(CurSU);
745       CurSU = AvailableQueue->pop();
746     }
747
748     // All candidates are delayed due to live physical reg dependencies.
749     // Try backtracking, code duplication, or inserting cross class copies
750     // to resolve it.
751     if (Delayed && !CurSU) {
752       for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
753         SUnit *TrySU = NotReady[i];
754         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
755
756         // Try unscheduling up to the point where it's safe to schedule
757         // this node.
758         unsigned LiveCycle = CurCycle;
759         for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
760           unsigned Reg = LRegs[j];
761           unsigned LCycle = LiveRegCycles[Reg];
762           LiveCycle = std::min(LiveCycle, LCycle);
763         }
764         SUnit *OldSU = Sequence[LiveCycle];
765         if (!WillCreateCycle(TrySU, OldSU))  {
766           BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
767           // Force the current node to be scheduled before the node that
768           // requires the physical reg dep.
769           if (OldSU->isAvailable) {
770             OldSU->isAvailable = false;
771             AvailableQueue->remove(OldSU);
772           }
773           AddPred(TrySU, SDep(OldSU, SDep::Order, /*Latency=*/1,
774                               /*Reg=*/0, /*isNormalMemory=*/false,
775                               /*isMustAlias=*/false, /*isArtificial=*/true));
776           // If one or more successors has been unscheduled, then the current
777           // node is no longer avaialable. Schedule a successor that's now
778           // available instead.
779           if (!TrySU->isAvailable)
780             CurSU = AvailableQueue->pop();
781           else {
782             CurSU = TrySU;
783             TrySU->isPending = false;
784             NotReady.erase(NotReady.begin()+i);
785           }
786           break;
787         }
788       }
789
790       if (!CurSU) {
791         // Can't backtrack. If it's too expensive to copy the value, then try
792         // duplicate the nodes that produces these "too expensive to copy"
793         // values to break the dependency. In case even that doesn't work,
794         // insert cross class copies.
795         // If it's not too expensive, i.e. cost != -1, issue copies.
796         SUnit *TrySU = NotReady[0];
797         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
798         assert(LRegs.size() == 1 && "Can't handle this yet!");
799         unsigned Reg = LRegs[0];
800         SUnit *LRDef = LiveRegDefs[Reg];
801         EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
802         const TargetRegisterClass *RC =
803           TRI->getMinimalPhysRegClass(Reg, VT);
804         const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
805
806         // If cross copy register class is null, then it must be possible copy
807         // the value directly. Do not try duplicate the def.
808         SUnit *NewDef = 0;
809         if (DestRC)
810           NewDef = CopyAndMoveSuccessors(LRDef);
811         else
812           DestRC = RC;
813         if (!NewDef) {
814           // Issue copies, these can be expensive cross register class copies.
815           SmallVector<SUnit*, 2> Copies;
816           InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
817           DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
818                        << " to SU #" << Copies.front()->NodeNum << "\n");
819           AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
820                               /*Reg=*/0, /*isNormalMemory=*/false,
821                               /*isMustAlias=*/false,
822                               /*isArtificial=*/true));
823           NewDef = Copies.back();
824         }
825
826         DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
827                      << " to SU #" << TrySU->NodeNum << "\n");
828         LiveRegDefs[Reg] = NewDef;
829         AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
830                              /*Reg=*/0, /*isNormalMemory=*/false,
831                              /*isMustAlias=*/false,
832                              /*isArtificial=*/true));
833         TrySU->isAvailable = false;
834         CurSU = NewDef;
835       }
836
837       assert(CurSU && "Unable to resolve live physical register dependencies!");
838     }
839
840     // Add the nodes that aren't ready back onto the available list.
841     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
842       NotReady[i]->isPending = false;
843       // May no longer be available due to backtracking.
844       if (NotReady[i]->isAvailable)
845         AvailableQueue->push(NotReady[i]);
846     }
847     NotReady.clear();
848
849     if (CurSU)
850       ScheduleNodeBottomUp(CurSU, CurCycle);
851     ++CurCycle;
852     AvailableQueue->setCurCycle(CurCycle);
853   }
854
855   // Reverse the order if it is bottom up.
856   std::reverse(Sequence.begin(), Sequence.end());
857   
858 #ifndef NDEBUG
859   VerifySchedule(isBottomUp);
860 #endif
861 }
862
863 //===----------------------------------------------------------------------===//
864 //  Top-Down Scheduling
865 //===----------------------------------------------------------------------===//
866
867 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
868 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
869 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
870   SUnit *SuccSU = SuccEdge->getSUnit();
871
872 #ifndef NDEBUG
873   if (SuccSU->NumPredsLeft == 0) {
874     dbgs() << "*** Scheduling failed! ***\n";
875     SuccSU->dump(this);
876     dbgs() << " has been released too many times!\n";
877     llvm_unreachable(0);
878   }
879 #endif
880   --SuccSU->NumPredsLeft;
881
882   // If all the node's predecessors are scheduled, this node is ready
883   // to be scheduled. Ignore the special ExitSU node.
884   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
885     SuccSU->isAvailable = true;
886     AvailableQueue->push(SuccSU);
887   }
888 }
889
890 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
891   // Top down: release successors
892   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
893        I != E; ++I) {
894     assert(!I->isAssignedRegDep() &&
895            "The list-tdrr scheduler doesn't yet support physreg dependencies!");
896
897     ReleaseSucc(SU, &*I);
898   }
899 }
900
901 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
902 /// count of its successors. If a successor pending count is zero, add it to
903 /// the Available queue.
904 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
905   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
906   DEBUG(SU->dump(this));
907
908   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
909   SU->setDepthToAtLeast(CurCycle);
910   Sequence.push_back(SU);
911
912   ReleaseSuccessors(SU);
913   SU->isScheduled = true;
914   AvailableQueue->ScheduledNode(SU);
915 }
916
917 /// ListScheduleTopDown - The main loop of list scheduling for top-down
918 /// schedulers.
919 void ScheduleDAGRRList::ListScheduleTopDown() {
920   unsigned CurCycle = 0;
921   AvailableQueue->setCurCycle(CurCycle);
922
923   // Release any successors of the special Entry node.
924   ReleaseSuccessors(&EntrySU);
925
926   // All leaves to Available queue.
927   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
928     // It is available if it has no predecessors.
929     if (SUnits[i].Preds.empty()) {
930       AvailableQueue->push(&SUnits[i]);
931       SUnits[i].isAvailable = true;
932     }
933   }
934   
935   // While Available queue is not empty, grab the node with the highest
936   // priority. If it is not ready put it back.  Schedule the node.
937   Sequence.reserve(SUnits.size());
938   while (!AvailableQueue->empty()) {
939     SUnit *CurSU = AvailableQueue->pop();
940     
941     if (CurSU)
942       ScheduleNodeTopDown(CurSU, CurCycle);
943     ++CurCycle;
944     AvailableQueue->setCurCycle(CurCycle);
945   }
946   
947 #ifndef NDEBUG
948   VerifySchedule(isBottomUp);
949 #endif
950 }
951
952
953 //===----------------------------------------------------------------------===//
954 //                RegReductionPriorityQueue Implementation
955 //===----------------------------------------------------------------------===//
956 //
957 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
958 // to reduce register pressure.
959 // 
960 namespace {
961   template<class SF>
962   class RegReductionPriorityQueue;
963   
964   /// bu_ls_rr_sort - Priority function for bottom up register pressure
965   // reduction scheduler.
966   struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
967     RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
968     bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
969     bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
970     
971     bool operator()(const SUnit* left, const SUnit* right) const;
972   };
973
974   // td_ls_rr_sort - Priority function for top down register pressure reduction
975   // scheduler.
976   struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
977     RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
978     td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
979     td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
980     
981     bool operator()(const SUnit* left, const SUnit* right) const;
982   };
983
984   // src_ls_rr_sort - Priority function for source order scheduler.
985   struct src_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
986     RegReductionPriorityQueue<src_ls_rr_sort> *SPQ;
987     src_ls_rr_sort(RegReductionPriorityQueue<src_ls_rr_sort> *spq)
988       : SPQ(spq) {}
989     src_ls_rr_sort(const src_ls_rr_sort &RHS)
990       : SPQ(RHS.SPQ) {}
991     
992     bool operator()(const SUnit* left, const SUnit* right) const;
993   };
994
995   // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
996   struct hybrid_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
997     RegReductionPriorityQueue<hybrid_ls_rr_sort> *SPQ;
998     hybrid_ls_rr_sort(RegReductionPriorityQueue<hybrid_ls_rr_sort> *spq)
999       : SPQ(spq) {}
1000     hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1001       : SPQ(RHS.SPQ) {}
1002
1003     bool operator()(const SUnit* left, const SUnit* right) const;
1004   };
1005
1006   // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1007   // scheduler.
1008   struct ilp_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1009     RegReductionPriorityQueue<ilp_ls_rr_sort> *SPQ;
1010     ilp_ls_rr_sort(RegReductionPriorityQueue<ilp_ls_rr_sort> *spq)
1011       : SPQ(spq) {}
1012     ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1013       : SPQ(RHS.SPQ) {}
1014
1015     bool operator()(const SUnit* left, const SUnit* right) const;
1016   };
1017 }  // end anonymous namespace
1018
1019 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1020 /// Smaller number is the higher priority.
1021 static unsigned
1022 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1023   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1024   if (SethiUllmanNumber != 0)
1025     return SethiUllmanNumber;
1026
1027   unsigned Extra = 0;
1028   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1029        I != E; ++I) {
1030     if (I->isCtrl()) continue;  // ignore chain preds
1031     SUnit *PredSU = I->getSUnit();
1032     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1033     if (PredSethiUllman > SethiUllmanNumber) {
1034       SethiUllmanNumber = PredSethiUllman;
1035       Extra = 0;
1036     } else if (PredSethiUllman == SethiUllmanNumber)
1037       ++Extra;
1038   }
1039
1040   SethiUllmanNumber += Extra;
1041
1042   if (SethiUllmanNumber == 0)
1043     SethiUllmanNumber = 1;
1044   
1045   return SethiUllmanNumber;
1046 }
1047
1048 namespace {
1049   template<class SF>
1050   class RegReductionPriorityQueue : public SchedulingPriorityQueue {
1051     std::vector<SUnit*> Queue;
1052     SF Picker;
1053     unsigned CurQueueId;
1054     bool TracksRegPressure;
1055
1056   protected:
1057     // SUnits - The SUnits for the current graph.
1058     std::vector<SUnit> *SUnits;
1059
1060     MachineFunction &MF;
1061     const TargetInstrInfo *TII;
1062     const TargetRegisterInfo *TRI;
1063     const TargetLowering *TLI;
1064     ScheduleDAGRRList *scheduleDAG;
1065
1066     // SethiUllmanNumbers - The SethiUllman number for each node.
1067     std::vector<unsigned> SethiUllmanNumbers;
1068
1069     /// RegPressure - Tracking current reg pressure per register class.
1070     ///
1071     std::vector<unsigned> RegPressure;
1072
1073     /// RegLimit - Tracking the number of allocatable registers per register
1074     /// class.
1075     std::vector<unsigned> RegLimit;
1076
1077   public:
1078     RegReductionPriorityQueue(MachineFunction &mf,
1079                               bool tracksrp,
1080                               const TargetInstrInfo *tii,
1081                               const TargetRegisterInfo *tri,
1082                               const TargetLowering *tli)
1083       : Picker(this), CurQueueId(0), TracksRegPressure(tracksrp),
1084         MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1085       if (TracksRegPressure) {
1086         unsigned NumRC = TRI->getNumRegClasses();
1087         RegLimit.resize(NumRC);
1088         RegPressure.resize(NumRC);
1089         std::fill(RegLimit.begin(), RegLimit.end(), 0);
1090         std::fill(RegPressure.begin(), RegPressure.end(), 0);
1091         for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1092                E = TRI->regclass_end(); I != E; ++I)
1093           RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1094       }
1095     }
1096     
1097     void initNodes(std::vector<SUnit> &sunits) {
1098       SUnits = &sunits;
1099       // Add pseudo dependency edges for two-address nodes.
1100       AddPseudoTwoAddrDeps();
1101       // Reroute edges to nodes with multiple uses.
1102       PrescheduleNodesWithMultipleUses();
1103       // Calculate node priorities.
1104       CalculateSethiUllmanNumbers();
1105     }
1106
1107     void addNode(const SUnit *SU) {
1108       unsigned SUSize = SethiUllmanNumbers.size();
1109       if (SUnits->size() > SUSize)
1110         SethiUllmanNumbers.resize(SUSize*2, 0);
1111       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1112     }
1113
1114     void updateNode(const SUnit *SU) {
1115       SethiUllmanNumbers[SU->NodeNum] = 0;
1116       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1117     }
1118
1119     void releaseState() {
1120       SUnits = 0;
1121       SethiUllmanNumbers.clear();
1122       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1123     }
1124
1125     unsigned getNodePriority(const SUnit *SU) const {
1126       assert(SU->NodeNum < SethiUllmanNumbers.size());
1127       unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1128       if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1129         // CopyToReg should be close to its uses to facilitate coalescing and
1130         // avoid spilling.
1131         return 0;
1132       if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1133           Opc == TargetOpcode::SUBREG_TO_REG ||
1134           Opc == TargetOpcode::INSERT_SUBREG)
1135         // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1136         // close to their uses to facilitate coalescing.
1137         return 0;
1138       if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1139         // If SU does not have a register use, i.e. it doesn't produce a value
1140         // that would be consumed (e.g. store), then it terminates a chain of
1141         // computation.  Give it a large SethiUllman number so it will be
1142         // scheduled right before its predecessors that it doesn't lengthen
1143         // their live ranges.
1144         return 0xffff;
1145       if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1146         // If SU does not have a register def, schedule it close to its uses
1147         // because it does not lengthen any live ranges.
1148         return 0;
1149       return SethiUllmanNumbers[SU->NodeNum];
1150     }
1151
1152     unsigned getNodeOrdering(const SUnit *SU) const {
1153       return scheduleDAG->DAG->GetOrdering(SU->getNode());
1154     }
1155
1156     bool empty() const { return Queue.empty(); }
1157     
1158     void push(SUnit *U) {
1159       assert(!U->NodeQueueId && "Node in the queue already");
1160       U->NodeQueueId = ++CurQueueId;
1161       Queue.push_back(U);
1162     }
1163
1164     SUnit *pop() {
1165       if (empty()) return NULL;
1166       std::vector<SUnit *>::iterator Best = Queue.begin();
1167       for (std::vector<SUnit *>::iterator I = llvm::next(Queue.begin()),
1168            E = Queue.end(); I != E; ++I)
1169         if (Picker(*Best, *I))
1170           Best = I;
1171       SUnit *V = *Best;
1172       if (Best != prior(Queue.end()))
1173         std::swap(*Best, Queue.back());
1174       Queue.pop_back();
1175       V->NodeQueueId = 0;
1176       return V;
1177     }
1178
1179     void remove(SUnit *SU) {
1180       assert(!Queue.empty() && "Queue is empty!");
1181       assert(SU->NodeQueueId != 0 && "Not in queue!");
1182       std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1183                                                    SU);
1184       if (I != prior(Queue.end()))
1185         std::swap(*I, Queue.back());
1186       Queue.pop_back();
1187       SU->NodeQueueId = 0;
1188     }
1189
1190     bool HighRegPressure(const SUnit *SU) const {
1191       if (!TLI)
1192         return false;
1193
1194       for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1195            I != E; ++I) {
1196         if (I->isCtrl())
1197           continue;
1198         SUnit *PredSU = I->getSUnit();
1199         const SDNode *PN = PredSU->getNode();
1200         if (!PN->isMachineOpcode()) {
1201           if (PN->getOpcode() == ISD::CopyFromReg) {
1202             EVT VT = PN->getValueType(0);
1203             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1204             unsigned Cost = TLI->getRepRegClassCostFor(VT);
1205             if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1206               return true;
1207           }
1208           continue;
1209         }
1210         unsigned POpc = PN->getMachineOpcode();
1211         if (POpc == TargetOpcode::IMPLICIT_DEF)
1212           continue;
1213         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1214           EVT VT = PN->getOperand(0).getValueType();
1215           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1216           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1217           // Check if this increases register pressure of the specific register
1218           // class to the point where it would cause spills.
1219           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1220             return true;
1221           continue;            
1222         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1223                    POpc == TargetOpcode::SUBREG_TO_REG) {
1224           EVT VT = PN->getValueType(0);
1225           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1226           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1227           // Check if this increases register pressure of the specific register
1228           // class to the point where it would cause spills.
1229           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1230             return true;
1231           continue;
1232         }
1233         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1234         for (unsigned i = 0; i != NumDefs; ++i) {
1235           EVT VT = PN->getValueType(i);
1236           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1237           if (RegPressure[RCId] >= RegLimit[RCId])
1238             return true; // Reg pressure already high.
1239           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1240           if (!PN->hasAnyUseOfValue(i))
1241             continue;
1242           // Check if this increases register pressure of the specific register
1243           // class to the point where it would cause spills.
1244           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1245             return true;
1246         }
1247       }
1248
1249       return false;
1250     }
1251
1252     void ScheduledNode(SUnit *SU) {
1253       if (!TracksRegPressure)
1254         return;
1255
1256       const SDNode *N = SU->getNode();
1257       if (!N->isMachineOpcode()) {
1258         if (N->getOpcode() != ISD::CopyToReg)
1259           return;
1260       } else {
1261         unsigned Opc = N->getMachineOpcode();
1262         if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1263             Opc == TargetOpcode::INSERT_SUBREG ||
1264             Opc == TargetOpcode::SUBREG_TO_REG ||
1265             Opc == TargetOpcode::REG_SEQUENCE ||
1266             Opc == TargetOpcode::IMPLICIT_DEF)
1267           return;
1268       }
1269
1270       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1271            I != E; ++I) {
1272         if (I->isCtrl())
1273           continue;
1274         SUnit *PredSU = I->getSUnit();
1275         if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
1276           continue;
1277         const SDNode *PN = PredSU->getNode();
1278         if (!PN->isMachineOpcode()) {
1279           if (PN->getOpcode() == ISD::CopyFromReg) {
1280             EVT VT = PN->getValueType(0);
1281             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1282             RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1283           }
1284           continue;
1285         }
1286         unsigned POpc = PN->getMachineOpcode();
1287         if (POpc == TargetOpcode::IMPLICIT_DEF)
1288           continue;
1289         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1290           EVT VT = PN->getOperand(0).getValueType();
1291           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1292           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1293           continue;            
1294         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1295                    POpc == TargetOpcode::SUBREG_TO_REG) {
1296           EVT VT = PN->getValueType(0);
1297           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1298           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1299           continue;
1300         }
1301         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1302         for (unsigned i = 0; i != NumDefs; ++i) {
1303           EVT VT = PN->getValueType(i);
1304           if (!PN->hasAnyUseOfValue(i))
1305             continue;
1306           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1307           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1308         }
1309       }
1310
1311       // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1312       // may transfer data dependencies to CopyToReg.
1313       if (SU->NumSuccs && N->isMachineOpcode()) {
1314         unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1315         for (unsigned i = 0; i != NumDefs; ++i) {
1316           EVT VT = N->getValueType(i);
1317           if (!N->hasAnyUseOfValue(i))
1318             continue;
1319           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1320           if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1321             // Register pressure tracking is imprecise. This can happen.
1322             RegPressure[RCId] = 0;
1323           else
1324             RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1325         }
1326       }
1327
1328       dumpRegPressure();
1329     }
1330
1331     void UnscheduledNode(SUnit *SU) {
1332       if (!TracksRegPressure)
1333         return;
1334
1335       const SDNode *N = SU->getNode();
1336       if (!N->isMachineOpcode()) {
1337         if (N->getOpcode() != ISD::CopyToReg)
1338           return;
1339       } else {
1340         unsigned Opc = N->getMachineOpcode();
1341         if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1342             Opc == TargetOpcode::INSERT_SUBREG ||
1343             Opc == TargetOpcode::SUBREG_TO_REG ||
1344             Opc == TargetOpcode::REG_SEQUENCE ||
1345             Opc == TargetOpcode::IMPLICIT_DEF)
1346           return;
1347       }
1348
1349       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1350            I != E; ++I) {
1351         if (I->isCtrl())
1352           continue;
1353         SUnit *PredSU = I->getSUnit();
1354         if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
1355           continue;
1356         const SDNode *PN = PredSU->getNode();
1357         if (!PN->isMachineOpcode()) {
1358           if (PN->getOpcode() == ISD::CopyFromReg) {
1359             EVT VT = PN->getValueType(0);
1360             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1361             RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1362           }
1363           continue;
1364         }
1365         unsigned POpc = PN->getMachineOpcode();
1366         if (POpc == TargetOpcode::IMPLICIT_DEF)
1367           continue;
1368         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1369           EVT VT = PN->getOperand(0).getValueType();
1370           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1371           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1372           continue;            
1373         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1374                    POpc == TargetOpcode::SUBREG_TO_REG) {
1375           EVT VT = PN->getValueType(0);
1376           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1377           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1378           continue;
1379         }
1380         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1381         for (unsigned i = 0; i != NumDefs; ++i) {
1382           EVT VT = PN->getValueType(i);
1383           if (!PN->hasAnyUseOfValue(i))
1384             continue;
1385           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1386           if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1387             // Register pressure tracking is imprecise. This can happen.
1388             RegPressure[RCId] = 0;
1389           else
1390             RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1391         }
1392       }
1393
1394       // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1395       // may transfer data dependencies to CopyToReg.
1396       if (SU->NumSuccs && N->isMachineOpcode()) {
1397         unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1398         for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1399           EVT VT = N->getValueType(i);
1400           if (VT == MVT::Flag || VT == MVT::Other)
1401             continue;
1402           if (!N->hasAnyUseOfValue(i))
1403             continue;
1404           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1405           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1406         }
1407       }
1408
1409       dumpRegPressure();
1410     }
1411
1412     void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 
1413       scheduleDAG = scheduleDag; 
1414     }
1415
1416     void dumpRegPressure() const {
1417       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1418              E = TRI->regclass_end(); I != E; ++I) {
1419         const TargetRegisterClass *RC = *I;
1420         unsigned Id = RC->getID();
1421         unsigned RP = RegPressure[Id];
1422         if (!RP) continue;
1423         DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1424               << '\n');
1425       }
1426     }
1427
1428   protected:
1429     bool canClobber(const SUnit *SU, const SUnit *Op);
1430     void AddPseudoTwoAddrDeps();
1431     void PrescheduleNodesWithMultipleUses();
1432     void CalculateSethiUllmanNumbers();
1433   };
1434
1435   typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1436     BURegReductionPriorityQueue;
1437
1438   typedef RegReductionPriorityQueue<td_ls_rr_sort>
1439     TDRegReductionPriorityQueue;
1440
1441   typedef RegReductionPriorityQueue<src_ls_rr_sort>
1442     SrcRegReductionPriorityQueue;
1443
1444   typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1445     HybridBURRPriorityQueue;
1446
1447   typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1448     ILPBURRPriorityQueue;
1449 }
1450
1451 /// closestSucc - Returns the scheduled cycle of the successor which is
1452 /// closest to the current cycle.
1453 static unsigned closestSucc(const SUnit *SU) {
1454   unsigned MaxHeight = 0;
1455   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1456        I != E; ++I) {
1457     if (I->isCtrl()) continue;  // ignore chain succs
1458     unsigned Height = I->getSUnit()->getHeight();
1459     // If there are bunch of CopyToRegs stacked up, they should be considered
1460     // to be at the same position.
1461     if (I->getSUnit()->getNode() &&
1462         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1463       Height = closestSucc(I->getSUnit())+1;
1464     if (Height > MaxHeight)
1465       MaxHeight = Height;
1466   }
1467   return MaxHeight;
1468 }
1469
1470 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1471 /// for scratch registers, i.e. number of data dependencies.
1472 static unsigned calcMaxScratches(const SUnit *SU) {
1473   unsigned Scratches = 0;
1474   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1475        I != E; ++I) {
1476     if (I->isCtrl()) continue;  // ignore chain preds
1477     Scratches++;
1478   }
1479   return Scratches;
1480 }
1481
1482 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1483 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1484 /// it has no other use. It should be scheduled closer to the terminator.
1485 static bool hasOnlyLiveOutUses(const SUnit *SU) {
1486   bool RetVal = false;
1487   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1488        I != E; ++I) {
1489     if (I->isCtrl()) continue;
1490     const SUnit *SuccSU = I->getSUnit();
1491     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1492       unsigned Reg =
1493         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1494       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1495         RetVal = true;
1496         continue;
1497       }
1498     }
1499     return false;
1500   }
1501   return RetVal;
1502 }
1503
1504 /// UnitsSharePred - Return true if the two scheduling units share a common
1505 /// data predecessor.
1506 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1507   SmallSet<const SUnit*, 4> Preds;
1508   for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1509        I != E; ++I) {
1510     if (I->isCtrl()) continue;  // ignore chain preds
1511     Preds.insert(I->getSUnit());
1512   }
1513   for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1514        I != E; ++I) {
1515     if (I->isCtrl()) continue;  // ignore chain preds
1516     if (Preds.count(I->getSUnit()))
1517       return true;
1518   }
1519   return false;
1520 }
1521
1522 template <typename RRSort>
1523 static bool BURRSort(const SUnit *left, const SUnit *right,
1524                      const RegReductionPriorityQueue<RRSort> *SPQ) {
1525   unsigned LPriority = SPQ->getNodePriority(left);
1526   unsigned RPriority = SPQ->getNodePriority(right);
1527   if (LPriority != RPriority)
1528     return LPriority > RPriority;
1529
1530   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1531   // e.g.
1532   // t1 = op t2, c1
1533   // t3 = op t4, c2
1534   //
1535   // and the following instructions are both ready.
1536   // t2 = op c3
1537   // t4 = op c4
1538   //
1539   // Then schedule t2 = op first.
1540   // i.e.
1541   // t4 = op c4
1542   // t2 = op c3
1543   // t1 = op t2, c1
1544   // t3 = op t4, c2
1545   //
1546   // This creates more short live intervals.
1547   unsigned LDist = closestSucc(left);
1548   unsigned RDist = closestSucc(right);
1549   if (LDist != RDist)
1550     return LDist < RDist;
1551
1552   // How many registers becomes live when the node is scheduled.
1553   unsigned LScratch = calcMaxScratches(left);
1554   unsigned RScratch = calcMaxScratches(right);
1555   if (LScratch != RScratch)
1556     return LScratch > RScratch;
1557
1558   if (left->getHeight() != right->getHeight())
1559     return left->getHeight() > right->getHeight();
1560   
1561   if (left->getDepth() != right->getDepth())
1562     return left->getDepth() < right->getDepth();
1563
1564   assert(left->NodeQueueId && right->NodeQueueId && 
1565          "NodeQueueId cannot be zero");
1566   return (left->NodeQueueId > right->NodeQueueId);
1567 }
1568
1569 // Bottom up
1570 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1571   return BURRSort(left, right, SPQ);
1572 }
1573
1574 // Source order, otherwise bottom up.
1575 bool src_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1576   unsigned LOrder = SPQ->getNodeOrdering(left);
1577   unsigned ROrder = SPQ->getNodeOrdering(right);
1578
1579   // Prefer an ordering where the lower the non-zero order number, the higher
1580   // the preference.
1581   if ((LOrder || ROrder) && LOrder != ROrder)
1582     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
1583
1584   return BURRSort(left, right, SPQ);
1585 }
1586
1587 bool hybrid_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const{
1588   if (left->isCall || right->isCall)
1589     // No way to compute latency of calls.
1590     return BURRSort(left, right, SPQ);
1591
1592   bool LHigh = SPQ->HighRegPressure(left);
1593   bool RHigh = SPQ->HighRegPressure(right);
1594   // Avoid causing spills. If register pressure is high, schedule for
1595   // register pressure reduction.
1596   if (LHigh && !RHigh)
1597     return true;
1598   else if (!LHigh && RHigh)
1599     return false;
1600   else if (!LHigh && !RHigh) {
1601     // If the two nodes share an operand and one of them has a single
1602     // use that is a live out copy, favor the one that is live out. Otherwise
1603     // it will be difficult to eliminate the copy if the instruction is a
1604     // loop induction variable update. e.g.
1605     // BB:
1606     // sub r1, r3, #1
1607     // str r0, [r2, r3]
1608     // mov r3, r1
1609     // cmp
1610     // bne BB
1611     bool SharePred = UnitsSharePred(left, right);
1612     // FIXME: Only adjust if BB is a loop back edge.
1613     // FIXME: What's the cost of a copy?
1614     int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1615     int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1616     int LHeight = (int)left->getHeight() - LBonus;
1617     int RHeight = (int)right->getHeight() - RBonus;
1618
1619     // Low register pressure situation, schedule for latency if possible.
1620     bool LStall = left->SchedulingPref == Sched::Latency &&
1621       (int)SPQ->getCurCycle() < LHeight;
1622     bool RStall = right->SchedulingPref == Sched::Latency &&
1623       (int)SPQ->getCurCycle() < RHeight;
1624     // If scheduling one of the node will cause a pipeline stall, delay it.
1625     // If scheduling either one of the node will cause a pipeline stall, sort
1626     // them according to their height.
1627     if (LStall) {
1628       if (!RStall)
1629         return true;
1630       if (LHeight != RHeight)
1631         return LHeight > RHeight;
1632     } else if (RStall)
1633       return false;
1634
1635     // If either node is scheduling for latency, sort them by height
1636     // and latency.
1637     if (left->SchedulingPref == Sched::Latency ||
1638         right->SchedulingPref == Sched::Latency) {
1639       if (LHeight != RHeight)
1640         return LHeight > RHeight;
1641       if (left->Latency != right->Latency)
1642         return left->Latency > right->Latency;
1643     }
1644   }
1645
1646   return BURRSort(left, right, SPQ);
1647 }
1648
1649 bool ilp_ls_rr_sort::operator()(const SUnit *left,
1650                                 const SUnit *right) const {
1651   if (left->isCall || right->isCall)
1652     // No way to compute latency of calls.
1653     return BURRSort(left, right, SPQ);
1654
1655   bool LHigh = SPQ->HighRegPressure(left);
1656   bool RHigh = SPQ->HighRegPressure(right);
1657   // Avoid causing spills. If register pressure is high, schedule for
1658   // register pressure reduction.
1659   if (LHigh && !RHigh)
1660     return true;
1661   else if (!LHigh && RHigh)
1662     return false;
1663   else if (!LHigh && !RHigh) {
1664     // Low register pressure situation, schedule to maximize instruction level
1665     // parallelism.
1666     if (left->NumPreds > right->NumPreds)
1667       return false;
1668     else if (left->NumPreds < right->NumPreds)
1669       return false;
1670   }
1671
1672   return BURRSort(left, right, SPQ);
1673 }
1674
1675 template<class SF>
1676 bool
1677 RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1678   if (SU->isTwoAddress) {
1679     unsigned Opc = SU->getNode()->getMachineOpcode();
1680     const TargetInstrDesc &TID = TII->get(Opc);
1681     unsigned NumRes = TID.getNumDefs();
1682     unsigned NumOps = TID.getNumOperands() - NumRes;
1683     for (unsigned i = 0; i != NumOps; ++i) {
1684       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1685         SDNode *DU = SU->getNode()->getOperand(i).getNode();
1686         if (DU->getNodeId() != -1 &&
1687             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1688           return true;
1689       }
1690     }
1691   }
1692   return false;
1693 }
1694
1695 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1696 /// physical register defs.
1697 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1698                                   const TargetInstrInfo *TII,
1699                                   const TargetRegisterInfo *TRI) {
1700   SDNode *N = SuccSU->getNode();
1701   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1702   const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1703   assert(ImpDefs && "Caller should check hasPhysRegDefs");
1704   for (const SDNode *SUNode = SU->getNode(); SUNode;
1705        SUNode = SUNode->getFlaggedNode()) {
1706     if (!SUNode->isMachineOpcode())
1707       continue;
1708     const unsigned *SUImpDefs =
1709       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
1710     if (!SUImpDefs)
1711       return false;
1712     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1713       EVT VT = N->getValueType(i);
1714       if (VT == MVT::Flag || VT == MVT::Other)
1715         continue;
1716       if (!N->hasAnyUseOfValue(i))
1717         continue;
1718       unsigned Reg = ImpDefs[i - NumDefs];
1719       for (;*SUImpDefs; ++SUImpDefs) {
1720         unsigned SUReg = *SUImpDefs;
1721         if (TRI->regsOverlap(Reg, SUReg))
1722           return true;
1723       }
1724     }
1725   }
1726   return false;
1727 }
1728
1729 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
1730 /// are not handled well by the general register pressure reduction
1731 /// heuristics. When presented with code like this:
1732 ///
1733 ///      N
1734 ///    / |
1735 ///   /  |
1736 ///  U  store
1737 ///  |
1738 /// ...
1739 ///
1740 /// the heuristics tend to push the store up, but since the
1741 /// operand of the store has another use (U), this would increase
1742 /// the length of that other use (the U->N edge).
1743 ///
1744 /// This function transforms code like the above to route U's
1745 /// dependence through the store when possible, like this:
1746 ///
1747 ///      N
1748 ///      ||
1749 ///      ||
1750 ///     store
1751 ///       |
1752 ///       U
1753 ///       |
1754 ///      ...
1755 ///
1756 /// This results in the store being scheduled immediately
1757 /// after N, which shortens the U->N live range, reducing
1758 /// register pressure.
1759 ///
1760 template<class SF>
1761 void RegReductionPriorityQueue<SF>::PrescheduleNodesWithMultipleUses() {
1762   // Visit all the nodes in topological order, working top-down.
1763   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1764     SUnit *SU = &(*SUnits)[i];
1765     // For now, only look at nodes with no data successors, such as stores.
1766     // These are especially important, due to the heuristics in
1767     // getNodePriority for nodes with no data successors.
1768     if (SU->NumSuccs != 0)
1769       continue;
1770     // For now, only look at nodes with exactly one data predecessor.
1771     if (SU->NumPreds != 1)
1772       continue;
1773     // Avoid prescheduling copies to virtual registers, which don't behave
1774     // like other nodes from the perspective of scheduling heuristics.
1775     if (SDNode *N = SU->getNode())
1776       if (N->getOpcode() == ISD::CopyToReg &&
1777           TargetRegisterInfo::isVirtualRegister
1778             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
1779         continue;
1780
1781     // Locate the single data predecessor.
1782     SUnit *PredSU = 0;
1783     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
1784          EE = SU->Preds.end(); II != EE; ++II)
1785       if (!II->isCtrl()) {
1786         PredSU = II->getSUnit();
1787         break;
1788       }
1789     assert(PredSU);
1790
1791     // Don't rewrite edges that carry physregs, because that requires additional
1792     // support infrastructure.
1793     if (PredSU->hasPhysRegDefs)
1794       continue;
1795     // Short-circuit the case where SU is PredSU's only data successor.
1796     if (PredSU->NumSuccs == 1)
1797       continue;
1798     // Avoid prescheduling to copies from virtual registers, which don't behave
1799     // like other nodes from the perspective of scheduling // heuristics.
1800     if (SDNode *N = SU->getNode())
1801       if (N->getOpcode() == ISD::CopyFromReg &&
1802           TargetRegisterInfo::isVirtualRegister
1803             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
1804         continue;
1805
1806     // Perform checks on the successors of PredSU.
1807     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
1808          EE = PredSU->Succs.end(); II != EE; ++II) {
1809       SUnit *PredSuccSU = II->getSUnit();
1810       if (PredSuccSU == SU) continue;
1811       // If PredSU has another successor with no data successors, for
1812       // now don't attempt to choose either over the other.
1813       if (PredSuccSU->NumSuccs == 0)
1814         goto outer_loop_continue;
1815       // Don't break physical register dependencies.
1816       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
1817         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
1818           goto outer_loop_continue;
1819       // Don't introduce graph cycles.
1820       if (scheduleDAG->IsReachable(SU, PredSuccSU))
1821         goto outer_loop_continue;
1822     }
1823
1824     // Ok, the transformation is safe and the heuristics suggest it is
1825     // profitable. Update the graph.
1826     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
1827                  << " next to PredSU #" << PredSU->NodeNum
1828                  << " to guide scheduling in the presence of multiple uses\n");
1829     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
1830       SDep Edge = PredSU->Succs[i];
1831       assert(!Edge.isAssignedRegDep());
1832       SUnit *SuccSU = Edge.getSUnit();
1833       if (SuccSU != SU) {
1834         Edge.setSUnit(PredSU);
1835         scheduleDAG->RemovePred(SuccSU, Edge);
1836         scheduleDAG->AddPred(SU, Edge);
1837         Edge.setSUnit(SU);
1838         scheduleDAG->AddPred(SuccSU, Edge);
1839         --i;
1840       }
1841     }
1842   outer_loop_continue:;
1843   }
1844 }
1845
1846 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1847 /// it as a def&use operand. Add a pseudo control edge from it to the other
1848 /// node (if it won't create a cycle) so the two-address one will be scheduled
1849 /// first (lower in the schedule). If both nodes are two-address, favor the
1850 /// one that has a CopyToReg use (more likely to be a loop induction update).
1851 /// If both are two-address, but one is commutable while the other is not
1852 /// commutable, favor the one that's not commutable.
1853 template<class SF>
1854 void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1855   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1856     SUnit *SU = &(*SUnits)[i];
1857     if (!SU->isTwoAddress)
1858       continue;
1859
1860     SDNode *Node = SU->getNode();
1861     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1862       continue;
1863
1864     bool isLiveOut = hasOnlyLiveOutUses(SU);
1865     unsigned Opc = Node->getMachineOpcode();
1866     const TargetInstrDesc &TID = TII->get(Opc);
1867     unsigned NumRes = TID.getNumDefs();
1868     unsigned NumOps = TID.getNumOperands() - NumRes;
1869     for (unsigned j = 0; j != NumOps; ++j) {
1870       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1871         continue;
1872       SDNode *DU = SU->getNode()->getOperand(j).getNode();
1873       if (DU->getNodeId() == -1)
1874         continue;
1875       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1876       if (!DUSU) continue;
1877       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1878            E = DUSU->Succs.end(); I != E; ++I) {
1879         if (I->isCtrl()) continue;
1880         SUnit *SuccSU = I->getSUnit();
1881         if (SuccSU == SU)
1882           continue;
1883         // Be conservative. Ignore if nodes aren't at roughly the same
1884         // depth and height.
1885         if (SuccSU->getHeight() < SU->getHeight() &&
1886             (SU->getHeight() - SuccSU->getHeight()) > 1)
1887           continue;
1888         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
1889         // constrains whatever is using the copy, instead of the copy
1890         // itself. In the case that the copy is coalesced, this
1891         // preserves the intent of the pseudo two-address heurietics.
1892         while (SuccSU->Succs.size() == 1 &&
1893                SuccSU->getNode()->isMachineOpcode() &&
1894                SuccSU->getNode()->getMachineOpcode() ==
1895                  TargetOpcode::COPY_TO_REGCLASS)
1896           SuccSU = SuccSU->Succs.front().getSUnit();
1897         // Don't constrain non-instruction nodes.
1898         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1899           continue;
1900         // Don't constrain nodes with physical register defs if the
1901         // predecessor can clobber them.
1902         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
1903           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1904             continue;
1905         }
1906         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
1907         // these may be coalesced away. We want them close to their uses.
1908         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1909         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
1910             SuccOpc == TargetOpcode::INSERT_SUBREG ||
1911             SuccOpc == TargetOpcode::SUBREG_TO_REG)
1912           continue;
1913         if ((!canClobber(SuccSU, DUSU) ||
1914              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
1915              (!SU->isCommutable && SuccSU->isCommutable)) &&
1916             !scheduleDAG->IsReachable(SuccSU, SU)) {
1917           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
1918                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
1919           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
1920                                         /*Reg=*/0, /*isNormalMemory=*/false,
1921                                         /*isMustAlias=*/false,
1922                                         /*isArtificial=*/true));
1923         }
1924       }
1925     }
1926   }
1927 }
1928
1929 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1930 /// scheduling units.
1931 template<class SF>
1932 void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1933   SethiUllmanNumbers.assign(SUnits->size(), 0);
1934   
1935   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1936     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1937 }
1938
1939 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1940 /// predecessors of the successors of the SUnit SU. Stop when the provided
1941 /// limit is exceeded.
1942 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU, 
1943                                                     unsigned Limit) {
1944   unsigned Sum = 0;
1945   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1946        I != E; ++I) {
1947     const SUnit *SuccSU = I->getSUnit();
1948     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1949          EE = SuccSU->Preds.end(); II != EE; ++II) {
1950       SUnit *PredSU = II->getSUnit();
1951       if (!PredSU->isScheduled)
1952         if (++Sum > Limit)
1953           return Sum;
1954     }
1955   }
1956   return Sum;
1957 }
1958
1959
1960 // Top down
1961 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1962   unsigned LPriority = SPQ->getNodePriority(left);
1963   unsigned RPriority = SPQ->getNodePriority(right);
1964   bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1965   bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1966   bool LIsFloater = LIsTarget && left->NumPreds == 0;
1967   bool RIsFloater = RIsTarget && right->NumPreds == 0;
1968   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1969   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1970
1971   if (left->NumSuccs == 0 && right->NumSuccs != 0)
1972     return false;
1973   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1974     return true;
1975
1976   if (LIsFloater)
1977     LBonus -= 2;
1978   if (RIsFloater)
1979     RBonus -= 2;
1980   if (left->NumSuccs == 1)
1981     LBonus += 2;
1982   if (right->NumSuccs == 1)
1983     RBonus += 2;
1984
1985   if (LPriority+LBonus != RPriority+RBonus)
1986     return LPriority+LBonus < RPriority+RBonus;
1987
1988   if (left->getDepth() != right->getDepth())
1989     return left->getDepth() < right->getDepth();
1990
1991   if (left->NumSuccsLeft != right->NumSuccsLeft)
1992     return left->NumSuccsLeft > right->NumSuccsLeft;
1993
1994   assert(left->NodeQueueId && right->NodeQueueId && 
1995          "NodeQueueId cannot be zero");
1996   return (left->NodeQueueId > right->NodeQueueId);
1997 }
1998
1999 //===----------------------------------------------------------------------===//
2000 //                         Public Constructor Functions
2001 //===----------------------------------------------------------------------===//
2002
2003 llvm::ScheduleDAGSDNodes *
2004 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2005   const TargetMachine &TM = IS->TM;
2006   const TargetInstrInfo *TII = TM.getInstrInfo();
2007   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2008   
2009   BURegReductionPriorityQueue *PQ =
2010     new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2011   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, false, PQ);
2012   PQ->setScheduleDAG(SD);
2013   return SD;  
2014 }
2015
2016 llvm::ScheduleDAGSDNodes *
2017 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2018   const TargetMachine &TM = IS->TM;
2019   const TargetInstrInfo *TII = TM.getInstrInfo();
2020   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2021   
2022   TDRegReductionPriorityQueue *PQ =
2023     new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2024   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, false, PQ);
2025   PQ->setScheduleDAG(SD);
2026   return SD;
2027 }
2028
2029 llvm::ScheduleDAGSDNodes *
2030 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2031   const TargetMachine &TM = IS->TM;
2032   const TargetInstrInfo *TII = TM.getInstrInfo();
2033   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2034   
2035   SrcRegReductionPriorityQueue *PQ =
2036     new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2037   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, false, PQ);
2038   PQ->setScheduleDAG(SD);
2039   return SD;  
2040 }
2041
2042 llvm::ScheduleDAGSDNodes *
2043 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2044   const TargetMachine &TM = IS->TM;
2045   const TargetInstrInfo *TII = TM.getInstrInfo();
2046   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2047   const TargetLowering *TLI = &IS->getTargetLowering();
2048   
2049   HybridBURRPriorityQueue *PQ =
2050     new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2051   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, true, PQ);
2052   PQ->setScheduleDAG(SD);
2053   return SD;  
2054 }
2055
2056 llvm::ScheduleDAGSDNodes *
2057 llvm::createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2058   const TargetMachine &TM = IS->TM;
2059   const TargetInstrInfo *TII = TM.getInstrInfo();
2060   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2061   const TargetLowering *TLI = &IS->getTargetLowering();
2062   
2063   ILPBURRPriorityQueue *PQ =
2064     new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2065   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, true, PQ);
2066   PQ->setScheduleDAG(SD);
2067   return SD;  
2068 }