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 "ScheduleDAGInstrs.h"
18 #include "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachinePassRegistry.h"
21 #include "llvm/CodeGen/Passes.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"
34 //===----------------------------------------------------------------------===//
35 // Machine Instruction Scheduling Pass and Registry
36 //===----------------------------------------------------------------------===//
39 /// MachineScheduler runs after coalescing and before register allocation.
40 class MachineScheduler : public MachineFunctionPass {
43 const TargetInstrInfo *TII;
44 const MachineLoopInfo *MLI;
45 const MachineDominatorTree *MDT;
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
52 virtual void releaseMemory() {}
54 virtual bool runOnMachineFunction(MachineFunction&);
56 virtual void print(raw_ostream &O, const Module* = 0) const;
58 static char ID; // Class identification, replacement for typeinfo
62 char MachineScheduler::ID = 0;
64 char &llvm::MachineSchedulerID = MachineScheduler::ID;
66 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
67 "Machine Instruction Scheduler", false, false)
68 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
69 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
70 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
71 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
72 INITIALIZE_PASS_END(MachineScheduler, "misched",
73 "Machine Instruction Scheduler", false, false)
75 MachineScheduler::MachineScheduler()
76 : MachineFunctionPass(ID), MF(0), MLI(0), MDT(0) {
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.addPreserved<AliasAnalysis>();
86 AU.addRequired<SlotIndexes>();
87 AU.addPreserved<SlotIndexes>();
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 AU.addRequired<LiveDebugVariables>();
91 AU.addPreserved<LiveDebugVariables>();
92 MachineFunctionPass::getAnalysisUsage(AU);
96 /// MachineSchedRegistry provides a selection of available machine instruction
98 class MachineSchedRegistry : public MachinePassRegistryNode {
100 typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineScheduler *);
102 // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
103 typedef ScheduleDAGCtor FunctionPassCtor;
105 static MachinePassRegistry Registry;
107 MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
108 : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
111 ~MachineSchedRegistry() { Registry.Remove(this); }
115 MachineSchedRegistry *getNext() const {
116 return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
118 static MachineSchedRegistry *getList() {
119 return (MachineSchedRegistry *)Registry.getList();
121 static ScheduleDAGCtor getDefault() {
122 return (ScheduleDAGCtor)Registry.getDefault();
124 static void setDefault(ScheduleDAGCtor C) {
125 Registry.setDefault((MachinePassCtor)C);
127 static void setListener(MachinePassRegistryListener *L) {
128 Registry.setListener(L);
133 MachinePassRegistry MachineSchedRegistry::Registry;
135 static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P);
137 /// MachineSchedOpt allows command line selection of the scheduler.
138 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
139 RegisterPassParser<MachineSchedRegistry> >
140 MachineSchedOpt("misched",
141 cl::init(&createDefaultMachineSched), cl::Hidden,
142 cl::desc("Machine instruction scheduler to use"));
144 //===----------------------------------------------------------------------===//
145 // Machine Instruction Scheduling Common Implementation
146 //===----------------------------------------------------------------------===//
149 /// ScheduleTopDownLive is an implementation of ScheduleDAGInstrs that schedules
150 /// machine instructions while updating LiveIntervals.
151 class ScheduleTopDownLive : public ScheduleDAGInstrs {
153 MachineScheduler *Pass;
155 ScheduleTopDownLive(MachineScheduler *P):
156 ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false), Pass(P) {}
158 /// ScheduleDAGInstrs callback.
161 /// Interface implemented by the selected top-down liveinterval scheduler.
163 /// Pick the next node to schedule, or return NULL.
164 virtual SUnit *pickNode() = 0;
166 /// When all preceeding dependencies have been resolved, free this node for
168 virtual void releaseNode(SUnit *SU) = 0;
171 void releaseSucc(SUnit *SU, SDep *SuccEdge);
172 void releaseSuccessors(SUnit *SU);
176 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
177 /// NumPredsLeft reaches zero, release the successor node.
178 void ScheduleTopDownLive::releaseSucc(SUnit *SU, SDep *SuccEdge) {
179 SUnit *SuccSU = SuccEdge->getSUnit();
182 if (SuccSU->NumPredsLeft == 0) {
183 dbgs() << "*** Scheduling failed! ***\n";
185 dbgs() << " has been released too many times!\n";
189 --SuccSU->NumPredsLeft;
190 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
194 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
195 void ScheduleTopDownLive::releaseSuccessors(SUnit *SU) {
196 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
198 releaseSucc(SU, &*I);
202 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
203 /// time to do some work.
204 void ScheduleTopDownLive::Schedule() {
205 BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
207 DEBUG(dbgs() << "********** MI Scheduling **********\n");
208 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
209 SUnits[su].dumpAll(this));
211 // Release any successors of the special Entry node. It is currently unused,
212 // but we keep up appearances.
213 releaseSuccessors(&EntrySU);
215 // Release all DAG roots for scheduling.
216 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
218 // A SUnit is ready to schedule if it has no predecessors.
219 if (I->Preds.empty())
224 while (SUnit *SU = pickNode()) {
225 DEBUG(dbgs() << "*** Scheduling Instruction:\n"; SU->dump(this));
227 // Move the instruction to its new location in the instruction stream.
228 MachineInstr *MI = SU->getInstr();
229 if (&*InsertPos == MI)
232 BB->splice(InsertPos, BB, MI);
233 Pass->LIS->handleMove(MI);
234 if (Begin == InsertPos)
238 // Release dependent instructions for scheduling.
239 releaseSuccessors(SU);
243 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
244 // Initialize the context of the pass.
246 MLI = &getAnalysis<MachineLoopInfo>();
247 MDT = &getAnalysis<MachineDominatorTree>();
248 LIS = &getAnalysis<LiveIntervals>();
249 TII = MF->getTarget().getInstrInfo();
251 // Select the scheduler, or set the default.
252 MachineSchedRegistry::ScheduleDAGCtor Ctor =
253 MachineSchedRegistry::getDefault();
255 Ctor = MachineSchedOpt;
256 MachineSchedRegistry::setDefault(Ctor);
258 // Instantiate the selected scheduler.
259 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
261 // Visit all machine basic blocks.
262 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
263 MBB != MBBEnd; ++MBB) {
265 // Break the block into scheduling regions [I, RegionEnd), and schedule each
266 // region as soon as it is discovered.
267 unsigned RemainingCount = MBB->size();
268 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
269 RegionEnd != MBB->begin();) {
270 // The next region starts above the previous region. Look backward in the
271 // instruction stream until we find the nearest boundary.
272 MachineBasicBlock::iterator I = RegionEnd;
273 for(;I != MBB->begin(); --I, --RemainingCount) {
274 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
277 if (I == RegionEnd) {
278 // Skip empty scheduling regions.
279 RegionEnd = llvm::prior(RegionEnd);
283 // Skip regions with one instruction.
284 if (I == llvm::prior(RegionEnd)) {
285 RegionEnd = llvm::prior(RegionEnd);
288 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
289 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
290 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
291 else dbgs() << "End";
292 dbgs() << " Remaining: " << RemainingCount << "\n");
294 // Inform ScheduleDAGInstrs of the region being scheduled. It calls back
295 // to our Schedule() method.
296 Scheduler->Run(MBB, I, RegionEnd, MBB->size());
297 RegionEnd = Scheduler->Begin;
299 assert(RemainingCount == 0 && "Instruction count mismatch!");
304 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
308 //===----------------------------------------------------------------------===//
309 // Placeholder for extending the machine instruction scheduler.
310 //===----------------------------------------------------------------------===//
313 class DefaultMachineScheduler : public ScheduleDAGInstrs {
314 MachineScheduler *Pass;
316 DefaultMachineScheduler(MachineScheduler *P):
317 ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false), Pass(P) {}
319 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
320 /// time to do some work.
325 static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P) {
326 return new DefaultMachineScheduler(P);
328 static MachineSchedRegistry
329 SchedDefaultRegistry("default", "Activate the scheduler pass, "
330 "but don't reorder instructions",
331 createDefaultMachineSched);
334 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
335 /// time to do some work.
336 void DefaultMachineScheduler::Schedule() {
337 BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
339 DEBUG(dbgs() << "********** MI Scheduling **********\n");
340 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
341 SUnits[su].dumpAll(this));
343 // TODO: Put interesting things here.
345 // When this is fully implemented, it will become a subclass of
346 // ScheduleTopDownLive. So this driver will disappear.
349 //===----------------------------------------------------------------------===//
350 // Machine Instruction Shuffler for Correctness Testing
351 //===----------------------------------------------------------------------===//
355 // Nodes with a higher number have lower priority. This way we attempt to
356 // schedule the latest instructions earliest.
358 // TODO: Relies on the property of the BuildSchedGraph that results in SUnits
359 // being ordered in sequence bottom-up. This will be formalized, probably be
360 // constructing SUnits in a prepass.
361 struct ShuffleSUnitOrder {
362 bool operator()(SUnit *A, SUnit *B) const {
363 return A->NodeNum > B->NodeNum;
367 /// Reorder instructions as much as possible.
368 class InstructionShuffler : public ScheduleTopDownLive {
369 std::priority_queue<SUnit*, std::vector<SUnit*>, ShuffleSUnitOrder> Queue;
371 InstructionShuffler(MachineScheduler *P):
372 ScheduleTopDownLive(P) {}
374 /// ScheduleTopDownLive Interface
376 virtual SUnit *pickNode() {
377 if (Queue.empty()) return NULL;
378 SUnit *SU = Queue.top();
383 virtual void releaseNode(SUnit *SU) {
389 static ScheduleDAGInstrs *createInstructionShuffler(MachineScheduler *P) {
390 return new InstructionShuffler(P);
392 static MachineSchedRegistry ShufflerRegistry("shuffle",
393 "Shuffle machine instructions",
394 createInstructionShuffler);