1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "misched"
17 #include "RegisterClassInfo.h"
18 #include "RegisterPressure.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineScheduler.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/ADT/PriorityQueue.h"
36 static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38 static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
48 static bool ViewMISchedDAGs = false;
51 //===----------------------------------------------------------------------===//
52 // Machine Instruction Scheduling Pass and Registry
53 //===----------------------------------------------------------------------===//
55 MachineSchedContext::MachineSchedContext():
56 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
57 RegClassInfo = new RegisterClassInfo();
60 MachineSchedContext::~MachineSchedContext() {
65 /// MachineScheduler runs after coalescing and before register allocation.
66 class MachineScheduler : public MachineSchedContext,
67 public MachineFunctionPass {
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
73 virtual void releaseMemory() {}
75 virtual bool runOnMachineFunction(MachineFunction&);
77 virtual void print(raw_ostream &O, const Module* = 0) const;
79 static char ID; // Class identification, replacement for typeinfo
83 char MachineScheduler::ID = 0;
85 char &llvm::MachineSchedulerID = MachineScheduler::ID;
87 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
88 "Machine Instruction Scheduler", false, false)
89 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
91 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
92 INITIALIZE_PASS_END(MachineScheduler, "misched",
93 "Machine Instruction Scheduler", false, false)
95 MachineScheduler::MachineScheduler()
96 : MachineFunctionPass(ID) {
97 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
100 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesCFG();
102 AU.addRequiredID(MachineDominatorsID);
103 AU.addRequired<MachineLoopInfo>();
104 AU.addRequired<AliasAnalysis>();
105 AU.addRequired<TargetPassConfig>();
106 AU.addRequired<SlotIndexes>();
107 AU.addPreserved<SlotIndexes>();
108 AU.addRequired<LiveIntervals>();
109 AU.addPreserved<LiveIntervals>();
110 MachineFunctionPass::getAnalysisUsage(AU);
113 MachinePassRegistry MachineSchedRegistry::Registry;
115 /// A dummy default scheduler factory indicates whether the scheduler
116 /// is overridden on the command line.
117 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
121 /// MachineSchedOpt allows command line selection of the scheduler.
122 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
123 RegisterPassParser<MachineSchedRegistry> >
124 MachineSchedOpt("misched",
125 cl::init(&useDefaultMachineSched), cl::Hidden,
126 cl::desc("Machine instruction scheduler to use"));
128 static MachineSchedRegistry
129 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
130 useDefaultMachineSched);
132 /// Forward declare the standard machine scheduler. This will be used as the
133 /// default scheduler if the target does not set a default.
134 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
137 /// Decrement this iterator until reaching the top or a non-debug instr.
138 static MachineBasicBlock::iterator
139 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
140 assert(I != Beg && "reached the top of the region, cannot decrement");
142 if (!I->isDebugValue())
148 /// If this iterator is a debug value, increment until reaching the End or a
149 /// non-debug instruction.
150 static MachineBasicBlock::iterator
151 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
153 if (!I->isDebugValue())
159 /// Top-level MachineScheduler pass driver.
161 /// Visit blocks in function order. Divide each block into scheduling regions
162 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
163 /// consistent with the DAG builder, which traverses the interior of the
164 /// scheduling regions bottom-up.
166 /// This design avoids exposing scheduling boundaries to the DAG builder,
167 /// simplifying the DAG builder's support for "special" target instructions.
168 /// At the same time the design allows target schedulers to operate across
169 /// scheduling boundaries, for example to bundle the boudary instructions
170 /// without reordering them. This creates complexity, because the target
171 /// scheduler must update the RegionBegin and RegionEnd positions cached by
172 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
173 /// design would be to split blocks at scheduling boundaries, but LLVM has a
174 /// general bias against block splitting purely for implementation simplicity.
175 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
176 // Initialize the context of the pass.
178 MLI = &getAnalysis<MachineLoopInfo>();
179 MDT = &getAnalysis<MachineDominatorTree>();
180 PassConfig = &getAnalysis<TargetPassConfig>();
181 AA = &getAnalysis<AliasAnalysis>();
183 LIS = &getAnalysis<LiveIntervals>();
184 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
186 RegClassInfo->runOnMachineFunction(*MF);
188 // Select the scheduler, or set the default.
189 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
190 if (Ctor == useDefaultMachineSched) {
191 // Get the default scheduler set by the target.
192 Ctor = MachineSchedRegistry::getDefault();
194 Ctor = createConvergingSched;
195 MachineSchedRegistry::setDefault(Ctor);
198 // Instantiate the selected scheduler.
199 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
201 // Visit all machine basic blocks.
203 // TODO: Visit blocks in global postorder or postorder within the bottom-up
204 // loop tree. Then we can optionally compute global RegPressure.
205 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
206 MBB != MBBEnd; ++MBB) {
208 Scheduler->startBlock(MBB);
210 // Break the block into scheduling regions [I, RegionEnd), and schedule each
211 // region as soon as it is discovered. RegionEnd points the the scheduling
212 // boundary at the bottom of the region. The DAG does not include RegionEnd,
213 // but the region does (i.e. the next RegionEnd is above the previous
214 // RegionBegin). If the current block has no terminator then RegionEnd ==
215 // MBB->end() for the bottom region.
217 // The Scheduler may insert instructions during either schedule() or
218 // exitRegion(), even for empty regions. So the local iterators 'I' and
219 // 'RegionEnd' are invalid across these calls.
220 unsigned RemainingCount = MBB->size();
221 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
222 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
224 // Avoid decrementing RegionEnd for blocks with no terminator.
225 if (RegionEnd != MBB->end()
226 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
228 // Count the boundary instruction.
232 // The next region starts above the previous region. Look backward in the
233 // instruction stream until we find the nearest boundary.
234 MachineBasicBlock::iterator I = RegionEnd;
235 for(;I != MBB->begin(); --I, --RemainingCount) {
236 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
239 // Notify the scheduler of the region, even if we may skip scheduling
240 // it. Perhaps it still needs to be bundled.
241 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
243 // Skip empty scheduling regions (0 or 1 schedulable instructions).
244 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
245 // Close the current region. Bundle the terminator if needed.
246 // This invalidates 'RegionEnd' and 'I'.
247 Scheduler->exitRegion();
250 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
251 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
252 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
253 else dbgs() << "End";
254 dbgs() << " Remaining: " << RemainingCount << "\n");
256 // Schedule a region: possibly reorder instructions.
257 // This invalidates 'RegionEnd' and 'I'.
258 Scheduler->schedule();
260 // Close the current region.
261 Scheduler->exitRegion();
263 // Scheduling has invalidated the current iterator 'I'. Ask the
264 // scheduler for the top of it's scheduled region.
265 RegionEnd = Scheduler->begin();
267 assert(RemainingCount == 0 && "Instruction count mismatch!");
268 Scheduler->finishBlock();
270 Scheduler->finalizeSchedule();
271 DEBUG(LIS->print(dbgs()));
275 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
279 //===----------------------------------------------------------------------===//
280 // MachineSchedStrategy - Interface to a machine scheduling algorithm.
281 //===----------------------------------------------------------------------===//
286 /// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
287 /// scheduling algorithm.
289 /// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
290 /// in ScheduleDAGInstrs.h
291 class MachineSchedStrategy {
293 virtual ~MachineSchedStrategy() {}
295 /// Initialize the strategy after building the DAG for a new region.
296 virtual void initialize(ScheduleDAGMI *DAG) = 0;
298 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
299 /// schedule the node at the top of the unscheduled region. Otherwise it will
300 /// be scheduled at the bottom.
301 virtual SUnit *pickNode(bool &IsTopNode) = 0;
303 /// When all predecessor dependencies have been resolved, free this node for
304 /// top-down scheduling.
305 virtual void releaseTopNode(SUnit *SU) = 0;
306 /// When all successor dependencies have been resolved, free this node for
307 /// bottom-up scheduling.
308 virtual void releaseBottomNode(SUnit *SU) = 0;
312 //===----------------------------------------------------------------------===//
313 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
315 //===----------------------------------------------------------------------===//
318 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
319 /// machine instructions while updating LiveIntervals.
320 class ScheduleDAGMI : public ScheduleDAGInstrs {
322 RegisterClassInfo *RegClassInfo;
323 MachineSchedStrategy *SchedImpl;
325 MachineBasicBlock::iterator LiveRegionEnd;
327 // Register pressure in this region computed by buildSchedGraph.
328 IntervalPressure RegPressure;
329 RegPressureTracker RPTracker;
331 /// The top of the unscheduled zone.
332 MachineBasicBlock::iterator CurrentTop;
333 IntervalPressure TopPressure;
334 RegPressureTracker TopRPTracker;
336 /// The bottom of the unscheduled zone.
337 MachineBasicBlock::iterator CurrentBottom;
338 IntervalPressure BotPressure;
339 RegPressureTracker BotRPTracker;
341 /// The number of instructions scheduled so far. Used to cut off the
342 /// scheduler at the point determined by misched-cutoff.
343 unsigned NumInstrsScheduled;
345 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
346 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
347 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
348 RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
349 CurrentBottom(), BotRPTracker(BotPressure), NumInstrsScheduled(0) {}
355 MachineBasicBlock::iterator top() const { return CurrentTop; }
356 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
358 /// Get current register pressure for the top scheduled instructions.
359 const IntervalPressure &getTopPressure() const { return TopPressure; }
361 /// Get current register pressure for the bottom scheduled instructions.
362 const IntervalPressure &getBotPressure() const { return BotPressure; }
364 /// Get register pressure for the entire scheduling region before scheduling.
365 const IntervalPressure &getRegPressure() const { return RegPressure; }
367 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
368 /// region. This covers all instructions in a block, while schedule() may only
370 void enterRegion(MachineBasicBlock *bb,
371 MachineBasicBlock::iterator begin,
372 MachineBasicBlock::iterator end,
375 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
376 /// reorderable instructions.
380 void initRegPressure();
382 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
383 bool checkSchedLimit();
385 void releaseSucc(SUnit *SU, SDep *SuccEdge);
386 void releaseSuccessors(SUnit *SU);
387 void releasePred(SUnit *SU, SDep *PredEdge);
388 void releasePredecessors(SUnit *SU);
390 void placeDebugValues();
394 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
395 /// NumPredsLeft reaches zero, release the successor node.
396 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
397 SUnit *SuccSU = SuccEdge->getSUnit();
400 if (SuccSU->NumPredsLeft == 0) {
401 dbgs() << "*** Scheduling failed! ***\n";
403 dbgs() << " has been released too many times!\n";
407 --SuccSU->NumPredsLeft;
408 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
409 SchedImpl->releaseTopNode(SuccSU);
412 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
413 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
414 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
416 releaseSucc(SU, &*I);
420 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
421 /// NumSuccsLeft reaches zero, release the predecessor node.
422 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
423 SUnit *PredSU = PredEdge->getSUnit();
426 if (PredSU->NumSuccsLeft == 0) {
427 dbgs() << "*** Scheduling failed! ***\n";
429 dbgs() << " has been released too many times!\n";
433 --PredSU->NumSuccsLeft;
434 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
435 SchedImpl->releaseBottomNode(PredSU);
438 /// releasePredecessors - Call releasePred on each of SU's predecessors.
439 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
440 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
442 releasePred(SU, &*I);
446 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
447 MachineBasicBlock::iterator InsertPos) {
448 // Fix RegionBegin if the first instruction moves down.
449 if (&*RegionBegin == MI)
450 RegionBegin = llvm::next(RegionBegin);
451 BB->splice(InsertPos, BB, MI);
453 // Fix RegionBegin if another instruction moves above the first instruction.
454 if (RegionBegin == InsertPos)
456 // Fix TopRPTracker if we move something above CurrentTop.
457 if (CurrentTop == InsertPos)
458 TopRPTracker.setPos(MI);
461 bool ScheduleDAGMI::checkSchedLimit() {
463 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
464 CurrentTop = CurrentBottom;
467 ++NumInstrsScheduled;
472 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
473 /// crossing a scheduling boundary. [begin, end) includes all instructions in
474 /// the region, including the boundary itself and single-instruction regions
475 /// that don't get scheduled.
476 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
477 MachineBasicBlock::iterator begin,
478 MachineBasicBlock::iterator end,
481 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
483 // For convenience remember the end of the liveness region.
485 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
488 // Setup the register pressure trackers for the top scheduled top and bottom
489 // scheduled regions.
490 void ScheduleDAGMI::initRegPressure() {
491 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
492 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
494 // Close the RPTracker to finalize live ins.
495 RPTracker.closeRegion();
497 // Initialize the live ins and live outs.
498 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
499 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
501 // Close one end of the tracker so we can call
502 // getMaxUpward/DownwardPressureDelta before advancing across any
503 // instructions. This converts currently live regs into live ins/outs.
504 TopRPTracker.closeTop();
505 BotRPTracker.closeBottom();
507 // Account for liveness generated by the region boundary.
508 if (LiveRegionEnd != RegionEnd)
509 BotRPTracker.recede();
511 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
514 /// schedule - Called back from MachineScheduler::runOnMachineFunction
515 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
516 /// only includes instructions that have DAG nodes, not scheduling boundaries.
517 void ScheduleDAGMI::schedule() {
518 // Initialize the register pressure tracker used by buildSchedGraph.
519 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
521 // Account for liveness generate by the region boundary.
522 if (LiveRegionEnd != RegionEnd)
525 // Build the DAG, and compute current register pressure.
526 buildSchedGraph(AA, &RPTracker);
528 // Initialize top/bottom trackers after computing region pressure.
531 DEBUG(dbgs() << "********** MI Scheduling **********\n");
532 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
533 SUnits[su].dumpAll(this));
535 if (ViewMISchedDAGs) viewGraph();
537 SchedImpl->initialize(this);
539 // Release edges from the special Entry node or to the special Exit node.
540 releaseSuccessors(&EntrySU);
541 releasePredecessors(&ExitSU);
543 // Release all DAG roots for scheduling.
544 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
546 // A SUnit is ready to top schedule if it has no predecessors.
547 if (I->Preds.empty())
548 SchedImpl->releaseTopNode(&(*I));
549 // A SUnit is ready to bottom schedule if it has no successors.
550 if (I->Succs.empty())
551 SchedImpl->releaseBottomNode(&(*I));
554 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
555 CurrentBottom = RegionEnd;
556 bool IsTopNode = false;
557 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
558 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
559 << " Scheduling Instruction:\n"; SU->dump(this));
560 if (!checkSchedLimit())
563 // Move the instruction to its new location in the instruction stream.
564 MachineInstr *MI = SU->getInstr();
567 assert(SU->isTopReady() && "node still has unscheduled dependencies");
568 if (&*CurrentTop == MI)
569 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
571 moveInstruction(MI, CurrentTop);
573 // Update top scheduled pressure.
574 TopRPTracker.advance();
575 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
577 // Release dependent instructions for scheduling.
578 releaseSuccessors(SU);
581 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
582 MachineBasicBlock::iterator priorII =
583 priorNonDebug(CurrentBottom, CurrentTop);
585 CurrentBottom = priorII;
587 if (&*CurrentTop == MI)
588 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
589 moveInstruction(MI, CurrentBottom);
592 // Update bottom scheduled pressure.
593 BotRPTracker.recede();
594 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
596 // Release dependent instructions for scheduling.
597 releasePredecessors(SU);
599 SU->isScheduled = true;
601 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
606 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
607 void ScheduleDAGMI::placeDebugValues() {
608 // If first instruction was a DBG_VALUE then put it back.
610 BB->splice(RegionBegin, BB, FirstDbgValue);
611 RegionBegin = FirstDbgValue;
614 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
615 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
616 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
617 MachineInstr *DbgValue = P.first;
618 MachineBasicBlock::iterator OrigPrevMI = P.second;
619 BB->splice(++OrigPrevMI, BB, DbgValue);
620 if (OrigPrevMI == llvm::prior(RegionEnd))
621 RegionEnd = DbgValue;
624 FirstDbgValue = NULL;
627 //===----------------------------------------------------------------------===//
628 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
629 //===----------------------------------------------------------------------===//
633 typedef std::vector<SUnit*>::iterator iterator;
636 std::vector<SUnit*> Queue;
638 ReadyQ(unsigned id): ID(id) {}
640 bool isInQueue(SUnit *SU) const {
641 return SU->NodeQueueId & ID;
644 bool empty() const { return Queue.empty(); }
646 iterator begin() { return Queue.begin(); }
648 iterator end() { return Queue.end(); }
650 iterator find(SUnit *SU) {
651 return std::find(Queue.begin(), Queue.end(), SU);
654 void push(SUnit *SU) {
658 void remove(iterator I) {
664 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
666 class ConvergingScheduler : public MachineSchedStrategy {
673 // NodeQueueId = 0 (none), = 1 (top), = 2 (bottom), = 3 (both)
674 ConvergingScheduler(): TopQueue(1), BotQueue(2) {}
676 virtual void initialize(ScheduleDAGMI *dag) {
679 assert((!ForceTopDown || !ForceBottomUp) &&
680 "-misched-topdown incompatible with -misched-bottomup");
683 virtual SUnit *pickNode(bool &IsTopNode) {
684 if (DAG->top() == DAG->bottom()) {
685 assert(TopQueue.empty() && BotQueue.empty() && "ReadyQ garbage");
688 // As an initial placeholder heuristic, schedule in the direction that has
689 // the fewest choices.
692 || (!ForceBottomUp && TopQueue.Queue.size() <= BotQueue.Queue.size())) {
693 SU = DAG->getSUnit(DAG->top());
697 SU = DAG->getSUnit(priorNonDebug(DAG->bottom(), DAG->top()));
700 if (SU->isTopReady()) {
701 assert(!TopQueue.empty() && "bad ready count");
702 TopQueue.remove(TopQueue.find(SU));
704 if (SU->isBottomReady()) {
705 assert(!BotQueue.empty() && "bad ready count");
706 BotQueue.remove(BotQueue.find(SU));
711 virtual void releaseTopNode(SUnit *SU) {
712 if (!SU->isScheduled)
715 virtual void releaseBottomNode(SUnit *SU) {
716 if (!SU->isScheduled)
722 /// Create the standard converging machine scheduler. This will be used as the
723 /// default scheduler if the target does not set a default.
724 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
725 assert((!ForceTopDown || !ForceBottomUp) &&
726 "-misched-topdown incompatible with -misched-bottomup");
727 return new ScheduleDAGMI(C, new ConvergingScheduler());
729 static MachineSchedRegistry
730 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
731 createConvergingSched);
733 //===----------------------------------------------------------------------===//
734 // Machine Instruction Shuffler for Correctness Testing
735 //===----------------------------------------------------------------------===//
739 /// Apply a less-than relation on the node order, which corresponds to the
740 /// instruction order prior to scheduling. IsReverse implements greater-than.
741 template<bool IsReverse>
743 bool operator()(SUnit *A, SUnit *B) const {
745 return A->NodeNum > B->NodeNum;
747 return A->NodeNum < B->NodeNum;
751 /// Reorder instructions as much as possible.
752 class InstructionShuffler : public MachineSchedStrategy {
756 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
757 // gives nodes with a higher number higher priority causing the latest
758 // instructions to be scheduled first.
759 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
761 // When scheduling bottom-up, use greater-than as the queue priority.
762 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
765 InstructionShuffler(bool alternate, bool topdown)
766 : IsAlternating(alternate), IsTopDown(topdown) {}
768 virtual void initialize(ScheduleDAGMI *) {
773 /// Implement MachineSchedStrategy interface.
774 /// -----------------------------------------
776 virtual SUnit *pickNode(bool &IsTopNode) {
780 if (TopQ.empty()) return NULL;
783 } while (SU->isScheduled);
788 if (BottomQ.empty()) return NULL;
791 } while (SU->isScheduled);
795 IsTopDown = !IsTopDown;
799 virtual void releaseTopNode(SUnit *SU) {
802 virtual void releaseBottomNode(SUnit *SU) {
808 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
809 bool Alternate = !ForceTopDown && !ForceBottomUp;
810 bool TopDown = !ForceBottomUp;
811 assert((TopDown || !ForceTopDown) &&
812 "-misched-topdown incompatible with -misched-bottomup");
813 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
815 static MachineSchedRegistry ShufflerRegistry(
816 "shuffle", "Shuffle machine instructions alternating directions",
817 createInstructionShuffler);