mi-sched: Don't call MBB.size() in initSUnits. The driver already has instr count.
[oota-llvm.git] / lib / CodeGen / MachineScheduler.cpp
1 //===- MachineScheduler.cpp - Machine Instruction 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 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "misched"
16
17 #include "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/PriorityQueue.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDFS.h"
28 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include <queue>
36
37 using namespace llvm;
38
39 namespace llvm {
40 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41                            cl::desc("Force top-down list scheduling"));
42 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43                             cl::desc("Force bottom-up list scheduling"));
44 }
45
46 #ifndef NDEBUG
47 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48   cl::desc("Pop up a window to show MISched dags after they are processed"));
49
50 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
52 #else
53 static bool ViewMISchedDAGs = false;
54 #endif // NDEBUG
55
56 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
57   cl::desc("Enable load clustering."), cl::init(true));
58
59 // Experimental heuristics
60 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
61   cl::desc("Enable scheduling for macro fusion."), cl::init(true));
62
63 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
64   cl::desc("Verify machine instrs before and after machine scheduling"));
65
66 // DAG subtrees must have at least this many nodes.
67 static const unsigned MinSubtreeSize = 8;
68
69 //===----------------------------------------------------------------------===//
70 // Machine Instruction Scheduling Pass and Registry
71 //===----------------------------------------------------------------------===//
72
73 MachineSchedContext::MachineSchedContext():
74     MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
75   RegClassInfo = new RegisterClassInfo();
76 }
77
78 MachineSchedContext::~MachineSchedContext() {
79   delete RegClassInfo;
80 }
81
82 namespace {
83 /// MachineScheduler runs after coalescing and before register allocation.
84 class MachineScheduler : public MachineSchedContext,
85                          public MachineFunctionPass {
86 public:
87   MachineScheduler();
88
89   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
90
91   virtual void releaseMemory() {}
92
93   virtual bool runOnMachineFunction(MachineFunction&);
94
95   virtual void print(raw_ostream &O, const Module* = 0) const;
96
97   static char ID; // Class identification, replacement for typeinfo
98 };
99 } // namespace
100
101 char MachineScheduler::ID = 0;
102
103 char &llvm::MachineSchedulerID = MachineScheduler::ID;
104
105 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
106                       "Machine Instruction Scheduler", false, false)
107 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
108 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
109 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
110 INITIALIZE_PASS_END(MachineScheduler, "misched",
111                     "Machine Instruction Scheduler", false, false)
112
113 MachineScheduler::MachineScheduler()
114 : MachineFunctionPass(ID) {
115   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
116 }
117
118 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
119   AU.setPreservesCFG();
120   AU.addRequiredID(MachineDominatorsID);
121   AU.addRequired<MachineLoopInfo>();
122   AU.addRequired<AliasAnalysis>();
123   AU.addRequired<TargetPassConfig>();
124   AU.addRequired<SlotIndexes>();
125   AU.addPreserved<SlotIndexes>();
126   AU.addRequired<LiveIntervals>();
127   AU.addPreserved<LiveIntervals>();
128   MachineFunctionPass::getAnalysisUsage(AU);
129 }
130
131 MachinePassRegistry MachineSchedRegistry::Registry;
132
133 /// A dummy default scheduler factory indicates whether the scheduler
134 /// is overridden on the command line.
135 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
136   return 0;
137 }
138
139 /// MachineSchedOpt allows command line selection of the scheduler.
140 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
141                RegisterPassParser<MachineSchedRegistry> >
142 MachineSchedOpt("misched",
143                 cl::init(&useDefaultMachineSched), cl::Hidden,
144                 cl::desc("Machine instruction scheduler to use"));
145
146 static MachineSchedRegistry
147 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
148                      useDefaultMachineSched);
149
150 /// Forward declare the standard machine scheduler. This will be used as the
151 /// default scheduler if the target does not set a default.
152 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
153
154
155 /// Decrement this iterator until reaching the top or a non-debug instr.
156 static MachineBasicBlock::iterator
157 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
158   assert(I != Beg && "reached the top of the region, cannot decrement");
159   while (--I != Beg) {
160     if (!I->isDebugValue())
161       break;
162   }
163   return I;
164 }
165
166 /// If this iterator is a debug value, increment until reaching the End or a
167 /// non-debug instruction.
168 static MachineBasicBlock::iterator
169 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
170   for(; I != End; ++I) {
171     if (!I->isDebugValue())
172       break;
173   }
174   return I;
175 }
176
177 /// Top-level MachineScheduler pass driver.
178 ///
179 /// Visit blocks in function order. Divide each block into scheduling regions
180 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
181 /// consistent with the DAG builder, which traverses the interior of the
182 /// scheduling regions bottom-up.
183 ///
184 /// This design avoids exposing scheduling boundaries to the DAG builder,
185 /// simplifying the DAG builder's support for "special" target instructions.
186 /// At the same time the design allows target schedulers to operate across
187 /// scheduling boundaries, for example to bundle the boudary instructions
188 /// without reordering them. This creates complexity, because the target
189 /// scheduler must update the RegionBegin and RegionEnd positions cached by
190 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
191 /// design would be to split blocks at scheduling boundaries, but LLVM has a
192 /// general bias against block splitting purely for implementation simplicity.
193 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
194   DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
195
196   // Initialize the context of the pass.
197   MF = &mf;
198   MLI = &getAnalysis<MachineLoopInfo>();
199   MDT = &getAnalysis<MachineDominatorTree>();
200   PassConfig = &getAnalysis<TargetPassConfig>();
201   AA = &getAnalysis<AliasAnalysis>();
202
203   LIS = &getAnalysis<LiveIntervals>();
204   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
205
206   if (VerifyScheduling) {
207     DEBUG(LIS->dump());
208     MF->verify(this, "Before machine scheduling.");
209   }
210   RegClassInfo->runOnMachineFunction(*MF);
211
212   // Select the scheduler, or set the default.
213   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
214   if (Ctor == useDefaultMachineSched) {
215     // Get the default scheduler set by the target.
216     Ctor = MachineSchedRegistry::getDefault();
217     if (!Ctor) {
218       Ctor = createConvergingSched;
219       MachineSchedRegistry::setDefault(Ctor);
220     }
221   }
222   // Instantiate the selected scheduler.
223   OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
224
225   // Visit all machine basic blocks.
226   //
227   // TODO: Visit blocks in global postorder or postorder within the bottom-up
228   // loop tree. Then we can optionally compute global RegPressure.
229   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
230        MBB != MBBEnd; ++MBB) {
231
232     Scheduler->startBlock(MBB);
233
234     // Break the block into scheduling regions [I, RegionEnd), and schedule each
235     // region as soon as it is discovered. RegionEnd points the scheduling
236     // boundary at the bottom of the region. The DAG does not include RegionEnd,
237     // but the region does (i.e. the next RegionEnd is above the previous
238     // RegionBegin). If the current block has no terminator then RegionEnd ==
239     // MBB->end() for the bottom region.
240     //
241     // The Scheduler may insert instructions during either schedule() or
242     // exitRegion(), even for empty regions. So the local iterators 'I' and
243     // 'RegionEnd' are invalid across these calls.
244     unsigned RemainingInstrs = MBB->size();
245     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
246         RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
247
248       // Avoid decrementing RegionEnd for blocks with no terminator.
249       if (RegionEnd != MBB->end()
250           || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
251         --RegionEnd;
252         // Count the boundary instruction.
253         --RemainingInstrs;
254       }
255
256       // The next region starts above the previous region. Look backward in the
257       // instruction stream until we find the nearest boundary.
258       unsigned NumRegionInstrs = 0;
259       MachineBasicBlock::iterator I = RegionEnd;
260       for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
261         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
262           break;
263       }
264       // Notify the scheduler of the region, even if we may skip scheduling
265       // it. Perhaps it still needs to be bundled.
266       Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
267
268       // Skip empty scheduling regions (0 or 1 schedulable instructions).
269       if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
270         // Close the current region. Bundle the terminator if needed.
271         // This invalidates 'RegionEnd' and 'I'.
272         Scheduler->exitRegion();
273         continue;
274       }
275       DEBUG(dbgs() << "********** MI Scheduling **********\n");
276       DEBUG(dbgs() << MF->getName()
277             << ":BB#" << MBB->getNumber() << " " << MBB->getName()
278             << "\n  From: " << *I << "    To: ";
279             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
280             else dbgs() << "End";
281             dbgs() << " RegionInstrs: " << NumRegionInstrs
282             << " Remaining: " << RemainingInstrs << "\n");
283
284       // Schedule a region: possibly reorder instructions.
285       // This invalidates 'RegionEnd' and 'I'.
286       Scheduler->schedule();
287
288       // Close the current region.
289       Scheduler->exitRegion();
290
291       // Scheduling has invalidated the current iterator 'I'. Ask the
292       // scheduler for the top of it's scheduled region.
293       RegionEnd = Scheduler->begin();
294     }
295     assert(RemainingInstrs == 0 && "Instruction count mismatch!");
296     Scheduler->finishBlock();
297   }
298   Scheduler->finalizeSchedule();
299   DEBUG(LIS->dump());
300   if (VerifyScheduling)
301     MF->verify(this, "After machine scheduling.");
302   return true;
303 }
304
305 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
306   // unimplemented
307 }
308
309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
310 void ReadyQueue::dump() {
311   dbgs() << Name << ": ";
312   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
313     dbgs() << Queue[i]->NodeNum << " ";
314   dbgs() << "\n";
315 }
316 #endif
317
318 //===----------------------------------------------------------------------===//
319 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
320 // preservation.
321 //===----------------------------------------------------------------------===//
322
323 ScheduleDAGMI::~ScheduleDAGMI() {
324   delete DFSResult;
325   DeleteContainerPointers(Mutations);
326   delete SchedImpl;
327 }
328
329 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
330   return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
331 }
332
333 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
334   if (SuccSU != &ExitSU) {
335     // Do not use WillCreateCycle, it assumes SD scheduling.
336     // If Pred is reachable from Succ, then the edge creates a cycle.
337     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
338       return false;
339     Topo.AddPred(SuccSU, PredDep.getSUnit());
340   }
341   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
342   // Return true regardless of whether a new edge needed to be inserted.
343   return true;
344 }
345
346 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
347 /// NumPredsLeft reaches zero, release the successor node.
348 ///
349 /// FIXME: Adjust SuccSU height based on MinLatency.
350 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
351   SUnit *SuccSU = SuccEdge->getSUnit();
352
353   if (SuccEdge->isWeak()) {
354     --SuccSU->WeakPredsLeft;
355     if (SuccEdge->isCluster())
356       NextClusterSucc = SuccSU;
357     return;
358   }
359 #ifndef NDEBUG
360   if (SuccSU->NumPredsLeft == 0) {
361     dbgs() << "*** Scheduling failed! ***\n";
362     SuccSU->dump(this);
363     dbgs() << " has been released too many times!\n";
364     llvm_unreachable(0);
365   }
366 #endif
367   --SuccSU->NumPredsLeft;
368   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
369     SchedImpl->releaseTopNode(SuccSU);
370 }
371
372 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
373 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
374   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
375        I != E; ++I) {
376     releaseSucc(SU, &*I);
377   }
378 }
379
380 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
381 /// NumSuccsLeft reaches zero, release the predecessor node.
382 ///
383 /// FIXME: Adjust PredSU height based on MinLatency.
384 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
385   SUnit *PredSU = PredEdge->getSUnit();
386
387   if (PredEdge->isWeak()) {
388     --PredSU->WeakSuccsLeft;
389     if (PredEdge->isCluster())
390       NextClusterPred = PredSU;
391     return;
392   }
393 #ifndef NDEBUG
394   if (PredSU->NumSuccsLeft == 0) {
395     dbgs() << "*** Scheduling failed! ***\n";
396     PredSU->dump(this);
397     dbgs() << " has been released too many times!\n";
398     llvm_unreachable(0);
399   }
400 #endif
401   --PredSU->NumSuccsLeft;
402   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
403     SchedImpl->releaseBottomNode(PredSU);
404 }
405
406 /// releasePredecessors - Call releasePred on each of SU's predecessors.
407 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
408   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
409        I != E; ++I) {
410     releasePred(SU, &*I);
411   }
412 }
413
414 /// This is normally called from the main scheduler loop but may also be invoked
415 /// by the scheduling strategy to perform additional code motion.
416 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
417                                     MachineBasicBlock::iterator InsertPos) {
418   // Advance RegionBegin if the first instruction moves down.
419   if (&*RegionBegin == MI)
420     ++RegionBegin;
421
422   // Update the instruction stream.
423   BB->splice(InsertPos, BB, MI);
424
425   // Update LiveIntervals
426   LIS->handleMove(MI, /*UpdateFlags=*/true);
427
428   // Recede RegionBegin if an instruction moves above the first.
429   if (RegionBegin == InsertPos)
430     RegionBegin = MI;
431 }
432
433 bool ScheduleDAGMI::checkSchedLimit() {
434 #ifndef NDEBUG
435   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
436     CurrentTop = CurrentBottom;
437     return false;
438   }
439   ++NumInstrsScheduled;
440 #endif
441   return true;
442 }
443
444 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
445 /// crossing a scheduling boundary. [begin, end) includes all instructions in
446 /// the region, including the boundary itself and single-instruction regions
447 /// that don't get scheduled.
448 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
449                                 MachineBasicBlock::iterator begin,
450                                 MachineBasicBlock::iterator end,
451                                 unsigned regioninstrs)
452 {
453   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
454
455   // For convenience remember the end of the liveness region.
456   LiveRegionEnd =
457     (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
458 }
459
460 // Setup the register pressure trackers for the top scheduled top and bottom
461 // scheduled regions.
462 void ScheduleDAGMI::initRegPressure() {
463   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
464   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
465
466   // Close the RPTracker to finalize live ins.
467   RPTracker.closeRegion();
468
469   DEBUG(RPTracker.dump());
470
471   // Initialize the live ins and live outs.
472   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
473   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
474
475   // Close one end of the tracker so we can call
476   // getMaxUpward/DownwardPressureDelta before advancing across any
477   // instructions. This converts currently live regs into live ins/outs.
478   TopRPTracker.closeTop();
479   BotRPTracker.closeBottom();
480
481   BotRPTracker.initLiveThru(RPTracker);
482   if (!BotRPTracker.getLiveThru().empty()) {
483     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
484     DEBUG(dbgs() << "Live Thru: ";
485           dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
486   };
487
488   // Account for liveness generated by the region boundary.
489   if (LiveRegionEnd != RegionEnd)
490     BotRPTracker.recede();
491
492   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
493
494   // Cache the list of excess pressure sets in this region. This will also track
495   // the max pressure in the scheduled code for these sets.
496   RegionCriticalPSets.clear();
497   const std::vector<unsigned> &RegionPressure =
498     RPTracker.getPressure().MaxSetPressure;
499   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
500     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
501     if (RegionPressure[i] > Limit) {
502       DEBUG(dbgs() << TRI->getRegPressureSetName(i)
503             << " Limit " << Limit
504             << " Actual " << RegionPressure[i] << "\n");
505       RegionCriticalPSets.push_back(PressureElement(i, 0));
506     }
507   }
508   DEBUG(dbgs() << "Excess PSets: ";
509         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
510           dbgs() << TRI->getRegPressureSetName(
511             RegionCriticalPSets[i].PSetID) << " ";
512         dbgs() << "\n");
513 }
514
515 // FIXME: When the pressure tracker deals in pressure differences then we won't
516 // iterate over all RegionCriticalPSets[i].
517 void ScheduleDAGMI::
518 updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
519   for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
520     unsigned ID = RegionCriticalPSets[i].PSetID;
521     int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
522     if ((int)NewMaxPressure[ID] > MaxUnits)
523       MaxUnits = NewMaxPressure[ID];
524   }
525   DEBUG(
526     for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
527       unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
528       if (NewMaxPressure[i] > Limit ) {
529         dbgs() << "  " << TRI->getRegPressureSetName(i) << ": "
530                << NewMaxPressure[i] << " > " << Limit << "\n";
531       }
532     });
533 }
534
535 /// schedule - Called back from MachineScheduler::runOnMachineFunction
536 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
537 /// only includes instructions that have DAG nodes, not scheduling boundaries.
538 ///
539 /// This is a skeletal driver, with all the functionality pushed into helpers,
540 /// so that it can be easilly extended by experimental schedulers. Generally,
541 /// implementing MachineSchedStrategy should be sufficient to implement a new
542 /// scheduling algorithm. However, if a scheduler further subclasses
543 /// ScheduleDAGMI then it will want to override this virtual method in order to
544 /// update any specialized state.
545 void ScheduleDAGMI::schedule() {
546   buildDAGWithRegPressure();
547
548   Topo.InitDAGTopologicalSorting();
549
550   postprocessDAG();
551
552   SmallVector<SUnit*, 8> TopRoots, BotRoots;
553   findRootsAndBiasEdges(TopRoots, BotRoots);
554
555   // Initialize the strategy before modifying the DAG.
556   // This may initialize a DFSResult to be used for queue priority.
557   SchedImpl->initialize(this);
558
559   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
560           SUnits[su].dumpAll(this));
561   if (ViewMISchedDAGs) viewGraph();
562
563   // Initialize ready queues now that the DAG and priority data are finalized.
564   initQueues(TopRoots, BotRoots);
565
566   bool IsTopNode = false;
567   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
568     assert(!SU->isScheduled && "Node already scheduled");
569     if (!checkSchedLimit())
570       break;
571
572     scheduleMI(SU, IsTopNode);
573
574     updateQueues(SU, IsTopNode);
575   }
576   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
577
578   placeDebugValues();
579
580   DEBUG({
581       unsigned BBNum = begin()->getParent()->getNumber();
582       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
583       dumpSchedule();
584       dbgs() << '\n';
585     });
586 }
587
588 /// Build the DAG and setup three register pressure trackers.
589 void ScheduleDAGMI::buildDAGWithRegPressure() {
590   // Initialize the register pressure tracker used by buildSchedGraph.
591   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
592                  /*TrackUntiedDefs=*/true);
593
594   // Account for liveness generate by the region boundary.
595   if (LiveRegionEnd != RegionEnd)
596     RPTracker.recede();
597
598   // Build the DAG, and compute current register pressure.
599   buildSchedGraph(AA, &RPTracker);
600
601   // Initialize top/bottom trackers after computing region pressure.
602   initRegPressure();
603 }
604
605 /// Apply each ScheduleDAGMutation step in order.
606 void ScheduleDAGMI::postprocessDAG() {
607   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
608     Mutations[i]->apply(this);
609   }
610 }
611
612 void ScheduleDAGMI::computeDFSResult() {
613   if (!DFSResult)
614     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
615   DFSResult->clear();
616   ScheduledTrees.clear();
617   DFSResult->resize(SUnits.size());
618   DFSResult->compute(SUnits);
619   ScheduledTrees.resize(DFSResult->getNumSubtrees());
620 }
621
622 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
623                                           SmallVectorImpl<SUnit*> &BotRoots) {
624   for (std::vector<SUnit>::iterator
625          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
626     SUnit *SU = &(*I);
627     assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
628
629     // Order predecessors so DFSResult follows the critical path.
630     SU->biasCriticalPath();
631
632     // A SUnit is ready to top schedule if it has no predecessors.
633     if (!I->NumPredsLeft)
634       TopRoots.push_back(SU);
635     // A SUnit is ready to bottom schedule if it has no successors.
636     if (!I->NumSuccsLeft)
637       BotRoots.push_back(SU);
638   }
639   ExitSU.biasCriticalPath();
640 }
641
642 /// Identify DAG roots and setup scheduler queues.
643 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
644                                ArrayRef<SUnit*> BotRoots) {
645   NextClusterSucc = NULL;
646   NextClusterPred = NULL;
647
648   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
649   //
650   // Nodes with unreleased weak edges can still be roots.
651   // Release top roots in forward order.
652   for (SmallVectorImpl<SUnit*>::const_iterator
653          I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
654     SchedImpl->releaseTopNode(*I);
655   }
656   // Release bottom roots in reverse order so the higher priority nodes appear
657   // first. This is more natural and slightly more efficient.
658   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
659          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
660     SchedImpl->releaseBottomNode(*I);
661   }
662
663   releaseSuccessors(&EntrySU);
664   releasePredecessors(&ExitSU);
665
666   SchedImpl->registerRoots();
667
668   // Advance past initial DebugValues.
669   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
670   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
671   TopRPTracker.setPos(CurrentTop);
672
673   CurrentBottom = RegionEnd;
674 }
675
676 /// Move an instruction and update register pressure.
677 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
678   // Move the instruction to its new location in the instruction stream.
679   MachineInstr *MI = SU->getInstr();
680
681   if (IsTopNode) {
682     assert(SU->isTopReady() && "node still has unscheduled dependencies");
683     if (&*CurrentTop == MI)
684       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
685     else {
686       moveInstruction(MI, CurrentTop);
687       TopRPTracker.setPos(MI);
688     }
689
690     // Update top scheduled pressure.
691     TopRPTracker.advance();
692     assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
693     updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
694   }
695   else {
696     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
697     MachineBasicBlock::iterator priorII =
698       priorNonDebug(CurrentBottom, CurrentTop);
699     if (&*priorII == MI)
700       CurrentBottom = priorII;
701     else {
702       if (&*CurrentTop == MI) {
703         CurrentTop = nextIfDebug(++CurrentTop, priorII);
704         TopRPTracker.setPos(CurrentTop);
705       }
706       moveInstruction(MI, CurrentBottom);
707       CurrentBottom = MI;
708     }
709     // Update bottom scheduled pressure.
710     BotRPTracker.recede();
711     assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
712     updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
713   }
714 }
715
716 /// Update scheduler queues after scheduling an instruction.
717 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
718   // Release dependent instructions for scheduling.
719   if (IsTopNode)
720     releaseSuccessors(SU);
721   else
722     releasePredecessors(SU);
723
724   SU->isScheduled = true;
725
726   if (DFSResult) {
727     unsigned SubtreeID = DFSResult->getSubtreeID(SU);
728     if (!ScheduledTrees.test(SubtreeID)) {
729       ScheduledTrees.set(SubtreeID);
730       DFSResult->scheduleTree(SubtreeID);
731       SchedImpl->scheduleTree(SubtreeID);
732     }
733   }
734
735   // Notify the scheduling strategy after updating the DAG.
736   SchedImpl->schedNode(SU, IsTopNode);
737 }
738
739 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
740 void ScheduleDAGMI::placeDebugValues() {
741   // If first instruction was a DBG_VALUE then put it back.
742   if (FirstDbgValue) {
743     BB->splice(RegionBegin, BB, FirstDbgValue);
744     RegionBegin = FirstDbgValue;
745   }
746
747   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
748          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
749     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
750     MachineInstr *DbgValue = P.first;
751     MachineBasicBlock::iterator OrigPrevMI = P.second;
752     if (&*RegionBegin == DbgValue)
753       ++RegionBegin;
754     BB->splice(++OrigPrevMI, BB, DbgValue);
755     if (OrigPrevMI == llvm::prior(RegionEnd))
756       RegionEnd = DbgValue;
757   }
758   DbgValues.clear();
759   FirstDbgValue = NULL;
760 }
761
762 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
763 void ScheduleDAGMI::dumpSchedule() const {
764   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
765     if (SUnit *SU = getSUnit(&(*MI)))
766       SU->dump(this);
767     else
768       dbgs() << "Missing SUnit\n";
769   }
770 }
771 #endif
772
773 //===----------------------------------------------------------------------===//
774 // LoadClusterMutation - DAG post-processing to cluster loads.
775 //===----------------------------------------------------------------------===//
776
777 namespace {
778 /// \brief Post-process the DAG to create cluster edges between neighboring
779 /// loads.
780 class LoadClusterMutation : public ScheduleDAGMutation {
781   struct LoadInfo {
782     SUnit *SU;
783     unsigned BaseReg;
784     unsigned Offset;
785     LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
786       : SU(su), BaseReg(reg), Offset(ofs) {}
787   };
788   static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
789                            const LoadClusterMutation::LoadInfo &RHS);
790
791   const TargetInstrInfo *TII;
792   const TargetRegisterInfo *TRI;
793 public:
794   LoadClusterMutation(const TargetInstrInfo *tii,
795                       const TargetRegisterInfo *tri)
796     : TII(tii), TRI(tri) {}
797
798   virtual void apply(ScheduleDAGMI *DAG);
799 protected:
800   void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
801 };
802 } // anonymous
803
804 bool LoadClusterMutation::LoadInfoLess(
805   const LoadClusterMutation::LoadInfo &LHS,
806   const LoadClusterMutation::LoadInfo &RHS) {
807   if (LHS.BaseReg != RHS.BaseReg)
808     return LHS.BaseReg < RHS.BaseReg;
809   return LHS.Offset < RHS.Offset;
810 }
811
812 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
813                                                   ScheduleDAGMI *DAG) {
814   SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
815   for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
816     SUnit *SU = Loads[Idx];
817     unsigned BaseReg;
818     unsigned Offset;
819     if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
820       LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
821   }
822   if (LoadRecords.size() < 2)
823     return;
824   std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
825   unsigned ClusterLength = 1;
826   for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
827     if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
828       ClusterLength = 1;
829       continue;
830     }
831
832     SUnit *SUa = LoadRecords[Idx].SU;
833     SUnit *SUb = LoadRecords[Idx+1].SU;
834     if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
835         && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
836
837       DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
838             << SUb->NodeNum << ")\n");
839       // Copy successor edges from SUa to SUb. Interleaving computation
840       // dependent on SUa can prevent load combining due to register reuse.
841       // Predecessor edges do not need to be copied from SUb to SUa since nearby
842       // loads should have effectively the same inputs.
843       for (SUnit::const_succ_iterator
844              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
845         if (SI->getSUnit() == SUb)
846           continue;
847         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
848         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
849       }
850       ++ClusterLength;
851     }
852     else
853       ClusterLength = 1;
854   }
855 }
856
857 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
858 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
859   // Map DAG NodeNum to store chain ID.
860   DenseMap<unsigned, unsigned> StoreChainIDs;
861   // Map each store chain to a set of dependent loads.
862   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
863   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
864     SUnit *SU = &DAG->SUnits[Idx];
865     if (!SU->getInstr()->mayLoad())
866       continue;
867     unsigned ChainPredID = DAG->SUnits.size();
868     for (SUnit::const_pred_iterator
869            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
870       if (PI->isCtrl()) {
871         ChainPredID = PI->getSUnit()->NodeNum;
872         break;
873       }
874     }
875     // Check if this chain-like pred has been seen
876     // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
877     unsigned NumChains = StoreChainDependents.size();
878     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
879       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
880     if (Result.second)
881       StoreChainDependents.resize(NumChains + 1);
882     StoreChainDependents[Result.first->second].push_back(SU);
883   }
884   // Iterate over the store chains.
885   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
886     clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
887 }
888
889 //===----------------------------------------------------------------------===//
890 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
891 //===----------------------------------------------------------------------===//
892
893 namespace {
894 /// \brief Post-process the DAG to create cluster edges between instructions
895 /// that may be fused by the processor into a single operation.
896 class MacroFusion : public ScheduleDAGMutation {
897   const TargetInstrInfo *TII;
898 public:
899   MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
900
901   virtual void apply(ScheduleDAGMI *DAG);
902 };
903 } // anonymous
904
905 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
906 /// fused operations.
907 void MacroFusion::apply(ScheduleDAGMI *DAG) {
908   // For now, assume targets can only fuse with the branch.
909   MachineInstr *Branch = DAG->ExitSU.getInstr();
910   if (!Branch)
911     return;
912
913   for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
914     SUnit *SU = &DAG->SUnits[--Idx];
915     if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
916       continue;
917
918     // Create a single weak edge from SU to ExitSU. The only effect is to cause
919     // bottom-up scheduling to heavily prioritize the clustered SU.  There is no
920     // need to copy predecessor edges from ExitSU to SU, since top-down
921     // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
922     // of SU, we could create an artificial edge from the deepest root, but it
923     // hasn't been needed yet.
924     bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
925     (void)Success;
926     assert(Success && "No DAG nodes should be reachable from ExitSU");
927
928     DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
929     break;
930   }
931 }
932
933 //===----------------------------------------------------------------------===//
934 // CopyConstrain - DAG post-processing to encourage copy elimination.
935 //===----------------------------------------------------------------------===//
936
937 namespace {
938 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
939 /// the one use that defines the copy's source vreg, most likely an induction
940 /// variable increment.
941 class CopyConstrain : public ScheduleDAGMutation {
942   // Transient state.
943   SlotIndex RegionBeginIdx;
944   // RegionEndIdx is the slot index of the last non-debug instruction in the
945   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
946   SlotIndex RegionEndIdx;
947 public:
948   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
949
950   virtual void apply(ScheduleDAGMI *DAG);
951
952 protected:
953   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
954 };
955 } // anonymous
956
957 /// constrainLocalCopy handles two possibilities:
958 /// 1) Local src:
959 /// I0:     = dst
960 /// I1: src = ...
961 /// I2:     = dst
962 /// I3: dst = src (copy)
963 /// (create pred->succ edges I0->I1, I2->I1)
964 ///
965 /// 2) Local copy:
966 /// I0: dst = src (copy)
967 /// I1:     = dst
968 /// I2: src = ...
969 /// I3:     = dst
970 /// (create pred->succ edges I1->I2, I3->I2)
971 ///
972 /// Although the MachineScheduler is currently constrained to single blocks,
973 /// this algorithm should handle extended blocks. An EBB is a set of
974 /// contiguously numbered blocks such that the previous block in the EBB is
975 /// always the single predecessor.
976 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
977   LiveIntervals *LIS = DAG->getLIS();
978   MachineInstr *Copy = CopySU->getInstr();
979
980   // Check for pure vreg copies.
981   unsigned SrcReg = Copy->getOperand(1).getReg();
982   if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
983     return;
984
985   unsigned DstReg = Copy->getOperand(0).getReg();
986   if (!TargetRegisterInfo::isVirtualRegister(DstReg))
987     return;
988
989   // Check if either the dest or source is local. If it's live across a back
990   // edge, it's not local. Note that if both vregs are live across the back
991   // edge, we cannot successfully contrain the copy without cyclic scheduling.
992   unsigned LocalReg = DstReg;
993   unsigned GlobalReg = SrcReg;
994   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
995   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
996     LocalReg = SrcReg;
997     GlobalReg = DstReg;
998     LocalLI = &LIS->getInterval(LocalReg);
999     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1000       return;
1001   }
1002   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1003
1004   // Find the global segment after the start of the local LI.
1005   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1006   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1007   // local live range. We could create edges from other global uses to the local
1008   // start, but the coalescer should have already eliminated these cases, so
1009   // don't bother dealing with it.
1010   if (GlobalSegment == GlobalLI->end())
1011     return;
1012
1013   // If GlobalSegment is killed at the LocalLI->start, the call to find()
1014   // returned the next global segment. But if GlobalSegment overlaps with
1015   // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1016   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1017   if (GlobalSegment->contains(LocalLI->beginIndex()))
1018     ++GlobalSegment;
1019
1020   if (GlobalSegment == GlobalLI->end())
1021     return;
1022
1023   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1024   if (GlobalSegment != GlobalLI->begin()) {
1025     // Two address defs have no hole.
1026     if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1027                                GlobalSegment->start)) {
1028       return;
1029     }
1030     // If the prior global segment may be defined by the same two-address
1031     // instruction that also defines LocalLI, then can't make a hole here.
1032     if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1033                                LocalLI->beginIndex())) {
1034       return;
1035     }
1036     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1037     // it would be a disconnected component in the live range.
1038     assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1039            "Disconnected LRG within the scheduling region.");
1040   }
1041   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1042   if (!GlobalDef)
1043     return;
1044
1045   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1046   if (!GlobalSU)
1047     return;
1048
1049   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1050   // constraining the uses of the last local def to precede GlobalDef.
1051   SmallVector<SUnit*,8> LocalUses;
1052   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1053   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1054   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1055   for (SUnit::const_succ_iterator
1056          I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1057        I != E; ++I) {
1058     if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1059       continue;
1060     if (I->getSUnit() == GlobalSU)
1061       continue;
1062     if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1063       return;
1064     LocalUses.push_back(I->getSUnit());
1065   }
1066   // Open the top of the GlobalLI hole by constraining any earlier global uses
1067   // to precede the start of LocalLI.
1068   SmallVector<SUnit*,8> GlobalUses;
1069   MachineInstr *FirstLocalDef =
1070     LIS->getInstructionFromIndex(LocalLI->beginIndex());
1071   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1072   for (SUnit::const_pred_iterator
1073          I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1074     if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1075       continue;
1076     if (I->getSUnit() == FirstLocalSU)
1077       continue;
1078     if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1079       return;
1080     GlobalUses.push_back(I->getSUnit());
1081   }
1082   DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1083   // Add the weak edges.
1084   for (SmallVectorImpl<SUnit*>::const_iterator
1085          I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1086     DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1087           << GlobalSU->NodeNum << ")\n");
1088     DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1089   }
1090   for (SmallVectorImpl<SUnit*>::const_iterator
1091          I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1092     DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1093           << FirstLocalSU->NodeNum << ")\n");
1094     DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1095   }
1096 }
1097
1098 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1099 /// copy elimination.
1100 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1101   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1102   if (FirstPos == DAG->end())
1103     return;
1104   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1105   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1106     &*priorNonDebug(DAG->end(), DAG->begin()));
1107
1108   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1109     SUnit *SU = &DAG->SUnits[Idx];
1110     if (!SU->getInstr()->isCopy())
1111       continue;
1112
1113     constrainLocalCopy(SU, DAG);
1114   }
1115 }
1116
1117 //===----------------------------------------------------------------------===//
1118 // ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
1119 //===----------------------------------------------------------------------===//
1120
1121 namespace {
1122 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
1123 /// the schedule.
1124 class ConvergingScheduler : public MachineSchedStrategy {
1125 public:
1126   /// Represent the type of SchedCandidate found within a single queue.
1127   /// pickNodeBidirectional depends on these listed by decreasing priority.
1128   enum CandReason {
1129     NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
1130     ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
1131     TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
1132
1133 #ifndef NDEBUG
1134   static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
1135 #endif
1136
1137   /// Policy for scheduling the next instruction in the candidate's zone.
1138   struct CandPolicy {
1139     bool ReduceLatency;
1140     unsigned ReduceResIdx;
1141     unsigned DemandResIdx;
1142
1143     CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
1144   };
1145
1146   /// Status of an instruction's critical resource consumption.
1147   struct SchedResourceDelta {
1148     // Count critical resources in the scheduled region required by SU.
1149     unsigned CritResources;
1150
1151     // Count critical resources from another region consumed by SU.
1152     unsigned DemandedResources;
1153
1154     SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
1155
1156     bool operator==(const SchedResourceDelta &RHS) const {
1157       return CritResources == RHS.CritResources
1158         && DemandedResources == RHS.DemandedResources;
1159     }
1160     bool operator!=(const SchedResourceDelta &RHS) const {
1161       return !operator==(RHS);
1162     }
1163   };
1164
1165   /// Store the state used by ConvergingScheduler heuristics, required for the
1166   /// lifetime of one invocation of pickNode().
1167   struct SchedCandidate {
1168     CandPolicy Policy;
1169
1170     // The best SUnit candidate.
1171     SUnit *SU;
1172
1173     // The reason for this candidate.
1174     CandReason Reason;
1175
1176     // Set of reasons that apply to multiple candidates.
1177     uint32_t RepeatReasonSet;
1178
1179     // Register pressure values for the best candidate.
1180     RegPressureDelta RPDelta;
1181
1182     // Critical resource consumption of the best candidate.
1183     SchedResourceDelta ResDelta;
1184
1185     SchedCandidate(const CandPolicy &policy)
1186       : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
1187
1188     bool isValid() const { return SU; }
1189
1190     // Copy the status of another candidate without changing policy.
1191     void setBest(SchedCandidate &Best) {
1192       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
1193       SU = Best.SU;
1194       Reason = Best.Reason;
1195       RPDelta = Best.RPDelta;
1196       ResDelta = Best.ResDelta;
1197     }
1198
1199     bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
1200     void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
1201
1202     void initResourceDelta(const ScheduleDAGMI *DAG,
1203                            const TargetSchedModel *SchedModel);
1204   };
1205
1206   /// Summarize the unscheduled region.
1207   struct SchedRemainder {
1208     // Critical path through the DAG in expected latency.
1209     unsigned CriticalPath;
1210
1211     // Scaled count of micro-ops left to schedule.
1212     unsigned RemIssueCount;
1213
1214     // Unscheduled resources
1215     SmallVector<unsigned, 16> RemainingCounts;
1216
1217     void reset() {
1218       CriticalPath = 0;
1219       RemIssueCount = 0;
1220       RemainingCounts.clear();
1221     }
1222
1223     SchedRemainder() { reset(); }
1224
1225     void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1226   };
1227
1228   /// Each Scheduling boundary is associated with ready queues. It tracks the
1229   /// current cycle in the direction of movement, and maintains the state
1230   /// of "hazards" and other interlocks at the current cycle.
1231   struct SchedBoundary {
1232     ScheduleDAGMI *DAG;
1233     const TargetSchedModel *SchedModel;
1234     SchedRemainder *Rem;
1235
1236     ReadyQueue Available;
1237     ReadyQueue Pending;
1238     bool CheckPending;
1239
1240     // For heuristics, keep a list of the nodes that immediately depend on the
1241     // most recently scheduled node.
1242     SmallPtrSet<const SUnit*, 8> NextSUs;
1243
1244     ScheduleHazardRecognizer *HazardRec;
1245
1246     /// Number of cycles it takes to issue the instructions scheduled in this
1247     /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
1248     /// See getStalls().
1249     unsigned CurrCycle;
1250
1251     /// Micro-ops issued in the current cycle
1252     unsigned CurrMOps;
1253
1254     /// MinReadyCycle - Cycle of the soonest available instruction.
1255     unsigned MinReadyCycle;
1256
1257     // The expected latency of the critical path in this scheduled zone.
1258     unsigned ExpectedLatency;
1259
1260     // The latency of dependence chains leading into this zone.
1261     // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
1262     // For each cycle scheduled: DLat -= 1.
1263     unsigned DependentLatency;
1264
1265     /// Count the scheduled (issued) micro-ops that can be retired by
1266     /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
1267     unsigned RetiredMOps;
1268
1269     // Count scheduled resources that have been executed. Resources are
1270     // considered executed if they become ready in the time that it takes to
1271     // saturate any resource including the one in question. Counts are scaled
1272     // for direct comparison with other resources. Counts can be compared with
1273     // MOps * getMicroOpFactor and Latency * getLatencyFactor.
1274     SmallVector<unsigned, 16> ExecutedResCounts;
1275
1276     /// Cache the max count for a single resource.
1277     unsigned MaxExecutedResCount;
1278
1279     // Cache the critical resources ID in this scheduled zone.
1280     unsigned ZoneCritResIdx;
1281
1282     // Is the scheduled region resource limited vs. latency limited.
1283     bool IsResourceLimited;
1284
1285 #ifndef NDEBUG
1286     // Remember the greatest operand latency as an upper bound on the number of
1287     // times we should retry the pending queue because of a hazard.
1288     unsigned MaxObservedLatency;
1289 #endif
1290
1291     void reset() {
1292       // A new HazardRec is created for each DAG and owned by SchedBoundary.
1293       delete HazardRec;
1294
1295       Available.clear();
1296       Pending.clear();
1297       CheckPending = false;
1298       NextSUs.clear();
1299       HazardRec = 0;
1300       CurrCycle = 0;
1301       CurrMOps = 0;
1302       MinReadyCycle = UINT_MAX;
1303       ExpectedLatency = 0;
1304       DependentLatency = 0;
1305       RetiredMOps = 0;
1306       MaxExecutedResCount = 0;
1307       ZoneCritResIdx = 0;
1308       IsResourceLimited = false;
1309 #ifndef NDEBUG
1310       MaxObservedLatency = 0;
1311 #endif
1312       // Reserve a zero-count for invalid CritResIdx.
1313       ExecutedResCounts.resize(1);
1314       assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1315     }
1316
1317     /// Pending queues extend the ready queues with the same ID and the
1318     /// PendingFlag set.
1319     SchedBoundary(unsigned ID, const Twine &Name):
1320       DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1321       Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1322       HazardRec(0) {
1323       reset();
1324     }
1325
1326     ~SchedBoundary() { delete HazardRec; }
1327
1328     void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1329               SchedRemainder *rem);
1330
1331     bool isTop() const {
1332       return Available.getID() == ConvergingScheduler::TopQID;
1333     }
1334
1335 #ifndef NDEBUG
1336     const char *getResourceName(unsigned PIdx) {
1337       if (!PIdx)
1338         return "MOps";
1339       return SchedModel->getProcResource(PIdx)->Name;
1340     }
1341 #endif
1342
1343     /// Get the number of latency cycles "covered" by the scheduled
1344     /// instructions. This is the larger of the critical path within the zone
1345     /// and the number of cycles required to issue the instructions.
1346     unsigned getScheduledLatency() const {
1347       return std::max(ExpectedLatency, CurrCycle);
1348     }
1349
1350     unsigned getUnscheduledLatency(SUnit *SU) const {
1351       return isTop() ? SU->getHeight() : SU->getDepth();
1352     }
1353
1354     unsigned getResourceCount(unsigned ResIdx) const {
1355       return ExecutedResCounts[ResIdx];
1356     }
1357
1358     /// Get the scaled count of scheduled micro-ops and resources, including
1359     /// executed resources.
1360     unsigned getCriticalCount() const {
1361       if (!ZoneCritResIdx)
1362         return RetiredMOps * SchedModel->getMicroOpFactor();
1363       return getResourceCount(ZoneCritResIdx);
1364     }
1365
1366     /// Get a scaled count for the minimum execution time of the scheduled
1367     /// micro-ops that are ready to execute by getExecutedCount. Notice the
1368     /// feedback loop.
1369     unsigned getExecutedCount() const {
1370       return std::max(CurrCycle * SchedModel->getLatencyFactor(),
1371                       MaxExecutedResCount);
1372     }
1373
1374     bool checkHazard(SUnit *SU);
1375
1376     unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
1377
1378     unsigned getOtherResourceCount(unsigned &OtherCritIdx);
1379
1380     void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
1381
1382     void releaseNode(SUnit *SU, unsigned ReadyCycle);
1383
1384     void bumpCycle(unsigned NextCycle);
1385
1386     void incExecutedResources(unsigned PIdx, unsigned Count);
1387
1388     unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
1389
1390     void bumpNode(SUnit *SU);
1391
1392     void releasePending();
1393
1394     void removeReady(SUnit *SU);
1395
1396     SUnit *pickOnlyChoice();
1397
1398 #ifndef NDEBUG
1399     void dumpScheduledState();
1400 #endif
1401   };
1402
1403 private:
1404   ScheduleDAGMI *DAG;
1405   const TargetSchedModel *SchedModel;
1406   const TargetRegisterInfo *TRI;
1407
1408   // State of the top and bottom scheduled instruction boundaries.
1409   SchedRemainder Rem;
1410   SchedBoundary Top;
1411   SchedBoundary Bot;
1412
1413 public:
1414   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1415   enum {
1416     TopQID = 1,
1417     BotQID = 2,
1418     LogMaxQID = 2
1419   };
1420
1421   ConvergingScheduler():
1422     DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1423
1424   virtual void initialize(ScheduleDAGMI *dag);
1425
1426   virtual SUnit *pickNode(bool &IsTopNode);
1427
1428   virtual void schedNode(SUnit *SU, bool IsTopNode);
1429
1430   virtual void releaseTopNode(SUnit *SU);
1431
1432   virtual void releaseBottomNode(SUnit *SU);
1433
1434   virtual void registerRoots();
1435
1436 protected:
1437   void tryCandidate(SchedCandidate &Cand,
1438                     SchedCandidate &TryCand,
1439                     SchedBoundary &Zone,
1440                     const RegPressureTracker &RPTracker,
1441                     RegPressureTracker &TempTracker);
1442
1443   SUnit *pickNodeBidirectional(bool &IsTopNode);
1444
1445   void pickNodeFromQueue(SchedBoundary &Zone,
1446                          const RegPressureTracker &RPTracker,
1447                          SchedCandidate &Candidate);
1448
1449   void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1450
1451 #ifndef NDEBUG
1452   void traceCandidate(const SchedCandidate &Cand);
1453 #endif
1454 };
1455 } // namespace
1456
1457 void ConvergingScheduler::SchedRemainder::
1458 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1459   reset();
1460   if (!SchedModel->hasInstrSchedModel())
1461     return;
1462   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1463   for (std::vector<SUnit>::iterator
1464          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1465     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1466     RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1467       * SchedModel->getMicroOpFactor();
1468     for (TargetSchedModel::ProcResIter
1469            PI = SchedModel->getWriteProcResBegin(SC),
1470            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1471       unsigned PIdx = PI->ProcResourceIdx;
1472       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1473       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1474     }
1475   }
1476 }
1477
1478 void ConvergingScheduler::SchedBoundary::
1479 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1480   reset();
1481   DAG = dag;
1482   SchedModel = smodel;
1483   Rem = rem;
1484   if (SchedModel->hasInstrSchedModel())
1485     ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1486 }
1487
1488 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1489   DAG = dag;
1490   SchedModel = DAG->getSchedModel();
1491   TRI = DAG->TRI;
1492
1493   Rem.init(DAG, SchedModel);
1494   Top.init(DAG, SchedModel, &Rem);
1495   Bot.init(DAG, SchedModel, &Rem);
1496
1497   // Initialize resource counts.
1498
1499   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1500   // are disabled, then these HazardRecs will be disabled.
1501   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1502   const TargetMachine &TM = DAG->MF.getTarget();
1503   Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1504   Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1505
1506   assert((!ForceTopDown || !ForceBottomUp) &&
1507          "-misched-topdown incompatible with -misched-bottomup");
1508 }
1509
1510 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1511   if (SU->isScheduled)
1512     return;
1513
1514   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1515        I != E; ++I) {
1516     if (I->isWeak())
1517       continue;
1518     unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1519     unsigned Latency = I->getLatency();
1520 #ifndef NDEBUG
1521     Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
1522 #endif
1523     if (SU->TopReadyCycle < PredReadyCycle + Latency)
1524       SU->TopReadyCycle = PredReadyCycle + Latency;
1525   }
1526   Top.releaseNode(SU, SU->TopReadyCycle);
1527 }
1528
1529 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1530   if (SU->isScheduled)
1531     return;
1532
1533   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1534
1535   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1536        I != E; ++I) {
1537     if (I->isWeak())
1538       continue;
1539     unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1540     unsigned Latency = I->getLatency();
1541 #ifndef NDEBUG
1542     Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
1543 #endif
1544     if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1545       SU->BotReadyCycle = SuccReadyCycle + Latency;
1546   }
1547   Bot.releaseNode(SU, SU->BotReadyCycle);
1548 }
1549
1550 void ConvergingScheduler::registerRoots() {
1551   Rem.CriticalPath = DAG->ExitSU.getDepth();
1552   // Some roots may not feed into ExitSU. Check all of them in case.
1553   for (std::vector<SUnit*>::const_iterator
1554          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1555     if ((*I)->getDepth() > Rem.CriticalPath)
1556       Rem.CriticalPath = (*I)->getDepth();
1557   }
1558   DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1559 }
1560
1561 /// Does this SU have a hazard within the current instruction group.
1562 ///
1563 /// The scheduler supports two modes of hazard recognition. The first is the
1564 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1565 /// supports highly complicated in-order reservation tables
1566 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1567 ///
1568 /// The second is a streamlined mechanism that checks for hazards based on
1569 /// simple counters that the scheduler itself maintains. It explicitly checks
1570 /// for instruction dispatch limitations, including the number of micro-ops that
1571 /// can dispatch per cycle.
1572 ///
1573 /// TODO: Also check whether the SU must start a new group.
1574 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1575   if (HazardRec->isEnabled())
1576     return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1577
1578   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1579   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1580     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1581           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1582     return true;
1583   }
1584   return false;
1585 }
1586
1587 // Find the unscheduled node in ReadySUs with the highest latency.
1588 unsigned ConvergingScheduler::SchedBoundary::
1589 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1590   SUnit *LateSU = 0;
1591   unsigned RemLatency = 0;
1592   for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1593        I != E; ++I) {
1594     unsigned L = getUnscheduledLatency(*I);
1595     if (L > RemLatency) {
1596       RemLatency = L;
1597       LateSU = *I;
1598     }
1599   }
1600   if (LateSU) {
1601     DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1602           << LateSU->NodeNum << ") " << RemLatency << "c\n");
1603   }
1604   return RemLatency;
1605 }
1606
1607 // Count resources in this zone and the remaining unscheduled
1608 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1609 // resource index, or zero if the zone is issue limited.
1610 unsigned ConvergingScheduler::SchedBoundary::
1611 getOtherResourceCount(unsigned &OtherCritIdx) {
1612   OtherCritIdx = 0;
1613   if (!SchedModel->hasInstrSchedModel())
1614     return 0;
1615
1616   unsigned OtherCritCount = Rem->RemIssueCount
1617     + (RetiredMOps * SchedModel->getMicroOpFactor());
1618   DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
1619         << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1620   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1621        PIdx != PEnd; ++PIdx) {
1622     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1623     if (OtherCount > OtherCritCount) {
1624       OtherCritCount = OtherCount;
1625       OtherCritIdx = PIdx;
1626     }
1627   }
1628   if (OtherCritIdx) {
1629     DEBUG(dbgs() << "  " << Available.getName() << " + Remain CritRes: "
1630           << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1631           << " " << getResourceName(OtherCritIdx) << "\n");
1632   }
1633   return OtherCritCount;
1634 }
1635
1636 /// Set the CandPolicy for this zone given the current resources and latencies
1637 /// inside and outside the zone.
1638 void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
1639                                                    SchedBoundary &OtherZone) {
1640   // Now that potential stalls have been considered, apply preemptive heuristics
1641   // based on the the total latency and resources inside and outside this
1642   // zone.
1643
1644   // Compute remaining latency. We need this both to determine whether the
1645   // overall schedule has become latency-limited and whether the instructions
1646   // outside this zone are resource or latency limited.
1647   //
1648   // The "dependent" latency is updated incrementally during scheduling as the
1649   // max height/depth of scheduled nodes minus the cycles since it was
1650   // scheduled:
1651   //   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
1652   //
1653   // The "independent" latency is the max ready queue depth:
1654   //   ILat = max N.depth for N in Available|Pending
1655   //
1656   // RemainingLatency is the greater of independent and dependent latency.
1657   unsigned RemLatency = DependentLatency;
1658   RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
1659   RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
1660
1661   // Compute the critical resource outside the zone.
1662   unsigned OtherCritIdx;
1663   unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
1664
1665   bool OtherResLimited = false;
1666   if (SchedModel->hasInstrSchedModel()) {
1667     unsigned LFactor = SchedModel->getLatencyFactor();
1668     OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
1669   }
1670   if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
1671     Policy.ReduceLatency |= true;
1672     DEBUG(dbgs() << "  " << Available.getName() << " RemainingLatency "
1673           << RemLatency << " + " << CurrCycle << "c > CritPath "
1674           << Rem->CriticalPath << "\n");
1675   }
1676   // If the same resource is limiting inside and outside the zone, do nothing.
1677   if (ZoneCritResIdx == OtherCritIdx)
1678     return;
1679
1680   DEBUG(
1681     if (IsResourceLimited) {
1682       dbgs() << "  " << Available.getName() << " ResourceLimited: "
1683              << getResourceName(ZoneCritResIdx) << "\n";
1684     }
1685     if (OtherResLimited)
1686       dbgs() << "  RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
1687     if (!IsResourceLimited && !OtherResLimited)
1688       dbgs() << "  Latency limited both directions.\n");
1689
1690   if (IsResourceLimited && !Policy.ReduceResIdx)
1691     Policy.ReduceResIdx = ZoneCritResIdx;
1692
1693   if (OtherResLimited)
1694     Policy.DemandResIdx = OtherCritIdx;
1695 }
1696
1697 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1698                                                      unsigned ReadyCycle) {
1699   if (ReadyCycle < MinReadyCycle)
1700     MinReadyCycle = ReadyCycle;
1701
1702   // Check for interlocks first. For the purpose of other heuristics, an
1703   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1704   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1705   if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1706     Pending.push(SU);
1707   else
1708     Available.push(SU);
1709
1710   // Record this node as an immediate dependent of the scheduled node.
1711   NextSUs.insert(SU);
1712 }
1713
1714 /// Move the boundary of scheduled code by one cycle.
1715 void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
1716   if (SchedModel->getMicroOpBufferSize() == 0) {
1717     assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1718     if (MinReadyCycle > NextCycle)
1719       NextCycle = MinReadyCycle;
1720   }
1721   // Update the current micro-ops, which will issue in the next cycle.
1722   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1723   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1724
1725   // Decrement DependentLatency based on the next cycle.
1726   if ((NextCycle - CurrCycle) > DependentLatency)
1727     DependentLatency = 0;
1728   else
1729     DependentLatency -= (NextCycle - CurrCycle);
1730
1731   if (!HazardRec->isEnabled()) {
1732     // Bypass HazardRec virtual calls.
1733     CurrCycle = NextCycle;
1734   }
1735   else {
1736     // Bypass getHazardType calls in case of long latency.
1737     for (; CurrCycle != NextCycle; ++CurrCycle) {
1738       if (isTop())
1739         HazardRec->AdvanceCycle();
1740       else
1741         HazardRec->RecedeCycle();
1742     }
1743   }
1744   CheckPending = true;
1745   unsigned LFactor = SchedModel->getLatencyFactor();
1746   IsResourceLimited =
1747     (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1748     > (int)LFactor;
1749
1750   DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1751 }
1752
1753 void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
1754                                                               unsigned Count) {
1755   ExecutedResCounts[PIdx] += Count;
1756   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1757     MaxExecutedResCount = ExecutedResCounts[PIdx];
1758 }
1759
1760 /// Add the given processor resource to this scheduled zone.
1761 ///
1762 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1763 /// during which this resource is consumed.
1764 ///
1765 /// \return the next cycle at which the instruction may execute without
1766 /// oversubscribing resources.
1767 unsigned ConvergingScheduler::SchedBoundary::
1768 countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
1769   unsigned Factor = SchedModel->getResourceFactor(PIdx);
1770   unsigned Count = Factor * Cycles;
1771   DEBUG(dbgs() << "  " << getResourceName(PIdx)
1772         << " +" << Cycles << "x" << Factor << "u\n");
1773
1774   // Update Executed resources counts.
1775   incExecutedResources(PIdx, Count);
1776   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1777   Rem->RemainingCounts[PIdx] -= Count;
1778
1779   // Check if this resource exceeds the current critical resource. If so, it
1780   // becomes the critical resource.
1781   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1782     ZoneCritResIdx = PIdx;
1783     DEBUG(dbgs() << "  *** Critical resource "
1784           << getResourceName(PIdx) << ": "
1785           << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1786   }
1787   // TODO: We don't yet model reserved resources. It's not hard though.
1788   return CurrCycle;
1789 }
1790
1791 /// Move the boundary of scheduled code by one SUnit.
1792 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1793   // Update the reservation table.
1794   if (HazardRec->isEnabled()) {
1795     if (!isTop() && SU->isCall) {
1796       // Calls are scheduled with their preceding instructions. For bottom-up
1797       // scheduling, clear the pipeline state before emitting.
1798       HazardRec->Reset();
1799     }
1800     HazardRec->EmitInstruction(SU);
1801   }
1802   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1803   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1804   CurrMOps += IncMOps;
1805   // checkHazard prevents scheduling multiple instructions per cycle that exceed
1806   // issue width. However, we commonly reach the maximum. In this case
1807   // opportunistically bump the cycle to avoid uselessly checking everything in
1808   // the readyQ. Furthermore, a single instruction may produce more than one
1809   // cycle's worth of micro-ops.
1810   //
1811   // TODO: Also check if this SU must end a dispatch group.
1812   unsigned NextCycle = CurrCycle;
1813   if (CurrMOps >= SchedModel->getIssueWidth()) {
1814     ++NextCycle;
1815     DEBUG(dbgs() << "  *** Max MOps " << CurrMOps
1816           << " at cycle " << CurrCycle << '\n');
1817   }
1818   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1819   DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
1820
1821   switch (SchedModel->getMicroOpBufferSize()) {
1822   case 0:
1823     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1824     break;
1825   case 1:
1826     if (ReadyCycle > NextCycle) {
1827       NextCycle = ReadyCycle;
1828       DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
1829     }
1830     break;
1831   default:
1832     // We don't currently model the OOO reorder buffer, so consider all
1833     // scheduled MOps to be "retired".
1834     break;
1835   }
1836   RetiredMOps += IncMOps;
1837
1838   // Update resource counts and critical resource.
1839   if (SchedModel->hasInstrSchedModel()) {
1840     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1841     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1842     Rem->RemIssueCount -= DecRemIssue;
1843     if (ZoneCritResIdx) {
1844       // Scale scheduled micro-ops for comparing with the critical resource.
1845       unsigned ScaledMOps =
1846         RetiredMOps * SchedModel->getMicroOpFactor();
1847
1848       // If scaled micro-ops are now more than the previous critical resource by
1849       // a full cycle, then micro-ops issue becomes critical.
1850       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1851           >= (int)SchedModel->getLatencyFactor()) {
1852         ZoneCritResIdx = 0;
1853         DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
1854               << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1855       }
1856     }
1857     for (TargetSchedModel::ProcResIter
1858            PI = SchedModel->getWriteProcResBegin(SC),
1859            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1860       unsigned RCycle =
1861         countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
1862       if (RCycle > NextCycle)
1863         NextCycle = RCycle;
1864     }
1865   }
1866   // Update ExpectedLatency and DependentLatency.
1867   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1868   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1869   if (SU->getDepth() > TopLatency) {
1870     TopLatency = SU->getDepth();
1871     DEBUG(dbgs() << "  " << Available.getName()
1872           << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1873   }
1874   if (SU->getHeight() > BotLatency) {
1875     BotLatency = SU->getHeight();
1876     DEBUG(dbgs() << "  " << Available.getName()
1877           << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1878   }
1879   // If we stall for any reason, bump the cycle.
1880   if (NextCycle > CurrCycle) {
1881     bumpCycle(NextCycle);
1882   }
1883   else {
1884     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1885     // resource limited. If a stall occured, bumpCycle does this.
1886     unsigned LFactor = SchedModel->getLatencyFactor();
1887     IsResourceLimited =
1888       (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1889       > (int)LFactor;
1890   }
1891   DEBUG(dumpScheduledState());
1892 }
1893
1894 /// Release pending ready nodes in to the available queue. This makes them
1895 /// visible to heuristics.
1896 void ConvergingScheduler::SchedBoundary::releasePending() {
1897   // If the available queue is empty, it is safe to reset MinReadyCycle.
1898   if (Available.empty())
1899     MinReadyCycle = UINT_MAX;
1900
1901   // Check to see if any of the pending instructions are ready to issue.  If
1902   // so, add them to the available queue.
1903   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1904   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1905     SUnit *SU = *(Pending.begin()+i);
1906     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1907
1908     if (ReadyCycle < MinReadyCycle)
1909       MinReadyCycle = ReadyCycle;
1910
1911     if (!IsBuffered && ReadyCycle > CurrCycle)
1912       continue;
1913
1914     if (checkHazard(SU))
1915       continue;
1916
1917     Available.push(SU);
1918     Pending.remove(Pending.begin()+i);
1919     --i; --e;
1920   }
1921   DEBUG(if (!Pending.empty()) Pending.dump());
1922   CheckPending = false;
1923 }
1924
1925 /// Remove SU from the ready set for this boundary.
1926 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1927   if (Available.isInQueue(SU))
1928     Available.remove(Available.find(SU));
1929   else {
1930     assert(Pending.isInQueue(SU) && "bad ready count");
1931     Pending.remove(Pending.find(SU));
1932   }
1933 }
1934
1935 /// If this queue only has one ready candidate, return it. As a side effect,
1936 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1937 /// one node is ready. If multiple instructions are ready, return NULL.
1938 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1939   if (CheckPending)
1940     releasePending();
1941
1942   if (CurrMOps > 0) {
1943     // Defer any ready instrs that now have a hazard.
1944     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1945       if (checkHazard(*I)) {
1946         Pending.push(*I);
1947         I = Available.remove(I);
1948         continue;
1949       }
1950       ++I;
1951     }
1952   }
1953   for (unsigned i = 0; Available.empty(); ++i) {
1954     assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
1955            "permanent hazard"); (void)i;
1956     bumpCycle(CurrCycle + 1);
1957     releasePending();
1958   }
1959   if (Available.size() == 1)
1960     return *Available.begin();
1961   return NULL;
1962 }
1963
1964 #ifndef NDEBUG
1965 // This is useful information to dump after bumpNode.
1966 // Note that the Queue contents are more useful before pickNodeFromQueue.
1967 void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
1968   unsigned ResFactor;
1969   unsigned ResCount;
1970   if (ZoneCritResIdx) {
1971     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
1972     ResCount = getResourceCount(ZoneCritResIdx);
1973   }
1974   else {
1975     ResFactor = SchedModel->getMicroOpFactor();
1976     ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
1977   }
1978   unsigned LFactor = SchedModel->getLatencyFactor();
1979   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
1980          << "  Retired: " << RetiredMOps;
1981   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
1982   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
1983          << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
1984          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
1985          << (IsResourceLimited ? "  - Resource" : "  - Latency")
1986          << " limited.\n";
1987 }
1988 #endif
1989
1990 void ConvergingScheduler::SchedCandidate::
1991 initResourceDelta(const ScheduleDAGMI *DAG,
1992                   const TargetSchedModel *SchedModel) {
1993   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1994     return;
1995
1996   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1997   for (TargetSchedModel::ProcResIter
1998          PI = SchedModel->getWriteProcResBegin(SC),
1999          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2000     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2001       ResDelta.CritResources += PI->Cycles;
2002     if (PI->ProcResourceIdx == Policy.DemandResIdx)
2003       ResDelta.DemandedResources += PI->Cycles;
2004   }
2005 }
2006
2007
2008 /// Return true if this heuristic determines order.
2009 static bool tryLess(int TryVal, int CandVal,
2010                     ConvergingScheduler::SchedCandidate &TryCand,
2011                     ConvergingScheduler::SchedCandidate &Cand,
2012                     ConvergingScheduler::CandReason Reason) {
2013   if (TryVal < CandVal) {
2014     TryCand.Reason = Reason;
2015     return true;
2016   }
2017   if (TryVal > CandVal) {
2018     if (Cand.Reason > Reason)
2019       Cand.Reason = Reason;
2020     return true;
2021   }
2022   Cand.setRepeat(Reason);
2023   return false;
2024 }
2025
2026 static bool tryGreater(int TryVal, int CandVal,
2027                        ConvergingScheduler::SchedCandidate &TryCand,
2028                        ConvergingScheduler::SchedCandidate &Cand,
2029                        ConvergingScheduler::CandReason Reason) {
2030   if (TryVal > CandVal) {
2031     TryCand.Reason = Reason;
2032     return true;
2033   }
2034   if (TryVal < CandVal) {
2035     if (Cand.Reason > Reason)
2036       Cand.Reason = Reason;
2037     return true;
2038   }
2039   Cand.setRepeat(Reason);
2040   return false;
2041 }
2042
2043 static bool tryPressure(const PressureElement &TryP,
2044                         const PressureElement &CandP,
2045                         ConvergingScheduler::SchedCandidate &TryCand,
2046                         ConvergingScheduler::SchedCandidate &Cand,
2047                         ConvergingScheduler::CandReason Reason) {
2048   // If both candidates affect the same set, go with the smallest increase.
2049   if (TryP.PSetID == CandP.PSetID) {
2050     return tryLess(TryP.UnitIncrease, CandP.UnitIncrease, TryCand, Cand,
2051                    Reason);
2052   }
2053   // If one candidate decreases and the other increases, go with it.
2054   if (tryLess(TryP.UnitIncrease < 0, CandP.UnitIncrease < 0, TryCand, Cand,
2055               Reason)) {
2056     return true;
2057   }
2058   // If TryP has lower Rank, it has a higher priority.
2059   int TryRank = TryP.PSetRank();
2060   int CandRank = CandP.PSetRank();
2061   // If the candidates are decreasing pressure, reverse priority.
2062   if (TryP.UnitIncrease < 0)
2063     std::swap(TryRank, CandRank);
2064   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2065 }
2066
2067 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2068   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2069 }
2070
2071 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2072 /// their physreg def/use.
2073 ///
2074 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2075 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2076 /// with the operation that produces or consumes the physreg. We'll do this when
2077 /// regalloc has support for parallel copies.
2078 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2079   const MachineInstr *MI = SU->getInstr();
2080   if (!MI->isCopy())
2081     return 0;
2082
2083   unsigned ScheduledOper = isTop ? 1 : 0;
2084   unsigned UnscheduledOper = isTop ? 0 : 1;
2085   // If we have already scheduled the physreg produce/consumer, immediately
2086   // schedule the copy.
2087   if (TargetRegisterInfo::isPhysicalRegister(
2088         MI->getOperand(ScheduledOper).getReg()))
2089     return 1;
2090   // If the physreg is at the boundary, defer it. Otherwise schedule it
2091   // immediately to free the dependent. We can hoist the copy later.
2092   bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2093   if (TargetRegisterInfo::isPhysicalRegister(
2094         MI->getOperand(UnscheduledOper).getReg()))
2095     return AtBoundary ? -1 : 1;
2096   return 0;
2097 }
2098
2099 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2100 /// hierarchical. This may be more efficient than a graduated cost model because
2101 /// we don't need to evaluate all aspects of the model for each node in the
2102 /// queue. But it's really done to make the heuristics easier to debug and
2103 /// statistically analyze.
2104 ///
2105 /// \param Cand provides the policy and current best candidate.
2106 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2107 /// \param Zone describes the scheduled zone that we are extending.
2108 /// \param RPTracker describes reg pressure within the scheduled zone.
2109 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2110 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
2111                                        SchedCandidate &TryCand,
2112                                        SchedBoundary &Zone,
2113                                        const RegPressureTracker &RPTracker,
2114                                        RegPressureTracker &TempTracker) {
2115
2116   // Always initialize TryCand's RPDelta.
2117   TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
2118                                   DAG->getRegionCriticalPSets(),
2119                                   DAG->getRegPressure().MaxSetPressure);
2120
2121   // Initialize the candidate if needed.
2122   if (!Cand.isValid()) {
2123     TryCand.Reason = NodeOrder;
2124     return;
2125   }
2126
2127   if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2128                  biasPhysRegCopy(Cand.SU, Zone.isTop()),
2129                  TryCand, Cand, PhysRegCopy))
2130     return;
2131
2132   // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2133   // invalid; convert it to INT_MAX to give it lowest priority.
2134   if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
2135                   RegExcess))
2136     return;
2137
2138   // Avoid increasing the max critical pressure in the scheduled region.
2139   if (tryPressure(TryCand.RPDelta.CriticalMax, Cand.RPDelta.CriticalMax,
2140                   TryCand, Cand, RegCritical))
2141     return;
2142
2143   // Keep clustered nodes together to encourage downstream peephole
2144   // optimizations which may reduce resource requirements.
2145   //
2146   // This is a best effort to set things up for a post-RA pass. Optimizations
2147   // like generating loads of multiple registers should ideally be done within
2148   // the scheduler pass by combining the loads during DAG postprocessing.
2149   const SUnit *NextClusterSU =
2150     Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2151   if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2152                  TryCand, Cand, Cluster))
2153     return;
2154
2155   // Weak edges are for clustering and other constraints.
2156   if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2157               getWeakLeft(Cand.SU, Zone.isTop()),
2158               TryCand, Cand, Weak)) {
2159     return;
2160   }
2161   // Avoid increasing the max pressure of the entire region.
2162   if (tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax,
2163                   TryCand, Cand, RegMax))
2164     return;
2165
2166   // Avoid critical resource consumption and balance the schedule.
2167   TryCand.initResourceDelta(DAG, SchedModel);
2168   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2169               TryCand, Cand, ResourceReduce))
2170     return;
2171   if (tryGreater(TryCand.ResDelta.DemandedResources,
2172                  Cand.ResDelta.DemandedResources,
2173                  TryCand, Cand, ResourceDemand))
2174     return;
2175
2176   // Avoid serializing long latency dependence chains.
2177   if (Cand.Policy.ReduceLatency) {
2178     if (Zone.isTop()) {
2179       if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2180         if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2181                     TryCand, Cand, TopDepthReduce))
2182           return;
2183       }
2184       if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2185                      TryCand, Cand, TopPathReduce))
2186         return;
2187     }
2188     else {
2189       if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2190         if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2191                     TryCand, Cand, BotHeightReduce))
2192           return;
2193       }
2194       if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2195                      TryCand, Cand, BotPathReduce))
2196         return;
2197     }
2198   }
2199
2200   // Prefer immediate defs/users of the last scheduled instruction. This is a
2201   // local pressure avoidance strategy that also makes the machine code
2202   // readable.
2203   if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
2204                  TryCand, Cand, NextDefUse))
2205     return;
2206
2207   // Fall through to original instruction order.
2208   if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2209       || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2210     TryCand.Reason = NodeOrder;
2211   }
2212 }
2213
2214 #ifndef NDEBUG
2215 const char *ConvergingScheduler::getReasonStr(
2216   ConvergingScheduler::CandReason Reason) {
2217   switch (Reason) {
2218   case NoCand:         return "NOCAND    ";
2219   case PhysRegCopy:    return "PREG-COPY";
2220   case RegExcess:      return "REG-EXCESS";
2221   case RegCritical:    return "REG-CRIT  ";
2222   case Cluster:        return "CLUSTER   ";
2223   case Weak:           return "WEAK      ";
2224   case RegMax:         return "REG-MAX   ";
2225   case ResourceReduce: return "RES-REDUCE";
2226   case ResourceDemand: return "RES-DEMAND";
2227   case TopDepthReduce: return "TOP-DEPTH ";
2228   case TopPathReduce:  return "TOP-PATH  ";
2229   case BotHeightReduce:return "BOT-HEIGHT";
2230   case BotPathReduce:  return "BOT-PATH  ";
2231   case NextDefUse:     return "DEF-USE   ";
2232   case NodeOrder:      return "ORDER     ";
2233   };
2234   llvm_unreachable("Unknown reason!");
2235 }
2236
2237 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
2238   PressureElement P;
2239   unsigned ResIdx = 0;
2240   unsigned Latency = 0;
2241   switch (Cand.Reason) {
2242   default:
2243     break;
2244   case RegExcess:
2245     P = Cand.RPDelta.Excess;
2246     break;
2247   case RegCritical:
2248     P = Cand.RPDelta.CriticalMax;
2249     break;
2250   case RegMax:
2251     P = Cand.RPDelta.CurrentMax;
2252     break;
2253   case ResourceReduce:
2254     ResIdx = Cand.Policy.ReduceResIdx;
2255     break;
2256   case ResourceDemand:
2257     ResIdx = Cand.Policy.DemandResIdx;
2258     break;
2259   case TopDepthReduce:
2260     Latency = Cand.SU->getDepth();
2261     break;
2262   case TopPathReduce:
2263     Latency = Cand.SU->getHeight();
2264     break;
2265   case BotHeightReduce:
2266     Latency = Cand.SU->getHeight();
2267     break;
2268   case BotPathReduce:
2269     Latency = Cand.SU->getDepth();
2270     break;
2271   }
2272   dbgs() << "  SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2273   if (P.isValid())
2274     dbgs() << " " << TRI->getRegPressureSetName(P.PSetID)
2275            << ":" << P.UnitIncrease << " ";
2276   else
2277     dbgs() << "      ";
2278   if (ResIdx)
2279     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2280   else
2281     dbgs() << "         ";
2282   if (Latency)
2283     dbgs() << " " << Latency << " cycles ";
2284   else
2285     dbgs() << "          ";
2286   dbgs() << '\n';
2287 }
2288 #endif
2289
2290 /// Pick the best candidate from the top queue.
2291 ///
2292 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2293 /// DAG building. To adjust for the current scheduling location we need to
2294 /// maintain the number of vreg uses remaining to be top-scheduled.
2295 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2296                                             const RegPressureTracker &RPTracker,
2297                                             SchedCandidate &Cand) {
2298   ReadyQueue &Q = Zone.Available;
2299
2300   DEBUG(Q.dump());
2301
2302   // getMaxPressureDelta temporarily modifies the tracker.
2303   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2304
2305   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2306
2307     SchedCandidate TryCand(Cand.Policy);
2308     TryCand.SU = *I;
2309     tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2310     if (TryCand.Reason != NoCand) {
2311       // Initialize resource delta if needed in case future heuristics query it.
2312       if (TryCand.ResDelta == SchedResourceDelta())
2313         TryCand.initResourceDelta(DAG, SchedModel);
2314       Cand.setBest(TryCand);
2315       DEBUG(traceCandidate(Cand));
2316     }
2317   }
2318 }
2319
2320 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2321                       bool IsTop) {
2322   DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2323         << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
2324 }
2325
2326 /// Pick the best candidate node from either the top or bottom queue.
2327 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
2328   // Schedule as far as possible in the direction of no choice. This is most
2329   // efficient, but also provides the best heuristics for CriticalPSets.
2330   if (SUnit *SU = Bot.pickOnlyChoice()) {
2331     IsTopNode = false;
2332     DEBUG(dbgs() << "Pick Bot NOCAND\n");
2333     return SU;
2334   }
2335   if (SUnit *SU = Top.pickOnlyChoice()) {
2336     IsTopNode = true;
2337     DEBUG(dbgs() << "Pick Top NOCAND\n");
2338     return SU;
2339   }
2340   CandPolicy NoPolicy;
2341   SchedCandidate BotCand(NoPolicy);
2342   SchedCandidate TopCand(NoPolicy);
2343   Bot.setPolicy(BotCand.Policy, Top);
2344   Top.setPolicy(TopCand.Policy, Bot);
2345
2346   // Prefer bottom scheduling when heuristics are silent.
2347   pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2348   assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2349
2350   // If either Q has a single candidate that provides the least increase in
2351   // Excess pressure, we can immediately schedule from that Q.
2352   //
2353   // RegionCriticalPSets summarizes the pressure within the scheduled region and
2354   // affects picking from either Q. If scheduling in one direction must
2355   // increase pressure for one of the excess PSets, then schedule in that
2356   // direction first to provide more freedom in the other direction.
2357   if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2358       || (BotCand.Reason == RegCritical
2359           && !BotCand.isRepeat(RegCritical)))
2360   {
2361     IsTopNode = false;
2362     tracePick(BotCand, IsTopNode);
2363     return BotCand.SU;
2364   }
2365   // Check if the top Q has a better candidate.
2366   pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2367   assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2368
2369   // Choose the queue with the most important (lowest enum) reason.
2370   if (TopCand.Reason < BotCand.Reason) {
2371     IsTopNode = true;
2372     tracePick(TopCand, IsTopNode);
2373     return TopCand.SU;
2374   }
2375   // Otherwise prefer the bottom candidate, in node order if all else failed.
2376   IsTopNode = false;
2377   tracePick(BotCand, IsTopNode);
2378   return BotCand.SU;
2379 }
2380
2381 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2382 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2383   if (DAG->top() == DAG->bottom()) {
2384     assert(Top.Available.empty() && Top.Pending.empty() &&
2385            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2386     return NULL;
2387   }
2388   SUnit *SU;
2389   do {
2390     if (ForceTopDown) {
2391       SU = Top.pickOnlyChoice();
2392       if (!SU) {
2393         CandPolicy NoPolicy;
2394         SchedCandidate TopCand(NoPolicy);
2395         pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2396         assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2397         SU = TopCand.SU;
2398       }
2399       IsTopNode = true;
2400     }
2401     else if (ForceBottomUp) {
2402       SU = Bot.pickOnlyChoice();
2403       if (!SU) {
2404         CandPolicy NoPolicy;
2405         SchedCandidate BotCand(NoPolicy);
2406         pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2407         assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2408         SU = BotCand.SU;
2409       }
2410       IsTopNode = false;
2411     }
2412     else {
2413       SU = pickNodeBidirectional(IsTopNode);
2414     }
2415   } while (SU->isScheduled);
2416
2417   if (SU->isTopReady())
2418     Top.removeReady(SU);
2419   if (SU->isBottomReady())
2420     Bot.removeReady(SU);
2421
2422   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2423   return SU;
2424 }
2425
2426 void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2427
2428   MachineBasicBlock::iterator InsertPos = SU->getInstr();
2429   if (!isTop)
2430     ++InsertPos;
2431   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2432
2433   // Find already scheduled copies with a single physreg dependence and move
2434   // them just above the scheduled instruction.
2435   for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2436        I != E; ++I) {
2437     if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2438       continue;
2439     SUnit *DepSU = I->getSUnit();
2440     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2441       continue;
2442     MachineInstr *Copy = DepSU->getInstr();
2443     if (!Copy->isCopy())
2444       continue;
2445     DEBUG(dbgs() << "  Rescheduling physreg copy ";
2446           I->getSUnit()->dump(DAG));
2447     DAG->moveInstruction(Copy, InsertPos);
2448   }
2449 }
2450
2451 /// Update the scheduler's state after scheduling a node. This is the same node
2452 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2453 /// it's state based on the current cycle before MachineSchedStrategy does.
2454 ///
2455 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2456 /// them here. See comments in biasPhysRegCopy.
2457 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2458   if (IsTopNode) {
2459     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
2460     Top.bumpNode(SU);
2461     if (SU->hasPhysRegUses)
2462       reschedulePhysRegCopies(SU, true);
2463   }
2464   else {
2465     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
2466     Bot.bumpNode(SU);
2467     if (SU->hasPhysRegDefs)
2468       reschedulePhysRegCopies(SU, false);
2469   }
2470 }
2471
2472 /// Create the standard converging machine scheduler. This will be used as the
2473 /// default scheduler if the target does not set a default.
2474 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2475   assert((!ForceTopDown || !ForceBottomUp) &&
2476          "-misched-topdown incompatible with -misched-bottomup");
2477   ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2478   // Register DAG post-processors.
2479   //
2480   // FIXME: extend the mutation API to allow earlier mutations to instantiate
2481   // data and pass it to later mutations. Have a single mutation that gathers
2482   // the interesting nodes in one pass.
2483   DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
2484   if (EnableLoadCluster)
2485     DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2486   if (EnableMacroFusion)
2487     DAG->addMutation(new MacroFusion(DAG->TII));
2488   return DAG;
2489 }
2490 static MachineSchedRegistry
2491 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2492                         createConvergingSched);
2493
2494 //===----------------------------------------------------------------------===//
2495 // ILP Scheduler. Currently for experimental analysis of heuristics.
2496 //===----------------------------------------------------------------------===//
2497
2498 namespace {
2499 /// \brief Order nodes by the ILP metric.
2500 struct ILPOrder {
2501   const SchedDFSResult *DFSResult;
2502   const BitVector *ScheduledTrees;
2503   bool MaximizeILP;
2504
2505   ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2506
2507   /// \brief Apply a less-than relation on node priority.
2508   ///
2509   /// (Return true if A comes after B in the Q.)
2510   bool operator()(const SUnit *A, const SUnit *B) const {
2511     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2512     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2513     if (SchedTreeA != SchedTreeB) {
2514       // Unscheduled trees have lower priority.
2515       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2516         return ScheduledTrees->test(SchedTreeB);
2517
2518       // Trees with shallower connections have have lower priority.
2519       if (DFSResult->getSubtreeLevel(SchedTreeA)
2520           != DFSResult->getSubtreeLevel(SchedTreeB)) {
2521         return DFSResult->getSubtreeLevel(SchedTreeA)
2522           < DFSResult->getSubtreeLevel(SchedTreeB);
2523       }
2524     }
2525     if (MaximizeILP)
2526       return DFSResult->getILP(A) < DFSResult->getILP(B);
2527     else
2528       return DFSResult->getILP(A) > DFSResult->getILP(B);
2529   }
2530 };
2531
2532 /// \brief Schedule based on the ILP metric.
2533 class ILPScheduler : public MachineSchedStrategy {
2534   /// In case all subtrees are eventually connected to a common root through
2535   /// data dependence (e.g. reduction), place an upper limit on their size.
2536   ///
2537   /// FIXME: A subtree limit is generally good, but in the situation commented
2538   /// above, where multiple similar subtrees feed a common root, we should
2539   /// only split at a point where the resulting subtrees will be balanced.
2540   /// (a motivating test case must be found).
2541   static const unsigned SubtreeLimit = 16;
2542
2543   ScheduleDAGMI *DAG;
2544   ILPOrder Cmp;
2545
2546   std::vector<SUnit*> ReadyQ;
2547 public:
2548   ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2549
2550   virtual void initialize(ScheduleDAGMI *dag) {
2551     DAG = dag;
2552     DAG->computeDFSResult();
2553     Cmp.DFSResult = DAG->getDFSResult();
2554     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2555     ReadyQ.clear();
2556   }
2557
2558   virtual void registerRoots() {
2559     // Restore the heap in ReadyQ with the updated DFS results.
2560     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2561   }
2562
2563   /// Implement MachineSchedStrategy interface.
2564   /// -----------------------------------------
2565
2566   /// Callback to select the highest priority node from the ready Q.
2567   virtual SUnit *pickNode(bool &IsTopNode) {
2568     if (ReadyQ.empty()) return NULL;
2569     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2570     SUnit *SU = ReadyQ.back();
2571     ReadyQ.pop_back();
2572     IsTopNode = false;
2573     DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
2574           << " ILP: " << DAG->getDFSResult()->getILP(SU)
2575           << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2576           << DAG->getDFSResult()->getSubtreeLevel(
2577             DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2578           << "Scheduling " << *SU->getInstr());
2579     return SU;
2580   }
2581
2582   /// \brief Scheduler callback to notify that a new subtree is scheduled.
2583   virtual void scheduleTree(unsigned SubtreeID) {
2584     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2585   }
2586
2587   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2588   /// DFSResults, and resort the priority Q.
2589   virtual void schedNode(SUnit *SU, bool IsTopNode) {
2590     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2591   }
2592
2593   virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2594
2595   virtual void releaseBottomNode(SUnit *SU) {
2596     ReadyQ.push_back(SU);
2597     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2598   }
2599 };
2600 } // namespace
2601
2602 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2603   return new ScheduleDAGMI(C, new ILPScheduler(true));
2604 }
2605 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2606   return new ScheduleDAGMI(C, new ILPScheduler(false));
2607 }
2608 static MachineSchedRegistry ILPMaxRegistry(
2609   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2610 static MachineSchedRegistry ILPMinRegistry(
2611   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2612
2613 //===----------------------------------------------------------------------===//
2614 // Machine Instruction Shuffler for Correctness Testing
2615 //===----------------------------------------------------------------------===//
2616
2617 #ifndef NDEBUG
2618 namespace {
2619 /// Apply a less-than relation on the node order, which corresponds to the
2620 /// instruction order prior to scheduling. IsReverse implements greater-than.
2621 template<bool IsReverse>
2622 struct SUnitOrder {
2623   bool operator()(SUnit *A, SUnit *B) const {
2624     if (IsReverse)
2625       return A->NodeNum > B->NodeNum;
2626     else
2627       return A->NodeNum < B->NodeNum;
2628   }
2629 };
2630
2631 /// Reorder instructions as much as possible.
2632 class InstructionShuffler : public MachineSchedStrategy {
2633   bool IsAlternating;
2634   bool IsTopDown;
2635
2636   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2637   // gives nodes with a higher number higher priority causing the latest
2638   // instructions to be scheduled first.
2639   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2640     TopQ;
2641   // When scheduling bottom-up, use greater-than as the queue priority.
2642   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2643     BottomQ;
2644 public:
2645   InstructionShuffler(bool alternate, bool topdown)
2646     : IsAlternating(alternate), IsTopDown(topdown) {}
2647
2648   virtual void initialize(ScheduleDAGMI *) {
2649     TopQ.clear();
2650     BottomQ.clear();
2651   }
2652
2653   /// Implement MachineSchedStrategy interface.
2654   /// -----------------------------------------
2655
2656   virtual SUnit *pickNode(bool &IsTopNode) {
2657     SUnit *SU;
2658     if (IsTopDown) {
2659       do {
2660         if (TopQ.empty()) return NULL;
2661         SU = TopQ.top();
2662         TopQ.pop();
2663       } while (SU->isScheduled);
2664       IsTopNode = true;
2665     }
2666     else {
2667       do {
2668         if (BottomQ.empty()) return NULL;
2669         SU = BottomQ.top();
2670         BottomQ.pop();
2671       } while (SU->isScheduled);
2672       IsTopNode = false;
2673     }
2674     if (IsAlternating)
2675       IsTopDown = !IsTopDown;
2676     return SU;
2677   }
2678
2679   virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2680
2681   virtual void releaseTopNode(SUnit *SU) {
2682     TopQ.push(SU);
2683   }
2684   virtual void releaseBottomNode(SUnit *SU) {
2685     BottomQ.push(SU);
2686   }
2687 };
2688 } // namespace
2689
2690 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2691   bool Alternate = !ForceTopDown && !ForceBottomUp;
2692   bool TopDown = !ForceBottomUp;
2693   assert((TopDown || !ForceTopDown) &&
2694          "-misched-topdown incompatible with -misched-bottomup");
2695   return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2696 }
2697 static MachineSchedRegistry ShufflerRegistry(
2698   "shuffle", "Shuffle machine instructions alternating directions",
2699   createInstructionShuffler);
2700 #endif // !NDEBUG
2701
2702 //===----------------------------------------------------------------------===//
2703 // GraphWriter support for ScheduleDAGMI.
2704 //===----------------------------------------------------------------------===//
2705
2706 #ifndef NDEBUG
2707 namespace llvm {
2708
2709 template<> struct GraphTraits<
2710   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2711
2712 template<>
2713 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2714
2715   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2716
2717   static std::string getGraphName(const ScheduleDAG *G) {
2718     return G->MF.getName();
2719   }
2720
2721   static bool renderGraphFromBottomUp() {
2722     return true;
2723   }
2724
2725   static bool isNodeHidden(const SUnit *Node) {
2726     return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2727   }
2728
2729   static bool hasNodeAddressLabel(const SUnit *Node,
2730                                   const ScheduleDAG *Graph) {
2731     return false;
2732   }
2733
2734   /// If you want to override the dot attributes printed for a particular
2735   /// edge, override this method.
2736   static std::string getEdgeAttributes(const SUnit *Node,
2737                                        SUnitIterator EI,
2738                                        const ScheduleDAG *Graph) {
2739     if (EI.isArtificialDep())
2740       return "color=cyan,style=dashed";
2741     if (EI.isCtrlDep())
2742       return "color=blue,style=dashed";
2743     return "";
2744   }
2745
2746   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2747     std::string Str;
2748     raw_string_ostream SS(Str);
2749     SS << "SU(" << SU->NodeNum << ')';
2750     return SS.str();
2751   }
2752   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2753     return G->getGraphNodeLabel(SU);
2754   }
2755
2756   static std::string getNodeAttributes(const SUnit *N,
2757                                        const ScheduleDAG *Graph) {
2758     std::string Str("shape=Mrecord");
2759     const SchedDFSResult *DFS =
2760       static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2761     if (DFS) {
2762       Str += ",style=filled,fillcolor=\"#";
2763       Str += DOT::getColorString(DFS->getSubtreeID(N));
2764       Str += '"';
2765     }
2766     return Str;
2767   }
2768 };
2769 } // namespace llvm
2770 #endif // NDEBUG
2771
2772 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2773 /// rendered using 'dot'.
2774 ///
2775 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2776 #ifndef NDEBUG
2777   ViewGraph(this, Name, false, Title);
2778 #else
2779   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2780          << "systems with Graphviz or gv!\n";
2781 #endif  // NDEBUG
2782 }
2783
2784 /// Out-of-line implementation with no arguments is handy for gdb.
2785 void ScheduleDAGMI::viewGraph() {
2786   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
2787 }