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 "RegisterPressure.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineScheduler.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/PriorityQueue.h"
35 static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37 static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
41 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
42 cl::desc("Pop up a window to show MISched dags after they are processed"));
44 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
45 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
47 static bool ViewMISchedDAGs = false;
50 //===----------------------------------------------------------------------===//
51 // Machine Instruction Scheduling Pass and Registry
52 //===----------------------------------------------------------------------===//
55 /// MachineScheduler runs after coalescing and before register allocation.
56 class MachineScheduler : public MachineSchedContext,
57 public MachineFunctionPass {
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
63 virtual void releaseMemory() {}
65 virtual bool runOnMachineFunction(MachineFunction&);
67 virtual void print(raw_ostream &O, const Module* = 0) const;
69 static char ID; // Class identification, replacement for typeinfo
73 char MachineScheduler::ID = 0;
75 char &llvm::MachineSchedulerID = MachineScheduler::ID;
77 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
78 "Machine Instruction Scheduler", false, false)
79 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
80 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
82 INITIALIZE_PASS_END(MachineScheduler, "misched",
83 "Machine Instruction Scheduler", false, false)
85 MachineScheduler::MachineScheduler()
86 : MachineFunctionPass(ID) {
87 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
90 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequiredID(MachineDominatorsID);
93 AU.addRequired<MachineLoopInfo>();
94 AU.addRequired<AliasAnalysis>();
95 AU.addRequired<TargetPassConfig>();
96 AU.addRequired<SlotIndexes>();
97 AU.addPreserved<SlotIndexes>();
98 AU.addRequired<LiveIntervals>();
99 AU.addPreserved<LiveIntervals>();
100 MachineFunctionPass::getAnalysisUsage(AU);
103 MachinePassRegistry MachineSchedRegistry::Registry;
105 /// A dummy default scheduler factory indicates whether the scheduler
106 /// is overridden on the command line.
107 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
111 /// MachineSchedOpt allows command line selection of the scheduler.
112 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
113 RegisterPassParser<MachineSchedRegistry> >
114 MachineSchedOpt("misched",
115 cl::init(&useDefaultMachineSched), cl::Hidden,
116 cl::desc("Machine instruction scheduler to use"));
118 static MachineSchedRegistry
119 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
120 useDefaultMachineSched);
122 /// Forward declare the standard machine scheduler. This will be used as the
123 /// default scheduler if the target does not set a default.
124 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
126 /// Top-level MachineScheduler pass driver.
128 /// Visit blocks in function order. Divide each block into scheduling regions
129 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
130 /// consistent with the DAG builder, which traverses the interior of the
131 /// scheduling regions bottom-up.
133 /// This design avoids exposing scheduling boundaries to the DAG builder,
134 /// simplifying the DAG builder's support for "special" target instructions.
135 /// At the same time the design allows target schedulers to operate across
136 /// scheduling boundaries, for example to bundle the boudary instructions
137 /// without reordering them. This creates complexity, because the target
138 /// scheduler must update the RegionBegin and RegionEnd positions cached by
139 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
140 /// design would be to split blocks at scheduling boundaries, but LLVM has a
141 /// general bias against block splitting purely for implementation simplicity.
142 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
143 // Initialize the context of the pass.
145 MLI = &getAnalysis<MachineLoopInfo>();
146 MDT = &getAnalysis<MachineDominatorTree>();
147 PassConfig = &getAnalysis<TargetPassConfig>();
148 AA = &getAnalysis<AliasAnalysis>();
150 LIS = &getAnalysis<LiveIntervals>();
151 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
153 RegClassInfo.runOnMachineFunction(*MF);
155 // Select the scheduler, or set the default.
156 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
157 if (Ctor == useDefaultMachineSched) {
158 // Get the default scheduler set by the target.
159 Ctor = MachineSchedRegistry::getDefault();
161 Ctor = createConvergingSched;
162 MachineSchedRegistry::setDefault(Ctor);
165 // Instantiate the selected scheduler.
166 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
168 // Visit all machine basic blocks.
170 // TODO: Visit blocks in global postorder or postorder within the bottom-up
171 // loop tree. Then we can optionally compute global RegPressure.
172 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
173 MBB != MBBEnd; ++MBB) {
175 Scheduler->startBlock(MBB);
177 // Break the block into scheduling regions [I, RegionEnd), and schedule each
178 // region as soon as it is discovered. RegionEnd points the the scheduling
179 // boundary at the bottom of the region. The DAG does not include RegionEnd,
180 // but the region does (i.e. the next RegionEnd is above the previous
181 // RegionBegin). If the current block has no terminator then RegionEnd ==
182 // MBB->end() for the bottom region.
184 // The Scheduler may insert instructions during either schedule() or
185 // exitRegion(), even for empty regions. So the local iterators 'I' and
186 // 'RegionEnd' are invalid across these calls.
187 unsigned RemainingCount = MBB->size();
188 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
189 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
191 // Avoid decrementing RegionEnd for blocks with no terminator.
192 if (RegionEnd != MBB->end()
193 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
195 // Count the boundary instruction.
199 // The next region starts above the previous region. Look backward in the
200 // instruction stream until we find the nearest boundary.
201 MachineBasicBlock::iterator I = RegionEnd;
202 for(;I != MBB->begin(); --I, --RemainingCount) {
203 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
206 // Notify the scheduler of the region, even if we may skip scheduling
207 // it. Perhaps it still needs to be bundled.
208 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
210 // Skip empty scheduling regions (0 or 1 schedulable instructions).
211 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
212 // Close the current region. Bundle the terminator if needed.
213 // This invalidates 'RegionEnd' and 'I'.
214 Scheduler->exitRegion();
217 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
218 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
219 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
220 else dbgs() << "End";
221 dbgs() << " Remaining: " << RemainingCount << "\n");
223 // Schedule a region: possibly reorder instructions.
224 // This invalidates 'RegionEnd' and 'I'.
225 Scheduler->schedule();
227 // Close the current region.
228 Scheduler->exitRegion();
230 // Scheduling has invalidated the current iterator 'I'. Ask the
231 // scheduler for the top of it's scheduled region.
232 RegionEnd = Scheduler->begin();
234 assert(RemainingCount == 0 && "Instruction count mismatch!");
235 Scheduler->finishBlock();
237 Scheduler->finalizeSchedule();
238 DEBUG(LIS->print(dbgs()));
242 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
246 //===----------------------------------------------------------------------===//
247 // MachineSchedStrategy - Interface to a machine scheduling algorithm.
248 //===----------------------------------------------------------------------===//
253 /// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
254 /// scheduling algorithm.
256 /// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
257 /// in ScheduleDAGInstrs.h
258 class MachineSchedStrategy {
260 virtual ~MachineSchedStrategy() {}
262 /// Initialize the strategy after building the DAG for a new region.
263 virtual void initialize(ScheduleDAGMI *DAG) = 0;
265 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
266 /// schedule the node at the top of the unscheduled region. Otherwise it will
267 /// be scheduled at the bottom.
268 virtual SUnit *pickNode(bool &IsTopNode) = 0;
270 /// When all predecessor dependencies have been resolved, free this node for
271 /// top-down scheduling.
272 virtual void releaseTopNode(SUnit *SU) = 0;
273 /// When all successor dependencies have been resolved, free this node for
274 /// bottom-up scheduling.
275 virtual void releaseBottomNode(SUnit *SU) = 0;
279 //===----------------------------------------------------------------------===//
280 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
282 //===----------------------------------------------------------------------===//
285 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
286 /// machine instructions while updating LiveIntervals.
287 class ScheduleDAGMI : public ScheduleDAGInstrs {
289 RegisterClassInfo *RegClassInfo;
290 MachineSchedStrategy *SchedImpl;
292 // Register pressure in this region computed by buildSchedGraph.
293 IntervalPressure RegPressure;
294 RegPressureTracker RPTracker;
296 /// The top of the unscheduled zone.
297 MachineBasicBlock::iterator CurrentTop;
299 /// The bottom of the unscheduled zone.
300 MachineBasicBlock::iterator CurrentBottom;
302 /// The number of instructions scheduled so far. Used to cut off the
303 /// scheduler at the point determined by misched-cutoff.
304 unsigned NumInstrsScheduled;
306 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
307 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
308 AA(C->AA), RegClassInfo(&C->RegClassInfo), SchedImpl(S),
309 RPTracker(RegPressure), CurrentTop(), CurrentBottom(),
310 NumInstrsScheduled(0) {}
316 MachineBasicBlock::iterator top() const { return CurrentTop; }
317 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
319 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
320 /// region. This covers all instructions in a block, while schedule() may only
322 void enterRegion(MachineBasicBlock *bb,
323 MachineBasicBlock::iterator begin,
324 MachineBasicBlock::iterator end,
327 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
328 /// reorderable instructions.
332 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
333 bool checkSchedLimit();
335 void releaseSucc(SUnit *SU, SDep *SuccEdge);
336 void releaseSuccessors(SUnit *SU);
337 void releasePred(SUnit *SU, SDep *PredEdge);
338 void releasePredecessors(SUnit *SU);
342 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
343 /// NumPredsLeft reaches zero, release the successor node.
344 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
345 SUnit *SuccSU = SuccEdge->getSUnit();
348 if (SuccSU->NumPredsLeft == 0) {
349 dbgs() << "*** Scheduling failed! ***\n";
351 dbgs() << " has been released too many times!\n";
355 --SuccSU->NumPredsLeft;
356 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
357 SchedImpl->releaseTopNode(SuccSU);
360 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
361 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
362 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
364 releaseSucc(SU, &*I);
368 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
369 /// NumSuccsLeft reaches zero, release the predecessor node.
370 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
371 SUnit *PredSU = PredEdge->getSUnit();
374 if (PredSU->NumSuccsLeft == 0) {
375 dbgs() << "*** Scheduling failed! ***\n";
377 dbgs() << " has been released too many times!\n";
381 --PredSU->NumSuccsLeft;
382 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
383 SchedImpl->releaseBottomNode(PredSU);
386 /// releasePredecessors - Call releasePred on each of SU's predecessors.
387 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
388 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
390 releasePred(SU, &*I);
394 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
395 MachineBasicBlock::iterator InsertPos) {
396 // Fix RegionBegin if the first instruction moves down.
397 if (&*RegionBegin == MI)
398 RegionBegin = llvm::next(RegionBegin);
399 BB->splice(InsertPos, BB, MI);
401 // Fix RegionBegin if another instruction moves above the first instruction.
402 if (RegionBegin == InsertPos)
406 bool ScheduleDAGMI::checkSchedLimit() {
408 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
409 CurrentTop = CurrentBottom;
412 ++NumInstrsScheduled;
417 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
418 /// crossing a scheduling boundary. [begin, end) includes all instructions in
419 /// the region, including the boundary itself and single-instruction regions
420 /// that don't get scheduled.
421 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
422 MachineBasicBlock::iterator begin,
423 MachineBasicBlock::iterator end,
426 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
427 // Setup the register pressure tracker to begin tracking at the end of this
429 RPTracker.init(&MF, RegClassInfo, LIS, BB, end);
432 /// schedule - Called back from MachineScheduler::runOnMachineFunction
433 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
434 /// only includes instructions that have DAG nodes, not scheduling boundaries.
435 void ScheduleDAGMI::schedule() {
436 while(RPTracker.getPos() != RegionEnd) {
437 bool Moved = RPTracker.recede();
438 assert(Moved && "Regpressure tracker cannot find RegionEnd"); (void)Moved;
442 buildSchedGraph(AA, &RPTracker);
444 DEBUG(dbgs() << "********** MI Scheduling **********\n");
445 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
446 SUnits[su].dumpAll(this));
448 if (ViewMISchedDAGs) viewGraph();
450 SchedImpl->initialize(this);
452 // Release edges from the special Entry node or to the special Exit node.
453 releaseSuccessors(&EntrySU);
454 releasePredecessors(&ExitSU);
456 // Release all DAG roots for scheduling.
457 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
459 // A SUnit is ready to top schedule if it has no predecessors.
460 if (I->Preds.empty())
461 SchedImpl->releaseTopNode(&(*I));
462 // A SUnit is ready to bottom schedule if it has no successors.
463 if (I->Succs.empty())
464 SchedImpl->releaseBottomNode(&(*I));
467 CurrentTop = RegionBegin;
468 CurrentBottom = RegionEnd;
469 bool IsTopNode = false;
470 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
471 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
472 << " Scheduling Instruction:\n"; SU->dump(this));
473 if (!checkSchedLimit())
476 // Move the instruction to its new location in the instruction stream.
477 MachineInstr *MI = SU->getInstr();
480 assert(SU->isTopReady() && "node still has unscheduled dependencies");
481 if (&*CurrentTop == MI)
484 moveInstruction(MI, CurrentTop);
485 // Release dependent instructions for scheduling.
486 releaseSuccessors(SU);
489 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
490 if (&*llvm::prior(CurrentBottom) == MI)
493 if (&*CurrentTop == MI)
494 CurrentTop = llvm::next(CurrentTop);
495 moveInstruction(MI, CurrentBottom);
498 // Release dependent instructions for scheduling.
499 releasePredecessors(SU);
501 SU->isScheduled = true;
503 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
506 //===----------------------------------------------------------------------===//
507 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
508 //===----------------------------------------------------------------------===//
511 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
513 class ConvergingScheduler : public MachineSchedStrategy {
516 unsigned NumTopReady;
517 unsigned NumBottomReady;
520 virtual void initialize(ScheduleDAGMI *dag) {
523 assert((!ForceTopDown || !ForceBottomUp) &&
524 "-misched-topdown incompatible with -misched-bottomup");
527 virtual SUnit *pickNode(bool &IsTopNode) {
528 if (DAG->top() == DAG->bottom())
531 // As an initial placeholder heuristic, schedule in the direction that has
532 // the fewest choices.
534 if (ForceTopDown || (!ForceBottomUp && NumTopReady <= NumBottomReady)) {
535 SU = DAG->getSUnit(DAG->top());
539 SU = DAG->getSUnit(llvm::prior(DAG->bottom()));
542 if (SU->isTopReady()) {
543 assert(NumTopReady > 0 && "bad ready count");
546 if (SU->isBottomReady()) {
547 assert(NumBottomReady > 0 && "bad ready count");
553 virtual void releaseTopNode(SUnit *SU) {
556 virtual void releaseBottomNode(SUnit *SU) {
562 /// Create the standard converging machine scheduler. This will be used as the
563 /// default scheduler if the target does not set a default.
564 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
565 assert((!ForceTopDown || !ForceBottomUp) &&
566 "-misched-topdown incompatible with -misched-bottomup");
567 return new ScheduleDAGMI(C, new ConvergingScheduler());
569 static MachineSchedRegistry
570 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
571 createConvergingSched);
573 //===----------------------------------------------------------------------===//
574 // Machine Instruction Shuffler for Correctness Testing
575 //===----------------------------------------------------------------------===//
579 /// Apply a less-than relation on the node order, which corresponds to the
580 /// instruction order prior to scheduling. IsReverse implements greater-than.
581 template<bool IsReverse>
583 bool operator()(SUnit *A, SUnit *B) const {
585 return A->NodeNum > B->NodeNum;
587 return A->NodeNum < B->NodeNum;
591 /// Reorder instructions as much as possible.
592 class InstructionShuffler : public MachineSchedStrategy {
596 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
597 // gives nodes with a higher number higher priority causing the latest
598 // instructions to be scheduled first.
599 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
601 // When scheduling bottom-up, use greater-than as the queue priority.
602 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
605 InstructionShuffler(bool alternate, bool topdown)
606 : IsAlternating(alternate), IsTopDown(topdown) {}
608 virtual void initialize(ScheduleDAGMI *) {
613 /// Implement MachineSchedStrategy interface.
614 /// -----------------------------------------
616 virtual SUnit *pickNode(bool &IsTopNode) {
620 if (TopQ.empty()) return NULL;
623 } while (SU->isScheduled);
628 if (BottomQ.empty()) return NULL;
631 } while (SU->isScheduled);
635 IsTopDown = !IsTopDown;
639 virtual void releaseTopNode(SUnit *SU) {
642 virtual void releaseBottomNode(SUnit *SU) {
648 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
649 bool Alternate = !ForceTopDown && !ForceBottomUp;
650 bool TopDown = !ForceBottomUp;
651 assert((TopDown || !ForceTopDown) &&
652 "-misched-topdown incompatible with -misched-bottomup");
653 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
655 static MachineSchedRegistry ShufflerRegistry(
656 "shuffle", "Shuffle machine instructions alternating directions",
657 createInstructionShuffler);