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