Fix crashes when scheduling a CopyToReg node -- getMachineOpcode asserts on
[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         << " **********\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 bool 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   bool Added = false;
642   if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != SU) {
643     if (RegAdded.insert(Reg)) {
644       LRegs.push_back(Reg);
645       Added = true;
646     }
647   }
648   for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
649     if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
650       if (RegAdded.insert(*Alias)) {
651         LRegs.push_back(*Alias);
652         Added = true;
653       }
654     }
655   return Added;
656 }
657
658 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
659 /// scheduling of the given node to satisfy live physical register dependencies.
660 /// If the specific node is the last one that's available to schedule, do
661 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
662 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
663                                                  SmallVector<unsigned, 4> &LRegs){
664   if (NumLiveRegs == 0)
665     return false;
666
667   SmallSet<unsigned, 4> RegAdded;
668   // If this node would clobber any "live" register, then it's not ready.
669   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
670        I != E; ++I) {
671     if (I->isAssignedRegDep())
672       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
673                          RegAdded, LRegs, TRI);
674   }
675
676   for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
677     if (Node->getOpcode() == ISD::INLINEASM) {
678       // Inline asm can clobber physical defs.
679       unsigned NumOps = Node->getNumOperands();
680       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
681         --NumOps;  // Ignore the flag operand.
682
683       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
684         unsigned Flags =
685           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
686         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
687
688         ++i; // Skip the ID value.
689         if (InlineAsm::isRegDefKind(Flags) ||
690             InlineAsm::isRegDefEarlyClobberKind(Flags)) {
691           // Check for def of register or earlyclobber register.
692           for (; NumVals; --NumVals, ++i) {
693             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
694             if (TargetRegisterInfo::isPhysicalRegister(Reg))
695               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
696           }
697         } else
698           i += NumVals;
699       }
700       continue;
701     }
702
703     if (!Node->isMachineOpcode())
704       continue;
705     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
706     if (!TID.ImplicitDefs)
707       continue;
708     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
709       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
710   }
711   return !LRegs.empty();
712 }
713
714
715 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
716 /// schedulers.
717 void ScheduleDAGRRList::ListScheduleBottomUp() {
718   unsigned CurCycle = 0;
719
720   // Release any predecessors of the special Exit node.
721   ReleasePredecessors(&ExitSU, CurCycle);
722
723   // Add root to Available queue.
724   if (!SUnits.empty()) {
725     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
726     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
727     RootSU->isAvailable = true;
728     AvailableQueue->push(RootSU);
729   }
730
731   // While Available queue is not empty, grab the node with the highest
732   // priority. If it is not ready put it back.  Schedule the node.
733   SmallVector<SUnit*, 4> NotReady;
734   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
735   Sequence.reserve(SUnits.size());
736   while (!AvailableQueue->empty()) {
737     bool Delayed = false;
738     LRegsMap.clear();
739     SUnit *CurSU = AvailableQueue->pop();
740     while (CurSU) {
741       SmallVector<unsigned, 4> LRegs;
742       if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
743         break;
744       Delayed = true;
745       LRegsMap.insert(std::make_pair(CurSU, LRegs));
746
747       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
748       NotReady.push_back(CurSU);
749       CurSU = AvailableQueue->pop();
750     }
751
752     // All candidates are delayed due to live physical reg dependencies.
753     // Try backtracking, code duplication, or inserting cross class copies
754     // to resolve it.
755     if (Delayed && !CurSU) {
756       for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
757         SUnit *TrySU = NotReady[i];
758         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
759
760         // Try unscheduling up to the point where it's safe to schedule
761         // this node.
762         unsigned LiveCycle = CurCycle;
763         for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
764           unsigned Reg = LRegs[j];
765           unsigned LCycle = LiveRegCycles[Reg];
766           LiveCycle = std::min(LiveCycle, LCycle);
767         }
768         SUnit *OldSU = Sequence[LiveCycle];
769         if (!WillCreateCycle(TrySU, OldSU))  {
770           BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
771           // Force the current node to be scheduled before the node that
772           // requires the physical reg dep.
773           if (OldSU->isAvailable) {
774             OldSU->isAvailable = false;
775             AvailableQueue->remove(OldSU);
776           }
777           AddPred(TrySU, SDep(OldSU, SDep::Order, /*Latency=*/1,
778                               /*Reg=*/0, /*isNormalMemory=*/false,
779                               /*isMustAlias=*/false, /*isArtificial=*/true));
780           // If one or more successors has been unscheduled, then the current
781           // node is no longer avaialable. Schedule a successor that's now
782           // available instead.
783           if (!TrySU->isAvailable)
784             CurSU = AvailableQueue->pop();
785           else {
786             CurSU = TrySU;
787             TrySU->isPending = false;
788             NotReady.erase(NotReady.begin()+i);
789           }
790           break;
791         }
792       }
793
794       if (!CurSU) {
795         // Can't backtrack. If it's too expensive to copy the value, then try
796         // duplicate the nodes that produces these "too expensive to copy"
797         // values to break the dependency. In case even that doesn't work,
798         // insert cross class copies.
799         // If it's not too expensive, i.e. cost != -1, issue copies.
800         SUnit *TrySU = NotReady[0];
801         SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
802         assert(LRegs.size() == 1 && "Can't handle this yet!");
803         unsigned Reg = LRegs[0];
804         SUnit *LRDef = LiveRegDefs[Reg];
805         EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
806         const TargetRegisterClass *RC =
807           TRI->getMinimalPhysRegClass(Reg, VT);
808         const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
809
810         // If cross copy register class is null, then it must be possible copy
811         // the value directly. Do not try duplicate the def.
812         SUnit *NewDef = 0;
813         if (DestRC)
814           NewDef = CopyAndMoveSuccessors(LRDef);
815         else
816           DestRC = RC;
817         if (!NewDef) {
818           // Issue copies, these can be expensive cross register class copies.
819           SmallVector<SUnit*, 2> Copies;
820           InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
821           DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
822                        << " to SU #" << Copies.front()->NodeNum << "\n");
823           AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
824                               /*Reg=*/0, /*isNormalMemory=*/false,
825                               /*isMustAlias=*/false,
826                               /*isArtificial=*/true));
827           NewDef = Copies.back();
828         }
829
830         DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
831                      << " to SU #" << TrySU->NodeNum << "\n");
832         LiveRegDefs[Reg] = NewDef;
833         AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
834                              /*Reg=*/0, /*isNormalMemory=*/false,
835                              /*isMustAlias=*/false,
836                              /*isArtificial=*/true));
837         TrySU->isAvailable = false;
838         CurSU = NewDef;
839       }
840
841       assert(CurSU && "Unable to resolve live physical register dependencies!");
842     }
843
844     // Add the nodes that aren't ready back onto the available list.
845     for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
846       NotReady[i]->isPending = false;
847       // May no longer be available due to backtracking.
848       if (NotReady[i]->isAvailable)
849         AvailableQueue->push(NotReady[i]);
850     }
851     NotReady.clear();
852
853     if (CurSU)
854       ScheduleNodeBottomUp(CurSU, CurCycle);
855     ++CurCycle;
856     AvailableQueue->setCurCycle(CurCycle);
857   }
858
859   // Reverse the order if it is bottom up.
860   std::reverse(Sequence.begin(), Sequence.end());
861   
862 #ifndef NDEBUG
863   VerifySchedule(isBottomUp);
864 #endif
865 }
866
867 //===----------------------------------------------------------------------===//
868 //  Top-Down Scheduling
869 //===----------------------------------------------------------------------===//
870
871 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
872 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
873 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
874   SUnit *SuccSU = SuccEdge->getSUnit();
875
876 #ifndef NDEBUG
877   if (SuccSU->NumPredsLeft == 0) {
878     dbgs() << "*** Scheduling failed! ***\n";
879     SuccSU->dump(this);
880     dbgs() << " has been released too many times!\n";
881     llvm_unreachable(0);
882   }
883 #endif
884   --SuccSU->NumPredsLeft;
885
886   // If all the node's predecessors are scheduled, this node is ready
887   // to be scheduled. Ignore the special ExitSU node.
888   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
889     SuccSU->isAvailable = true;
890     AvailableQueue->push(SuccSU);
891   }
892 }
893
894 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
895   // Top down: release successors
896   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
897        I != E; ++I) {
898     assert(!I->isAssignedRegDep() &&
899            "The list-tdrr scheduler doesn't yet support physreg dependencies!");
900
901     ReleaseSucc(SU, &*I);
902   }
903 }
904
905 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
906 /// count of its successors. If a successor pending count is zero, add it to
907 /// the Available queue.
908 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
909   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
910   DEBUG(SU->dump(this));
911
912   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
913   SU->setDepthToAtLeast(CurCycle);
914   Sequence.push_back(SU);
915
916   ReleaseSuccessors(SU);
917   SU->isScheduled = true;
918   AvailableQueue->ScheduledNode(SU);
919 }
920
921 /// ListScheduleTopDown - The main loop of list scheduling for top-down
922 /// schedulers.
923 void ScheduleDAGRRList::ListScheduleTopDown() {
924   unsigned CurCycle = 0;
925   AvailableQueue->setCurCycle(CurCycle);
926
927   // Release any successors of the special Entry node.
928   ReleaseSuccessors(&EntrySU);
929
930   // All leaves to Available queue.
931   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
932     // It is available if it has no predecessors.
933     if (SUnits[i].Preds.empty()) {
934       AvailableQueue->push(&SUnits[i]);
935       SUnits[i].isAvailable = true;
936     }
937   }
938   
939   // While Available queue is not empty, grab the node with the highest
940   // priority. If it is not ready put it back.  Schedule the node.
941   Sequence.reserve(SUnits.size());
942   while (!AvailableQueue->empty()) {
943     SUnit *CurSU = AvailableQueue->pop();
944     
945     if (CurSU)
946       ScheduleNodeTopDown(CurSU, CurCycle);
947     ++CurCycle;
948     AvailableQueue->setCurCycle(CurCycle);
949   }
950   
951 #ifndef NDEBUG
952   VerifySchedule(isBottomUp);
953 #endif
954 }
955
956
957 //===----------------------------------------------------------------------===//
958 //                RegReductionPriorityQueue Implementation
959 //===----------------------------------------------------------------------===//
960 //
961 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
962 // to reduce register pressure.
963 // 
964 namespace {
965   template<class SF>
966   class RegReductionPriorityQueue;
967   
968   /// Sorting functions for the Available queue.
969   struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
970     RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
971     bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
972     bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
973     
974     bool operator()(const SUnit* left, const SUnit* right) const;
975   };
976
977   struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
978     RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
979     td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
980     td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
981     
982     bool operator()(const SUnit* left, const SUnit* right) const;
983   };
984
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   struct hybrid_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
996     RegReductionPriorityQueue<hybrid_ls_rr_sort> *SPQ;
997     hybrid_ls_rr_sort(RegReductionPriorityQueue<hybrid_ls_rr_sort> *spq)
998       : SPQ(spq) {}
999     hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1000       : SPQ(RHS.SPQ) {}
1001
1002     bool operator()(const SUnit* left, const SUnit* right) const;
1003   };
1004
1005   struct ilp_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1006     RegReductionPriorityQueue<ilp_ls_rr_sort> *SPQ;
1007     ilp_ls_rr_sort(RegReductionPriorityQueue<ilp_ls_rr_sort> *spq)
1008       : SPQ(spq) {}
1009     ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1010       : SPQ(RHS.SPQ) {}
1011
1012     bool operator()(const SUnit* left, const SUnit* right) const;
1013   };
1014 }  // end anonymous namespace
1015
1016 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1017 /// Smaller number is the higher priority.
1018 static unsigned
1019 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1020   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1021   if (SethiUllmanNumber != 0)
1022     return SethiUllmanNumber;
1023
1024   unsigned Extra = 0;
1025   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1026        I != E; ++I) {
1027     if (I->isCtrl()) continue;  // ignore chain preds
1028     SUnit *PredSU = I->getSUnit();
1029     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1030     if (PredSethiUllman > SethiUllmanNumber) {
1031       SethiUllmanNumber = PredSethiUllman;
1032       Extra = 0;
1033     } else if (PredSethiUllman == SethiUllmanNumber)
1034       ++Extra;
1035   }
1036
1037   SethiUllmanNumber += Extra;
1038
1039   if (SethiUllmanNumber == 0)
1040     SethiUllmanNumber = 1;
1041   
1042   return SethiUllmanNumber;
1043 }
1044
1045 namespace {
1046   template<class SF>
1047   class RegReductionPriorityQueue : public SchedulingPriorityQueue {
1048     std::vector<SUnit*> Queue;
1049     SF Picker;
1050     unsigned CurQueueId;
1051     bool TracksRegPressure;
1052
1053   protected:
1054     // SUnits - The SUnits for the current graph.
1055     std::vector<SUnit> *SUnits;
1056
1057     MachineFunction &MF;
1058     const TargetInstrInfo *TII;
1059     const TargetRegisterInfo *TRI;
1060     const TargetLowering *TLI;
1061     ScheduleDAGRRList *scheduleDAG;
1062
1063     // SethiUllmanNumbers - The SethiUllman number for each node.
1064     std::vector<unsigned> SethiUllmanNumbers;
1065
1066     /// RegPressure - Tracking current reg pressure per register class.
1067     ///
1068     std::vector<unsigned> RegPressure;
1069
1070     /// RegLimit - Tracking the number of allocatable registers per register
1071     /// class.
1072     std::vector<unsigned> RegLimit;
1073
1074   public:
1075     RegReductionPriorityQueue(MachineFunction &mf,
1076                               bool tracksrp,
1077                               const TargetInstrInfo *tii,
1078                               const TargetRegisterInfo *tri,
1079                               const TargetLowering *tli)
1080       : Picker(this), CurQueueId(0), TracksRegPressure(tracksrp),
1081         MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1082       if (TracksRegPressure) {
1083         unsigned NumRC = TRI->getNumRegClasses();
1084         RegLimit.resize(NumRC);
1085         RegPressure.resize(NumRC);
1086         std::fill(RegLimit.begin(), RegLimit.end(), 0);
1087         std::fill(RegPressure.begin(), RegPressure.end(), 0);
1088         for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1089                E = TRI->regclass_end(); I != E; ++I)
1090           RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1091       }
1092     }
1093     
1094     void initNodes(std::vector<SUnit> &sunits) {
1095       SUnits = &sunits;
1096       // Add pseudo dependency edges for two-address nodes.
1097       AddPseudoTwoAddrDeps();
1098       // Reroute edges to nodes with multiple uses.
1099       PrescheduleNodesWithMultipleUses();
1100       // Calculate node priorities.
1101       CalculateSethiUllmanNumbers();
1102     }
1103
1104     void addNode(const SUnit *SU) {
1105       unsigned SUSize = SethiUllmanNumbers.size();
1106       if (SUnits->size() > SUSize)
1107         SethiUllmanNumbers.resize(SUSize*2, 0);
1108       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1109     }
1110
1111     void updateNode(const SUnit *SU) {
1112       SethiUllmanNumbers[SU->NodeNum] = 0;
1113       CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1114     }
1115
1116     void releaseState() {
1117       SUnits = 0;
1118       SethiUllmanNumbers.clear();
1119       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1120     }
1121
1122     unsigned getNodePriority(const SUnit *SU) const {
1123       assert(SU->NodeNum < SethiUllmanNumbers.size());
1124       unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1125       if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1126         // CopyToReg should be close to its uses to facilitate coalescing and
1127         // avoid spilling.
1128         return 0;
1129       if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1130           Opc == TargetOpcode::SUBREG_TO_REG ||
1131           Opc == TargetOpcode::INSERT_SUBREG)
1132         // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1133         // close to their uses to facilitate coalescing.
1134         return 0;
1135       if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1136         // If SU does not have a register use, i.e. it doesn't produce a value
1137         // that would be consumed (e.g. store), then it terminates a chain of
1138         // computation.  Give it a large SethiUllman number so it will be
1139         // scheduled right before its predecessors that it doesn't lengthen
1140         // their live ranges.
1141         return 0xffff;
1142       if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1143         // If SU does not have a register def, schedule it close to its uses
1144         // because it does not lengthen any live ranges.
1145         return 0;
1146       return SethiUllmanNumbers[SU->NodeNum];
1147     }
1148
1149     unsigned getNodeOrdering(const SUnit *SU) const {
1150       return scheduleDAG->DAG->GetOrdering(SU->getNode());
1151     }
1152
1153     bool empty() const { return Queue.empty(); }
1154     
1155     void push(SUnit *U) {
1156       assert(!U->NodeQueueId && "Node in the queue already");
1157       U->NodeQueueId = ++CurQueueId;
1158       Queue.push_back(U);
1159     }
1160
1161     SUnit *pop() {
1162       if (empty()) return NULL;
1163       std::vector<SUnit *>::iterator Best = Queue.begin();
1164       for (std::vector<SUnit *>::iterator I = llvm::next(Queue.begin()),
1165            E = Queue.end(); I != E; ++I)
1166         if (Picker(*Best, *I))
1167           Best = I;
1168       SUnit *V = *Best;
1169       if (Best != prior(Queue.end()))
1170         std::swap(*Best, Queue.back());
1171       Queue.pop_back();
1172       V->NodeQueueId = 0;
1173       return V;
1174     }
1175
1176     void remove(SUnit *SU) {
1177       assert(!Queue.empty() && "Queue is empty!");
1178       assert(SU->NodeQueueId != 0 && "Not in queue!");
1179       std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1180                                                    SU);
1181       if (I != prior(Queue.end()))
1182         std::swap(*I, Queue.back());
1183       Queue.pop_back();
1184       SU->NodeQueueId = 0;
1185     }
1186
1187     bool HighRegPressure(const SUnit *SU, unsigned &Excess) const {
1188       if (!TLI)
1189         return false;
1190
1191       bool High = false;
1192       Excess = 0;
1193       for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1194            I != E; ++I) {
1195         if (I->isCtrl())
1196           continue;
1197         SUnit *PredSU = I->getSUnit();
1198         const SDNode *PN = PredSU->getNode();
1199         if (!PN->isMachineOpcode()) {
1200           if (PN->getOpcode() == ISD::CopyFromReg) {
1201             EVT VT = PN->getValueType(0);
1202             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1203             unsigned Cost = TLI->getRepRegClassCostFor(VT);
1204             if ((RegPressure[RCId] + Cost) >= RegLimit[RCId]) {
1205               High = true;
1206               Excess += (RegPressure[RCId] + Cost) - RegLimit[RCId];
1207             }
1208           }
1209           continue;
1210         }
1211         unsigned POpc = PN->getMachineOpcode();
1212         if (POpc == TargetOpcode::IMPLICIT_DEF)
1213           continue;
1214         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1215           EVT VT = PN->getOperand(0).getValueType();
1216           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1217           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1218           // Check if this increases register pressure of the specific register
1219           // class to the point where it would cause spills.
1220           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId]) {
1221             High = true;
1222             Excess += (RegPressure[RCId] + Cost) - RegLimit[RCId];
1223           }
1224           continue;            
1225         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1226                    POpc == TargetOpcode::SUBREG_TO_REG) {
1227           EVT VT = PN->getValueType(0);
1228           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1229           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1230           // Check if this increases register pressure of the specific register
1231           // class to the point where it would cause spills.
1232           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId]) {
1233             High = true;
1234             Excess += (RegPressure[RCId] + Cost) - RegLimit[RCId];
1235           }
1236           continue;
1237         }
1238         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1239         for (unsigned i = 0; i != NumDefs; ++i) {
1240           EVT VT = PN->getValueType(i);
1241           if (!PN->hasAnyUseOfValue(i))
1242             continue;
1243           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1244           unsigned Cost = TLI->getRepRegClassCostFor(VT);
1245           // Check if this increases register pressure of the specific register
1246           // class to the point where it would cause spills.
1247           if ((RegPressure[RCId] + Cost) >= RegLimit[RCId]) {
1248             High = true;
1249             Excess += (RegPressure[RCId] + Cost) - RegLimit[RCId];
1250           }
1251         }
1252       }
1253
1254       return High;
1255     }
1256
1257     void ScheduledNode(SUnit *SU) {
1258       if (!TracksRegPressure)
1259         return;
1260
1261       const SDNode *N = SU->getNode();
1262       if (!N->isMachineOpcode()) {
1263         if (N->getOpcode() != ISD::CopyToReg)
1264           return;
1265       } else {
1266         unsigned Opc = N->getMachineOpcode();
1267         if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1268             Opc == TargetOpcode::INSERT_SUBREG ||
1269             Opc == TargetOpcode::SUBREG_TO_REG ||
1270             Opc == TargetOpcode::REG_SEQUENCE ||
1271             Opc == TargetOpcode::IMPLICIT_DEF)
1272           return;
1273       }
1274
1275       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1276            I != E; ++I) {
1277         if (I->isCtrl())
1278           continue;
1279         SUnit *PredSU = I->getSUnit();
1280         if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
1281           continue;
1282         const SDNode *PN = PredSU->getNode();
1283         if (!PN->isMachineOpcode()) {
1284           if (PN->getOpcode() == ISD::CopyFromReg) {
1285             EVT VT = PN->getValueType(0);
1286             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1287             RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1288           }
1289           continue;
1290         }
1291         unsigned POpc = PN->getMachineOpcode();
1292         if (POpc == TargetOpcode::IMPLICIT_DEF)
1293           continue;
1294         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1295           EVT VT = PN->getOperand(0).getValueType();
1296           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1297           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1298           continue;            
1299         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1300                    POpc == TargetOpcode::SUBREG_TO_REG) {
1301           EVT VT = PN->getValueType(0);
1302           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1303           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1304           continue;
1305         }
1306         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1307         for (unsigned i = 0; i != NumDefs; ++i) {
1308           EVT VT = PN->getValueType(i);
1309           if (!PN->hasAnyUseOfValue(i))
1310             continue;
1311           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1312           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1313         }
1314       }
1315
1316       if (SU->NumSuccs && N->getOpcode() != ISD::CopyToReg) {
1317         unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1318         for (unsigned i = 0; i != NumDefs; ++i) {
1319           EVT VT = N->getValueType(i);
1320           if (!N->hasAnyUseOfValue(i))
1321             continue;
1322           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1323           if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1324             // Register pressure tracking is imprecise. This can happen.
1325             RegPressure[RCId] = 0;
1326           else
1327             RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1328         }
1329       }
1330
1331       dumpRegPressure();
1332     }
1333
1334     void UnscheduledNode(SUnit *SU) {
1335       if (!TracksRegPressure)
1336         return;
1337
1338       const SDNode *N = SU->getNode();
1339       if (!N->isMachineOpcode()) {
1340         if (N->getOpcode() != ISD::CopyToReg)
1341           return;
1342       } else {
1343         unsigned Opc = N->getMachineOpcode();
1344         if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1345             Opc == TargetOpcode::INSERT_SUBREG ||
1346             Opc == TargetOpcode::SUBREG_TO_REG ||
1347             Opc == TargetOpcode::REG_SEQUENCE ||
1348             Opc == TargetOpcode::IMPLICIT_DEF)
1349           return;
1350       }
1351
1352       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1353            I != E; ++I) {
1354         if (I->isCtrl())
1355           continue;
1356         SUnit *PredSU = I->getSUnit();
1357         if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
1358           continue;
1359         const SDNode *PN = PredSU->getNode();
1360         if (!PN->isMachineOpcode()) {
1361           if (PN->getOpcode() == ISD::CopyFromReg) {
1362             EVT VT = PN->getValueType(0);
1363             unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1364             RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1365           }
1366           continue;
1367         }
1368         unsigned POpc = PN->getMachineOpcode();
1369         if (POpc == TargetOpcode::IMPLICIT_DEF)
1370           continue;
1371         if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1372           EVT VT = PN->getOperand(0).getValueType();
1373           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1374           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1375           continue;            
1376         } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1377                    POpc == TargetOpcode::SUBREG_TO_REG) {
1378           EVT VT = PN->getValueType(0);
1379           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1380           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1381           continue;
1382         }
1383         unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1384         for (unsigned i = 0; i != NumDefs; ++i) {
1385           EVT VT = PN->getValueType(i);
1386           if (!PN->hasAnyUseOfValue(i))
1387             continue;
1388           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1389           if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1390             // Register pressure tracking is imprecise. This can happen.
1391             RegPressure[RCId] = 0;
1392           else
1393             RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1394         }
1395       }
1396
1397       if (SU->NumSuccs && N->getOpcode() != ISD::CopyToReg) {
1398         unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1399         for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1400           EVT VT = N->getValueType(i);
1401           if (VT == MVT::Flag || VT == MVT::Other)
1402             continue;
1403           if (!N->hasAnyUseOfValue(i))
1404             continue;
1405           unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1406           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1407         }
1408       }
1409
1410       dumpRegPressure();
1411     }
1412
1413     void setScheduleDAG(ScheduleDAGRRList *scheduleDag) { 
1414       scheduleDAG = scheduleDag; 
1415     }
1416
1417     void dumpRegPressure() const {
1418       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1419              E = TRI->regclass_end(); I != E; ++I) {
1420         const TargetRegisterClass *RC = *I;
1421         unsigned Id = RC->getID();
1422         unsigned RP = RegPressure[Id];
1423         if (!RP) continue;
1424         DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1425               << '\n');
1426       }
1427     }
1428
1429   protected:
1430     bool canClobber(const SUnit *SU, const SUnit *Op);
1431     void AddPseudoTwoAddrDeps();
1432     void PrescheduleNodesWithMultipleUses();
1433     void CalculateSethiUllmanNumbers();
1434   };
1435
1436   typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1437     BURegReductionPriorityQueue;
1438
1439   typedef RegReductionPriorityQueue<td_ls_rr_sort>
1440     TDRegReductionPriorityQueue;
1441
1442   typedef RegReductionPriorityQueue<src_ls_rr_sort>
1443     SrcRegReductionPriorityQueue;
1444
1445   typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1446     HybridBURRPriorityQueue;
1447
1448   typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1449     ILPBURRPriorityQueue;
1450 }
1451
1452 /// closestSucc - Returns the scheduled cycle of the successor which is
1453 /// closest to the current cycle.
1454 static unsigned closestSucc(const SUnit *SU) {
1455   unsigned MaxHeight = 0;
1456   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1457        I != E; ++I) {
1458     if (I->isCtrl()) continue;  // ignore chain succs
1459     unsigned Height = I->getSUnit()->getHeight();
1460     // If there are bunch of CopyToRegs stacked up, they should be considered
1461     // to be at the same position.
1462     if (I->getSUnit()->getNode() &&
1463         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1464       Height = closestSucc(I->getSUnit())+1;
1465     if (Height > MaxHeight)
1466       MaxHeight = Height;
1467   }
1468   return MaxHeight;
1469 }
1470
1471 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1472 /// for scratch registers, i.e. number of data dependencies.
1473 static unsigned calcMaxScratches(const SUnit *SU) {
1474   unsigned Scratches = 0;
1475   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1476        I != E; ++I) {
1477     if (I->isCtrl()) continue;  // ignore chain preds
1478     Scratches++;
1479   }
1480   return Scratches;
1481 }
1482
1483 template <typename RRSort>
1484 static bool BURRSort(const SUnit *left, const SUnit *right,
1485                      const RegReductionPriorityQueue<RRSort> *SPQ) {
1486   unsigned LPriority = SPQ->getNodePriority(left);
1487   unsigned RPriority = SPQ->getNodePriority(right);
1488   if (LPriority != RPriority)
1489     return LPriority > RPriority;
1490
1491   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1492   // e.g.
1493   // t1 = op t2, c1
1494   // t3 = op t4, c2
1495   //
1496   // and the following instructions are both ready.
1497   // t2 = op c3
1498   // t4 = op c4
1499   //
1500   // Then schedule t2 = op first.
1501   // i.e.
1502   // t4 = op c4
1503   // t2 = op c3
1504   // t1 = op t2, c1
1505   // t3 = op t4, c2
1506   //
1507   // This creates more short live intervals.
1508   unsigned LDist = closestSucc(left);
1509   unsigned RDist = closestSucc(right);
1510   if (LDist != RDist)
1511     return LDist < RDist;
1512
1513   // How many registers becomes live when the node is scheduled.
1514   unsigned LScratch = calcMaxScratches(left);
1515   unsigned RScratch = calcMaxScratches(right);
1516   if (LScratch != RScratch)
1517     return LScratch > RScratch;
1518
1519   if (left->getHeight() != right->getHeight())
1520     return left->getHeight() > right->getHeight();
1521   
1522   if (left->getDepth() != right->getDepth())
1523     return left->getDepth() < right->getDepth();
1524
1525   assert(left->NodeQueueId && right->NodeQueueId && 
1526          "NodeQueueId cannot be zero");
1527   return (left->NodeQueueId > right->NodeQueueId);
1528 }
1529
1530 // Bottom up
1531 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1532   return BURRSort(left, right, SPQ);
1533 }
1534
1535 // Source order, otherwise bottom up.
1536 bool src_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1537   unsigned LOrder = SPQ->getNodeOrdering(left);
1538   unsigned ROrder = SPQ->getNodeOrdering(right);
1539
1540   // Prefer an ordering where the lower the non-zero order number, the higher
1541   // the preference.
1542   if ((LOrder || ROrder) && LOrder != ROrder)
1543     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
1544
1545   return BURRSort(left, right, SPQ);
1546 }
1547
1548 bool hybrid_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const{
1549   unsigned LExcess, RExcess;
1550   bool LHigh = SPQ->HighRegPressure(left, LExcess);
1551   bool RHigh = SPQ->HighRegPressure(right, RExcess);
1552   // Avoid causing spills. If register pressure is high, schedule for
1553   // register pressure reduction.
1554   if (LHigh && !RHigh)
1555     return true;
1556   else if (!LHigh && RHigh)
1557     return false;
1558   else if (LHigh && RHigh) {
1559     if (LExcess > RExcess)
1560       return true;
1561     else if (LExcess < RExcess)
1562       return false;
1563   } else {
1564     // Low register pressure situation, schedule for latency if possible.
1565     bool LStall = left->SchedulingPref == Sched::Latency &&
1566       SPQ->getCurCycle() < left->getHeight();
1567     bool RStall = right->SchedulingPref == Sched::Latency &&
1568       SPQ->getCurCycle() < right->getHeight();
1569     // If scheduling one of the node will cause a pipeline stall, delay it.
1570     // If scheduling either one of the node will cause a pipeline stall, sort
1571     // them according to their height.
1572     // If neither will cause a pipeline stall, try to reduce register pressure.
1573     if (LStall) {
1574       if (!RStall)
1575         return true;
1576       if (left->getHeight() != right->getHeight())
1577         return left->getHeight() > right->getHeight();
1578     } else if (RStall)
1579       return false;
1580
1581     // If either node is scheduling for latency, sort them by height and latency
1582     // first.
1583     if (left->SchedulingPref == Sched::Latency ||
1584         right->SchedulingPref == Sched::Latency) {
1585       if (left->getHeight() != right->getHeight())
1586         return left->getHeight() > right->getHeight();
1587       if (left->Latency != right->Latency)
1588         return left->Latency > right->Latency;
1589     }
1590   }
1591
1592   return BURRSort(left, right, SPQ);
1593 }
1594
1595 bool ilp_ls_rr_sort::operator()(const SUnit *left,
1596                                 const SUnit *right) const {
1597   unsigned LExcess, RExcess;
1598   bool LHigh = SPQ->HighRegPressure(left, LExcess);
1599   bool RHigh = SPQ->HighRegPressure(right, RExcess);
1600   // Avoid causing spills. If register pressure is high, schedule for
1601   // register pressure reduction.
1602   if (LHigh && !RHigh)
1603     return true;
1604   else if (!LHigh && RHigh)
1605     return false;
1606   else if (LHigh && RHigh) {
1607     if (LExcess > RExcess)
1608       return true;
1609     else if (LExcess < RExcess)
1610       return false;    
1611   } else {
1612     // Low register pressure situation, schedule for ILP.
1613     if (left->NumPreds > right->NumPreds)
1614       return false;
1615     else if (left->NumPreds < right->NumPreds)
1616       return false;
1617   }
1618
1619   return BURRSort(left, right, SPQ);
1620 }
1621
1622 template<class SF>
1623 bool
1624 RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1625   if (SU->isTwoAddress) {
1626     unsigned Opc = SU->getNode()->getMachineOpcode();
1627     const TargetInstrDesc &TID = TII->get(Opc);
1628     unsigned NumRes = TID.getNumDefs();
1629     unsigned NumOps = TID.getNumOperands() - NumRes;
1630     for (unsigned i = 0; i != NumOps; ++i) {
1631       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1632         SDNode *DU = SU->getNode()->getOperand(i).getNode();
1633         if (DU->getNodeId() != -1 &&
1634             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1635           return true;
1636       }
1637     }
1638   }
1639   return false;
1640 }
1641
1642 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1643 /// CopyToReg node.
1644 static bool hasCopyToRegUse(const SUnit *SU) {
1645   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1646        I != E; ++I) {
1647     if (I->isCtrl()) continue;
1648     const SUnit *SuccSU = I->getSUnit();
1649     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg)
1650       return true;
1651   }
1652   return false;
1653 }
1654
1655 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1656 /// physical register defs.
1657 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1658                                   const TargetInstrInfo *TII,
1659                                   const TargetRegisterInfo *TRI) {
1660   SDNode *N = SuccSU->getNode();
1661   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1662   const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1663   assert(ImpDefs && "Caller should check hasPhysRegDefs");
1664   for (const SDNode *SUNode = SU->getNode(); SUNode;
1665        SUNode = SUNode->getFlaggedNode()) {
1666     if (!SUNode->isMachineOpcode())
1667       continue;
1668     const unsigned *SUImpDefs =
1669       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
1670     if (!SUImpDefs)
1671       return false;
1672     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1673       EVT VT = N->getValueType(i);
1674       if (VT == MVT::Flag || VT == MVT::Other)
1675         continue;
1676       if (!N->hasAnyUseOfValue(i))
1677         continue;
1678       unsigned Reg = ImpDefs[i - NumDefs];
1679       for (;*SUImpDefs; ++SUImpDefs) {
1680         unsigned SUReg = *SUImpDefs;
1681         if (TRI->regsOverlap(Reg, SUReg))
1682           return true;
1683       }
1684     }
1685   }
1686   return false;
1687 }
1688
1689 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
1690 /// are not handled well by the general register pressure reduction
1691 /// heuristics. When presented with code like this:
1692 ///
1693 ///      N
1694 ///    / |
1695 ///   /  |
1696 ///  U  store
1697 ///  |
1698 /// ...
1699 ///
1700 /// the heuristics tend to push the store up, but since the
1701 /// operand of the store has another use (U), this would increase
1702 /// the length of that other use (the U->N edge).
1703 ///
1704 /// This function transforms code like the above to route U's
1705 /// dependence through the store when possible, like this:
1706 ///
1707 ///      N
1708 ///      ||
1709 ///      ||
1710 ///     store
1711 ///       |
1712 ///       U
1713 ///       |
1714 ///      ...
1715 ///
1716 /// This results in the store being scheduled immediately
1717 /// after N, which shortens the U->N live range, reducing
1718 /// register pressure.
1719 ///
1720 template<class SF>
1721 void RegReductionPriorityQueue<SF>::PrescheduleNodesWithMultipleUses() {
1722   // Visit all the nodes in topological order, working top-down.
1723   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1724     SUnit *SU = &(*SUnits)[i];
1725     // For now, only look at nodes with no data successors, such as stores.
1726     // These are especially important, due to the heuristics in
1727     // getNodePriority for nodes with no data successors.
1728     if (SU->NumSuccs != 0)
1729       continue;
1730     // For now, only look at nodes with exactly one data predecessor.
1731     if (SU->NumPreds != 1)
1732       continue;
1733     // Avoid prescheduling copies to virtual registers, which don't behave
1734     // like other nodes from the perspective of scheduling heuristics.
1735     if (SDNode *N = SU->getNode())
1736       if (N->getOpcode() == ISD::CopyToReg &&
1737           TargetRegisterInfo::isVirtualRegister
1738             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
1739         continue;
1740
1741     // Locate the single data predecessor.
1742     SUnit *PredSU = 0;
1743     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
1744          EE = SU->Preds.end(); II != EE; ++II)
1745       if (!II->isCtrl()) {
1746         PredSU = II->getSUnit();
1747         break;
1748       }
1749     assert(PredSU);
1750
1751     // Don't rewrite edges that carry physregs, because that requires additional
1752     // support infrastructure.
1753     if (PredSU->hasPhysRegDefs)
1754       continue;
1755     // Short-circuit the case where SU is PredSU's only data successor.
1756     if (PredSU->NumSuccs == 1)
1757       continue;
1758     // Avoid prescheduling to copies from virtual registers, which don't behave
1759     // like other nodes from the perspective of scheduling // heuristics.
1760     if (SDNode *N = SU->getNode())
1761       if (N->getOpcode() == ISD::CopyFromReg &&
1762           TargetRegisterInfo::isVirtualRegister
1763             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
1764         continue;
1765
1766     // Perform checks on the successors of PredSU.
1767     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
1768          EE = PredSU->Succs.end(); II != EE; ++II) {
1769       SUnit *PredSuccSU = II->getSUnit();
1770       if (PredSuccSU == SU) continue;
1771       // If PredSU has another successor with no data successors, for
1772       // now don't attempt to choose either over the other.
1773       if (PredSuccSU->NumSuccs == 0)
1774         goto outer_loop_continue;
1775       // Don't break physical register dependencies.
1776       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
1777         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
1778           goto outer_loop_continue;
1779       // Don't introduce graph cycles.
1780       if (scheduleDAG->IsReachable(SU, PredSuccSU))
1781         goto outer_loop_continue;
1782     }
1783
1784     // Ok, the transformation is safe and the heuristics suggest it is
1785     // profitable. Update the graph.
1786     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
1787                  << " next to PredSU #" << PredSU->NodeNum
1788                  << " to guide scheduling in the presence of multiple uses\n");
1789     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
1790       SDep Edge = PredSU->Succs[i];
1791       assert(!Edge.isAssignedRegDep());
1792       SUnit *SuccSU = Edge.getSUnit();
1793       if (SuccSU != SU) {
1794         Edge.setSUnit(PredSU);
1795         scheduleDAG->RemovePred(SuccSU, Edge);
1796         scheduleDAG->AddPred(SU, Edge);
1797         Edge.setSUnit(SU);
1798         scheduleDAG->AddPred(SuccSU, Edge);
1799         --i;
1800       }
1801     }
1802   outer_loop_continue:;
1803   }
1804 }
1805
1806 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1807 /// it as a def&use operand. Add a pseudo control edge from it to the other
1808 /// node (if it won't create a cycle) so the two-address one will be scheduled
1809 /// first (lower in the schedule). If both nodes are two-address, favor the
1810 /// one that has a CopyToReg use (more likely to be a loop induction update).
1811 /// If both are two-address, but one is commutable while the other is not
1812 /// commutable, favor the one that's not commutable.
1813 template<class SF>
1814 void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1815   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1816     SUnit *SU = &(*SUnits)[i];
1817     if (!SU->isTwoAddress)
1818       continue;
1819
1820     SDNode *Node = SU->getNode();
1821     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1822       continue;
1823
1824     unsigned Opc = Node->getMachineOpcode();
1825     const TargetInstrDesc &TID = TII->get(Opc);
1826     unsigned NumRes = TID.getNumDefs();
1827     unsigned NumOps = TID.getNumOperands() - NumRes;
1828     for (unsigned j = 0; j != NumOps; ++j) {
1829       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1830         continue;
1831       SDNode *DU = SU->getNode()->getOperand(j).getNode();
1832       if (DU->getNodeId() == -1)
1833         continue;
1834       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1835       if (!DUSU) continue;
1836       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1837            E = DUSU->Succs.end(); I != E; ++I) {
1838         if (I->isCtrl()) continue;
1839         SUnit *SuccSU = I->getSUnit();
1840         if (SuccSU == SU)
1841           continue;
1842         // Be conservative. Ignore if nodes aren't at roughly the same
1843         // depth and height.
1844         if (SuccSU->getHeight() < SU->getHeight() &&
1845             (SU->getHeight() - SuccSU->getHeight()) > 1)
1846           continue;
1847         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
1848         // constrains whatever is using the copy, instead of the copy
1849         // itself. In the case that the copy is coalesced, this
1850         // preserves the intent of the pseudo two-address heurietics.
1851         while (SuccSU->Succs.size() == 1 &&
1852                SuccSU->getNode()->isMachineOpcode() &&
1853                SuccSU->getNode()->getMachineOpcode() ==
1854                  TargetOpcode::COPY_TO_REGCLASS)
1855           SuccSU = SuccSU->Succs.front().getSUnit();
1856         // Don't constrain non-instruction nodes.
1857         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1858           continue;
1859         // Don't constrain nodes with physical register defs if the
1860         // predecessor can clobber them.
1861         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
1862           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1863             continue;
1864         }
1865         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
1866         // these may be coalesced away. We want them close to their uses.
1867         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1868         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
1869             SuccOpc == TargetOpcode::INSERT_SUBREG ||
1870             SuccOpc == TargetOpcode::SUBREG_TO_REG)
1871           continue;
1872         if ((!canClobber(SuccSU, DUSU) ||
1873              (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1874              (!SU->isCommutable && SuccSU->isCommutable)) &&
1875             !scheduleDAG->IsReachable(SuccSU, SU)) {
1876           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
1877                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
1878           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
1879                                         /*Reg=*/0, /*isNormalMemory=*/false,
1880                                         /*isMustAlias=*/false,
1881                                         /*isArtificial=*/true));
1882         }
1883       }
1884     }
1885   }
1886 }
1887
1888 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1889 /// scheduling units.
1890 template<class SF>
1891 void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1892   SethiUllmanNumbers.assign(SUnits->size(), 0);
1893   
1894   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1895     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1896 }
1897
1898 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1899 /// predecessors of the successors of the SUnit SU. Stop when the provided
1900 /// limit is exceeded.
1901 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU, 
1902                                                     unsigned Limit) {
1903   unsigned Sum = 0;
1904   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1905        I != E; ++I) {
1906     const SUnit *SuccSU = I->getSUnit();
1907     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1908          EE = SuccSU->Preds.end(); II != EE; ++II) {
1909       SUnit *PredSU = II->getSUnit();
1910       if (!PredSU->isScheduled)
1911         if (++Sum > Limit)
1912           return Sum;
1913     }
1914   }
1915   return Sum;
1916 }
1917
1918
1919 // Top down
1920 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1921   unsigned LPriority = SPQ->getNodePriority(left);
1922   unsigned RPriority = SPQ->getNodePriority(right);
1923   bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1924   bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1925   bool LIsFloater = LIsTarget && left->NumPreds == 0;
1926   bool RIsFloater = RIsTarget && right->NumPreds == 0;
1927   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1928   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1929
1930   if (left->NumSuccs == 0 && right->NumSuccs != 0)
1931     return false;
1932   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1933     return true;
1934
1935   if (LIsFloater)
1936     LBonus -= 2;
1937   if (RIsFloater)
1938     RBonus -= 2;
1939   if (left->NumSuccs == 1)
1940     LBonus += 2;
1941   if (right->NumSuccs == 1)
1942     RBonus += 2;
1943
1944   if (LPriority+LBonus != RPriority+RBonus)
1945     return LPriority+LBonus < RPriority+RBonus;
1946
1947   if (left->getDepth() != right->getDepth())
1948     return left->getDepth() < right->getDepth();
1949
1950   if (left->NumSuccsLeft != right->NumSuccsLeft)
1951     return left->NumSuccsLeft > right->NumSuccsLeft;
1952
1953   assert(left->NodeQueueId && right->NodeQueueId && 
1954          "NodeQueueId cannot be zero");
1955   return (left->NodeQueueId > right->NodeQueueId);
1956 }
1957
1958 //===----------------------------------------------------------------------===//
1959 //                         Public Constructor Functions
1960 //===----------------------------------------------------------------------===//
1961
1962 llvm::ScheduleDAGSDNodes *
1963 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
1964   const TargetMachine &TM = IS->TM;
1965   const TargetInstrInfo *TII = TM.getInstrInfo();
1966   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1967   
1968   BURegReductionPriorityQueue *PQ =
1969     new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
1970   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, false, PQ);
1971   PQ->setScheduleDAG(SD);
1972   return SD;  
1973 }
1974
1975 llvm::ScheduleDAGSDNodes *
1976 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
1977   const TargetMachine &TM = IS->TM;
1978   const TargetInstrInfo *TII = TM.getInstrInfo();
1979   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1980   
1981   TDRegReductionPriorityQueue *PQ =
1982     new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
1983   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, false, PQ);
1984   PQ->setScheduleDAG(SD);
1985   return SD;
1986 }
1987
1988 llvm::ScheduleDAGSDNodes *
1989 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
1990   const TargetMachine &TM = IS->TM;
1991   const TargetInstrInfo *TII = TM.getInstrInfo();
1992   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1993   
1994   SrcRegReductionPriorityQueue *PQ =
1995     new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
1996   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, false, PQ);
1997   PQ->setScheduleDAG(SD);
1998   return SD;  
1999 }
2000
2001 llvm::ScheduleDAGSDNodes *
2002 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2003   const TargetMachine &TM = IS->TM;
2004   const TargetInstrInfo *TII = TM.getInstrInfo();
2005   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2006   const TargetLowering *TLI = &IS->getTargetLowering();
2007   
2008   HybridBURRPriorityQueue *PQ =
2009     new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2010   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, true, PQ);
2011   PQ->setScheduleDAG(SD);
2012   return SD;  
2013 }
2014
2015 llvm::ScheduleDAGSDNodes *
2016 llvm::createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
2017   const TargetMachine &TM = IS->TM;
2018   const TargetInstrInfo *TII = TM.getInstrInfo();
2019   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2020   const TargetLowering *TLI = &IS->getTargetLowering();
2021   
2022   ILPBURRPriorityQueue *PQ =
2023     new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2024   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, true, PQ);
2025   PQ->setScheduleDAG(SD);
2026   return SD;  
2027 }