blob: 53003d8dac755ff7f0bbeea0eeff6bfa02264175 [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
Andrew Trick006e1ab2012-04-24 17:56:43 +000017#include "RegisterPressure.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trickc174eaf2012-03-08 01:41:12 +000019#include "llvm/CodeGen/MachineScheduler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000020#include "llvm/CodeGen/Passes.h"
Andrew Tricked395c82012-03-07 23:01:06 +000021#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#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"
Andrew Trick17d35e52012-03-14 04:00:41 +000029#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000030
Andrew Trickc6cf11b2012-01-17 06:55:07 +000031#include <queue>
32
Andrew Trick96f678f2012-01-13 06:30:30 +000033using namespace llvm;
34
Andrew Trick17d35e52012-03-14 04:00:41 +000035static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39
Andrew Trick0df7f882012-03-07 00:18:25 +000040#ifndef NDEBUG
41static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
42 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000043
44static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
45 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000046#else
47static bool ViewMISchedDAGs = false;
48#endif // NDEBUG
49
Andrew Trick5edf2f02012-01-14 02:17:06 +000050//===----------------------------------------------------------------------===//
51// Machine Instruction Scheduling Pass and Registry
52//===----------------------------------------------------------------------===//
53
Andrew Trick96f678f2012-01-13 06:30:30 +000054namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000055/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000056class MachineScheduler : public MachineSchedContext,
57 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000058public:
Andrew Trick42b7a712012-01-17 06:55:03 +000059 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000060
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
62
63 virtual void releaseMemory() {}
64
65 virtual bool runOnMachineFunction(MachineFunction&);
66
67 virtual void print(raw_ostream &O, const Module* = 0) const;
68
69 static char ID; // Class identification, replacement for typeinfo
70};
71} // namespace
72
Andrew Trick42b7a712012-01-17 06:55:03 +000073char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000074
Andrew Trick42b7a712012-01-17 06:55:03 +000075char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000076
Andrew Trick42b7a712012-01-17 06:55:03 +000077INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000078 "Machine Instruction Scheduler", false, false)
79INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
80INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
81INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000082INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000083 "Machine Instruction Scheduler", false, false)
84
Andrew Trick42b7a712012-01-17 06:55:03 +000085MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000086: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000087 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000088}
89
Andrew Trick42b7a712012-01-17 06:55:03 +000090void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +000091 AU.setPreservesCFG();
92 AU.addRequiredID(MachineDominatorsID);
93 AU.addRequired<MachineLoopInfo>();
94 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +000095 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +000096 AU.addRequired<SlotIndexes>();
97 AU.addPreserved<SlotIndexes>();
98 AU.addRequired<LiveIntervals>();
99 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000100 MachineFunctionPass::getAnalysisUsage(AU);
101}
102
Andrew Trick96f678f2012-01-13 06:30:30 +0000103MachinePassRegistry MachineSchedRegistry::Registry;
104
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000105/// A dummy default scheduler factory indicates whether the scheduler
106/// is overridden on the command line.
107static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
108 return 0;
109}
Andrew Trick96f678f2012-01-13 06:30:30 +0000110
111/// MachineSchedOpt allows command line selection of the scheduler.
112static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
113 RegisterPassParser<MachineSchedRegistry> >
114MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000115 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000116 cl::desc("Machine instruction scheduler to use"));
117
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000118static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000119DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000120 useDefaultMachineSched);
121
Andrew Trick17d35e52012-03-14 04:00:41 +0000122/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000123/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000124static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000125
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000126
127/// Decrement this iterator until reaching the top or a non-debug instr.
128static MachineBasicBlock::iterator
129priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
130 assert(I != Beg && "reached the top of the region, cannot decrement");
131 while (--I != Beg) {
132 if (!I->isDebugValue())
133 break;
134 }
135 return I;
136}
137
138/// If this iterator is a debug value, increment until reaching the End or a
139/// non-debug instruction.
140static MachineBasicBlock::iterator
141nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
142 while(I != End) {
143 if (!I->isDebugValue())
144 break;
145 }
146 return I;
147}
148
Andrew Trickcb058d52012-03-14 04:00:38 +0000149/// Top-level MachineScheduler pass driver.
150///
151/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000152/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
153/// consistent with the DAG builder, which traverses the interior of the
154/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000155///
156/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000157/// simplifying the DAG builder's support for "special" target instructions.
158/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000159/// scheduling boundaries, for example to bundle the boudary instructions
160/// without reordering them. This creates complexity, because the target
161/// scheduler must update the RegionBegin and RegionEnd positions cached by
162/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
163/// design would be to split blocks at scheduling boundaries, but LLVM has a
164/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000165bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000166 // Initialize the context of the pass.
167 MF = &mf;
168 MLI = &getAnalysis<MachineLoopInfo>();
169 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000170 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000171 AA = &getAnalysis<AliasAnalysis>();
172
Lang Hames907cc8f2012-01-27 22:36:19 +0000173 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000174 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000175
Andrew Trick006e1ab2012-04-24 17:56:43 +0000176 RegClassInfo.runOnMachineFunction(*MF);
177
Andrew Trick96f678f2012-01-13 06:30:30 +0000178 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000179 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
180 if (Ctor == useDefaultMachineSched) {
181 // Get the default scheduler set by the target.
182 Ctor = MachineSchedRegistry::getDefault();
183 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000184 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000185 MachineSchedRegistry::setDefault(Ctor);
186 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000187 }
188 // Instantiate the selected scheduler.
189 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
190
191 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000192 //
193 // TODO: Visit blocks in global postorder or postorder within the bottom-up
194 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000195 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
196 MBB != MBBEnd; ++MBB) {
197
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000198 Scheduler->startBlock(MBB);
199
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000200 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000201 // region as soon as it is discovered. RegionEnd points the the scheduling
202 // boundary at the bottom of the region. The DAG does not include RegionEnd,
203 // but the region does (i.e. the next RegionEnd is above the previous
204 // RegionBegin). If the current block has no terminator then RegionEnd ==
205 // MBB->end() for the bottom region.
206 //
207 // The Scheduler may insert instructions during either schedule() or
208 // exitRegion(), even for empty regions. So the local iterators 'I' and
209 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000210 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000211 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000212 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000213
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000214 // Avoid decrementing RegionEnd for blocks with no terminator.
215 if (RegionEnd != MBB->end()
216 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
217 --RegionEnd;
218 // Count the boundary instruction.
219 --RemainingCount;
220 }
221
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000222 // The next region starts above the previous region. Look backward in the
223 // instruction stream until we find the nearest boundary.
224 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000225 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000226 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
227 break;
228 }
Andrew Trick47c14452012-03-07 05:21:52 +0000229 // Notify the scheduler of the region, even if we may skip scheduling
230 // it. Perhaps it still needs to be bundled.
231 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
232
233 // Skip empty scheduling regions (0 or 1 schedulable instructions).
234 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000235 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000236 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000237 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000238 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000239 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000240 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000241 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
242 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
243 else dbgs() << "End";
244 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000245
Andrew Trickd24da972012-03-09 03:46:42 +0000246 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000247 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000248 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000249
250 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000251 Scheduler->exitRegion();
252
253 // Scheduling has invalidated the current iterator 'I'. Ask the
254 // scheduler for the top of it's scheduled region.
255 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000256 }
257 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000258 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000259 }
Andrew Trick830da402012-04-01 07:24:23 +0000260 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000261 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000262 return true;
263}
264
Andrew Trick42b7a712012-01-17 06:55:03 +0000265void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000266 // unimplemented
267}
268
Andrew Trick5edf2f02012-01-14 02:17:06 +0000269//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000270// MachineSchedStrategy - Interface to a machine scheduling algorithm.
271//===----------------------------------------------------------------------===//
Andrew Trickc174eaf2012-03-08 01:41:12 +0000272
273namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000274class ScheduleDAGMI;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000275
Andrew Trick17d35e52012-03-14 04:00:41 +0000276/// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
277/// scheduling algorithm.
278///
279/// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
280/// in ScheduleDAGInstrs.h
281class MachineSchedStrategy {
282public:
283 virtual ~MachineSchedStrategy() {}
284
285 /// Initialize the strategy after building the DAG for a new region.
286 virtual void initialize(ScheduleDAGMI *DAG) = 0;
287
288 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
289 /// schedule the node at the top of the unscheduled region. Otherwise it will
290 /// be scheduled at the bottom.
291 virtual SUnit *pickNode(bool &IsTopNode) = 0;
292
293 /// When all predecessor dependencies have been resolved, free this node for
294 /// top-down scheduling.
295 virtual void releaseTopNode(SUnit *SU) = 0;
296 /// When all successor dependencies have been resolved, free this node for
297 /// bottom-up scheduling.
298 virtual void releaseBottomNode(SUnit *SU) = 0;
299};
300} // namespace
301
302//===----------------------------------------------------------------------===//
303// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
304// preservation.
305//===----------------------------------------------------------------------===//
306
307namespace {
308/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
309/// machine instructions while updating LiveIntervals.
310class ScheduleDAGMI : public ScheduleDAGInstrs {
311 AliasAnalysis *AA;
Andrew Trick006e1ab2012-04-24 17:56:43 +0000312 RegisterClassInfo *RegClassInfo;
Andrew Trick17d35e52012-03-14 04:00:41 +0000313 MachineSchedStrategy *SchedImpl;
314
Andrew Trick006e1ab2012-04-24 17:56:43 +0000315 // Register pressure in this region computed by buildSchedGraph.
316 IntervalPressure RegPressure;
317 RegPressureTracker RPTracker;
318
Andrew Trick17d35e52012-03-14 04:00:41 +0000319 /// The top of the unscheduled zone.
320 MachineBasicBlock::iterator CurrentTop;
321
322 /// The bottom of the unscheduled zone.
323 MachineBasicBlock::iterator CurrentBottom;
Lang Hames23f1cbb2012-03-19 18:38:38 +0000324
325 /// The number of instructions scheduled so far. Used to cut off the
326 /// scheduler at the point determined by misched-cutoff.
327 unsigned NumInstrsScheduled;
Andrew Trick17d35e52012-03-14 04:00:41 +0000328public:
329 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
330 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
Andrew Trick006e1ab2012-04-24 17:56:43 +0000331 AA(C->AA), RegClassInfo(&C->RegClassInfo), SchedImpl(S),
332 RPTracker(RegPressure), CurrentTop(), CurrentBottom(),
Lang Hames23f1cbb2012-03-19 18:38:38 +0000333 NumInstrsScheduled(0) {}
Andrew Trick17d35e52012-03-14 04:00:41 +0000334
335 ~ScheduleDAGMI() {
336 delete SchedImpl;
337 }
338
339 MachineBasicBlock::iterator top() const { return CurrentTop; }
340 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
341
Andrew Trick006e1ab2012-04-24 17:56:43 +0000342 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
343 /// region. This covers all instructions in a block, while schedule() may only
344 /// cover a subset.
345 void enterRegion(MachineBasicBlock *bb,
346 MachineBasicBlock::iterator begin,
347 MachineBasicBlock::iterator end,
348 unsigned endcount);
349
350 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
351 /// reorderable instructions.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000352 void schedule();
353
Andrew Trickc174eaf2012-03-08 01:41:12 +0000354protected:
Andrew Trick17d35e52012-03-14 04:00:41 +0000355 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000356 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000357
Andrew Trickc174eaf2012-03-08 01:41:12 +0000358 void releaseSucc(SUnit *SU, SDep *SuccEdge);
359 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000360 void releasePred(SUnit *SU, SDep *PredEdge);
361 void releasePredecessors(SUnit *SU);
Andrew Trick000b2502012-04-24 18:04:37 +0000362
363 void placeDebugValues();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000364};
365} // namespace
366
367/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
368/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick17d35e52012-03-14 04:00:41 +0000369void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000370 SUnit *SuccSU = SuccEdge->getSUnit();
371
372#ifndef NDEBUG
373 if (SuccSU->NumPredsLeft == 0) {
374 dbgs() << "*** Scheduling failed! ***\n";
375 SuccSU->dump(this);
376 dbgs() << " has been released too many times!\n";
377 llvm_unreachable(0);
378 }
379#endif
380 --SuccSU->NumPredsLeft;
381 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000382 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000383}
384
385/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000386void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000387 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
388 I != E; ++I) {
389 releaseSucc(SU, &*I);
390 }
391}
392
Andrew Trick17d35e52012-03-14 04:00:41 +0000393/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
394/// NumSuccsLeft reaches zero, release the predecessor node.
395void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
396 SUnit *PredSU = PredEdge->getSUnit();
397
398#ifndef NDEBUG
399 if (PredSU->NumSuccsLeft == 0) {
400 dbgs() << "*** Scheduling failed! ***\n";
401 PredSU->dump(this);
402 dbgs() << " has been released too many times!\n";
403 llvm_unreachable(0);
404 }
405#endif
406 --PredSU->NumSuccsLeft;
407 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
408 SchedImpl->releaseBottomNode(PredSU);
409}
410
411/// releasePredecessors - Call releasePred on each of SU's predecessors.
412void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
413 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
414 I != E; ++I) {
415 releasePred(SU, &*I);
416 }
417}
418
419void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
420 MachineBasicBlock::iterator InsertPos) {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000421 // Fix RegionBegin if the first instruction moves down.
422 if (&*RegionBegin == MI)
423 RegionBegin = llvm::next(RegionBegin);
Andrew Trick17d35e52012-03-14 04:00:41 +0000424 BB->splice(InsertPos, BB, MI);
425 LIS->handleMove(MI);
Andrew Trick1ce062f2012-03-21 04:12:10 +0000426 // Fix RegionBegin if another instruction moves above the first instruction.
Andrew Trick17d35e52012-03-14 04:00:41 +0000427 if (RegionBegin == InsertPos)
428 RegionBegin = MI;
429}
430
Andrew Trick0b0d8992012-03-21 04:12:07 +0000431bool ScheduleDAGMI::checkSchedLimit() {
432#ifndef NDEBUG
433 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
434 CurrentTop = CurrentBottom;
435 return false;
436 }
437 ++NumInstrsScheduled;
438#endif
439 return true;
440}
441
Andrew Trick006e1ab2012-04-24 17:56:43 +0000442/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
443/// crossing a scheduling boundary. [begin, end) includes all instructions in
444/// the region, including the boundary itself and single-instruction regions
445/// that don't get scheduled.
446void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
447 MachineBasicBlock::iterator begin,
448 MachineBasicBlock::iterator end,
449 unsigned endcount)
450{
451 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
452 // Setup the register pressure tracker to begin tracking at the end of this
453 // region.
454 RPTracker.init(&MF, RegClassInfo, LIS, BB, end);
455}
456
Andrew Trick17d35e52012-03-14 04:00:41 +0000457/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000458/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
459/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick17d35e52012-03-14 04:00:41 +0000460void ScheduleDAGMI::schedule() {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000461 while(RPTracker.getPos() != RegionEnd) {
462 bool Moved = RPTracker.recede();
463 assert(Moved && "Regpressure tracker cannot find RegionEnd"); (void)Moved;
464 }
465
466 // Build the DAG.
467 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000468
469 DEBUG(dbgs() << "********** MI Scheduling **********\n");
470 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
471 SUnits[su].dumpAll(this));
472
473 if (ViewMISchedDAGs) viewGraph();
474
Andrew Trick17d35e52012-03-14 04:00:41 +0000475 SchedImpl->initialize(this);
476
477 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000478 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000479 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000480
481 // Release all DAG roots for scheduling.
482 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
483 I != E; ++I) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000484 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000485 if (I->Preds.empty())
Andrew Trick17d35e52012-03-14 04:00:41 +0000486 SchedImpl->releaseTopNode(&(*I));
487 // A SUnit is ready to bottom schedule if it has no successors.
488 if (I->Succs.empty())
489 SchedImpl->releaseBottomNode(&(*I));
Andrew Trickc174eaf2012-03-08 01:41:12 +0000490 }
491
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000492 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000493 CurrentBottom = RegionEnd;
494 bool IsTopNode = false;
495 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
496 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
497 << " Scheduling Instruction:\n"; SU->dump(this));
Andrew Trick0b0d8992012-03-21 04:12:07 +0000498 if (!checkSchedLimit())
499 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000500
501 // Move the instruction to its new location in the instruction stream.
502 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000503
Andrew Trick17d35e52012-03-14 04:00:41 +0000504 if (IsTopNode) {
505 assert(SU->isTopReady() && "node still has unscheduled dependencies");
506 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000507 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000508 else
509 moveInstruction(MI, CurrentTop);
510 // Release dependent instructions for scheduling.
511 releaseSuccessors(SU);
512 }
513 else {
514 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000515 MachineBasicBlock::iterator priorII =
516 priorNonDebug(CurrentBottom, CurrentTop);
517 if (&*priorII == MI)
518 CurrentBottom = priorII;
Andrew Trick17d35e52012-03-14 04:00:41 +0000519 else {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000520 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000521 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000522 moveInstruction(MI, CurrentBottom);
523 CurrentBottom = MI;
524 }
525 // Release dependent instructions for scheduling.
526 releasePredecessors(SU);
527 }
528 SU->isScheduled = true;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000529 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000530 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trick000b2502012-04-24 18:04:37 +0000531
532 placeDebugValues();
533}
534
535/// Reinsert any remaining debug_values, just like the PostRA scheduler.
536void ScheduleDAGMI::placeDebugValues() {
537 // If first instruction was a DBG_VALUE then put it back.
538 if (FirstDbgValue) {
539 BB->splice(RegionBegin, BB, FirstDbgValue);
540 RegionBegin = FirstDbgValue;
541 }
542
543 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
544 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
545 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
546 MachineInstr *DbgValue = P.first;
547 MachineBasicBlock::iterator OrigPrevMI = P.second;
548 BB->splice(++OrigPrevMI, BB, DbgValue);
549 if (OrigPrevMI == llvm::prior(RegionEnd))
550 RegionEnd = DbgValue;
551 }
552 DbgValues.clear();
553 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000554}
555
556//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000557// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000558//===----------------------------------------------------------------------===//
559
560namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000561/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
562/// the schedule.
563class ConvergingScheduler : public MachineSchedStrategy {
564 ScheduleDAGMI *DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +0000565
Andrew Trick17d35e52012-03-14 04:00:41 +0000566 unsigned NumTopReady;
567 unsigned NumBottomReady;
568
569public:
570 virtual void initialize(ScheduleDAGMI *dag) {
571 DAG = dag;
572
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000573 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000574 "-misched-topdown incompatible with -misched-bottomup");
575 }
576
577 virtual SUnit *pickNode(bool &IsTopNode) {
578 if (DAG->top() == DAG->bottom())
579 return NULL;
580
581 // As an initial placeholder heuristic, schedule in the direction that has
582 // the fewest choices.
583 SUnit *SU;
584 if (ForceTopDown || (!ForceBottomUp && NumTopReady <= NumBottomReady)) {
585 SU = DAG->getSUnit(DAG->top());
586 IsTopNode = true;
587 }
588 else {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000589 SU = DAG->getSUnit(priorNonDebug(DAG->bottom(), DAG->top()));
Andrew Trick17d35e52012-03-14 04:00:41 +0000590 IsTopNode = false;
591 }
592 if (SU->isTopReady()) {
593 assert(NumTopReady > 0 && "bad ready count");
594 --NumTopReady;
595 }
596 if (SU->isBottomReady()) {
597 assert(NumBottomReady > 0 && "bad ready count");
598 --NumBottomReady;
599 }
600 return SU;
601 }
602
603 virtual void releaseTopNode(SUnit *SU) {
604 ++NumTopReady;
605 }
606 virtual void releaseBottomNode(SUnit *SU) {
607 ++NumBottomReady;
608 }
Andrew Trick42b7a712012-01-17 06:55:03 +0000609};
610} // namespace
611
Andrew Trick17d35e52012-03-14 04:00:41 +0000612/// Create the standard converging machine scheduler. This will be used as the
613/// default scheduler if the target does not set a default.
614static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000615 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000616 "-misched-topdown incompatible with -misched-bottomup");
617 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +0000618}
619static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000620ConvergingSchedRegistry("converge", "Standard converging scheduler.",
621 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +0000622
623//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +0000624// Machine Instruction Shuffler for Correctness Testing
625//===----------------------------------------------------------------------===//
626
Andrew Trick96f678f2012-01-13 06:30:30 +0000627#ifndef NDEBUG
628namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000629/// Apply a less-than relation on the node order, which corresponds to the
630/// instruction order prior to scheduling. IsReverse implements greater-than.
631template<bool IsReverse>
632struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000633 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +0000634 if (IsReverse)
635 return A->NodeNum > B->NodeNum;
636 else
637 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000638 }
639};
640
Andrew Trick96f678f2012-01-13 06:30:30 +0000641/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +0000642class InstructionShuffler : public MachineSchedStrategy {
643 bool IsAlternating;
644 bool IsTopDown;
645
646 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
647 // gives nodes with a higher number higher priority causing the latest
648 // instructions to be scheduled first.
649 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
650 TopQ;
651 // When scheduling bottom-up, use greater-than as the queue priority.
652 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
653 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +0000654public:
Andrew Trick17d35e52012-03-14 04:00:41 +0000655 InstructionShuffler(bool alternate, bool topdown)
656 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +0000657
Andrew Trick17d35e52012-03-14 04:00:41 +0000658 virtual void initialize(ScheduleDAGMI *) {
659 TopQ.clear();
660 BottomQ.clear();
661 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000662
Andrew Trick17d35e52012-03-14 04:00:41 +0000663 /// Implement MachineSchedStrategy interface.
664 /// -----------------------------------------
665
666 virtual SUnit *pickNode(bool &IsTopNode) {
667 SUnit *SU;
668 if (IsTopDown) {
669 do {
670 if (TopQ.empty()) return NULL;
671 SU = TopQ.top();
672 TopQ.pop();
673 } while (SU->isScheduled);
674 IsTopNode = true;
675 }
676 else {
677 do {
678 if (BottomQ.empty()) return NULL;
679 SU = BottomQ.top();
680 BottomQ.pop();
681 } while (SU->isScheduled);
682 IsTopNode = false;
683 }
684 if (IsAlternating)
685 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000686 return SU;
687 }
688
Andrew Trick17d35e52012-03-14 04:00:41 +0000689 virtual void releaseTopNode(SUnit *SU) {
690 TopQ.push(SU);
691 }
692 virtual void releaseBottomNode(SUnit *SU) {
693 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +0000694 }
695};
696} // namespace
697
Andrew Trickc174eaf2012-03-08 01:41:12 +0000698static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000699 bool Alternate = !ForceTopDown && !ForceBottomUp;
700 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000701 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000702 "-misched-topdown incompatible with -misched-bottomup");
703 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +0000704}
Andrew Trick17d35e52012-03-14 04:00:41 +0000705static MachineSchedRegistry ShufflerRegistry(
706 "shuffle", "Shuffle machine instructions alternating directions",
707 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +0000708#endif // !NDEBUG