Selection DAG scheduler register pressure heuristic fixes.
[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/CodeGen/ScheduleHazardRecognizer.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <climits>
36 using namespace llvm;
37
38 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
39 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
40 STATISTIC(NumDups,       "Number of duplicated nodes");
41 STATISTIC(NumPRCopies,   "Number of physical register copies");
42
43 static RegisterScheduler
44   burrListDAGScheduler("list-burr",
45                        "Bottom-up register reduction list scheduling",
46                        createBURRListDAGScheduler);
47 static RegisterScheduler
48   tdrListrDAGScheduler("list-tdrr",
49                        "Top-down register reduction list scheduling",
50                        createTDRRListDAGScheduler);
51 static RegisterScheduler
52   sourceListDAGScheduler("source",
53                          "Similar to list-burr but schedules in source "
54                          "order when possible",
55                          createSourceListDAGScheduler);
56
57 static RegisterScheduler
58   hybridListDAGScheduler("list-hybrid",
59                          "Bottom-up register pressure aware list scheduling "
60                          "which tries to balance latency and register pressure",
61                          createHybridListDAGScheduler);
62
63 static RegisterScheduler
64   ILPListDAGScheduler("list-ilp",
65                       "Bottom-up register pressure aware list scheduling "
66                       "which tries to balance ILP and register pressure",
67                       createILPListDAGScheduler);
68
69 static cl::opt<bool> EnableSchedCycles(
70   "enable-sched-cycles",
71   cl::desc("Enable cycle-level precision during preRA scheduling"),
72   cl::init(false), cl::Hidden);
73
74 namespace {
75 //===----------------------------------------------------------------------===//
76 /// ScheduleDAGRRList - The actual register reduction list scheduler
77 /// implementation.  This supports both top-down and bottom-up scheduling.
78 ///
79 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
80 private:
81   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
82   /// it is top-down.
83   bool isBottomUp;
84
85   /// NeedLatency - True if the scheduler will make use of latency information.
86   ///
87   bool NeedLatency;
88
89   /// AvailableQueue - The priority queue to use for the available SUnits.
90   SchedulingPriorityQueue *AvailableQueue;
91
92   /// PendingQueue - This contains all of the instructions whose operands have
93   /// been issued, but their results are not ready yet (due to the latency of
94   /// the operation).  Once the operands becomes available, the instruction is
95   /// added to the AvailableQueue.
96   std::vector<SUnit*> PendingQueue;
97
98   /// HazardRec - The hazard recognizer to use.
99   ScheduleHazardRecognizer *HazardRec;
100
101   /// CurCycle - The current scheduler state corresponds to this cycle.
102   unsigned CurCycle;
103
104   /// MinAvailableCycle - Cycle of the soonest available instruction.
105   unsigned MinAvailableCycle;
106
107   /// LiveRegDefs - A set of physical registers and their definition
108   /// that are "live". These nodes must be scheduled before any other nodes that
109   /// modifies the registers can be scheduled.
110   unsigned NumLiveRegs;
111   std::vector<SUnit*> LiveRegDefs;
112   std::vector<SUnit*> LiveRegGens;
113
114   /// Topo - A topological ordering for SUnits which permits fast IsReachable
115   /// and similar queries.
116   ScheduleDAGTopologicalSort Topo;
117
118 public:
119   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
120                     SchedulingPriorityQueue *availqueue,
121                     CodeGenOpt::Level OptLevel)
122     : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
123       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
124       Topo(SUnits) {
125
126     const TargetMachine &tm = mf.getTarget();
127     if (EnableSchedCycles && OptLevel != CodeGenOpt::None)
128       HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
129     else
130       HazardRec = new ScheduleHazardRecognizer();
131   }
132
133   ~ScheduleDAGRRList() {
134     delete HazardRec;
135     delete AvailableQueue;
136   }
137
138   void Schedule();
139
140   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
141
142   /// IsReachable - Checks if SU is reachable from TargetSU.
143   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
144     return Topo.IsReachable(SU, TargetSU);
145   }
146
147   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
148   /// create a cycle.
149   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
150     return Topo.WillCreateCycle(SU, TargetSU);
151   }
152
153   /// AddPred - adds a predecessor edge to SUnit SU.
154   /// This returns true if this is a new predecessor.
155   /// Updates the topological ordering if required.
156   void AddPred(SUnit *SU, const SDep &D) {
157     Topo.AddPred(SU, D.getSUnit());
158     SU->addPred(D);
159   }
160
161   /// RemovePred - removes a predecessor edge from SUnit SU.
162   /// This returns true if an edge was removed.
163   /// Updates the topological ordering if required.
164   void RemovePred(SUnit *SU, const SDep &D) {
165     Topo.RemovePred(SU, D.getSUnit());
166     SU->removePred(D);
167   }
168
169 private:
170   bool isReady(SUnit *SU) {
171     return !EnableSchedCycles || !AvailableQueue->hasReadyFilter() ||
172       AvailableQueue->isReady(SU);
173   }
174
175   void ReleasePred(SUnit *SU, const SDep *PredEdge);
176   void ReleasePredecessors(SUnit *SU);
177   void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
178   void ReleaseSuccessors(SUnit *SU);
179   void ReleasePending();
180   void AdvanceToCycle(unsigned NextCycle);
181   void AdvancePastStalls(SUnit *SU);
182   void EmitNode(SUnit *SU);
183   void ScheduleNodeBottomUp(SUnit*);
184   void CapturePred(SDep *PredEdge);
185   void UnscheduleNodeBottomUp(SUnit*);
186   void RestoreHazardCheckerBottomUp();
187   void BacktrackBottomUp(SUnit*, SUnit*);
188   SUnit *CopyAndMoveSuccessors(SUnit*);
189   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
190                                 const TargetRegisterClass*,
191                                 const TargetRegisterClass*,
192                                 SmallVector<SUnit*, 2>&);
193   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
194
195   SUnit *PickNodeToScheduleBottomUp();
196   void ListScheduleBottomUp();
197
198   void ScheduleNodeTopDown(SUnit*);
199   void ListScheduleTopDown();
200
201
202   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
203   /// Updates the topological ordering if required.
204   SUnit *CreateNewSUnit(SDNode *N) {
205     unsigned NumSUnits = SUnits.size();
206     SUnit *NewNode = NewSUnit(N);
207     // Update the topological ordering.
208     if (NewNode->NodeNum >= NumSUnits)
209       Topo.InitDAGTopologicalSorting();
210     return NewNode;
211   }
212
213   /// CreateClone - Creates a new SUnit from an existing one.
214   /// Updates the topological ordering if required.
215   SUnit *CreateClone(SUnit *N) {
216     unsigned NumSUnits = SUnits.size();
217     SUnit *NewNode = Clone(N);
218     // Update the topological ordering.
219     if (NewNode->NodeNum >= NumSUnits)
220       Topo.InitDAGTopologicalSorting();
221     return NewNode;
222   }
223
224   /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
225   /// need actual latency information but the hybrid scheduler does.
226   bool ForceUnitLatencies() const {
227     return !NeedLatency;
228   }
229 };
230 }  // end anonymous namespace
231
232
233 /// Schedule - Schedule the DAG using list scheduling.
234 void ScheduleDAGRRList::Schedule() {
235   DEBUG(dbgs()
236         << "********** List Scheduling BB#" << BB->getNumber()
237         << " '" << BB->getName() << "' **********\n");
238
239   CurCycle = 0;
240   MinAvailableCycle = EnableSchedCycles ? UINT_MAX : 0;
241   NumLiveRegs = 0;
242   LiveRegDefs.resize(TRI->getNumRegs(), NULL);
243   LiveRegGens.resize(TRI->getNumRegs(), NULL);
244
245   // Build the scheduling graph.
246   BuildSchedGraph(NULL);
247
248   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
249           SUnits[su].dumpAll(this));
250   Topo.InitDAGTopologicalSorting();
251
252   AvailableQueue->initNodes(SUnits);
253
254   HazardRec->Reset();
255
256   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
257   if (isBottomUp)
258     ListScheduleBottomUp();
259   else
260     ListScheduleTopDown();
261
262   AvailableQueue->releaseState();
263 }
264
265 //===----------------------------------------------------------------------===//
266 //  Bottom-Up Scheduling
267 //===----------------------------------------------------------------------===//
268
269 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
270 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
271 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
272   SUnit *PredSU = PredEdge->getSUnit();
273
274 #ifndef NDEBUG
275   if (PredSU->NumSuccsLeft == 0) {
276     dbgs() << "*** Scheduling failed! ***\n";
277     PredSU->dump(this);
278     dbgs() << " has been released too many times!\n";
279     llvm_unreachable(0);
280   }
281 #endif
282   --PredSU->NumSuccsLeft;
283
284   if (!ForceUnitLatencies()) {
285     // Updating predecessor's height. This is now the cycle when the
286     // predecessor can be scheduled without causing a pipeline stall.
287     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
288   }
289
290   // If all the node's successors are scheduled, this node is ready
291   // to be scheduled. Ignore the special EntrySU node.
292   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
293     PredSU->isAvailable = true;
294
295     unsigned Height = PredSU->getHeight();
296     if (Height < MinAvailableCycle)
297       MinAvailableCycle = Height;
298
299     if (isReady(SU)) {
300       AvailableQueue->push(PredSU);
301     }
302     // CapturePred and others may have left the node in the pending queue, avoid
303     // adding it twice.
304     else if (!PredSU->isPending) {
305       PredSU->isPending = true;
306       PendingQueue.push_back(PredSU);
307     }
308   }
309 }
310
311 /// Call ReleasePred for each predecessor, then update register live def/gen.
312 /// Always update LiveRegDefs for a register dependence even if the current SU
313 /// also defines the register. This effectively create one large live range
314 /// across a sequence of two-address node. This is important because the
315 /// entire chain must be scheduled together. Example:
316 ///
317 /// flags = (3) add
318 /// flags = (2) addc flags
319 /// flags = (1) addc flags
320 ///
321 /// results in
322 ///
323 /// LiveRegDefs[flags] = 3
324 /// LiveRegGens[flags] = 1
325 ///
326 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
327 /// interference on flags.
328 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
329   // Bottom up: release predecessors
330   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
331        I != E; ++I) {
332     ReleasePred(SU, &*I);
333     if (I->isAssignedRegDep()) {
334       // This is a physical register dependency and it's impossible or
335       // expensive to copy the register. Make sure nothing that can
336       // clobber the register is scheduled between the predecessor and
337       // this node.
338       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
339       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
340              "interference on register dependence");
341       LiveRegDefs[I->getReg()] = I->getSUnit();
342       if (!LiveRegGens[I->getReg()]) {
343         ++NumLiveRegs;
344         LiveRegGens[I->getReg()] = SU;
345       }
346     }
347   }
348 }
349
350 /// Check to see if any of the pending instructions are ready to issue.  If
351 /// so, add them to the available queue.
352 void ScheduleDAGRRList::ReleasePending() {
353   if (!EnableSchedCycles) {
354     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
355     return;
356   }
357
358   // If the available queue is empty, it is safe to reset MinAvailableCycle.
359   if (AvailableQueue->empty())
360     MinAvailableCycle = UINT_MAX;
361
362   // Check to see if any of the pending instructions are ready to issue.  If
363   // so, add them to the available queue.
364   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
365     unsigned ReadyCycle =
366       isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
367     if (ReadyCycle < MinAvailableCycle)
368       MinAvailableCycle = ReadyCycle;
369
370     if (PendingQueue[i]->isAvailable) {
371       if (!isReady(PendingQueue[i]))
372           continue;
373       AvailableQueue->push(PendingQueue[i]);
374     }
375     PendingQueue[i]->isPending = false;
376     PendingQueue[i] = PendingQueue.back();
377     PendingQueue.pop_back();
378     --i; --e;
379   }
380 }
381
382 /// Move the scheduler state forward by the specified number of Cycles.
383 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
384   if (NextCycle <= CurCycle)
385     return;
386
387   AvailableQueue->setCurCycle(NextCycle);
388   if (HazardRec->getMaxLookAhead() == 0) {
389     // Bypass lots of virtual calls in case of long latency.
390     CurCycle = NextCycle;
391   }
392   else {
393     for (; CurCycle != NextCycle; ++CurCycle) {
394       if (isBottomUp)
395         HazardRec->RecedeCycle();
396       else
397         HazardRec->AdvanceCycle();
398     }
399   }
400   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
401   // available Q to release pending nodes at least once before popping.
402   ReleasePending();
403 }
404
405 /// Move the scheduler state forward until the specified node's dependents are
406 /// ready and can be scheduled with no resource conflicts.
407 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
408   if (!EnableSchedCycles)
409     return;
410
411   unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
412
413   // Bump CurCycle to account for latency. We assume the latency of other
414   // available instructions may be hidden by the stall (not a full pipe stall).
415   // This updates the hazard recognizer's cycle before reserving resources for
416   // this instruction.
417   AdvanceToCycle(ReadyCycle);
418
419   // Calls are scheduled in their preceding cycle, so don't conflict with
420   // hazards from instructions after the call. EmitNode will reset the
421   // scoreboard state before emitting the call.
422   if (isBottomUp && SU->isCall)
423     return;
424
425   // FIXME: For resource conflicts in very long non-pipelined stages, we
426   // should probably skip ahead here to avoid useless scoreboard checks.
427   int Stalls = 0;
428   while (true) {
429     ScheduleHazardRecognizer::HazardType HT =
430       HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
431
432     if (HT == ScheduleHazardRecognizer::NoHazard)
433       break;
434
435     ++Stalls;
436   }
437   AdvanceToCycle(CurCycle + Stalls);
438 }
439
440 /// Record this SUnit in the HazardRecognizer.
441 /// Does not update CurCycle.
442 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
443   if (!EnableSchedCycles || HazardRec->getMaxLookAhead() == 0)
444     return;
445
446   // Check for phys reg copy.
447   if (!SU->getNode())
448     return;
449
450   switch (SU->getNode()->getOpcode()) {
451   default:
452     assert(SU->getNode()->isMachineOpcode() &&
453            "This target-independent node should not be scheduled.");
454     break;
455   case ISD::MERGE_VALUES:
456   case ISD::TokenFactor:
457   case ISD::CopyToReg:
458   case ISD::CopyFromReg:
459   case ISD::EH_LABEL:
460     // Noops don't affect the scoreboard state. Copies are likely to be
461     // removed.
462     return;
463   case ISD::INLINEASM:
464     // For inline asm, clear the pipeline state.
465     HazardRec->Reset();
466     return;
467   }
468   if (isBottomUp && SU->isCall) {
469     // Calls are scheduled with their preceding instructions. For bottom-up
470     // scheduling, clear the pipeline state before emitting.
471     HazardRec->Reset();
472   }
473
474   HazardRec->EmitInstruction(SU);
475
476   if (!isBottomUp && SU->isCall) {
477     HazardRec->Reset();
478   }
479 }
480
481 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
482 /// count of its predecessors. If a predecessor pending count is zero, add it to
483 /// the Available queue.
484 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
485   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
486   DEBUG(SU->dump(this));
487
488 #ifndef NDEBUG
489   if (CurCycle < SU->getHeight())
490     DEBUG(dbgs() << "   Height [" << SU->getHeight() << "] pipeline stall!\n");
491 #endif
492
493   // FIXME: Do not modify node height. It may interfere with
494   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
495   // node it's ready cycle can aid heuristics, and after scheduling it can
496   // indicate the scheduled cycle.
497   SU->setHeightToAtLeast(CurCycle);
498
499   // Reserve resources for the scheduled intruction.
500   EmitNode(SU);
501
502   Sequence.push_back(SU);
503
504   AvailableQueue->ScheduledNode(SU);
505
506   // Update liveness of predecessors before successors to avoid treating a
507   // two-address node as a live range def.
508   ReleasePredecessors(SU);
509
510   // Release all the implicit physical register defs that are live.
511   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
512        I != E; ++I) {
513     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
514     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
515       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
516       --NumLiveRegs;
517       LiveRegDefs[I->getReg()] = NULL;
518       LiveRegGens[I->getReg()] = NULL;
519     }
520   }
521
522   SU->isScheduled = true;
523
524   // Conditions under which the scheduler should eagerly advance the cycle:
525   // (1) No available instructions
526   // (2) All pipelines full, so available instructions must have hazards.
527   //
528   // If SchedCycles is disabled, count each inst as one cycle.
529   if (!EnableSchedCycles ||
530       AvailableQueue->empty() || HazardRec->atIssueLimit())
531     AdvanceToCycle(CurCycle + 1);
532 }
533
534 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
535 /// unscheduled, incrcease the succ left count of its predecessors. Remove
536 /// them from AvailableQueue if necessary.
537 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
538   SUnit *PredSU = PredEdge->getSUnit();
539   if (PredSU->isAvailable) {
540     PredSU->isAvailable = false;
541     if (!PredSU->isPending)
542       AvailableQueue->remove(PredSU);
543   }
544
545   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
546   ++PredSU->NumSuccsLeft;
547 }
548
549 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
550 /// its predecessor states to reflect the change.
551 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
552   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
553   DEBUG(SU->dump(this));
554
555   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
556        I != E; ++I) {
557     CapturePred(&*I);
558     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
559       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
560       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
561              "Physical register dependency violated?");
562       --NumLiveRegs;
563       LiveRegDefs[I->getReg()] = NULL;
564       LiveRegGens[I->getReg()] = NULL;
565     }
566   }
567
568   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
569        I != E; ++I) {
570     if (I->isAssignedRegDep()) {
571       // This becomes the nearest def. Note that an earlier def may still be
572       // pending if this is a two-address node.
573       LiveRegDefs[I->getReg()] = SU;
574       if (!LiveRegDefs[I->getReg()]) {
575         ++NumLiveRegs;
576       }
577       if (LiveRegGens[I->getReg()] == NULL ||
578           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
579         LiveRegGens[I->getReg()] = I->getSUnit();
580     }
581   }
582   if (SU->getHeight() < MinAvailableCycle)
583     MinAvailableCycle = SU->getHeight();
584
585   SU->setHeightDirty();
586   SU->isScheduled = false;
587   SU->isAvailable = true;
588   if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
589     // Don't make available until backtracking is complete.
590     SU->isPending = true;
591     PendingQueue.push_back(SU);
592   }
593   else {
594     AvailableQueue->push(SU);
595   }
596   AvailableQueue->UnscheduledNode(SU);
597 }
598
599 /// After backtracking, the hazard checker needs to be restored to a state
600 /// corresponding the the current cycle.
601 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
602   HazardRec->Reset();
603
604   unsigned LookAhead = std::min((unsigned)Sequence.size(),
605                                 HazardRec->getMaxLookAhead());
606   if (LookAhead == 0)
607     return;
608
609   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
610   unsigned HazardCycle = (*I)->getHeight();
611   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
612     SUnit *SU = *I;
613     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
614       HazardRec->RecedeCycle();
615     }
616     EmitNode(SU);
617   }
618 }
619
620 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
621 /// BTCycle in order to schedule a specific node.
622 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
623   SUnit *OldSU = Sequence.back();
624   while (true) {
625     Sequence.pop_back();
626     if (SU->isSucc(OldSU))
627       // Don't try to remove SU from AvailableQueue.
628       SU->isAvailable = false;
629     // FIXME: use ready cycle instead of height
630     CurCycle = OldSU->getHeight();
631     UnscheduleNodeBottomUp(OldSU);
632     AvailableQueue->setCurCycle(CurCycle);
633     if (OldSU == BtSU)
634       break;
635     OldSU = Sequence.back();
636   }
637
638   assert(!SU->isSucc(OldSU) && "Something is wrong!");
639
640   RestoreHazardCheckerBottomUp();
641
642   ReleasePending();
643
644   ++NumBacktracks;
645 }
646
647 static bool isOperandOf(const SUnit *SU, SDNode *N) {
648   for (const SDNode *SUNode = SU->getNode(); SUNode;
649        SUNode = SUNode->getGluedNode()) {
650     if (SUNode->isOperandOf(N))
651       return true;
652   }
653   return false;
654 }
655
656 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
657 /// successors to the newly created node.
658 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
659   SDNode *N = SU->getNode();
660   if (!N)
661     return NULL;
662
663   if (SU->getNode()->getGluedNode())
664     return NULL;
665
666   SUnit *NewSU;
667   bool TryUnfold = false;
668   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
669     EVT VT = N->getValueType(i);
670     if (VT == MVT::Glue)
671       return NULL;
672     else if (VT == MVT::Other)
673       TryUnfold = true;
674   }
675   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
676     const SDValue &Op = N->getOperand(i);
677     EVT VT = Op.getNode()->getValueType(Op.getResNo());
678     if (VT == MVT::Glue)
679       return NULL;
680   }
681
682   if (TryUnfold) {
683     SmallVector<SDNode*, 2> NewNodes;
684     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
685       return NULL;
686
687     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
688     assert(NewNodes.size() == 2 && "Expected a load folding node!");
689
690     N = NewNodes[1];
691     SDNode *LoadNode = NewNodes[0];
692     unsigned NumVals = N->getNumValues();
693     unsigned OldNumVals = SU->getNode()->getNumValues();
694     for (unsigned i = 0; i != NumVals; ++i)
695       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
696     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
697                                    SDValue(LoadNode, 1));
698
699     // LoadNode may already exist. This can happen when there is another
700     // load from the same location and producing the same type of value
701     // but it has different alignment or volatileness.
702     bool isNewLoad = true;
703     SUnit *LoadSU;
704     if (LoadNode->getNodeId() != -1) {
705       LoadSU = &SUnits[LoadNode->getNodeId()];
706       isNewLoad = false;
707     } else {
708       LoadSU = CreateNewSUnit(LoadNode);
709       LoadNode->setNodeId(LoadSU->NodeNum);
710       ComputeLatency(LoadSU);
711     }
712
713     SUnit *NewSU = CreateNewSUnit(N);
714     assert(N->getNodeId() == -1 && "Node already inserted!");
715     N->setNodeId(NewSU->NodeNum);
716
717     const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
718     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
719       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
720         NewSU->isTwoAddress = true;
721         break;
722       }
723     }
724     if (TID.isCommutable())
725       NewSU->isCommutable = true;
726     ComputeLatency(NewSU);
727
728     // Record all the edges to and from the old SU, by category.
729     SmallVector<SDep, 4> ChainPreds;
730     SmallVector<SDep, 4> ChainSuccs;
731     SmallVector<SDep, 4> LoadPreds;
732     SmallVector<SDep, 4> NodePreds;
733     SmallVector<SDep, 4> NodeSuccs;
734     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
735          I != E; ++I) {
736       if (I->isCtrl())
737         ChainPreds.push_back(*I);
738       else if (isOperandOf(I->getSUnit(), LoadNode))
739         LoadPreds.push_back(*I);
740       else
741         NodePreds.push_back(*I);
742     }
743     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
744          I != E; ++I) {
745       if (I->isCtrl())
746         ChainSuccs.push_back(*I);
747       else
748         NodeSuccs.push_back(*I);
749     }
750
751     // Now assign edges to the newly-created nodes.
752     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
753       const SDep &Pred = ChainPreds[i];
754       RemovePred(SU, Pred);
755       if (isNewLoad)
756         AddPred(LoadSU, Pred);
757     }
758     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
759       const SDep &Pred = LoadPreds[i];
760       RemovePred(SU, Pred);
761       if (isNewLoad)
762         AddPred(LoadSU, Pred);
763     }
764     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
765       const SDep &Pred = NodePreds[i];
766       RemovePred(SU, Pred);
767       AddPred(NewSU, Pred);
768     }
769     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
770       SDep D = NodeSuccs[i];
771       SUnit *SuccDep = D.getSUnit();
772       D.setSUnit(SU);
773       RemovePred(SuccDep, D);
774       D.setSUnit(NewSU);
775       AddPred(SuccDep, D);
776     }
777     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
778       SDep D = ChainSuccs[i];
779       SUnit *SuccDep = D.getSUnit();
780       D.setSUnit(SU);
781       RemovePred(SuccDep, D);
782       if (isNewLoad) {
783         D.setSUnit(LoadSU);
784         AddPred(SuccDep, D);
785       }
786     }
787
788     // Add a data dependency to reflect that NewSU reads the value defined
789     // by LoadSU.
790     AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
791
792     if (isNewLoad)
793       AvailableQueue->addNode(LoadSU);
794     AvailableQueue->addNode(NewSU);
795
796     ++NumUnfolds;
797
798     if (NewSU->NumSuccsLeft == 0) {
799       NewSU->isAvailable = true;
800       return NewSU;
801     }
802     SU = NewSU;
803   }
804
805   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
806   NewSU = CreateClone(SU);
807
808   // New SUnit has the exact same predecessors.
809   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
810        I != E; ++I)
811     if (!I->isArtificial())
812       AddPred(NewSU, *I);
813
814   // Only copy scheduled successors. Cut them from old node's successor
815   // list and move them over.
816   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
817   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
818        I != E; ++I) {
819     if (I->isArtificial())
820       continue;
821     SUnit *SuccSU = I->getSUnit();
822     if (SuccSU->isScheduled) {
823       SDep D = *I;
824       D.setSUnit(NewSU);
825       AddPred(SuccSU, D);
826       D.setSUnit(SU);
827       DelDeps.push_back(std::make_pair(SuccSU, D));
828     }
829   }
830   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
831     RemovePred(DelDeps[i].first, DelDeps[i].second);
832
833   AvailableQueue->updateNode(SU);
834   AvailableQueue->addNode(NewSU);
835
836   ++NumDups;
837   return NewSU;
838 }
839
840 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
841 /// scheduled successors of the given SUnit to the last copy.
842 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
843                                                const TargetRegisterClass *DestRC,
844                                                const TargetRegisterClass *SrcRC,
845                                                SmallVector<SUnit*, 2> &Copies) {
846   SUnit *CopyFromSU = CreateNewSUnit(NULL);
847   CopyFromSU->CopySrcRC = SrcRC;
848   CopyFromSU->CopyDstRC = DestRC;
849
850   SUnit *CopyToSU = CreateNewSUnit(NULL);
851   CopyToSU->CopySrcRC = DestRC;
852   CopyToSU->CopyDstRC = SrcRC;
853
854   // Only copy scheduled successors. Cut them from old node's successor
855   // list and move them over.
856   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
857   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
858        I != E; ++I) {
859     if (I->isArtificial())
860       continue;
861     SUnit *SuccSU = I->getSUnit();
862     if (SuccSU->isScheduled) {
863       SDep D = *I;
864       D.setSUnit(CopyToSU);
865       AddPred(SuccSU, D);
866       DelDeps.push_back(std::make_pair(SuccSU, *I));
867     }
868   }
869   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
870     RemovePred(DelDeps[i].first, DelDeps[i].second);
871
872   AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
873   AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
874
875   AvailableQueue->updateNode(SU);
876   AvailableQueue->addNode(CopyFromSU);
877   AvailableQueue->addNode(CopyToSU);
878   Copies.push_back(CopyFromSU);
879   Copies.push_back(CopyToSU);
880
881   ++NumPRCopies;
882 }
883
884 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
885 /// definition of the specified node.
886 /// FIXME: Move to SelectionDAG?
887 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
888                                  const TargetInstrInfo *TII) {
889   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
890   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
891   unsigned NumRes = TID.getNumDefs();
892   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
893     if (Reg == *ImpDef)
894       break;
895     ++NumRes;
896   }
897   return N->getValueType(NumRes);
898 }
899
900 /// CheckForLiveRegDef - Return true and update live register vector if the
901 /// specified register def of the specified SUnit clobbers any "live" registers.
902 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
903                                std::vector<SUnit*> &LiveRegDefs,
904                                SmallSet<unsigned, 4> &RegAdded,
905                                SmallVector<unsigned, 4> &LRegs,
906                                const TargetRegisterInfo *TRI) {
907   for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
908
909     // Check if Ref is live.
910     if (!LiveRegDefs[Reg]) continue;
911
912     // Allow multiple uses of the same def.
913     if (LiveRegDefs[Reg] == SU) continue;
914
915     // Add Reg to the set of interfering live regs.
916     if (RegAdded.insert(Reg))
917       LRegs.push_back(Reg);
918   }
919 }
920
921 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
922 /// scheduling of the given node to satisfy live physical register dependencies.
923 /// If the specific node is the last one that's available to schedule, do
924 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
925 bool ScheduleDAGRRList::
926 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
927   if (NumLiveRegs == 0)
928     return false;
929
930   SmallSet<unsigned, 4> RegAdded;
931   // If this node would clobber any "live" register, then it's not ready.
932   //
933   // If SU is the currently live definition of the same register that it uses,
934   // then we are free to schedule it.
935   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
936        I != E; ++I) {
937     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
938       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
939                          RegAdded, LRegs, TRI);
940   }
941
942   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
943     if (Node->getOpcode() == ISD::INLINEASM) {
944       // Inline asm can clobber physical defs.
945       unsigned NumOps = Node->getNumOperands();
946       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
947         --NumOps;  // Ignore the glue operand.
948
949       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
950         unsigned Flags =
951           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
952         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
953
954         ++i; // Skip the ID value.
955         if (InlineAsm::isRegDefKind(Flags) ||
956             InlineAsm::isRegDefEarlyClobberKind(Flags)) {
957           // Check for def of register or earlyclobber register.
958           for (; NumVals; --NumVals, ++i) {
959             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
960             if (TargetRegisterInfo::isPhysicalRegister(Reg))
961               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
962           }
963         } else
964           i += NumVals;
965       }
966       continue;
967     }
968
969     if (!Node->isMachineOpcode())
970       continue;
971     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
972     if (!TID.ImplicitDefs)
973       continue;
974     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
975       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
976   }
977
978   return !LRegs.empty();
979 }
980
981 /// Return a node that can be scheduled in this cycle. Requirements:
982 /// (1) Ready: latency has been satisfied
983 /// (2) No Hazards: resources are available
984 /// (3) No Interferences: may unschedule to break register interferences.
985 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
986   SmallVector<SUnit*, 4> Interferences;
987   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
988
989   SUnit *CurSU = AvailableQueue->pop();
990   while (CurSU) {
991     SmallVector<unsigned, 4> LRegs;
992     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
993       break;
994     LRegsMap.insert(std::make_pair(CurSU, LRegs));
995
996     CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
997     Interferences.push_back(CurSU);
998     CurSU = AvailableQueue->pop();
999   }
1000   if (CurSU) {
1001     // Add the nodes that aren't ready back onto the available list.
1002     for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1003       Interferences[i]->isPending = false;
1004       assert(Interferences[i]->isAvailable && "must still be available");
1005       AvailableQueue->push(Interferences[i]);
1006     }
1007     return CurSU;
1008   }
1009
1010   // All candidates are delayed due to live physical reg dependencies.
1011   // Try backtracking, code duplication, or inserting cross class copies
1012   // to resolve it.
1013   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1014     SUnit *TrySU = Interferences[i];
1015     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1016
1017     // Try unscheduling up to the point where it's safe to schedule
1018     // this node.
1019     SUnit *BtSU = NULL;
1020     unsigned LiveCycle = UINT_MAX;
1021     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1022       unsigned Reg = LRegs[j];
1023       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1024         BtSU = LiveRegGens[Reg];
1025         LiveCycle = BtSU->getHeight();
1026       }
1027     }
1028     if (!WillCreateCycle(TrySU, BtSU))  {
1029       BacktrackBottomUp(TrySU, BtSU);
1030
1031       // Force the current node to be scheduled before the node that
1032       // requires the physical reg dep.
1033       if (BtSU->isAvailable) {
1034         BtSU->isAvailable = false;
1035         if (!BtSU->isPending)
1036           AvailableQueue->remove(BtSU);
1037       }
1038       AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1039                           /*Reg=*/0, /*isNormalMemory=*/false,
1040                           /*isMustAlias=*/false, /*isArtificial=*/true));
1041
1042       // If one or more successors has been unscheduled, then the current
1043       // node is no longer avaialable. Schedule a successor that's now
1044       // available instead.
1045       if (!TrySU->isAvailable) {
1046         CurSU = AvailableQueue->pop();
1047       }
1048       else {
1049         CurSU = TrySU;
1050         TrySU->isPending = false;
1051         Interferences.erase(Interferences.begin()+i);
1052       }
1053       break;
1054     }
1055   }
1056
1057   if (!CurSU) {
1058     // Can't backtrack. If it's too expensive to copy the value, then try
1059     // duplicate the nodes that produces these "too expensive to copy"
1060     // values to break the dependency. In case even that doesn't work,
1061     // insert cross class copies.
1062     // If it's not too expensive, i.e. cost != -1, issue copies.
1063     SUnit *TrySU = Interferences[0];
1064     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1065     assert(LRegs.size() == 1 && "Can't handle this yet!");
1066     unsigned Reg = LRegs[0];
1067     SUnit *LRDef = LiveRegDefs[Reg];
1068     EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1069     const TargetRegisterClass *RC =
1070       TRI->getMinimalPhysRegClass(Reg, VT);
1071     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1072
1073     // If cross copy register class is null, then it must be possible copy
1074     // the value directly. Do not try duplicate the def.
1075     SUnit *NewDef = 0;
1076     if (DestRC)
1077       NewDef = CopyAndMoveSuccessors(LRDef);
1078     else
1079       DestRC = RC;
1080     if (!NewDef) {
1081       // Issue copies, these can be expensive cross register class copies.
1082       SmallVector<SUnit*, 2> Copies;
1083       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1084       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
1085             << " to SU #" << Copies.front()->NodeNum << "\n");
1086       AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1087                           /*Reg=*/0, /*isNormalMemory=*/false,
1088                           /*isMustAlias=*/false,
1089                           /*isArtificial=*/true));
1090       NewDef = Copies.back();
1091     }
1092
1093     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
1094           << " to SU #" << TrySU->NodeNum << "\n");
1095     LiveRegDefs[Reg] = NewDef;
1096     AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1097                          /*Reg=*/0, /*isNormalMemory=*/false,
1098                          /*isMustAlias=*/false,
1099                          /*isArtificial=*/true));
1100     TrySU->isAvailable = false;
1101     CurSU = NewDef;
1102   }
1103
1104   assert(CurSU && "Unable to resolve live physical register dependencies!");
1105
1106   // Add the nodes that aren't ready back onto the available list.
1107   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1108     Interferences[i]->isPending = false;
1109     // May no longer be available due to backtracking.
1110     if (Interferences[i]->isAvailable) {
1111       AvailableQueue->push(Interferences[i]);
1112     }
1113   }
1114   return CurSU;
1115 }
1116
1117 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1118 /// schedulers.
1119 void ScheduleDAGRRList::ListScheduleBottomUp() {
1120   // Release any predecessors of the special Exit node.
1121   ReleasePredecessors(&ExitSU);
1122
1123   // Add root to Available queue.
1124   if (!SUnits.empty()) {
1125     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1126     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1127     RootSU->isAvailable = true;
1128     AvailableQueue->push(RootSU);
1129   }
1130
1131   // While Available queue is not empty, grab the node with the highest
1132   // priority. If it is not ready put it back.  Schedule the node.
1133   Sequence.reserve(SUnits.size());
1134   while (!AvailableQueue->empty()) {
1135     DEBUG(dbgs() << "\n*** Examining Available\n";
1136           AvailableQueue->dump(this));
1137
1138     // Pick the best node to schedule taking all constraints into
1139     // consideration.
1140     SUnit *SU = PickNodeToScheduleBottomUp();
1141
1142     AdvancePastStalls(SU);
1143
1144     ScheduleNodeBottomUp(SU);
1145
1146     while (AvailableQueue->empty() && !PendingQueue.empty()) {
1147       // Advance the cycle to free resources. Skip ahead to the next ready SU.
1148       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1149       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1150     }
1151   }
1152
1153   // Reverse the order if it is bottom up.
1154   std::reverse(Sequence.begin(), Sequence.end());
1155
1156 #ifndef NDEBUG
1157   VerifySchedule(isBottomUp);
1158 #endif
1159 }
1160
1161 //===----------------------------------------------------------------------===//
1162 //  Top-Down Scheduling
1163 //===----------------------------------------------------------------------===//
1164
1165 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1166 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1167 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1168   SUnit *SuccSU = SuccEdge->getSUnit();
1169
1170 #ifndef NDEBUG
1171   if (SuccSU->NumPredsLeft == 0) {
1172     dbgs() << "*** Scheduling failed! ***\n";
1173     SuccSU->dump(this);
1174     dbgs() << " has been released too many times!\n";
1175     llvm_unreachable(0);
1176   }
1177 #endif
1178   --SuccSU->NumPredsLeft;
1179
1180   // If all the node's predecessors are scheduled, this node is ready
1181   // to be scheduled. Ignore the special ExitSU node.
1182   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1183     SuccSU->isAvailable = true;
1184     AvailableQueue->push(SuccSU);
1185   }
1186 }
1187
1188 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1189   // Top down: release successors
1190   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1191        I != E; ++I) {
1192     assert(!I->isAssignedRegDep() &&
1193            "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1194
1195     ReleaseSucc(SU, &*I);
1196   }
1197 }
1198
1199 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1200 /// count of its successors. If a successor pending count is zero, add it to
1201 /// the Available queue.
1202 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1203   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1204   DEBUG(SU->dump(this));
1205
1206   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1207   SU->setDepthToAtLeast(CurCycle);
1208   Sequence.push_back(SU);
1209
1210   ReleaseSuccessors(SU);
1211   SU->isScheduled = true;
1212   AvailableQueue->ScheduledNode(SU);
1213 }
1214
1215 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1216 /// schedulers.
1217 void ScheduleDAGRRList::ListScheduleTopDown() {
1218   AvailableQueue->setCurCycle(CurCycle);
1219
1220   // Release any successors of the special Entry node.
1221   ReleaseSuccessors(&EntrySU);
1222
1223   // All leaves to Available queue.
1224   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1225     // It is available if it has no predecessors.
1226     if (SUnits[i].Preds.empty()) {
1227       AvailableQueue->push(&SUnits[i]);
1228       SUnits[i].isAvailable = true;
1229     }
1230   }
1231
1232   // While Available queue is not empty, grab the node with the highest
1233   // priority. If it is not ready put it back.  Schedule the node.
1234   Sequence.reserve(SUnits.size());
1235   while (!AvailableQueue->empty()) {
1236     SUnit *CurSU = AvailableQueue->pop();
1237
1238     if (CurSU)
1239       ScheduleNodeTopDown(CurSU);
1240     ++CurCycle;
1241     AvailableQueue->setCurCycle(CurCycle);
1242   }
1243
1244 #ifndef NDEBUG
1245   VerifySchedule(isBottomUp);
1246 #endif
1247 }
1248
1249
1250 //===----------------------------------------------------------------------===//
1251 //                RegReductionPriorityQueue Definition
1252 //===----------------------------------------------------------------------===//
1253 //
1254 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1255 // to reduce register pressure.
1256 //
1257 namespace {
1258 class RegReductionPQBase;
1259
1260 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1261   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1262 };
1263
1264 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1265 // reduction scheduler.
1266 struct bu_ls_rr_sort : public queue_sort {
1267   enum {
1268     IsBottomUp = true,
1269     HasReadyFilter = false
1270   };
1271
1272   RegReductionPQBase *SPQ;
1273   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1274   bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1275
1276   bool operator()(SUnit* left, SUnit* right) const;
1277 };
1278
1279 // td_ls_rr_sort - Priority function for top down register pressure reduction
1280 // scheduler.
1281 struct td_ls_rr_sort : public queue_sort {
1282   enum {
1283     IsBottomUp = false,
1284     HasReadyFilter = false
1285   };
1286
1287   RegReductionPQBase *SPQ;
1288   td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1289   td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1290
1291   bool operator()(const SUnit* left, const SUnit* right) const;
1292 };
1293
1294 // src_ls_rr_sort - Priority function for source order scheduler.
1295 struct src_ls_rr_sort : public queue_sort {
1296   enum {
1297     IsBottomUp = true,
1298     HasReadyFilter = false
1299   };
1300
1301   RegReductionPQBase *SPQ;
1302   src_ls_rr_sort(RegReductionPQBase *spq)
1303     : SPQ(spq) {}
1304   src_ls_rr_sort(const src_ls_rr_sort &RHS)
1305     : SPQ(RHS.SPQ) {}
1306
1307   bool operator()(SUnit* left, SUnit* right) const;
1308 };
1309
1310 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1311 struct hybrid_ls_rr_sort : public queue_sort {
1312   enum {
1313     IsBottomUp = true,
1314     HasReadyFilter = true
1315   };
1316
1317   RegReductionPQBase *SPQ;
1318   hybrid_ls_rr_sort(RegReductionPQBase *spq)
1319     : SPQ(spq) {}
1320   hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1321     : SPQ(RHS.SPQ) {}
1322
1323   bool isReady(SUnit *SU, unsigned CurCycle) const;
1324
1325   bool operator()(SUnit* left, SUnit* right) const;
1326 };
1327
1328 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1329 // scheduler.
1330 struct ilp_ls_rr_sort : public queue_sort {
1331   enum {
1332     IsBottomUp = true,
1333     HasReadyFilter = true
1334   };
1335
1336   RegReductionPQBase *SPQ;
1337   ilp_ls_rr_sort(RegReductionPQBase *spq)
1338     : SPQ(spq) {}
1339   ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1340     : SPQ(RHS.SPQ) {}
1341
1342   bool isReady(SUnit *SU, unsigned CurCycle) const;
1343
1344   bool operator()(SUnit* left, SUnit* right) const;
1345 };
1346
1347 class RegReductionPQBase : public SchedulingPriorityQueue {
1348 protected:
1349   std::vector<SUnit*> Queue;
1350   unsigned CurQueueId;
1351   bool TracksRegPressure;
1352
1353   // SUnits - The SUnits for the current graph.
1354   std::vector<SUnit> *SUnits;
1355
1356   MachineFunction &MF;
1357   const TargetInstrInfo *TII;
1358   const TargetRegisterInfo *TRI;
1359   const TargetLowering *TLI;
1360   ScheduleDAGRRList *scheduleDAG;
1361
1362   // SethiUllmanNumbers - The SethiUllman number for each node.
1363   std::vector<unsigned> SethiUllmanNumbers;
1364
1365   /// RegPressure - Tracking current reg pressure per register class.
1366   ///
1367   std::vector<unsigned> RegPressure;
1368
1369   /// RegLimit - Tracking the number of allocatable registers per register
1370   /// class.
1371   std::vector<unsigned> RegLimit;
1372
1373 public:
1374   RegReductionPQBase(MachineFunction &mf,
1375                      bool hasReadyFilter,
1376                      bool tracksrp,
1377                      const TargetInstrInfo *tii,
1378                      const TargetRegisterInfo *tri,
1379                      const TargetLowering *tli)
1380     : SchedulingPriorityQueue(hasReadyFilter),
1381       CurQueueId(0), TracksRegPressure(tracksrp),
1382       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1383     if (TracksRegPressure) {
1384       unsigned NumRC = TRI->getNumRegClasses();
1385       RegLimit.resize(NumRC);
1386       RegPressure.resize(NumRC);
1387       std::fill(RegLimit.begin(), RegLimit.end(), 0);
1388       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1389       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1390              E = TRI->regclass_end(); I != E; ++I)
1391         RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1392     }
1393   }
1394
1395   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1396     scheduleDAG = scheduleDag;
1397   }
1398
1399   ScheduleHazardRecognizer* getHazardRec() {
1400     return scheduleDAG->getHazardRec();
1401   }
1402
1403   void initNodes(std::vector<SUnit> &sunits);
1404
1405   void addNode(const SUnit *SU);
1406
1407   void updateNode(const SUnit *SU);
1408
1409   void releaseState() {
1410     SUnits = 0;
1411     SethiUllmanNumbers.clear();
1412     std::fill(RegPressure.begin(), RegPressure.end(), 0);
1413   }
1414
1415   unsigned getNodePriority(const SUnit *SU) const;
1416
1417   unsigned getNodeOrdering(const SUnit *SU) const {
1418     return scheduleDAG->DAG->GetOrdering(SU->getNode());
1419   }
1420
1421   bool empty() const { return Queue.empty(); }
1422
1423   void push(SUnit *U) {
1424     assert(!U->NodeQueueId && "Node in the queue already");
1425     U->NodeQueueId = ++CurQueueId;
1426     Queue.push_back(U);
1427   }
1428
1429   void remove(SUnit *SU) {
1430     assert(!Queue.empty() && "Queue is empty!");
1431     assert(SU->NodeQueueId != 0 && "Not in queue!");
1432     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1433                                                  SU);
1434     if (I != prior(Queue.end()))
1435       std::swap(*I, Queue.back());
1436     Queue.pop_back();
1437     SU->NodeQueueId = 0;
1438   }
1439
1440   void dumpRegPressure() const;
1441
1442   bool HighRegPressure(const SUnit *SU) const;
1443
1444   bool MayReduceRegPressure(SUnit *SU);
1445
1446   void ScheduledNode(SUnit *SU);
1447
1448   void UnscheduledNode(SUnit *SU);
1449
1450 protected:
1451   bool canClobber(const SUnit *SU, const SUnit *Op);
1452   void AddPseudoTwoAddrDeps();
1453   void PrescheduleNodesWithMultipleUses();
1454   void CalculateSethiUllmanNumbers();
1455 };
1456
1457 template<class SF>
1458 class RegReductionPriorityQueue : public RegReductionPQBase {
1459   static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1460     std::vector<SUnit *>::iterator Best = Q.begin();
1461     for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1462            E = Q.end(); I != E; ++I)
1463       if (Picker(*Best, *I))
1464         Best = I;
1465     SUnit *V = *Best;
1466     if (Best != prior(Q.end()))
1467       std::swap(*Best, Q.back());
1468     Q.pop_back();
1469     return V;
1470   }
1471
1472   SF Picker;
1473
1474 public:
1475   RegReductionPriorityQueue(MachineFunction &mf,
1476                             bool tracksrp,
1477                             const TargetInstrInfo *tii,
1478                             const TargetRegisterInfo *tri,
1479                             const TargetLowering *tli)
1480     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1481       Picker(this) {}
1482
1483   bool isBottomUp() const { return SF::IsBottomUp; }
1484
1485   bool isReady(SUnit *U) const {
1486     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1487   }
1488
1489   SUnit *pop() {
1490     if (Queue.empty()) return NULL;
1491
1492     SUnit *V = popFromQueue(Queue, Picker);
1493     V->NodeQueueId = 0;
1494     return V;
1495   }
1496
1497   void dump(ScheduleDAG *DAG) const {
1498     // Emulate pop() without clobbering NodeQueueIds.
1499     std::vector<SUnit*> DumpQueue = Queue;
1500     SF DumpPicker = Picker;
1501     while (!DumpQueue.empty()) {
1502       SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1503       if (isBottomUp())
1504         dbgs() << "Height " << SU->getHeight() << ": ";
1505       else
1506         dbgs() << "Depth " << SU->getDepth() << ": ";
1507       SU->dump(DAG);
1508     }
1509   }
1510 };
1511
1512 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1513 BURegReductionPriorityQueue;
1514
1515 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1516 TDRegReductionPriorityQueue;
1517
1518 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1519 SrcRegReductionPriorityQueue;
1520
1521 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1522 HybridBURRPriorityQueue;
1523
1524 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1525 ILPBURRPriorityQueue;
1526 } // end anonymous namespace
1527
1528 //===----------------------------------------------------------------------===//
1529 //           Static Node Priority for Register Pressure Reduction
1530 //===----------------------------------------------------------------------===//
1531
1532 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1533 /// Smaller number is the higher priority.
1534 static unsigned
1535 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1536   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1537   if (SethiUllmanNumber != 0)
1538     return SethiUllmanNumber;
1539
1540   unsigned Extra = 0;
1541   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1542        I != E; ++I) {
1543     if (I->isCtrl()) continue;  // ignore chain preds
1544     SUnit *PredSU = I->getSUnit();
1545     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1546     if (PredSethiUllman > SethiUllmanNumber) {
1547       SethiUllmanNumber = PredSethiUllman;
1548       Extra = 0;
1549     } else if (PredSethiUllman == SethiUllmanNumber)
1550       ++Extra;
1551   }
1552
1553   SethiUllmanNumber += Extra;
1554
1555   if (SethiUllmanNumber == 0)
1556     SethiUllmanNumber = 1;
1557
1558   return SethiUllmanNumber;
1559 }
1560
1561 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1562 /// scheduling units.
1563 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1564   SethiUllmanNumbers.assign(SUnits->size(), 0);
1565
1566   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1567     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1568 }
1569
1570 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1571   SUnits = &sunits;
1572   // Add pseudo dependency edges for two-address nodes.
1573   AddPseudoTwoAddrDeps();
1574   // Reroute edges to nodes with multiple uses.
1575   PrescheduleNodesWithMultipleUses();
1576   // Calculate node priorities.
1577   CalculateSethiUllmanNumbers();
1578 }
1579
1580 void RegReductionPQBase::addNode(const SUnit *SU) {
1581   unsigned SUSize = SethiUllmanNumbers.size();
1582   if (SUnits->size() > SUSize)
1583     SethiUllmanNumbers.resize(SUSize*2, 0);
1584   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1585 }
1586
1587 void RegReductionPQBase::updateNode(const SUnit *SU) {
1588   SethiUllmanNumbers[SU->NodeNum] = 0;
1589   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1590 }
1591
1592 // Lower priority means schedule further down. For bottom-up scheduling, lower
1593 // priority SUs are scheduled before higher priority SUs.
1594 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1595   assert(SU->NodeNum < SethiUllmanNumbers.size());
1596   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1597   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1598     // CopyToReg should be close to its uses to facilitate coalescing and
1599     // avoid spilling.
1600     return 0;
1601   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1602       Opc == TargetOpcode::SUBREG_TO_REG ||
1603       Opc == TargetOpcode::INSERT_SUBREG)
1604     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1605     // close to their uses to facilitate coalescing.
1606     return 0;
1607   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1608     // If SU does not have a register use, i.e. it doesn't produce a value
1609     // that would be consumed (e.g. store), then it terminates a chain of
1610     // computation.  Give it a large SethiUllman number so it will be
1611     // scheduled right before its predecessors that it doesn't lengthen
1612     // their live ranges.
1613     return 0xffff;
1614   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1615     // If SU does not have a register def, schedule it close to its uses
1616     // because it does not lengthen any live ranges.
1617     return 0;
1618   return SethiUllmanNumbers[SU->NodeNum];
1619 }
1620
1621 //===----------------------------------------------------------------------===//
1622 //                     Register Pressure Tracking
1623 //===----------------------------------------------------------------------===//
1624
1625 void RegReductionPQBase::dumpRegPressure() const {
1626   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1627          E = TRI->regclass_end(); I != E; ++I) {
1628     const TargetRegisterClass *RC = *I;
1629     unsigned Id = RC->getID();
1630     unsigned RP = RegPressure[Id];
1631     if (!RP) continue;
1632     DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1633           << '\n');
1634   }
1635 }
1636
1637 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1638   if (!TLI)
1639     return false;
1640
1641   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1642        I != E; ++I) {
1643     if (I->isCtrl())
1644       continue;
1645     SUnit *PredSU = I->getSUnit();
1646     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1647     // counts data deps.  To be more precise, we could maintain a
1648     // NumDataSuccsLeft count.
1649     if (PredSU->NumSuccsLeft != PredSU->Succs.size()) {
1650       DEBUG(dbgs() << "  SU(" << PredSU->NodeNum << ") live across SU("
1651             << SU->NodeNum << ")\n");
1652       continue;
1653     }
1654     const SDNode *PN = PredSU->getNode();
1655     if (!PN->isMachineOpcode()) {
1656       if (PN->getOpcode() == ISD::CopyFromReg) {
1657         EVT VT = PN->getValueType(0);
1658         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1659         unsigned Cost = TLI->getRepRegClassCostFor(VT);
1660         if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1661           return true;
1662       }
1663       continue;
1664     }
1665     unsigned POpc = PN->getMachineOpcode();
1666     if (POpc == TargetOpcode::IMPLICIT_DEF)
1667       continue;
1668     if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1669       EVT VT = PN->getOperand(0).getValueType();
1670       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1671       unsigned Cost = TLI->getRepRegClassCostFor(VT);
1672       // Check if this increases register pressure of the specific register
1673       // class to the point where it would cause spills.
1674       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1675         return true;
1676       continue;
1677     } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1678                POpc == TargetOpcode::SUBREG_TO_REG) {
1679       EVT VT = PN->getValueType(0);
1680       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1681       unsigned Cost = TLI->getRepRegClassCostFor(VT);
1682       // Check if this increases register pressure of the specific register
1683       // class to the point where it would cause spills.
1684       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1685         return true;
1686       continue;
1687     }
1688     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1689     for (unsigned i = 0; i != NumDefs; ++i) {
1690       EVT VT = PN->getValueType(i);
1691       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1692       if (RegPressure[RCId] >= RegLimit[RCId])
1693         return true; // Reg pressure already high.
1694       unsigned Cost = TLI->getRepRegClassCostFor(VT);
1695       if (!PN->hasAnyUseOfValue(i))
1696         continue;
1697       // Check if this increases register pressure of the specific register
1698       // class to the point where it would cause spills.
1699       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1700         return true;
1701     }
1702   }
1703
1704   return false;
1705 }
1706
1707 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1708   const SDNode *N = SU->getNode();
1709
1710   if (!N->isMachineOpcode() || !SU->NumSuccs)
1711     return false;
1712
1713   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1714   for (unsigned i = 0; i != NumDefs; ++i) {
1715     EVT VT = N->getValueType(i);
1716     if (!N->hasAnyUseOfValue(i))
1717       continue;
1718     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1719     if (RegPressure[RCId] >= RegLimit[RCId])
1720       return true;
1721   }
1722   return false;
1723 }
1724
1725 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1726   if (!TracksRegPressure)
1727     return;
1728
1729   const SDNode *N = SU->getNode();
1730   if (!N->isMachineOpcode()) {
1731     if (N->getOpcode() != ISD::CopyToReg)
1732       return;
1733   } else {
1734     unsigned Opc = N->getMachineOpcode();
1735     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1736         Opc == TargetOpcode::INSERT_SUBREG ||
1737         Opc == TargetOpcode::SUBREG_TO_REG ||
1738         Opc == TargetOpcode::REG_SEQUENCE ||
1739         Opc == TargetOpcode::IMPLICIT_DEF)
1740       return;
1741   }
1742
1743   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1744        I != E; ++I) {
1745     if (I->isCtrl())
1746       continue;
1747     SUnit *PredSU = I->getSUnit();
1748     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1749     // counts data deps.
1750     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1751       continue;
1752     const SDNode *PN = PredSU->getNode();
1753     if (!PN->isMachineOpcode()) {
1754       if (PN->getOpcode() == ISD::CopyFromReg) {
1755         EVT VT = PN->getValueType(0);
1756         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1757         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1758       }
1759       continue;
1760     }
1761     unsigned POpc = PN->getMachineOpcode();
1762     if (POpc == TargetOpcode::IMPLICIT_DEF)
1763       continue;
1764     if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1765       EVT VT = PN->getOperand(0).getValueType();
1766       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1767       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1768       continue;
1769     } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1770                POpc == TargetOpcode::SUBREG_TO_REG) {
1771       EVT VT = PN->getValueType(0);
1772       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1773       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1774       continue;
1775     }
1776     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1777     for (unsigned i = 0; i != NumDefs; ++i) {
1778       EVT VT = PN->getValueType(i);
1779       if (!PN->hasAnyUseOfValue(i))
1780         continue;
1781       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1782       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1783     }
1784   }
1785
1786   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1787   // may transfer data dependencies to CopyToReg.
1788   if (SU->NumSuccs && N->isMachineOpcode()) {
1789     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1790     for (unsigned i = 0; i != NumDefs; ++i) {
1791       EVT VT = N->getValueType(i);
1792       if (!N->hasAnyUseOfValue(i))
1793         continue;
1794       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1795       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1796         // Register pressure tracking is imprecise. This can happen.
1797         RegPressure[RCId] = 0;
1798       else
1799         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1800     }
1801   }
1802
1803   dumpRegPressure();
1804 }
1805
1806 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1807   if (!TracksRegPressure)
1808     return;
1809
1810   const SDNode *N = SU->getNode();
1811   if (!N->isMachineOpcode()) {
1812     if (N->getOpcode() != ISD::CopyToReg)
1813       return;
1814   } else {
1815     unsigned Opc = N->getMachineOpcode();
1816     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1817         Opc == TargetOpcode::INSERT_SUBREG ||
1818         Opc == TargetOpcode::SUBREG_TO_REG ||
1819         Opc == TargetOpcode::REG_SEQUENCE ||
1820         Opc == TargetOpcode::IMPLICIT_DEF)
1821       return;
1822   }
1823
1824   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1825        I != E; ++I) {
1826     if (I->isCtrl())
1827       continue;
1828     SUnit *PredSU = I->getSUnit();
1829     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1830     // counts data deps.
1831     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1832       continue;
1833     const SDNode *PN = PredSU->getNode();
1834     if (!PN->isMachineOpcode()) {
1835       if (PN->getOpcode() == ISD::CopyFromReg) {
1836         EVT VT = PN->getValueType(0);
1837         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1838         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1839       }
1840       continue;
1841     }
1842     unsigned POpc = PN->getMachineOpcode();
1843     if (POpc == TargetOpcode::IMPLICIT_DEF)
1844       continue;
1845     if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1846       EVT VT = PN->getOperand(0).getValueType();
1847       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1848       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1849       continue;
1850     } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1851                POpc == TargetOpcode::SUBREG_TO_REG) {
1852       EVT VT = PN->getValueType(0);
1853       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1854       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1855       continue;
1856     }
1857     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1858     for (unsigned i = 0; i != NumDefs; ++i) {
1859       EVT VT = PN->getValueType(i);
1860       if (!PN->hasAnyUseOfValue(i))
1861         continue;
1862       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1863       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1864         // Register pressure tracking is imprecise. This can happen.
1865         RegPressure[RCId] = 0;
1866       else
1867         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1868     }
1869   }
1870
1871   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1872   // may transfer data dependencies to CopyToReg.
1873   if (SU->NumSuccs && N->isMachineOpcode()) {
1874     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1875     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1876       EVT VT = N->getValueType(i);
1877       if (VT == MVT::Glue || VT == MVT::Other)
1878         continue;
1879       if (!N->hasAnyUseOfValue(i))
1880         continue;
1881       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1882       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1883     }
1884   }
1885
1886   dumpRegPressure();
1887 }
1888
1889 //===----------------------------------------------------------------------===//
1890 //           Dynamic Node Priority for Register Pressure Reduction
1891 //===----------------------------------------------------------------------===//
1892
1893 /// closestSucc - Returns the scheduled cycle of the successor which is
1894 /// closest to the current cycle.
1895 static unsigned closestSucc(const SUnit *SU) {
1896   unsigned MaxHeight = 0;
1897   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1898        I != E; ++I) {
1899     if (I->isCtrl()) continue;  // ignore chain succs
1900     unsigned Height = I->getSUnit()->getHeight();
1901     // If there are bunch of CopyToRegs stacked up, they should be considered
1902     // to be at the same position.
1903     if (I->getSUnit()->getNode() &&
1904         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1905       Height = closestSucc(I->getSUnit())+1;
1906     if (Height > MaxHeight)
1907       MaxHeight = Height;
1908   }
1909   return MaxHeight;
1910 }
1911
1912 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1913 /// for scratch registers, i.e. number of data dependencies.
1914 static unsigned calcMaxScratches(const SUnit *SU) {
1915   unsigned Scratches = 0;
1916   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1917        I != E; ++I) {
1918     if (I->isCtrl()) continue;  // ignore chain preds
1919     Scratches++;
1920   }
1921   return Scratches;
1922 }
1923
1924 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1925 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1926 /// it has no other use. It should be scheduled closer to the terminator.
1927 static bool hasOnlyLiveOutUses(const SUnit *SU) {
1928   bool RetVal = false;
1929   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1930        I != E; ++I) {
1931     if (I->isCtrl()) continue;
1932     const SUnit *SuccSU = I->getSUnit();
1933     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1934       unsigned Reg =
1935         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1936       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1937         RetVal = true;
1938         continue;
1939       }
1940     }
1941     return false;
1942   }
1943   return RetVal;
1944 }
1945
1946 /// UnitsSharePred - Return true if the two scheduling units share a common
1947 /// data predecessor.
1948 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1949   SmallSet<const SUnit*, 4> Preds;
1950   for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1951        I != E; ++I) {
1952     if (I->isCtrl()) continue;  // ignore chain preds
1953     Preds.insert(I->getSUnit());
1954   }
1955   for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1956        I != E; ++I) {
1957     if (I->isCtrl()) continue;  // ignore chain preds
1958     if (Preds.count(I->getSUnit()))
1959       return true;
1960   }
1961   return false;
1962 }
1963
1964 // Check for either a dependence (latency) or resource (hazard) stall.
1965 //
1966 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1967 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1968   if ((int)SPQ->getCurCycle() < Height) return true;
1969   if (SPQ->getHazardRec()->getHazardType(SU, 0)
1970       != ScheduleHazardRecognizer::NoHazard)
1971     return true;
1972   return false;
1973 }
1974
1975 // Return -1 if left has higher priority, 1 if right has higher priority.
1976 // Return 0 if latency-based priority is equivalent.
1977 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1978                             RegReductionPQBase *SPQ) {
1979   // If the two nodes share an operand and one of them has a single
1980   // use that is a live out copy, favor the one that is live out. Otherwise
1981   // it will be difficult to eliminate the copy if the instruction is a
1982   // loop induction variable update. e.g.
1983   // BB:
1984   // sub r1, r3, #1
1985   // str r0, [r2, r3]
1986   // mov r3, r1
1987   // cmp
1988   // bne BB
1989   bool SharePred = UnitsSharePred(left, right);
1990   // FIXME: Only adjust if BB is a loop back edge.
1991   // FIXME: What's the cost of a copy?
1992   int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1993   int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1994   int LHeight = (int)left->getHeight() - LBonus;
1995   int RHeight = (int)right->getHeight() - RBonus;
1996
1997   bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1998     BUHasStall(left, LHeight, SPQ);
1999   bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2000     BUHasStall(right, RHeight, SPQ);
2001
2002   // If scheduling one of the node will cause a pipeline stall, delay it.
2003   // If scheduling either one of the node will cause a pipeline stall, sort
2004   // them according to their height.
2005   if (LStall) {
2006     if (!RStall)
2007       return 1;
2008     if (LHeight != RHeight)
2009       return LHeight > RHeight ? 1 : -1;
2010   } else if (RStall)
2011     return -1;
2012
2013   // If either node is scheduling for latency, sort them by depth
2014   // and latency.
2015   if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2016                      right->SchedulingPref == Sched::Latency)) {
2017     int LDepth = (int)left->getDepth();
2018     int RDepth = (int)right->getDepth();
2019
2020     if (EnableSchedCycles) {
2021       if (LDepth != RDepth)
2022         DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
2023               << ") depth " << LDepth << " vs SU (" << right->NodeNum
2024               << ") depth " << RDepth << ")\n");
2025         return LDepth < RDepth ? 1 : -1;
2026     }
2027     else {
2028       if (LHeight != RHeight)
2029         return LHeight > RHeight ? 1 : -1;
2030     }
2031     if (left->Latency != right->Latency)
2032       return left->Latency > right->Latency ? 1 : -1;
2033   }
2034   return 0;
2035 }
2036
2037 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2038   unsigned LPriority = SPQ->getNodePriority(left);
2039   unsigned RPriority = SPQ->getNodePriority(right);
2040   if (LPriority != RPriority)
2041     return LPriority > RPriority;
2042
2043   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2044   // e.g.
2045   // t1 = op t2, c1
2046   // t3 = op t4, c2
2047   //
2048   // and the following instructions are both ready.
2049   // t2 = op c3
2050   // t4 = op c4
2051   //
2052   // Then schedule t2 = op first.
2053   // i.e.
2054   // t4 = op c4
2055   // t2 = op c3
2056   // t1 = op t2, c1
2057   // t3 = op t4, c2
2058   //
2059   // This creates more short live intervals.
2060   unsigned LDist = closestSucc(left);
2061   unsigned RDist = closestSucc(right);
2062   if (LDist != RDist)
2063     return LDist < RDist;
2064
2065   // How many registers becomes live when the node is scheduled.
2066   unsigned LScratch = calcMaxScratches(left);
2067   unsigned RScratch = calcMaxScratches(right);
2068   if (LScratch != RScratch)
2069     return LScratch > RScratch;
2070
2071   if (EnableSchedCycles) {
2072     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2073     if (result != 0)
2074       return result > 0;
2075   }
2076   else {
2077     if (left->getHeight() != right->getHeight())
2078       return left->getHeight() > right->getHeight();
2079
2080     if (left->getDepth() != right->getDepth())
2081       return left->getDepth() < right->getDepth();
2082   }
2083
2084   assert(left->NodeQueueId && right->NodeQueueId &&
2085          "NodeQueueId cannot be zero");
2086   return (left->NodeQueueId > right->NodeQueueId);
2087 }
2088
2089 // Bottom up
2090 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2091   return BURRSort(left, right, SPQ);
2092 }
2093
2094 // Source order, otherwise bottom up.
2095 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2096   unsigned LOrder = SPQ->getNodeOrdering(left);
2097   unsigned ROrder = SPQ->getNodeOrdering(right);
2098
2099   // Prefer an ordering where the lower the non-zero order number, the higher
2100   // the preference.
2101   if ((LOrder || ROrder) && LOrder != ROrder)
2102     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2103
2104   return BURRSort(left, right, SPQ);
2105 }
2106
2107 // If the time between now and when the instruction will be ready can cover
2108 // the spill code, then avoid adding it to the ready queue. This gives long
2109 // stalls highest priority and allows hoisting across calls. It should also
2110 // speed up processing the available queue.
2111 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2112   static const unsigned ReadyDelay = 3;
2113
2114   if (SPQ->MayReduceRegPressure(SU)) return true;
2115
2116   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2117
2118   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2119       != ScheduleHazardRecognizer::NoHazard)
2120     return false;
2121
2122   return true;
2123 }
2124
2125 // Return true if right should be scheduled with higher priority than left.
2126 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2127   if (left->isCall || right->isCall)
2128     // No way to compute latency of calls.
2129     return BURRSort(left, right, SPQ);
2130
2131   bool LHigh = SPQ->HighRegPressure(left);
2132   bool RHigh = SPQ->HighRegPressure(right);
2133   // Avoid causing spills. If register pressure is high, schedule for
2134   // register pressure reduction.
2135   if (LHigh && !RHigh) {
2136     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
2137           << right->NodeNum << ")\n");
2138     return true;
2139   }
2140   else if (!LHigh && RHigh) {
2141     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
2142           << left->NodeNum << ")\n");
2143     return false;
2144   }
2145   else if (!LHigh && !RHigh) {
2146     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2147     if (result != 0)
2148       return result > 0;
2149   }
2150   return BURRSort(left, right, SPQ);
2151 }
2152
2153 // Schedule as many instructions in each cycle as possible. So don't make an
2154 // instruction available unless it is ready in the current cycle.
2155 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2156   if (SU->getHeight() > CurCycle) return false;
2157
2158   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2159       != ScheduleHazardRecognizer::NoHazard)
2160     return false;
2161
2162   return SU->getHeight() <= CurCycle;
2163 }
2164
2165 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2166   if (left->isCall || right->isCall)
2167     // No way to compute latency of calls.
2168     return BURRSort(left, right, SPQ);
2169
2170   bool LHigh = SPQ->HighRegPressure(left);
2171   bool RHigh = SPQ->HighRegPressure(right);
2172   // Avoid causing spills. If register pressure is high, schedule for
2173   // register pressure reduction.
2174   if (LHigh && !RHigh)
2175     return true;
2176   else if (!LHigh && RHigh)
2177     return false;
2178   else if (!LHigh && !RHigh) {
2179     // Low register pressure situation, schedule to maximize instruction level
2180     // parallelism.
2181     if (left->NumPreds > right->NumPreds)
2182       return false;
2183     else if (left->NumPreds < right->NumPreds)
2184       return false;
2185   }
2186
2187   return BURRSort(left, right, SPQ);
2188 }
2189
2190 //===----------------------------------------------------------------------===//
2191 //                    Preschedule for Register Pressure
2192 //===----------------------------------------------------------------------===//
2193
2194 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2195   if (SU->isTwoAddress) {
2196     unsigned Opc = SU->getNode()->getMachineOpcode();
2197     const TargetInstrDesc &TID = TII->get(Opc);
2198     unsigned NumRes = TID.getNumDefs();
2199     unsigned NumOps = TID.getNumOperands() - NumRes;
2200     for (unsigned i = 0; i != NumOps; ++i) {
2201       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2202         SDNode *DU = SU->getNode()->getOperand(i).getNode();
2203         if (DU->getNodeId() != -1 &&
2204             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2205           return true;
2206       }
2207     }
2208   }
2209   return false;
2210 }
2211
2212 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2213 /// physical register defs.
2214 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2215                                   const TargetInstrInfo *TII,
2216                                   const TargetRegisterInfo *TRI) {
2217   SDNode *N = SuccSU->getNode();
2218   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2219   const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2220   assert(ImpDefs && "Caller should check hasPhysRegDefs");
2221   for (const SDNode *SUNode = SU->getNode(); SUNode;
2222        SUNode = SUNode->getGluedNode()) {
2223     if (!SUNode->isMachineOpcode())
2224       continue;
2225     const unsigned *SUImpDefs =
2226       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2227     if (!SUImpDefs)
2228       return false;
2229     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2230       EVT VT = N->getValueType(i);
2231       if (VT == MVT::Glue || VT == MVT::Other)
2232         continue;
2233       if (!N->hasAnyUseOfValue(i))
2234         continue;
2235       unsigned Reg = ImpDefs[i - NumDefs];
2236       for (;*SUImpDefs; ++SUImpDefs) {
2237         unsigned SUReg = *SUImpDefs;
2238         if (TRI->regsOverlap(Reg, SUReg))
2239           return true;
2240       }
2241     }
2242   }
2243   return false;
2244 }
2245
2246 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2247 /// are not handled well by the general register pressure reduction
2248 /// heuristics. When presented with code like this:
2249 ///
2250 ///      N
2251 ///    / |
2252 ///   /  |
2253 ///  U  store
2254 ///  |
2255 /// ...
2256 ///
2257 /// the heuristics tend to push the store up, but since the
2258 /// operand of the store has another use (U), this would increase
2259 /// the length of that other use (the U->N edge).
2260 ///
2261 /// This function transforms code like the above to route U's
2262 /// dependence through the store when possible, like this:
2263 ///
2264 ///      N
2265 ///      ||
2266 ///      ||
2267 ///     store
2268 ///       |
2269 ///       U
2270 ///       |
2271 ///      ...
2272 ///
2273 /// This results in the store being scheduled immediately
2274 /// after N, which shortens the U->N live range, reducing
2275 /// register pressure.
2276 ///
2277 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2278   // Visit all the nodes in topological order, working top-down.
2279   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2280     SUnit *SU = &(*SUnits)[i];
2281     // For now, only look at nodes with no data successors, such as stores.
2282     // These are especially important, due to the heuristics in
2283     // getNodePriority for nodes with no data successors.
2284     if (SU->NumSuccs != 0)
2285       continue;
2286     // For now, only look at nodes with exactly one data predecessor.
2287     if (SU->NumPreds != 1)
2288       continue;
2289     // Avoid prescheduling copies to virtual registers, which don't behave
2290     // like other nodes from the perspective of scheduling heuristics.
2291     if (SDNode *N = SU->getNode())
2292       if (N->getOpcode() == ISD::CopyToReg &&
2293           TargetRegisterInfo::isVirtualRegister
2294             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2295         continue;
2296
2297     // Locate the single data predecessor.
2298     SUnit *PredSU = 0;
2299     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2300          EE = SU->Preds.end(); II != EE; ++II)
2301       if (!II->isCtrl()) {
2302         PredSU = II->getSUnit();
2303         break;
2304       }
2305     assert(PredSU);
2306
2307     // Don't rewrite edges that carry physregs, because that requires additional
2308     // support infrastructure.
2309     if (PredSU->hasPhysRegDefs)
2310       continue;
2311     // Short-circuit the case where SU is PredSU's only data successor.
2312     if (PredSU->NumSuccs == 1)
2313       continue;
2314     // Avoid prescheduling to copies from virtual registers, which don't behave
2315     // like other nodes from the perspective of scheduling // heuristics.
2316     if (SDNode *N = SU->getNode())
2317       if (N->getOpcode() == ISD::CopyFromReg &&
2318           TargetRegisterInfo::isVirtualRegister
2319             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2320         continue;
2321
2322     // Perform checks on the successors of PredSU.
2323     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2324          EE = PredSU->Succs.end(); II != EE; ++II) {
2325       SUnit *PredSuccSU = II->getSUnit();
2326       if (PredSuccSU == SU) continue;
2327       // If PredSU has another successor with no data successors, for
2328       // now don't attempt to choose either over the other.
2329       if (PredSuccSU->NumSuccs == 0)
2330         goto outer_loop_continue;
2331       // Don't break physical register dependencies.
2332       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2333         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2334           goto outer_loop_continue;
2335       // Don't introduce graph cycles.
2336       if (scheduleDAG->IsReachable(SU, PredSuccSU))
2337         goto outer_loop_continue;
2338     }
2339
2340     // Ok, the transformation is safe and the heuristics suggest it is
2341     // profitable. Update the graph.
2342     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
2343                  << " next to PredSU #" << PredSU->NodeNum
2344                  << " to guide scheduling in the presence of multiple uses\n");
2345     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2346       SDep Edge = PredSU->Succs[i];
2347       assert(!Edge.isAssignedRegDep());
2348       SUnit *SuccSU = Edge.getSUnit();
2349       if (SuccSU != SU) {
2350         Edge.setSUnit(PredSU);
2351         scheduleDAG->RemovePred(SuccSU, Edge);
2352         scheduleDAG->AddPred(SU, Edge);
2353         Edge.setSUnit(SU);
2354         scheduleDAG->AddPred(SuccSU, Edge);
2355         --i;
2356       }
2357     }
2358   outer_loop_continue:;
2359   }
2360 }
2361
2362 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2363 /// it as a def&use operand. Add a pseudo control edge from it to the other
2364 /// node (if it won't create a cycle) so the two-address one will be scheduled
2365 /// first (lower in the schedule). If both nodes are two-address, favor the
2366 /// one that has a CopyToReg use (more likely to be a loop induction update).
2367 /// If both are two-address, but one is commutable while the other is not
2368 /// commutable, favor the one that's not commutable.
2369 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2370   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2371     SUnit *SU = &(*SUnits)[i];
2372     if (!SU->isTwoAddress)
2373       continue;
2374
2375     SDNode *Node = SU->getNode();
2376     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2377       continue;
2378
2379     bool isLiveOut = hasOnlyLiveOutUses(SU);
2380     unsigned Opc = Node->getMachineOpcode();
2381     const TargetInstrDesc &TID = TII->get(Opc);
2382     unsigned NumRes = TID.getNumDefs();
2383     unsigned NumOps = TID.getNumOperands() - NumRes;
2384     for (unsigned j = 0; j != NumOps; ++j) {
2385       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2386         continue;
2387       SDNode *DU = SU->getNode()->getOperand(j).getNode();
2388       if (DU->getNodeId() == -1)
2389         continue;
2390       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2391       if (!DUSU) continue;
2392       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2393            E = DUSU->Succs.end(); I != E; ++I) {
2394         if (I->isCtrl()) continue;
2395         SUnit *SuccSU = I->getSUnit();
2396         if (SuccSU == SU)
2397           continue;
2398         // Be conservative. Ignore if nodes aren't at roughly the same
2399         // depth and height.
2400         if (SuccSU->getHeight() < SU->getHeight() &&
2401             (SU->getHeight() - SuccSU->getHeight()) > 1)
2402           continue;
2403         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2404         // constrains whatever is using the copy, instead of the copy
2405         // itself. In the case that the copy is coalesced, this
2406         // preserves the intent of the pseudo two-address heurietics.
2407         while (SuccSU->Succs.size() == 1 &&
2408                SuccSU->getNode()->isMachineOpcode() &&
2409                SuccSU->getNode()->getMachineOpcode() ==
2410                  TargetOpcode::COPY_TO_REGCLASS)
2411           SuccSU = SuccSU->Succs.front().getSUnit();
2412         // Don't constrain non-instruction nodes.
2413         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2414           continue;
2415         // Don't constrain nodes with physical register defs if the
2416         // predecessor can clobber them.
2417         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2418           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2419             continue;
2420         }
2421         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2422         // these may be coalesced away. We want them close to their uses.
2423         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2424         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2425             SuccOpc == TargetOpcode::INSERT_SUBREG ||
2426             SuccOpc == TargetOpcode::SUBREG_TO_REG)
2427           continue;
2428         if ((!canClobber(SuccSU, DUSU) ||
2429              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2430              (!SU->isCommutable && SuccSU->isCommutable)) &&
2431             !scheduleDAG->IsReachable(SuccSU, SU)) {
2432           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
2433                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2434           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2435                                         /*Reg=*/0, /*isNormalMemory=*/false,
2436                                         /*isMustAlias=*/false,
2437                                         /*isArtificial=*/true));
2438         }
2439       }
2440     }
2441   }
2442 }
2443
2444 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2445 /// predecessors of the successors of the SUnit SU. Stop when the provided
2446 /// limit is exceeded.
2447 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2448                                                     unsigned Limit) {
2449   unsigned Sum = 0;
2450   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2451        I != E; ++I) {
2452     const SUnit *SuccSU = I->getSUnit();
2453     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2454          EE = SuccSU->Preds.end(); II != EE; ++II) {
2455       SUnit *PredSU = II->getSUnit();
2456       if (!PredSU->isScheduled)
2457         if (++Sum > Limit)
2458           return Sum;
2459     }
2460   }
2461   return Sum;
2462 }
2463
2464
2465 // Top down
2466 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2467   unsigned LPriority = SPQ->getNodePriority(left);
2468   unsigned RPriority = SPQ->getNodePriority(right);
2469   bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2470   bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2471   bool LIsFloater = LIsTarget && left->NumPreds == 0;
2472   bool RIsFloater = RIsTarget && right->NumPreds == 0;
2473   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2474   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2475
2476   if (left->NumSuccs == 0 && right->NumSuccs != 0)
2477     return false;
2478   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2479     return true;
2480
2481   if (LIsFloater)
2482     LBonus -= 2;
2483   if (RIsFloater)
2484     RBonus -= 2;
2485   if (left->NumSuccs == 1)
2486     LBonus += 2;
2487   if (right->NumSuccs == 1)
2488     RBonus += 2;
2489
2490   if (LPriority+LBonus != RPriority+RBonus)
2491     return LPriority+LBonus < RPriority+RBonus;
2492
2493   if (left->getDepth() != right->getDepth())
2494     return left->getDepth() < right->getDepth();
2495
2496   if (left->NumSuccsLeft != right->NumSuccsLeft)
2497     return left->NumSuccsLeft > right->NumSuccsLeft;
2498
2499   assert(left->NodeQueueId && right->NodeQueueId &&
2500          "NodeQueueId cannot be zero");
2501   return (left->NodeQueueId > right->NodeQueueId);
2502 }
2503
2504 //===----------------------------------------------------------------------===//
2505 //                         Public Constructor Functions
2506 //===----------------------------------------------------------------------===//
2507
2508 llvm::ScheduleDAGSDNodes *
2509 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2510                                  CodeGenOpt::Level OptLevel) {
2511   const TargetMachine &TM = IS->TM;
2512   const TargetInstrInfo *TII = TM.getInstrInfo();
2513   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2514
2515   BURegReductionPriorityQueue *PQ =
2516     new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2517   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2518   PQ->setScheduleDAG(SD);
2519   return SD;
2520 }
2521
2522 llvm::ScheduleDAGSDNodes *
2523 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2524                                  CodeGenOpt::Level OptLevel) {
2525   const TargetMachine &TM = IS->TM;
2526   const TargetInstrInfo *TII = TM.getInstrInfo();
2527   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2528
2529   TDRegReductionPriorityQueue *PQ =
2530     new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2531   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2532   PQ->setScheduleDAG(SD);
2533   return SD;
2534 }
2535
2536 llvm::ScheduleDAGSDNodes *
2537 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2538                                    CodeGenOpt::Level OptLevel) {
2539   const TargetMachine &TM = IS->TM;
2540   const TargetInstrInfo *TII = TM.getInstrInfo();
2541   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2542
2543   SrcRegReductionPriorityQueue *PQ =
2544     new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2545   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2546   PQ->setScheduleDAG(SD);
2547   return SD;
2548 }
2549
2550 llvm::ScheduleDAGSDNodes *
2551 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2552                                    CodeGenOpt::Level OptLevel) {
2553   const TargetMachine &TM = IS->TM;
2554   const TargetInstrInfo *TII = TM.getInstrInfo();
2555   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2556   const TargetLowering *TLI = &IS->getTargetLowering();
2557
2558   HybridBURRPriorityQueue *PQ =
2559     new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2560
2561   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2562   PQ->setScheduleDAG(SD);
2563   return SD;
2564 }
2565
2566 llvm::ScheduleDAGSDNodes *
2567 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2568                                 CodeGenOpt::Level OptLevel) {
2569   const TargetMachine &TM = IS->TM;
2570   const TargetInstrInfo *TII = TM.getInstrInfo();
2571   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2572   const TargetLowering *TLI = &IS->getTargetLowering();
2573
2574   ILPBURRPriorityQueue *PQ =
2575     new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2576   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2577   PQ->setScheduleDAG(SD);
2578   return SD;
2579 }