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 "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineScheduler.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
34 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
35 cl::desc("Pop up a window to show MISched dags after they are processed"));
37 static bool ViewMISchedDAGs = false;
40 //===----------------------------------------------------------------------===//
41 // Machine Instruction Scheduling Pass and Registry
42 //===----------------------------------------------------------------------===//
45 /// MachineScheduler runs after coalescing and before register allocation.
46 class MachineScheduler : public MachineSchedContext,
47 public MachineFunctionPass {
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
53 virtual void releaseMemory() {}
55 virtual bool runOnMachineFunction(MachineFunction&);
57 virtual void print(raw_ostream &O, const Module* = 0) const;
59 static char ID; // Class identification, replacement for typeinfo
63 char MachineScheduler::ID = 0;
65 char &llvm::MachineSchedulerID = MachineScheduler::ID;
67 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
68 "Machine Instruction Scheduler", false, false)
69 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
70 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
71 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
72 INITIALIZE_PASS_END(MachineScheduler, "misched",
73 "Machine Instruction Scheduler", false, false)
75 MachineScheduler::MachineScheduler()
76 : MachineFunctionPass(ID) {
77 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
80 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.addRequiredID(MachineDominatorsID);
83 AU.addRequired<MachineLoopInfo>();
84 AU.addRequired<AliasAnalysis>();
85 AU.addRequired<TargetPassConfig>();
86 AU.addRequired<SlotIndexes>();
87 AU.addPreserved<SlotIndexes>();
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 MachineFunctionPass::getAnalysisUsage(AU);
93 MachinePassRegistry MachineSchedRegistry::Registry;
95 /// A dummy default scheduler factory indicates whether the scheduler
96 /// is overridden on the command line.
97 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
101 /// MachineSchedOpt allows command line selection of the scheduler.
102 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
103 RegisterPassParser<MachineSchedRegistry> >
104 MachineSchedOpt("misched",
105 cl::init(&useDefaultMachineSched), cl::Hidden,
106 cl::desc("Machine instruction scheduler to use"));
108 static MachineSchedRegistry
109 SchedDefaultRegistry("default", "Use the target's default scheduler choice.",
110 useDefaultMachineSched);
112 /// Forward declare the common machine scheduler. This will be used as the
113 /// default scheduler if the target does not set a default.
114 static ScheduleDAGInstrs *createCommonMachineSched(MachineSchedContext *C);
116 /// Top-level MachineScheduler pass driver.
118 /// Visit blocks in function order. Divide each block into scheduling regions
119 /// and visit them bottom-up. This is consistent with the DAG builder, which
120 /// traverses scheduling regions bottom-up, but not essential.
122 /// This design avoids exposing scheduling boundaries to the DAG builder,
123 /// simplifying the DAG builder's support for "special" target instructions,
124 /// while at the same time allowing target schedulers to operate across
125 /// scheduling boundaries, for example to bundle the boudary instructions
126 /// without reordering them. This creates complexity, because the target
127 /// scheduler must update the RegionBegin and RegionEnd positions cached by
128 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
129 /// design would be to split blocks at scheduling boundaries, but LLVM has a
130 /// general bias against block splitting purely for implementation simplicity.
131 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
132 // Initialize the context of the pass.
134 MLI = &getAnalysis<MachineLoopInfo>();
135 MDT = &getAnalysis<MachineDominatorTree>();
136 PassConfig = &getAnalysis<TargetPassConfig>();
137 AA = &getAnalysis<AliasAnalysis>();
139 LIS = &getAnalysis<LiveIntervals>();
140 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
142 // Select the scheduler, or set the default.
143 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
144 if (Ctor == useDefaultMachineSched) {
145 // Get the default scheduler set by the target.
146 Ctor = MachineSchedRegistry::getDefault();
148 Ctor = createCommonMachineSched;
149 MachineSchedRegistry::setDefault(Ctor);
152 // Instantiate the selected scheduler.
153 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
155 // Visit all machine basic blocks.
156 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
157 MBB != MBBEnd; ++MBB) {
159 Scheduler->startBlock(MBB);
161 // Break the block into scheduling regions [I, RegionEnd), and schedule each
162 // region as soon as it is discovered. RegionEnd points the the scheduling
163 // boundary at the bottom of the region. The DAG does not include RegionEnd,
164 // but the region does (i.e. the next RegionEnd is above the previous
165 // RegionBegin). If the current block has no terminator then RegionEnd ==
166 // MBB->end() for the bottom region.
168 // The Scheduler may insert instructions during either schedule() or
169 // exitRegion(), even for empty regions. So the local iterators 'I' and
170 // 'RegionEnd' are invalid across these calls.
171 unsigned RemainingCount = MBB->size();
172 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
173 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
174 // Avoid decrementing RegionEnd for blocks with no terminator.
175 if (RegionEnd != MBB->end()
176 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
178 // Count the boundary instruction.
182 // The next region starts above the previous region. Look backward in the
183 // instruction stream until we find the nearest boundary.
184 MachineBasicBlock::iterator I = RegionEnd;
185 for(;I != MBB->begin(); --I, --RemainingCount) {
186 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
189 // Notify the scheduler of the region, even if we may skip scheduling
190 // it. Perhaps it still needs to be bundled.
191 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
193 // Skip empty scheduling regions (0 or 1 schedulable instructions).
194 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
195 // Close the current region. Bundle the terminator if needed.
196 // This invalidates 'RegionEnd' and 'I'.
197 Scheduler->exitRegion();
200 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
201 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
202 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
203 else dbgs() << "End";
204 dbgs() << " Remaining: " << RemainingCount << "\n");
206 // Schedule a region: possibly reorder instructions.
207 // This invalidates 'RegionEnd' and 'I'.
208 Scheduler->schedule();
210 // Close the current region.
211 Scheduler->exitRegion();
213 // Scheduling has invalidated the current iterator 'I'. Ask the
214 // scheduler for the top of it's scheduled region.
215 RegionEnd = Scheduler->begin();
217 assert(RemainingCount == 0 && "Instruction count mismatch!");
218 Scheduler->finishBlock();
223 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
227 //===----------------------------------------------------------------------===//
228 // ScheduleTopeDownLive - Base class for basic top-down scheduling with
229 // LiveIntervals preservation.
230 // ===----------------------------------------------------------------------===//
233 /// ScheduleTopDownLive is an implementation of ScheduleDAGInstrs that schedules
234 /// machine instructions while updating LiveIntervals.
235 class ScheduleTopDownLive : public ScheduleDAGInstrs {
238 ScheduleTopDownLive(MachineSchedContext *C):
239 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
242 /// ScheduleDAGInstrs interface.
245 /// Interface implemented by the selected top-down liveinterval scheduler.
247 /// Pick the next node to schedule, or return NULL.
248 virtual SUnit *pickNode() = 0;
250 /// When all preceeding dependencies have been resolved, free this node for
252 virtual void releaseNode(SUnit *SU) = 0;
255 void releaseSucc(SUnit *SU, SDep *SuccEdge);
256 void releaseSuccessors(SUnit *SU);
260 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
261 /// NumPredsLeft reaches zero, release the successor node.
262 void ScheduleTopDownLive::releaseSucc(SUnit *SU, SDep *SuccEdge) {
263 SUnit *SuccSU = SuccEdge->getSUnit();
266 if (SuccSU->NumPredsLeft == 0) {
267 dbgs() << "*** Scheduling failed! ***\n";
269 dbgs() << " has been released too many times!\n";
273 --SuccSU->NumPredsLeft;
274 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
278 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
279 void ScheduleTopDownLive::releaseSuccessors(SUnit *SU) {
280 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
282 releaseSucc(SU, &*I);
286 /// schedule - This is called back from ScheduleDAGInstrs::Run() when it's
287 /// time to do some work.
288 void ScheduleTopDownLive::schedule() {
291 DEBUG(dbgs() << "********** MI Scheduling **********\n");
292 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
293 SUnits[su].dumpAll(this));
295 if (ViewMISchedDAGs) viewGraph();
297 // Release any successors of the special Entry node. It is currently unused,
298 // but we keep up appearances.
299 releaseSuccessors(&EntrySU);
301 // Release all DAG roots for scheduling.
302 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
304 // A SUnit is ready to schedule if it has no predecessors.
305 if (I->Preds.empty())
309 MachineBasicBlock::iterator InsertPos = RegionBegin;
310 while (SUnit *SU = pickNode()) {
311 DEBUG(dbgs() << "*** Scheduling Instruction:\n"; SU->dump(this));
313 // Move the instruction to its new location in the instruction stream.
314 MachineInstr *MI = SU->getInstr();
315 if (&*InsertPos == MI)
318 BB->splice(InsertPos, BB, MI);
320 if (RegionBegin == InsertPos)
324 // Release dependent instructions for scheduling.
325 releaseSuccessors(SU);
329 //===----------------------------------------------------------------------===//
330 // Placeholder for the default machine instruction scheduler.
331 //===----------------------------------------------------------------------===//
334 class CommonMachineScheduler : public ScheduleDAGInstrs {
337 CommonMachineScheduler(MachineSchedContext *C):
338 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
341 /// schedule - This is called back from ScheduleDAGInstrs::Run() when it's
342 /// time to do some work.
347 /// The common machine scheduler will be used as the default scheduler if the
348 /// target does not set a default.
349 static ScheduleDAGInstrs *createCommonMachineSched(MachineSchedContext *C) {
350 return new CommonMachineScheduler(C);
352 static MachineSchedRegistry
353 SchedCommonRegistry("common", "Use the target's default scheduler choice.",
354 createCommonMachineSched);
356 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
357 /// time to do some work.
358 void CommonMachineScheduler::schedule() {
361 DEBUG(dbgs() << "********** MI Scheduling **********\n");
362 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
363 SUnits[su].dumpAll(this));
365 // TODO: Put interesting things here.
367 // When this is fully implemented, it will become a subclass of
368 // ScheduleTopDownLive. So this driver will disappear.
371 //===----------------------------------------------------------------------===//
372 // Machine Instruction Shuffler for Correctness Testing
373 //===----------------------------------------------------------------------===//
377 // Nodes with a higher number have higher priority. This way we attempt to
378 // schedule the latest instructions earliest.
380 // TODO: Relies on the property of the BuildSchedGraph that results in SUnits
381 // being ordered in sequence top-down.
382 struct ShuffleSUnitOrder {
383 bool operator()(SUnit *A, SUnit *B) const {
384 return A->NodeNum < B->NodeNum;
388 /// Reorder instructions as much as possible.
389 class InstructionShuffler : public ScheduleTopDownLive {
390 std::priority_queue<SUnit*, std::vector<SUnit*>, ShuffleSUnitOrder> Queue;
392 InstructionShuffler(MachineSchedContext *C):
393 ScheduleTopDownLive(C) {}
395 /// ScheduleTopDownLive Interface
397 virtual SUnit *pickNode() {
398 if (Queue.empty()) return NULL;
399 SUnit *SU = Queue.top();
404 virtual void releaseNode(SUnit *SU) {
410 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
411 return new InstructionShuffler(C);
413 static MachineSchedRegistry ShufflerRegistry("shuffle",
414 "Shuffle machine instructions",
415 createInstructionShuffler);