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