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 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
178 // Initialize the context of the pass.
180 MLI = &getAnalysis<MachineLoopInfo>();
181 MDT = &getAnalysis<MachineDominatorTree>();
182 PassConfig = &getAnalysis<TargetPassConfig>();
183 AA = &getAnalysis<AliasAnalysis>();
185 LIS = &getAnalysis<LiveIntervals>();
186 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
188 RegClassInfo->runOnMachineFunction(*MF);
190 // Select the scheduler, or set the default.
191 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
192 if (Ctor == useDefaultMachineSched) {
193 // Get the default scheduler set by the target.
194 Ctor = MachineSchedRegistry::getDefault();
196 Ctor = createConvergingSched;
197 MachineSchedRegistry::setDefault(Ctor);
200 // Instantiate the selected scheduler.
201 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
203 // Visit all machine basic blocks.
205 // TODO: Visit blocks in global postorder or postorder within the bottom-up
206 // loop tree. Then we can optionally compute global RegPressure.
207 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
208 MBB != MBBEnd; ++MBB) {
210 Scheduler->startBlock(MBB);
212 // Break the block into scheduling regions [I, RegionEnd), and schedule each
213 // region as soon as it is discovered. RegionEnd points the the scheduling
214 // boundary at the bottom of the region. The DAG does not include RegionEnd,
215 // but the region does (i.e. the next RegionEnd is above the previous
216 // RegionBegin). If the current block has no terminator then RegionEnd ==
217 // MBB->end() for the bottom region.
219 // The Scheduler may insert instructions during either schedule() or
220 // exitRegion(), even for empty regions. So the local iterators 'I' and
221 // 'RegionEnd' are invalid across these calls.
222 unsigned RemainingCount = MBB->size();
223 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
224 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
226 // Avoid decrementing RegionEnd for blocks with no terminator.
227 if (RegionEnd != MBB->end()
228 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
230 // Count the boundary instruction.
234 // The next region starts above the previous region. Look backward in the
235 // instruction stream until we find the nearest boundary.
236 MachineBasicBlock::iterator I = RegionEnd;
237 for(;I != MBB->begin(); --I, --RemainingCount) {
238 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
241 // Notify the scheduler of the region, even if we may skip scheduling
242 // it. Perhaps it still needs to be bundled.
243 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
245 // Skip empty scheduling regions (0 or 1 schedulable instructions).
246 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
247 // Close the current region. Bundle the terminator if needed.
248 // This invalidates 'RegionEnd' and 'I'.
249 Scheduler->exitRegion();
252 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
253 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
254 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
255 else dbgs() << "End";
256 dbgs() << " Remaining: " << RemainingCount << "\n");
258 // Schedule a region: possibly reorder instructions.
259 // This invalidates 'RegionEnd' and 'I'.
260 Scheduler->schedule();
262 // Close the current region.
263 Scheduler->exitRegion();
265 // Scheduling has invalidated the current iterator 'I'. Ask the
266 // scheduler for the top of it's scheduled region.
267 RegionEnd = Scheduler->begin();
269 assert(RemainingCount == 0 && "Instruction count mismatch!");
270 Scheduler->finishBlock();
272 Scheduler->finalizeSchedule();
273 DEBUG(LIS->print(dbgs()));
277 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
281 //===----------------------------------------------------------------------===//
282 // MachineSchedStrategy - Interface to a machine scheduling algorithm.
283 //===----------------------------------------------------------------------===//
288 /// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
289 /// scheduling algorithm.
291 /// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
292 /// in ScheduleDAGInstrs.h
293 class MachineSchedStrategy {
295 virtual ~MachineSchedStrategy() {}
297 /// Initialize the strategy after building the DAG for a new region.
298 virtual void initialize(ScheduleDAGMI *DAG) = 0;
300 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
301 /// schedule the node at the top of the unscheduled region. Otherwise it will
302 /// be scheduled at the bottom.
303 virtual SUnit *pickNode(bool &IsTopNode) = 0;
305 /// When all predecessor dependencies have been resolved, free this node for
306 /// top-down scheduling.
307 virtual void releaseTopNode(SUnit *SU) = 0;
308 /// When all successor dependencies have been resolved, free this node for
309 /// bottom-up scheduling.
310 virtual void releaseBottomNode(SUnit *SU) = 0;
314 //===----------------------------------------------------------------------===//
315 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
317 //===----------------------------------------------------------------------===//
320 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
321 /// machine instructions while updating LiveIntervals.
322 class ScheduleDAGMI : public ScheduleDAGInstrs {
324 RegisterClassInfo *RegClassInfo;
325 MachineSchedStrategy *SchedImpl;
327 MachineBasicBlock::iterator LiveRegionEnd;
329 // Register pressure in this region computed by buildSchedGraph.
330 IntervalPressure RegPressure;
331 RegPressureTracker RPTracker;
333 /// The top of the unscheduled zone.
334 MachineBasicBlock::iterator CurrentTop;
335 IntervalPressure TopPressure;
336 RegPressureTracker TopRPTracker;
338 /// The bottom of the unscheduled zone.
339 MachineBasicBlock::iterator CurrentBottom;
340 IntervalPressure BotPressure;
341 RegPressureTracker BotRPTracker;
343 /// The number of instructions scheduled so far. Used to cut off the
344 /// scheduler at the point determined by misched-cutoff.
345 unsigned NumInstrsScheduled;
347 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
348 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
349 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
350 RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
351 CurrentBottom(), BotRPTracker(BotPressure), NumInstrsScheduled(0) {}
357 MachineBasicBlock::iterator top() const { return CurrentTop; }
358 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
360 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
361 /// region. This covers all instructions in a block, while schedule() may only
363 void enterRegion(MachineBasicBlock *bb,
364 MachineBasicBlock::iterator begin,
365 MachineBasicBlock::iterator end,
368 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
369 /// reorderable instructions.
372 /// Get current register pressure for the top scheduled instructions.
373 const IntervalPressure &getTopPressure() const { return TopPressure; }
374 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
376 /// Get current register pressure for the bottom scheduled instructions.
377 const IntervalPressure &getBotPressure() const { return BotPressure; }
378 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
380 /// Get register pressure for the entire scheduling region before scheduling.
381 const IntervalPressure &getRegPressure() const { return RegPressure; }
384 void initRegPressure();
386 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
387 bool checkSchedLimit();
389 void releaseSucc(SUnit *SU, SDep *SuccEdge);
390 void releaseSuccessors(SUnit *SU);
391 void releasePred(SUnit *SU, SDep *PredEdge);
392 void releasePredecessors(SUnit *SU);
394 void placeDebugValues();
398 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
399 /// NumPredsLeft reaches zero, release the successor node.
400 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
401 SUnit *SuccSU = SuccEdge->getSUnit();
404 if (SuccSU->NumPredsLeft == 0) {
405 dbgs() << "*** Scheduling failed! ***\n";
407 dbgs() << " has been released too many times!\n";
411 --SuccSU->NumPredsLeft;
412 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
413 SchedImpl->releaseTopNode(SuccSU);
416 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
417 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
418 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
420 releaseSucc(SU, &*I);
424 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
425 /// NumSuccsLeft reaches zero, release the predecessor node.
426 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
427 SUnit *PredSU = PredEdge->getSUnit();
430 if (PredSU->NumSuccsLeft == 0) {
431 dbgs() << "*** Scheduling failed! ***\n";
433 dbgs() << " has been released too many times!\n";
437 --PredSU->NumSuccsLeft;
438 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
439 SchedImpl->releaseBottomNode(PredSU);
442 /// releasePredecessors - Call releasePred on each of SU's predecessors.
443 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
444 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
446 releasePred(SU, &*I);
450 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
451 MachineBasicBlock::iterator InsertPos) {
452 // Fix RegionBegin if the first instruction moves down.
453 if (&*RegionBegin == MI)
454 RegionBegin = llvm::next(RegionBegin);
455 BB->splice(InsertPos, BB, MI);
457 // Fix RegionBegin if another instruction moves above the first instruction.
458 if (RegionBegin == InsertPos)
460 // Fix TopRPTracker if we move something above CurrentTop.
461 if (CurrentTop == InsertPos)
462 TopRPTracker.setPos(MI);
465 bool ScheduleDAGMI::checkSchedLimit() {
467 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
468 CurrentTop = CurrentBottom;
471 ++NumInstrsScheduled;
476 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
477 /// crossing a scheduling boundary. [begin, end) includes all instructions in
478 /// the region, including the boundary itself and single-instruction regions
479 /// that don't get scheduled.
480 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
481 MachineBasicBlock::iterator begin,
482 MachineBasicBlock::iterator end,
485 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
487 // For convenience remember the end of the liveness region.
489 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
492 // Setup the register pressure trackers for the top scheduled top and bottom
493 // scheduled regions.
494 void ScheduleDAGMI::initRegPressure() {
495 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
496 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
498 // Close the RPTracker to finalize live ins.
499 RPTracker.closeRegion();
501 // Initialize the live ins and live outs.
502 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
503 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
505 // Close one end of the tracker so we can call
506 // getMaxUpward/DownwardPressureDelta before advancing across any
507 // instructions. This converts currently live regs into live ins/outs.
508 TopRPTracker.closeTop();
509 BotRPTracker.closeBottom();
511 // Account for liveness generated by the region boundary.
512 if (LiveRegionEnd != RegionEnd)
513 BotRPTracker.recede();
515 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
518 /// schedule - Called back from MachineScheduler::runOnMachineFunction
519 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
520 /// only includes instructions that have DAG nodes, not scheduling boundaries.
521 void ScheduleDAGMI::schedule() {
522 // Initialize the register pressure tracker used by buildSchedGraph.
523 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
525 // Account for liveness generate by the region boundary.
526 if (LiveRegionEnd != RegionEnd)
529 // Build the DAG, and compute current register pressure.
530 buildSchedGraph(AA, &RPTracker);
532 // Initialize top/bottom trackers after computing region pressure.
535 DEBUG(dbgs() << "********** MI Scheduling **********\n");
536 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
537 SUnits[su].dumpAll(this));
539 if (ViewMISchedDAGs) viewGraph();
541 SchedImpl->initialize(this);
543 // Release edges from the special Entry node or to the special Exit node.
544 releaseSuccessors(&EntrySU);
545 releasePredecessors(&ExitSU);
547 // Release all DAG roots for scheduling.
548 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
550 // A SUnit is ready to top schedule if it has no predecessors.
551 if (I->Preds.empty())
552 SchedImpl->releaseTopNode(&(*I));
553 // A SUnit is ready to bottom schedule if it has no successors.
554 if (I->Succs.empty())
555 SchedImpl->releaseBottomNode(&(*I));
558 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
559 CurrentBottom = RegionEnd;
560 bool IsTopNode = false;
561 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
562 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
563 << " Scheduling Instruction:\n"; SU->dump(this));
564 if (!checkSchedLimit())
567 // Move the instruction to its new location in the instruction stream.
568 MachineInstr *MI = SU->getInstr();
571 assert(SU->isTopReady() && "node still has unscheduled dependencies");
572 if (&*CurrentTop == MI)
573 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
575 moveInstruction(MI, CurrentTop);
577 // Update top scheduled pressure.
578 TopRPTracker.advance();
579 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
581 // Release dependent instructions for scheduling.
582 releaseSuccessors(SU);
585 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
586 MachineBasicBlock::iterator priorII =
587 priorNonDebug(CurrentBottom, CurrentTop);
589 CurrentBottom = priorII;
591 if (&*CurrentTop == MI)
592 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
593 moveInstruction(MI, CurrentBottom);
596 // Update bottom scheduled pressure.
597 BotRPTracker.recede();
598 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
600 // Release dependent instructions for scheduling.
601 releasePredecessors(SU);
603 SU->isScheduled = true;
605 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
610 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
611 void ScheduleDAGMI::placeDebugValues() {
612 // If first instruction was a DBG_VALUE then put it back.
614 BB->splice(RegionBegin, BB, FirstDbgValue);
615 RegionBegin = FirstDbgValue;
618 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
619 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
620 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
621 MachineInstr *DbgValue = P.first;
622 MachineBasicBlock::iterator OrigPrevMI = P.second;
623 BB->splice(++OrigPrevMI, BB, DbgValue);
624 if (OrigPrevMI == llvm::prior(RegionEnd))
625 RegionEnd = DbgValue;
628 FirstDbgValue = NULL;
631 //===----------------------------------------------------------------------===//
632 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
633 //===----------------------------------------------------------------------===//
636 /// Wrapper around a vector of SUnits with some basic convenience methods.
638 typedef std::vector<SUnit*>::iterator iterator;
641 std::vector<SUnit*> Queue;
643 ReadyQ(unsigned id): ID(id) {}
645 bool isInQueue(SUnit *SU) const {
646 return SU->NodeQueueId & ID;
649 bool empty() const { return Queue.empty(); }
651 iterator begin() { return Queue.begin(); }
653 iterator end() { return Queue.end(); }
655 iterator find(SUnit *SU) {
656 return std::find(Queue.begin(), Queue.end(), SU);
659 void push(SUnit *SU) {
661 SU->NodeQueueId |= ID;
664 void remove(iterator I) {
665 (*I)->NodeQueueId &= ~ID;
671 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
673 class ConvergingScheduler : public MachineSchedStrategy {
675 /// Store the state used by ConvergingScheduler heuristics, required for the
676 /// lifetime of one invocation of pickNode().
677 struct SchedCandidate {
678 // The best SUnit candidate.
681 // Register pressure values for the best candidate.
682 RegPressureDelta RPDelta;
684 SchedCandidate(): SU(NULL) {}
688 const TargetRegisterInfo *TRI;
694 /// SUnit::NodeQueueId = 0 (none), = 1 (top), = 2 (bottom), = 3 (both)
700 ConvergingScheduler(): DAG(0), TRI(0), TopQueue(TopQID), BotQueue(BotQID) {}
702 static const char *getQName(unsigned ID) {
704 default: return "NoQ";
705 case TopQID: return "TopQ";
706 case BotQID: return "BotQ";
710 virtual void initialize(ScheduleDAGMI *dag) {
714 assert((!ForceTopDown || !ForceBottomUp) &&
715 "-misched-topdown incompatible with -misched-bottomup");
718 virtual SUnit *pickNode(bool &IsTopNode);
720 virtual void releaseTopNode(SUnit *SU) {
721 if (!SU->isScheduled)
724 virtual void releaseBottomNode(SUnit *SU) {
725 if (!SU->isScheduled)
730 void traceCandidate(const char *Label, unsigned QID, SUnit *SU,
731 int RPDiff, unsigned PSetID);
733 bool pickNodeFromQueue(ReadyQ &Q, const RegPressureTracker &RPTracker,
734 SchedCandidate &Candidate);
739 void ConvergingScheduler::
740 traceCandidate(const char *Label, unsigned QID, SUnit *SU,
741 int RPDiff, unsigned PSetID) {
742 dbgs() << Label << getQName(QID) << " ";
744 dbgs() << TRI->getRegPressureSetName(PSetID) << ":" << RPDiff << " ";
751 /// Pick the best candidate from the top queue.
753 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
754 /// DAG building. To adjust for the current scheduling location we need to
755 /// maintain the number of vreg uses remaining to be top-scheduled.
756 bool ConvergingScheduler::pickNodeFromQueue(ReadyQ &Q,
757 const RegPressureTracker &RPTracker,
758 SchedCandidate &Candidate) {
759 // getMaxPressureDelta temporarily modifies the tracker.
760 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
762 // BestSU remains NULL if no top candidates beat the best existing candidate.
763 bool FoundCandidate = false;
764 for (ReadyQ::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
766 RegPressureDelta RPDelta;
767 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta);
769 // Avoid exceeding the target's limit.
770 if (!Candidate.SU || RPDelta.ExcessUnits < Candidate.RPDelta.ExcessUnits) {
771 DEBUG(traceCandidate(Candidate.SU ? "PCAND" : "ACAND", Q.ID, *I,
772 RPDelta.ExcessUnits, RPDelta.ExcessSetID));
774 Candidate.RPDelta = RPDelta;
775 FoundCandidate = true;
778 if (RPDelta.ExcessUnits > Candidate.RPDelta.ExcessUnits)
781 // Avoid increasing the max pressure.
782 if (RPDelta.MaxUnitIncrease < Candidate.RPDelta.MaxUnitIncrease) {
783 DEBUG(traceCandidate("MCAND", Q.ID, *I,
784 RPDelta.ExcessUnits, RPDelta.ExcessSetID));
786 Candidate.RPDelta = RPDelta;
787 FoundCandidate = true;
790 if (RPDelta.MaxUnitIncrease > Candidate.RPDelta.MaxUnitIncrease)
793 // Fall through to original instruction order.
794 // Only consider node order if BestSU was chosen from this Q.
798 if ((Q.ID == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
799 || (Q.ID == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
800 DEBUG(traceCandidate("NCAND", Q.ID, *I, 0, 0));
802 Candidate.RPDelta = RPDelta;
803 FoundCandidate = true;
806 return FoundCandidate;
809 /// Pick the best node from either the top or bottom queue to balance the
811 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
812 if (DAG->top() == DAG->bottom()) {
813 assert(TopQueue.empty() && BotQueue.empty() && "ReadyQ garbage");
816 // As an initial placeholder heuristic, schedule in the direction that has
817 // the fewest choices.
820 SU = DAG->getSUnit(DAG->top());
823 else if (ForceBottomUp) {
824 SU = DAG->getSUnit(priorNonDebug(DAG->bottom(), DAG->top()));
828 SchedCandidate Candidate;
829 // Prefer picking from the bottom.
830 pickNodeFromQueue(BotQueue, DAG->getBotRPTracker(), Candidate);
832 pickNodeFromQueue(TopQueue, DAG->getTopRPTracker(), Candidate);
835 if (SU->isTopReady()) {
836 assert(!TopQueue.empty() && "bad ready count");
837 TopQueue.remove(TopQueue.find(SU));
839 if (SU->isBottomReady()) {
840 assert(!BotQueue.empty() && "bad ready count");
841 BotQueue.remove(BotQueue.find(SU));
846 /// Create the standard converging machine scheduler. This will be used as the
847 /// default scheduler if the target does not set a default.
848 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
849 assert((!ForceTopDown || !ForceBottomUp) &&
850 "-misched-topdown incompatible with -misched-bottomup");
851 return new ScheduleDAGMI(C, new ConvergingScheduler());
853 static MachineSchedRegistry
854 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
855 createConvergingSched);
857 //===----------------------------------------------------------------------===//
858 // Machine Instruction Shuffler for Correctness Testing
859 //===----------------------------------------------------------------------===//
863 /// Apply a less-than relation on the node order, which corresponds to the
864 /// instruction order prior to scheduling. IsReverse implements greater-than.
865 template<bool IsReverse>
867 bool operator()(SUnit *A, SUnit *B) const {
869 return A->NodeNum > B->NodeNum;
871 return A->NodeNum < B->NodeNum;
875 /// Reorder instructions as much as possible.
876 class InstructionShuffler : public MachineSchedStrategy {
880 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
881 // gives nodes with a higher number higher priority causing the latest
882 // instructions to be scheduled first.
883 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
885 // When scheduling bottom-up, use greater-than as the queue priority.
886 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
889 InstructionShuffler(bool alternate, bool topdown)
890 : IsAlternating(alternate), IsTopDown(topdown) {}
892 virtual void initialize(ScheduleDAGMI *) {
897 /// Implement MachineSchedStrategy interface.
898 /// -----------------------------------------
900 virtual SUnit *pickNode(bool &IsTopNode) {
904 if (TopQ.empty()) return NULL;
907 } while (SU->isScheduled);
912 if (BottomQ.empty()) return NULL;
915 } while (SU->isScheduled);
919 IsTopDown = !IsTopDown;
923 virtual void releaseTopNode(SUnit *SU) {
926 virtual void releaseBottomNode(SUnit *SU) {
932 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
933 bool Alternate = !ForceTopDown && !ForceBottomUp;
934 bool TopDown = !ForceBottomUp;
935 assert((TopDown || !ForceTopDown) &&
936 "-misched-topdown incompatible with -misched-bottomup");
937 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
939 static MachineSchedRegistry ShufflerRegistry(
940 "shuffle", "Shuffle machine instructions alternating directions",
941 createInstructionShuffler);