blob: a14b3912236de6be3b1e8c91dbf7d1f4c42110cf [file] [log] [blame]
Andrew Trick96f678f2012-01-13 06:30:30 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
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"
Andrew Tricke9ef4ed2012-01-14 02:17:09 +000023#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000024#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
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick5edf2f02012-01-14 02:17:06 +000034//===----------------------------------------------------------------------===//
35// Machine Instruction Scheduling Pass and Registry
36//===----------------------------------------------------------------------===//
37
Andrew Trick96f678f2012-01-13 06:30:30 +000038namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000039/// MachineScheduler runs after coalescing and before register allocation.
40class MachineScheduler : public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000041public:
42 MachineFunction *MF;
Andrew Trick5edf2f02012-01-14 02:17:06 +000043 const TargetInstrInfo *TII;
Andrew Trick96f678f2012-01-13 06:30:30 +000044 const MachineLoopInfo *MLI;
45 const MachineDominatorTree *MDT;
46
Andrew Trick42b7a712012-01-17 06:55:03 +000047 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000048
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
50
51 virtual void releaseMemory() {}
52
53 virtual bool runOnMachineFunction(MachineFunction&);
54
55 virtual void print(raw_ostream &O, const Module* = 0) const;
56
57 static char ID; // Class identification, replacement for typeinfo
58};
59} // namespace
60
Andrew Trick42b7a712012-01-17 06:55:03 +000061char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000062
Andrew Trick42b7a712012-01-17 06:55:03 +000063char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000064
Andrew Trick42b7a712012-01-17 06:55:03 +000065INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000066 "Machine Instruction Scheduler", false, false)
67INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
68INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
69INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
70INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
71INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
72INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
Andrew Trick42b7a712012-01-17 06:55:03 +000073INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000074 "Machine Instruction Scheduler", false, false)
75
Andrew Trick42b7a712012-01-17 06:55:03 +000076MachineScheduler::MachineScheduler()
Andrew Trick96f678f2012-01-13 06:30:30 +000077: MachineFunctionPass(ID), MF(0), MLI(0), MDT(0) {
Andrew Trick42b7a712012-01-17 06:55:03 +000078 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000079}
80
Andrew Trick42b7a712012-01-17 06:55:03 +000081void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +000082 AU.setPreservesCFG();
83 AU.addRequiredID(MachineDominatorsID);
84 AU.addRequired<MachineLoopInfo>();
85 AU.addRequired<AliasAnalysis>();
86 AU.addPreserved<AliasAnalysis>();
87 AU.addRequired<SlotIndexes>();
88 AU.addPreserved<SlotIndexes>();
89 AU.addRequired<LiveIntervals>();
90 AU.addPreserved<LiveIntervals>();
91 AU.addRequired<LiveDebugVariables>();
92 AU.addPreserved<LiveDebugVariables>();
93 if (StrongPHIElim) {
94 AU.addRequiredID(StrongPHIEliminationID);
95 AU.addPreservedID(StrongPHIEliminationID);
96 }
97 AU.addRequiredID(RegisterCoalescerPassID);
98 AU.addPreservedID(RegisterCoalescerPassID);
99 MachineFunctionPass::getAnalysisUsage(AU);
100}
101
102namespace {
Andrew Trick96f678f2012-01-13 06:30:30 +0000103/// MachineSchedRegistry provides a selection of available machine instruction
104/// schedulers.
105class MachineSchedRegistry : public MachinePassRegistryNode {
106public:
Andrew Trick42b7a712012-01-17 06:55:03 +0000107 typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineScheduler *);
Andrew Trick96f678f2012-01-13 06:30:30 +0000108
109 // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
110 typedef ScheduleDAGCtor FunctionPassCtor;
111
112 static MachinePassRegistry Registry;
113
114 MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
115 : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
116 Registry.Add(this);
117 }
118 ~MachineSchedRegistry() { Registry.Remove(this); }
119
120 // Accessors.
121 //
122 MachineSchedRegistry *getNext() const {
123 return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
124 }
125 static MachineSchedRegistry *getList() {
126 return (MachineSchedRegistry *)Registry.getList();
127 }
128 static ScheduleDAGCtor getDefault() {
129 return (ScheduleDAGCtor)Registry.getDefault();
130 }
131 static void setDefault(ScheduleDAGCtor C) {
132 Registry.setDefault((MachinePassCtor)C);
133 }
134 static void setListener(MachinePassRegistryListener *L) {
135 Registry.setListener(L);
136 }
137};
138} // namespace
139
140MachinePassRegistry MachineSchedRegistry::Registry;
141
Andrew Trick42b7a712012-01-17 06:55:03 +0000142static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P);
Andrew Trick96f678f2012-01-13 06:30:30 +0000143
144/// MachineSchedOpt allows command line selection of the scheduler.
145static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
146 RegisterPassParser<MachineSchedRegistry> >
147MachineSchedOpt("misched",
148 cl::init(&createDefaultMachineSched), cl::Hidden,
149 cl::desc("Machine instruction scheduler to use"));
150
Andrew Trick5edf2f02012-01-14 02:17:06 +0000151//===----------------------------------------------------------------------===//
Andrew Trick42b7a712012-01-17 06:55:03 +0000152// Machine Instruction Scheduling Common Implementation
Andrew Trick5edf2f02012-01-14 02:17:06 +0000153//===----------------------------------------------------------------------===//
154
155namespace {
156/// MachineScheduler is an implementation of ScheduleDAGInstrs that schedules
157/// machine instructions while updating LiveIntervals.
Andrew Trick42b7a712012-01-17 06:55:03 +0000158class ScheduleTopDownLive : public ScheduleDAGInstrs {
159protected:
160 MachineScheduler *Pass;
Andrew Trick5edf2f02012-01-14 02:17:06 +0000161public:
Andrew Trick42b7a712012-01-17 06:55:03 +0000162 ScheduleTopDownLive(MachineScheduler *P):
Andrew Trick5e920d72012-01-14 02:17:12 +0000163 ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false), Pass(P) {}
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000164
165 /// ScheduleDAGInstrs callback.
166 void Schedule();
167
168 /// Interface implemented by the selected top-down liveinterval scheduler.
169 ///
170 /// Pick the next node to schedule, or return NULL.
171 virtual SUnit *pickNode() = 0;
172
173 /// When all preceeding dependencies have been resolved, free this node for
174 /// scheduling.
175 virtual void releaseNode(SUnit *SU) = 0;
176
177protected:
178 void releaseSucc(SUnit *SU, SDep *SuccEdge);
179 void releaseSuccessors(SUnit *SU);
Andrew Trick5edf2f02012-01-14 02:17:06 +0000180};
181} // namespace
182
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000183/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
184/// NumPredsLeft reaches zero, release the successor node.
185void ScheduleTopDownLive::releaseSucc(SUnit *SU, SDep *SuccEdge) {
186 SUnit *SuccSU = SuccEdge->getSUnit();
187
188#ifndef NDEBUG
189 if (SuccSU->NumPredsLeft == 0) {
190 dbgs() << "*** Scheduling failed! ***\n";
191 SuccSU->dump(this);
192 dbgs() << " has been released too many times!\n";
193 llvm_unreachable(0);
194 }
195#endif
196 --SuccSU->NumPredsLeft;
197 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
198 releaseNode(SuccSU);
199}
200
201/// releaseSuccessors - Call releaseSucc on each of SU's successors.
202void ScheduleTopDownLive::releaseSuccessors(SUnit *SU) {
203 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
204 I != E; ++I) {
205 releaseSucc(SU, &*I);
206 }
207}
208
209/// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
210/// time to do some work.
211void ScheduleTopDownLive::Schedule() {
212 BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
213
214 DEBUG(dbgs() << "********** MI Scheduling **********\n");
215 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
216 SUnits[su].dumpAll(this));
217
218 // Release any successors of the special Entry node. It is currently unused,
219 // but we keep up appearances.
220 releaseSuccessors(&EntrySU);
221
222 // Release all DAG roots for scheduling.
223 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
224 I != E; ++I) {
225 // A SUnit is ready to schedule if it has no predecessors.
226 if (I->Preds.empty())
227 releaseNode(&(*I));
228 }
229
230 InsertPos = Begin;
231 while (SUnit *SU = pickNode()) {
232 DEBUG(dbgs() << "*** Scheduling Instruction:\n"; SU->dump(this));
233
234 // Move the instruction to its new location in the instruction stream.
235 MachineInstr *MI = SU->getInstr();
236 if (&*InsertPos == MI)
237 ++InsertPos;
238 else {
239 BB->splice(InsertPos, BB, MI);
240 if (Begin == InsertPos)
241 Begin = MI;
242 }
243
244 // TODO: Update live intervals.
245
246 // Release dependent instructions for scheduling.
247 releaseSuccessors(SU);
248 }
249}
250
Andrew Trick42b7a712012-01-17 06:55:03 +0000251bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000252 // Initialize the context of the pass.
253 MF = &mf;
254 MLI = &getAnalysis<MachineLoopInfo>();
255 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick5edf2f02012-01-14 02:17:06 +0000256 TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000257
258 // Select the scheduler, or set the default.
259 MachineSchedRegistry::ScheduleDAGCtor Ctor =
260 MachineSchedRegistry::getDefault();
261 if (!Ctor) {
262 Ctor = MachineSchedOpt;
263 MachineSchedRegistry::setDefault(Ctor);
264 }
265 // Instantiate the selected scheduler.
266 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
267
268 // Visit all machine basic blocks.
269 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
270 MBB != MBBEnd; ++MBB) {
271
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000272 // Break the block into scheduling regions [I, RegionEnd), and schedule each
273 // region as soon as it is discovered.
274 unsigned RemainingCount = MBB->size();
275 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
276 RegionEnd != MBB->begin();) {
277 // The next region starts above the previous region. Look backward in the
278 // instruction stream until we find the nearest boundary.
279 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000280 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000281 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
282 break;
283 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000284 if (I == RegionEnd) {
285 // Skip empty scheduling regions.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000286 RegionEnd = llvm::prior(RegionEnd);
Andrew Trick3c58ba82012-01-14 02:17:18 +0000287 --RemainingCount;
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000288 continue;
289 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000290 // Skip regions with one instruction.
291 if (I == llvm::prior(RegionEnd)) {
292 RegionEnd = llvm::prior(RegionEnd);
293 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000294 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000295 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
296 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: "
297 << *RegionEnd << " Remaining: " << RemainingCount << "\n");
298
299 // Inform ScheduleDAGInstrs of the region being scheduled. It calls back
300 // to our Schedule() method.
301 Scheduler->Run(MBB, I, RegionEnd, MBB->size());
302 RegionEnd = Scheduler->Begin;
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000303 }
304 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick96f678f2012-01-13 06:30:30 +0000305 }
306 return true;
307}
308
Andrew Trick42b7a712012-01-17 06:55:03 +0000309void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000310 // unimplemented
311}
312
Andrew Trick5edf2f02012-01-14 02:17:06 +0000313//===----------------------------------------------------------------------===//
Andrew Trick42b7a712012-01-17 06:55:03 +0000314// Placeholder for extending the machine instruction scheduler.
315//===----------------------------------------------------------------------===//
316
317namespace {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000318class DefaultMachineScheduler : public ScheduleDAGInstrs {
319 MachineScheduler *Pass;
Andrew Trick42b7a712012-01-17 06:55:03 +0000320public:
321 DefaultMachineScheduler(MachineScheduler *P):
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000322 ScheduleDAGInstrs(*P->MF, *P->MLI, *P->MDT, /*IsPostRA=*/false), Pass(P) {}
Andrew Trick42b7a712012-01-17 06:55:03 +0000323
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000324 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
325 /// time to do some work.
Andrew Trick42b7a712012-01-17 06:55:03 +0000326 void Schedule();
327};
328} // namespace
329
330static ScheduleDAGInstrs *createDefaultMachineSched(MachineScheduler *P) {
331 return new DefaultMachineScheduler(P);
332}
333static MachineSchedRegistry
334SchedDefaultRegistry("default", "Activate the scheduler pass, "
335 "but don't reorder instructions",
336 createDefaultMachineSched);
337
338
339/// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
340/// time to do some work.
341void DefaultMachineScheduler::Schedule() {
342 BuildSchedGraph(&Pass->getAnalysis<AliasAnalysis>());
343
344 DEBUG(dbgs() << "********** MI Scheduling **********\n");
345 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
346 SUnits[su].dumpAll(this));
347
348 // TODO: Put interesting things here.
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000349 //
350 // When this is fully implemented, it will become a subclass of
351 // ScheduleTopDownLive. So this driver will disappear.
Andrew Trick42b7a712012-01-17 06:55:03 +0000352}
353
354//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +0000355// Machine Instruction Shuffler for Correctness Testing
356//===----------------------------------------------------------------------===//
357
Andrew Trick96f678f2012-01-13 06:30:30 +0000358#ifndef NDEBUG
359namespace {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000360// Nodes with a higher number have lower priority. This way we attempt to
361// schedule the latest instructions earliest.
362//
363// TODO: Relies on the property of the BuildSchedGraph that results in SUnits
364// being ordered in sequence bottom-up. This will be formalized, probably be
365// constructing SUnits in a prepass.
366struct ShuffleSUnitOrder {
367 bool operator()(SUnit *A, SUnit *B) const {
368 return A->NodeNum > B->NodeNum;
369 }
370};
371
Andrew Trick96f678f2012-01-13 06:30:30 +0000372/// Reorder instructions as much as possible.
Andrew Trick42b7a712012-01-17 06:55:03 +0000373class InstructionShuffler : public ScheduleTopDownLive {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000374 std::priority_queue<SUnit*, std::vector<SUnit*>, ShuffleSUnitOrder> Queue;
Andrew Trick96f678f2012-01-13 06:30:30 +0000375public:
Andrew Trick42b7a712012-01-17 06:55:03 +0000376 InstructionShuffler(MachineScheduler *P):
377 ScheduleTopDownLive(P) {}
Andrew Trick96f678f2012-01-13 06:30:30 +0000378
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000379 /// ScheduleTopDownLive Interface
380
381 virtual SUnit *pickNode() {
382 if (Queue.empty()) return NULL;
383 SUnit *SU = Queue.top();
384 Queue.pop();
385 return SU;
386 }
387
388 virtual void releaseNode(SUnit *SU) {
389 Queue.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +0000390 }
391};
392} // namespace
393
Andrew Trick42b7a712012-01-17 06:55:03 +0000394static ScheduleDAGInstrs *createInstructionShuffler(MachineScheduler *P) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000395 return new InstructionShuffler(P);
396}
397static MachineSchedRegistry ShufflerRegistry("shuffle",
398 "Shuffle machine instructions",
399 createInstructionShuffler);
400#endif // !NDEBUG