blob: 11a7d4760cb0af94f36be6c577ab63a11f85a377 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
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 Trick96f678f2012-01-13 06:30:30 +000017#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trickc174eaf2012-03-08 01:41:12 +000018#include "llvm/CodeGen/MachineScheduler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000019#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000020#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000021#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trickb7e02892012-06-05 21:11:27 +000022#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000023#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"
Andrew Trick17d35e52012-03-14 04:00:41 +000028#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000029
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick78e5efe2012-09-11 00:39:15 +000034namespace llvm {
35cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39}
Andrew Trick17d35e52012-03-14 04:00:41 +000040
Andrew Trick0df7f882012-03-07 00:18:25 +000041#ifndef NDEBUG
42static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000044
45static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000047#else
48static bool ViewMISchedDAGs = false;
49#endif // NDEBUG
50
Andrew Trick5edf2f02012-01-14 02:17:06 +000051//===----------------------------------------------------------------------===//
52// Machine Instruction Scheduling Pass and Registry
53//===----------------------------------------------------------------------===//
54
Andrew Trick86b7e2a2012-04-24 20:36:19 +000055MachineSchedContext::MachineSchedContext():
56 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
57 RegClassInfo = new RegisterClassInfo();
58}
59
60MachineSchedContext::~MachineSchedContext() {
61 delete RegClassInfo;
62}
63
Andrew Trick96f678f2012-01-13 06:30:30 +000064namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000065/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000066class MachineScheduler : public MachineSchedContext,
67 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000068public:
Andrew Trick42b7a712012-01-17 06:55:03 +000069 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000070
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
72
73 virtual void releaseMemory() {}
74
75 virtual bool runOnMachineFunction(MachineFunction&);
76
77 virtual void print(raw_ostream &O, const Module* = 0) const;
78
79 static char ID; // Class identification, replacement for typeinfo
80};
81} // namespace
82
Andrew Trick42b7a712012-01-17 06:55:03 +000083char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000084
Andrew Trick42b7a712012-01-17 06:55:03 +000085char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000086
Andrew Trick42b7a712012-01-17 06:55:03 +000087INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000088 "Machine Instruction Scheduler", false, false)
89INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
91INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000092INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000093 "Machine Instruction Scheduler", false, false)
94
Andrew Trick42b7a712012-01-17 06:55:03 +000095MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000096: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000097 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000098}
99
Andrew Trick42b7a712012-01-17 06:55:03 +0000100void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000101 AU.setPreservesCFG();
102 AU.addRequiredID(MachineDominatorsID);
103 AU.addRequired<MachineLoopInfo>();
104 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000105 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000106 AU.addRequired<SlotIndexes>();
107 AU.addPreserved<SlotIndexes>();
108 AU.addRequired<LiveIntervals>();
109 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000110 MachineFunctionPass::getAnalysisUsage(AU);
111}
112
Andrew Trick96f678f2012-01-13 06:30:30 +0000113MachinePassRegistry MachineSchedRegistry::Registry;
114
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000115/// A dummy default scheduler factory indicates whether the scheduler
116/// is overridden on the command line.
117static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
118 return 0;
119}
Andrew Trick96f678f2012-01-13 06:30:30 +0000120
121/// MachineSchedOpt allows command line selection of the scheduler.
122static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
123 RegisterPassParser<MachineSchedRegistry> >
124MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000125 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000126 cl::desc("Machine instruction scheduler to use"));
127
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000128static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000129DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000130 useDefaultMachineSched);
131
Andrew Trick17d35e52012-03-14 04:00:41 +0000132/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000133/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000134static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000135
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000136
137/// Decrement this iterator until reaching the top or a non-debug instr.
138static MachineBasicBlock::iterator
139priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
140 assert(I != Beg && "reached the top of the region, cannot decrement");
141 while (--I != Beg) {
142 if (!I->isDebugValue())
143 break;
144 }
145 return I;
146}
147
148/// If this iterator is a debug value, increment until reaching the End or a
149/// non-debug instruction.
150static MachineBasicBlock::iterator
151nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000152 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000153 if (!I->isDebugValue())
154 break;
155 }
156 return I;
157}
158
Andrew Trickcb058d52012-03-14 04:00:38 +0000159/// Top-level MachineScheduler pass driver.
160///
161/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000162/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
163/// consistent with the DAG builder, which traverses the interior of the
164/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000165///
166/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000167/// simplifying the DAG builder's support for "special" target instructions.
168/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000169/// scheduling boundaries, for example to bundle the boudary instructions
170/// without reordering them. This creates complexity, because the target
171/// scheduler must update the RegionBegin and RegionEnd positions cached by
172/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
173/// design would be to split blocks at scheduling boundaries, but LLVM has a
174/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000175bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000176 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
177
Andrew Trick96f678f2012-01-13 06:30:30 +0000178 // Initialize the context of the pass.
179 MF = &mf;
180 MLI = &getAnalysis<MachineLoopInfo>();
181 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000182 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000183 AA = &getAnalysis<AliasAnalysis>();
184
Lang Hames907cc8f2012-01-27 22:36:19 +0000185 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000186 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000187
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000188 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000189
Andrew Trick96f678f2012-01-13 06:30:30 +0000190 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000191 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
192 if (Ctor == useDefaultMachineSched) {
193 // Get the default scheduler set by the target.
194 Ctor = MachineSchedRegistry::getDefault();
195 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000196 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000197 MachineSchedRegistry::setDefault(Ctor);
198 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000199 }
200 // Instantiate the selected scheduler.
201 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
202
203 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000204 //
205 // TODO: Visit blocks in global postorder or postorder within the bottom-up
206 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000207 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
208 MBB != MBBEnd; ++MBB) {
209
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000210 Scheduler->startBlock(MBB);
211
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000212 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000213 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000214 // boundary at the bottom of the region. The DAG does not include RegionEnd,
215 // but the region does (i.e. the next RegionEnd is above the previous
216 // RegionBegin). If the current block has no terminator then RegionEnd ==
217 // MBB->end() for the bottom region.
218 //
219 // The Scheduler may insert instructions during either schedule() or
220 // exitRegion(), even for empty regions. So the local iterators 'I' and
221 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000222 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000223 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000224 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000225
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000226 // Avoid decrementing RegionEnd for blocks with no terminator.
227 if (RegionEnd != MBB->end()
228 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
229 --RegionEnd;
230 // Count the boundary instruction.
231 --RemainingCount;
232 }
233
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000234 // The next region starts above the previous region. Look backward in the
235 // instruction stream until we find the nearest boundary.
236 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000237 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000238 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
239 break;
240 }
Andrew Trick47c14452012-03-07 05:21:52 +0000241 // Notify the scheduler of the region, even if we may skip scheduling
242 // it. Perhaps it still needs to be bundled.
243 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
244
245 // Skip empty scheduling regions (0 or 1 schedulable instructions).
246 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000247 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000248 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000249 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000250 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000251 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000252 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000253 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000254 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
255 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
256 else dbgs() << "End";
257 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000258
Andrew Trickd24da972012-03-09 03:46:42 +0000259 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000260 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000261 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000262
263 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000264 Scheduler->exitRegion();
265
266 // Scheduling has invalidated the current iterator 'I'. Ask the
267 // scheduler for the top of it's scheduled region.
268 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000269 }
270 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000271 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000272 }
Andrew Trick830da402012-04-01 07:24:23 +0000273 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000274 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000275 return true;
276}
277
Andrew Trick42b7a712012-01-17 06:55:03 +0000278void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000279 // unimplemented
280}
281
Manman Renb720be62012-09-11 22:23:19 +0000282#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000283void ReadyQueue::dump() {
284 dbgs() << Name << ": ";
285 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
286 dbgs() << Queue[i]->NodeNum << " ";
287 dbgs() << "\n";
288}
289#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000290
291//===----------------------------------------------------------------------===//
292// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
293// preservation.
294//===----------------------------------------------------------------------===//
295
Andrew Trickc174eaf2012-03-08 01:41:12 +0000296/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
297/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000298///
299/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000300void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000301 SUnit *SuccSU = SuccEdge->getSUnit();
302
303#ifndef NDEBUG
304 if (SuccSU->NumPredsLeft == 0) {
305 dbgs() << "*** Scheduling failed! ***\n";
306 SuccSU->dump(this);
307 dbgs() << " has been released too many times!\n";
308 llvm_unreachable(0);
309 }
310#endif
311 --SuccSU->NumPredsLeft;
312 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000313 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000314}
315
316/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000317void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000318 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
319 I != E; ++I) {
320 releaseSucc(SU, &*I);
321 }
322}
323
Andrew Trick17d35e52012-03-14 04:00:41 +0000324/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
325/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000326///
327/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000328void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
329 SUnit *PredSU = PredEdge->getSUnit();
330
331#ifndef NDEBUG
332 if (PredSU->NumSuccsLeft == 0) {
333 dbgs() << "*** Scheduling failed! ***\n";
334 PredSU->dump(this);
335 dbgs() << " has been released too many times!\n";
336 llvm_unreachable(0);
337 }
338#endif
339 --PredSU->NumSuccsLeft;
340 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
341 SchedImpl->releaseBottomNode(PredSU);
342}
343
344/// releasePredecessors - Call releasePred on each of SU's predecessors.
345void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
346 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
347 I != E; ++I) {
348 releasePred(SU, &*I);
349 }
350}
351
352void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
353 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000354 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000355 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000356 ++RegionBegin;
357
358 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000359 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000360
361 // Update LiveIntervals
Andrew Trick17d35e52012-03-14 04:00:41 +0000362 LIS->handleMove(MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000363
364 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000365 if (RegionBegin == InsertPos)
366 RegionBegin = MI;
367}
368
Andrew Trick0b0d8992012-03-21 04:12:07 +0000369bool ScheduleDAGMI::checkSchedLimit() {
370#ifndef NDEBUG
371 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
372 CurrentTop = CurrentBottom;
373 return false;
374 }
375 ++NumInstrsScheduled;
376#endif
377 return true;
378}
379
Andrew Trick006e1ab2012-04-24 17:56:43 +0000380/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
381/// crossing a scheduling boundary. [begin, end) includes all instructions in
382/// the region, including the boundary itself and single-instruction regions
383/// that don't get scheduled.
384void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
385 MachineBasicBlock::iterator begin,
386 MachineBasicBlock::iterator end,
387 unsigned endcount)
388{
389 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000390
391 // For convenience remember the end of the liveness region.
392 LiveRegionEnd =
393 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
394}
395
396// Setup the register pressure trackers for the top scheduled top and bottom
397// scheduled regions.
398void ScheduleDAGMI::initRegPressure() {
399 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
400 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
401
402 // Close the RPTracker to finalize live ins.
403 RPTracker.closeRegion();
404
Andrew Trickbb0a2422012-05-24 22:11:14 +0000405 DEBUG(RPTracker.getPressure().dump(TRI));
406
Andrew Trick7f8ab782012-05-10 21:06:10 +0000407 // Initialize the live ins and live outs.
408 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
409 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
410
411 // Close one end of the tracker so we can call
412 // getMaxUpward/DownwardPressureDelta before advancing across any
413 // instructions. This converts currently live regs into live ins/outs.
414 TopRPTracker.closeTop();
415 BotRPTracker.closeBottom();
416
417 // Account for liveness generated by the region boundary.
418 if (LiveRegionEnd != RegionEnd)
419 BotRPTracker.recede();
420
421 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000422
423 // Cache the list of excess pressure sets in this region. This will also track
424 // the max pressure in the scheduled code for these sets.
425 RegionCriticalPSets.clear();
426 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
427 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
428 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000429 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
430 << "Limit " << Limit
431 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000432 if (RegionPressure[i] > Limit)
433 RegionCriticalPSets.push_back(PressureElement(i, 0));
434 }
435 DEBUG(dbgs() << "Excess PSets: ";
436 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
437 dbgs() << TRI->getRegPressureSetName(
438 RegionCriticalPSets[i].PSetID) << " ";
439 dbgs() << "\n");
440}
441
442// FIXME: When the pressure tracker deals in pressure differences then we won't
443// iterate over all RegionCriticalPSets[i].
444void ScheduleDAGMI::
445updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
446 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
447 unsigned ID = RegionCriticalPSets[i].PSetID;
448 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
449 if ((int)NewMaxPressure[ID] > MaxUnits)
450 MaxUnits = NewMaxPressure[ID];
451 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000452}
453
Andrew Trick2aa689d2012-05-24 22:11:05 +0000454// Release all DAG roots for scheduling.
455void ScheduleDAGMI::releaseRoots() {
456 SmallVector<SUnit*, 16> BotRoots;
457
458 for (std::vector<SUnit>::iterator
459 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
460 // A SUnit is ready to top schedule if it has no predecessors.
461 if (I->Preds.empty())
462 SchedImpl->releaseTopNode(&(*I));
463 // A SUnit is ready to bottom schedule if it has no successors.
464 if (I->Succs.empty())
465 BotRoots.push_back(&(*I));
466 }
467 // Release bottom roots in reverse order so the higher priority nodes appear
468 // first. This is more natural and slightly more efficient.
469 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
470 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
471 SchedImpl->releaseBottomNode(*I);
472}
473
Andrew Trick17d35e52012-03-14 04:00:41 +0000474/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000475/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
476/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000477///
478/// This is a skeletal driver, with all the functionality pushed into helpers,
479/// so that it can be easilly extended by experimental schedulers. Generally,
480/// implementing MachineSchedStrategy should be sufficient to implement a new
481/// scheduling algorithm. However, if a scheduler further subclasses
482/// ScheduleDAGMI then it will want to override this virtual method in order to
483/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000484void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000485 buildDAGWithRegPressure();
486
Andrew Trickd039b382012-09-14 17:22:42 +0000487 postprocessDAG();
488
Andrew Trick78e5efe2012-09-11 00:39:15 +0000489 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
490 SUnits[su].dumpAll(this));
491
492 if (ViewMISchedDAGs) viewGraph();
493
494 initQueues();
495
496 bool IsTopNode = false;
497 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000498 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000499 if (!checkSchedLimit())
500 break;
501
502 scheduleMI(SU, IsTopNode);
503
504 updateQueues(SU, IsTopNode);
505 }
506 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
507
508 placeDebugValues();
509}
510
511/// Build the DAG and setup three register pressure trackers.
512void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000513 // Initialize the register pressure tracker used by buildSchedGraph.
514 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000515
Andrew Trick7f8ab782012-05-10 21:06:10 +0000516 // Account for liveness generate by the region boundary.
517 if (LiveRegionEnd != RegionEnd)
518 RPTracker.recede();
519
520 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000521 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000522 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000523
Andrew Trick7f8ab782012-05-10 21:06:10 +0000524 // Initialize top/bottom trackers after computing region pressure.
525 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000526}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000527
Andrew Trickd039b382012-09-14 17:22:42 +0000528/// Apply each ScheduleDAGMutation step in order.
529void ScheduleDAGMI::postprocessDAG() {
530 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
531 Mutations[i]->apply(this);
532 }
533}
534
Andrew Trick78e5efe2012-09-11 00:39:15 +0000535/// Identify DAG roots and setup scheduler queues.
536void ScheduleDAGMI::initQueues() {
537 // Initialize the strategy before modifying the DAG.
Andrew Trick17d35e52012-03-14 04:00:41 +0000538 SchedImpl->initialize(this);
539
540 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000541 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000542 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000543
544 // Release all DAG roots for scheduling.
Andrew Trick2aa689d2012-05-24 22:11:05 +0000545 releaseRoots();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000546
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000547 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000548 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000549}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000550
Andrew Trick78e5efe2012-09-11 00:39:15 +0000551/// Move an instruction and update register pressure.
552void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
553 // Move the instruction to its new location in the instruction stream.
554 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000555
Andrew Trick78e5efe2012-09-11 00:39:15 +0000556 if (IsTopNode) {
557 assert(SU->isTopReady() && "node still has unscheduled dependencies");
558 if (&*CurrentTop == MI)
559 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000560 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000561 moveInstruction(MI, CurrentTop);
562 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000563 }
Andrew Trick000b2502012-04-24 18:04:37 +0000564
Andrew Trick78e5efe2012-09-11 00:39:15 +0000565 // Update top scheduled pressure.
566 TopRPTracker.advance();
567 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
568 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
569 }
570 else {
571 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
572 MachineBasicBlock::iterator priorII =
573 priorNonDebug(CurrentBottom, CurrentTop);
574 if (&*priorII == MI)
575 CurrentBottom = priorII;
576 else {
577 if (&*CurrentTop == MI) {
578 CurrentTop = nextIfDebug(++CurrentTop, priorII);
579 TopRPTracker.setPos(CurrentTop);
580 }
581 moveInstruction(MI, CurrentBottom);
582 CurrentBottom = MI;
583 }
584 // Update bottom scheduled pressure.
585 BotRPTracker.recede();
586 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
587 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
588 }
589}
590
591/// Update scheduler queues after scheduling an instruction.
592void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
593 // Release dependent instructions for scheduling.
594 if (IsTopNode)
595 releaseSuccessors(SU);
596 else
597 releasePredecessors(SU);
598
599 SU->isScheduled = true;
600
601 // Notify the scheduling strategy after updating the DAG.
602 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000603}
604
605/// Reinsert any remaining debug_values, just like the PostRA scheduler.
606void ScheduleDAGMI::placeDebugValues() {
607 // If first instruction was a DBG_VALUE then put it back.
608 if (FirstDbgValue) {
609 BB->splice(RegionBegin, BB, FirstDbgValue);
610 RegionBegin = FirstDbgValue;
611 }
612
613 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
614 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
615 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
616 MachineInstr *DbgValue = P.first;
617 MachineBasicBlock::iterator OrigPrevMI = P.second;
618 BB->splice(++OrigPrevMI, BB, DbgValue);
619 if (OrigPrevMI == llvm::prior(RegionEnd))
620 RegionEnd = DbgValue;
621 }
622 DbgValues.clear();
623 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000624}
625
626//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000627// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000628//===----------------------------------------------------------------------===//
629
630namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000631/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
632/// the schedule.
633class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000634
635 /// Store the state used by ConvergingScheduler heuristics, required for the
636 /// lifetime of one invocation of pickNode().
637 struct SchedCandidate {
638 // The best SUnit candidate.
639 SUnit *SU;
640
641 // Register pressure values for the best candidate.
642 RegPressureDelta RPDelta;
643
644 SchedCandidate(): SU(NULL) {}
645 };
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000646 /// Represent the type of SchedCandidate found within a single queue.
647 enum CandResult {
648 NoCand, NodeOrder, SingleExcess, SingleCritical, SingleMax, MultiPressure };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000649
Andrew Trickf3234242012-05-24 22:11:12 +0000650 /// Each Scheduling boundary is associated with ready queues. It tracks the
651 /// current cycle in whichever direction at has moved, and maintains the state
652 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000653 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000654 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000655 const TargetSchedModel *SchedModel;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000656
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000657 ReadyQueue Available;
658 ReadyQueue Pending;
659 bool CheckPending;
660
661 ScheduleHazardRecognizer *HazardRec;
662
663 unsigned CurrCycle;
664 unsigned IssueCount;
665
666 /// MinReadyCycle - Cycle of the soonest available instruction.
667 unsigned MinReadyCycle;
668
Andrew Trickb7e02892012-06-05 21:11:27 +0000669 // Remember the greatest min operand latency.
670 unsigned MaxMinLatency;
671
Andrew Trickf3234242012-05-24 22:11:12 +0000672 /// Pending queues extend the ready queues with the same ID and the
673 /// PendingFlag set.
674 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick412cd2f2012-10-10 05:43:09 +0000675 DAG(0), SchedModel(0), Available(ID, Name+".A"),
Andrew Trickf3234242012-05-24 22:11:12 +0000676 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
677 CheckPending(false), HazardRec(0), CurrCycle(0), IssueCount(0),
Andrew Trickb7e02892012-06-05 21:11:27 +0000678 MinReadyCycle(UINT_MAX), MaxMinLatency(0) {}
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000679
680 ~SchedBoundary() { delete HazardRec; }
681
Andrew Trick412cd2f2012-10-10 05:43:09 +0000682 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel) {
683 DAG = dag;
684 SchedModel = smodel;
685 }
686
Andrew Trickf3234242012-05-24 22:11:12 +0000687 bool isTop() const {
688 return Available.getID() == ConvergingScheduler::TopQID;
689 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000690
Andrew Trick5559ffa2012-06-29 03:23:24 +0000691 bool checkHazard(SUnit *SU);
692
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000693 void releaseNode(SUnit *SU, unsigned ReadyCycle);
694
695 void bumpCycle();
696
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000697 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +0000698
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000699 void releasePending();
700
701 void removeReady(SUnit *SU);
702
703 SUnit *pickOnlyChoice();
704 };
705
Andrew Trick17d35e52012-03-14 04:00:41 +0000706 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000707 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000708 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +0000709
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000710 // State of the top and bottom scheduled instruction boundaries.
711 SchedBoundary Top;
712 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +0000713
714public:
Andrew Trickf3234242012-05-24 22:11:12 +0000715 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +0000716 enum {
717 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +0000718 BotQID = 2,
719 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +0000720 };
721
Andrew Trickf3234242012-05-24 22:11:12 +0000722 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +0000723 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000724
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000725 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +0000726
Andrew Trick7196a8f2012-05-10 21:06:16 +0000727 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +0000728
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000729 virtual void schedNode(SUnit *SU, bool IsTopNode);
730
731 virtual void releaseTopNode(SUnit *SU);
732
733 virtual void releaseBottomNode(SUnit *SU);
734
Andrew Trick7196a8f2012-05-10 21:06:16 +0000735protected:
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000736 SUnit *pickNodeBidrectional(bool &IsTopNode);
737
Andrew Trick8c2d9212012-05-24 22:11:03 +0000738 CandResult pickNodeFromQueue(ReadyQueue &Q,
739 const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000740 SchedCandidate &Candidate);
Andrew Trick28ebc892012-05-10 21:06:19 +0000741#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +0000742 void traceCandidate(const char *Label, const ReadyQueue &Q, SUnit *SU,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000743 PressureElement P = PressureElement());
Andrew Trick28ebc892012-05-10 21:06:19 +0000744#endif
Andrew Trick42b7a712012-01-17 06:55:03 +0000745};
746} // namespace
747
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000748void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
749 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000750 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000751 TRI = DAG->TRI;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000752 Top.init(DAG, SchedModel);
753 Bot.init(DAG, SchedModel);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000754
Andrew Trick412cd2f2012-10-10 05:43:09 +0000755 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
756 // are disabled, then these HazardRecs will be disabled.
757 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000758 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000759 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
760 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
761
762 assert((!ForceTopDown || !ForceBottomUp) &&
763 "-misched-topdown incompatible with -misched-bottomup");
764}
765
766void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000767 if (SU->isScheduled)
768 return;
769
770 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
771 I != E; ++I) {
772 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +0000773 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +0000774#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +0000775 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +0000776#endif
Andrew Trickffd25262012-08-23 00:39:43 +0000777 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
778 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +0000779 }
780 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000781}
782
783void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000784 if (SU->isScheduled)
785 return;
786
787 assert(SU->getInstr() && "Scheduled SUnit must have instr");
788
789 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
790 I != E; ++I) {
791 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +0000792 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +0000793#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +0000794 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +0000795#endif
Andrew Trickffd25262012-08-23 00:39:43 +0000796 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
797 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +0000798 }
799 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000800}
801
Andrew Trick5559ffa2012-06-29 03:23:24 +0000802/// Does this SU have a hazard within the current instruction group.
803///
804/// The scheduler supports two modes of hazard recognition. The first is the
805/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
806/// supports highly complicated in-order reservation tables
807/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
808///
809/// The second is a streamlined mechanism that checks for hazards based on
810/// simple counters that the scheduler itself maintains. It explicitly checks
811/// for instruction dispatch limitations, including the number of micro-ops that
812/// can dispatch per cycle.
813///
814/// TODO: Also check whether the SU must start a new group.
815bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
816 if (HazardRec->isEnabled())
817 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
818
Andrew Trick412cd2f2012-10-10 05:43:09 +0000819 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
820 if (IssueCount + uops > SchedModel->getIssueWidth())
Andrew Trick5559ffa2012-06-29 03:23:24 +0000821 return true;
822
823 return false;
824}
825
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000826void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
827 unsigned ReadyCycle) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000828 if (ReadyCycle < MinReadyCycle)
829 MinReadyCycle = ReadyCycle;
830
831 // Check for interlocks first. For the purpose of other heuristics, an
832 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +0000833 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000834 Pending.push(SU);
835 else
836 Available.push(SU);
837}
838
839/// Move the boundary of scheduled code by one cycle.
840void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +0000841 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000842 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000843
844 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
845 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
846
847 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000848 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000849 CurrCycle = NextCycle;
850 }
851 else {
Andrew Trickb7e02892012-06-05 21:11:27 +0000852 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000853 for (; CurrCycle != NextCycle; ++CurrCycle) {
854 if (isTop())
855 HazardRec->AdvanceCycle();
856 else
857 HazardRec->RecedeCycle();
858 }
859 }
860 CheckPending = true;
861
Andrew Trickf3234242012-05-24 22:11:12 +0000862 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000863 << CurrCycle << '\n');
864}
865
Andrew Trickb7e02892012-06-05 21:11:27 +0000866/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000867void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000868 // Update the reservation table.
869 if (HazardRec->isEnabled()) {
870 if (!isTop() && SU->isCall) {
871 // Calls are scheduled with their preceding instructions. For bottom-up
872 // scheduling, clear the pipeline state before emitting.
873 HazardRec->Reset();
874 }
875 HazardRec->EmitInstruction(SU);
876 }
Andrew Trick5559ffa2012-06-29 03:23:24 +0000877 // Check the instruction group dispatch limit.
878 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +0000879 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
880 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000881 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
882 bumpCycle();
883 }
884}
885
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000886/// Release pending ready nodes in to the available queue. This makes them
887/// visible to heuristics.
888void ConvergingScheduler::SchedBoundary::releasePending() {
889 // If the available queue is empty, it is safe to reset MinReadyCycle.
890 if (Available.empty())
891 MinReadyCycle = UINT_MAX;
892
893 // Check to see if any of the pending instructions are ready to issue. If
894 // so, add them to the available queue.
895 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
896 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +0000897 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000898
899 if (ReadyCycle < MinReadyCycle)
900 MinReadyCycle = ReadyCycle;
901
902 if (ReadyCycle > CurrCycle)
903 continue;
904
Andrew Trick5559ffa2012-06-29 03:23:24 +0000905 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000906 continue;
907
908 Available.push(SU);
909 Pending.remove(Pending.begin()+i);
910 --i; --e;
911 }
912 CheckPending = false;
913}
914
915/// Remove SU from the ready set for this boundary.
916void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
917 if (Available.isInQueue(SU))
918 Available.remove(Available.find(SU));
919 else {
920 assert(Pending.isInQueue(SU) && "bad ready count");
921 Pending.remove(Pending.find(SU));
922 }
923}
924
925/// If this queue only has one ready candidate, return it. As a side effect,
926/// advance the cycle until at least one node is ready. If multiple instructions
927/// are ready, return NULL.
928SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
929 if (CheckPending)
930 releasePending();
931
932 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000933 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
934 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000935 bumpCycle();
936 releasePending();
937 }
938 if (Available.size() == 1)
939 return *Available.begin();
940 return NULL;
941}
942
Andrew Trick28ebc892012-05-10 21:06:19 +0000943#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +0000944void ConvergingScheduler::traceCandidate(const char *Label, const ReadyQueue &Q,
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000945 SUnit *SU, PressureElement P) {
Andrew Trickf3234242012-05-24 22:11:12 +0000946 dbgs() << Label << " " << Q.getName() << " ";
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000947 if (P.isValid())
948 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
949 << " ";
Andrew Trick28ebc892012-05-10 21:06:19 +0000950 else
951 dbgs() << " ";
952 SU->dump(DAG);
953}
954#endif
955
Andrew Trick5429a6b2012-05-17 22:37:09 +0000956/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
957/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000958static bool compareRPDelta(const RegPressureDelta &LHS,
959 const RegPressureDelta &RHS) {
960 // Compare each component of pressure in decreasing order of importance
961 // without checking if any are valid. Invalid PressureElements are assumed to
962 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +0000963
964 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000965 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease)
966 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
967
Andrew Trickc8fe4ec2012-05-24 22:11:01 +0000968 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000969 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease)
970 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
971
Andrew Trickc8fe4ec2012-05-24 22:11:01 +0000972 // Avoid increasing the max pressure of the entire region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000973 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease)
974 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
975
976 return false;
977}
978
Andrew Trick7196a8f2012-05-10 21:06:16 +0000979/// Pick the best candidate from the top queue.
980///
981/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
982/// DAG building. To adjust for the current scheduling location we need to
983/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000984ConvergingScheduler::CandResult ConvergingScheduler::
Andrew Trick8c2d9212012-05-24 22:11:03 +0000985pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000986 SchedCandidate &Candidate) {
Andrew Trickf3234242012-05-24 22:11:12 +0000987 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000988
Andrew Trick7196a8f2012-05-10 21:06:16 +0000989 // getMaxPressureDelta temporarily modifies the tracker.
990 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
991
992 // BestSU remains NULL if no top candidates beat the best existing candidate.
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000993 CandResult FoundCandidate = NoCand;
Andrew Trick8c2d9212012-05-24 22:11:03 +0000994 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000995 RegPressureDelta RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000996 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
997 DAG->getRegionCriticalPSets(),
998 DAG->getRegPressure().MaxSetPressure);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000999
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001000 // Initialize the candidate if needed.
1001 if (!Candidate.SU) {
1002 Candidate.SU = *I;
1003 Candidate.RPDelta = RPDelta;
1004 FoundCandidate = NodeOrder;
1005 continue;
1006 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001007 // Avoid exceeding the target's limit.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001008 if (RPDelta.Excess.UnitIncrease < Candidate.RPDelta.Excess.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001009 DEBUG(traceCandidate("ECAND", Q, *I, RPDelta.Excess));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001010 Candidate.SU = *I;
1011 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001012 FoundCandidate = SingleExcess;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001013 continue;
1014 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001015 if (RPDelta.Excess.UnitIncrease > Candidate.RPDelta.Excess.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001016 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001017 if (FoundCandidate == SingleExcess)
1018 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001019
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001020 // Avoid increasing the max critical pressure in the scheduled region.
1021 if (RPDelta.CriticalMax.UnitIncrease
1022 < Candidate.RPDelta.CriticalMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001023 DEBUG(traceCandidate("PCAND", Q, *I, RPDelta.CriticalMax));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001024 Candidate.SU = *I;
1025 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001026 FoundCandidate = SingleCritical;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001027 continue;
1028 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001029 if (RPDelta.CriticalMax.UnitIncrease
1030 > Candidate.RPDelta.CriticalMax.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001031 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001032 if (FoundCandidate == SingleCritical)
1033 FoundCandidate = MultiPressure;
1034
1035 // Avoid increasing the max pressure of the entire region.
1036 if (RPDelta.CurrentMax.UnitIncrease
1037 < Candidate.RPDelta.CurrentMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001038 DEBUG(traceCandidate("MCAND", Q, *I, RPDelta.CurrentMax));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001039 Candidate.SU = *I;
1040 Candidate.RPDelta = RPDelta;
1041 FoundCandidate = SingleMax;
1042 continue;
1043 }
1044 if (RPDelta.CurrentMax.UnitIncrease
1045 > Candidate.RPDelta.CurrentMax.UnitIncrease)
1046 continue;
1047 if (FoundCandidate == SingleMax)
1048 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001049
1050 // Fall through to original instruction order.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001051 // Only consider node order if Candidate was chosen from this Q.
1052 if (FoundCandidate == NoCand)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001053 continue;
1054
Andrew Trickf3234242012-05-24 22:11:12 +00001055 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
1056 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
1057 DEBUG(traceCandidate("NCAND", Q, *I));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001058 Candidate.SU = *I;
1059 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001060 FoundCandidate = NodeOrder;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001061 }
1062 }
1063 return FoundCandidate;
1064}
1065
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001066/// Pick the best candidate node from either the top or bottom queue.
1067SUnit *ConvergingScheduler::pickNodeBidrectional(bool &IsTopNode) {
1068 // Schedule as far as possible in the direction of no choice. This is most
1069 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001070 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001071 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001072 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001073 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001074 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001075 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001076 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001077 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001078 SchedCandidate BotCand;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001079 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001080 CandResult BotResult = pickNodeFromQueue(Bot.Available,
1081 DAG->getBotRPTracker(), BotCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001082 assert(BotResult != NoCand && "failed to find the first candidate");
1083
1084 // If either Q has a single candidate that provides the least increase in
1085 // Excess pressure, we can immediately schedule from that Q.
1086 //
1087 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1088 // affects picking from either Q. If scheduling in one direction must
1089 // increase pressure for one of the excess PSets, then schedule in that
1090 // direction first to provide more freedom in the other direction.
1091 if (BotResult == SingleExcess || BotResult == SingleCritical) {
1092 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001093 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001094 }
1095 // Check if the top Q has a better candidate.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001096 SchedCandidate TopCand;
1097 CandResult TopResult = pickNodeFromQueue(Top.Available,
1098 DAG->getTopRPTracker(), TopCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001099 assert(TopResult != NoCand && "failed to find the first candidate");
1100
1101 if (TopResult == SingleExcess || TopResult == SingleCritical) {
1102 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001103 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001104 }
1105 // If either Q has a single candidate that minimizes pressure above the
1106 // original region's pressure pick it.
1107 if (BotResult == SingleMax) {
1108 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001109 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001110 }
1111 if (TopResult == SingleMax) {
1112 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001113 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001114 }
1115 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001116 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001117 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001118 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001119 }
1120 // Otherwise prefer the bottom candidate in node order.
1121 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001122 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001123}
1124
1125/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001126SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1127 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001128 assert(Top.Available.empty() && Top.Pending.empty() &&
1129 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001130 return NULL;
1131 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001132 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00001133 do {
1134 if (ForceTopDown) {
1135 SU = Top.pickOnlyChoice();
1136 if (!SU) {
1137 SchedCandidate TopCand;
1138 CandResult TopResult =
1139 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
1140 assert(TopResult != NoCand && "failed to find the first candidate");
1141 (void)TopResult;
1142 SU = TopCand.SU;
1143 }
1144 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001145 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001146 else if (ForceBottomUp) {
1147 SU = Bot.pickOnlyChoice();
1148 if (!SU) {
1149 SchedCandidate BotCand;
1150 CandResult BotResult =
1151 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
1152 assert(BotResult != NoCand && "failed to find the first candidate");
1153 (void)BotResult;
1154 SU = BotCand.SU;
1155 }
1156 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001157 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001158 else {
1159 SU = pickNodeBidrectional(IsTopNode);
1160 }
1161 } while (SU->isScheduled);
1162
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001163 if (SU->isTopReady())
1164 Top.removeReady(SU);
1165 if (SU->isBottomReady())
1166 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00001167
1168 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1169 << " Scheduling Instruction in cycle "
1170 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1171 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001172 return SU;
1173}
1174
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001175/// Update the scheduler's state after scheduling a node. This is the same node
1176/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00001177/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001178void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001179 if (IsTopNode) {
1180 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001181 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001182 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001183 else {
1184 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001185 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001186 }
1187}
1188
Andrew Trick17d35e52012-03-14 04:00:41 +00001189/// Create the standard converging machine scheduler. This will be used as the
1190/// default scheduler if the target does not set a default.
1191static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001192 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001193 "-misched-topdown incompatible with -misched-bottomup");
1194 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +00001195}
1196static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00001197ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1198 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00001199
1200//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00001201// Machine Instruction Shuffler for Correctness Testing
1202//===----------------------------------------------------------------------===//
1203
Andrew Trick96f678f2012-01-13 06:30:30 +00001204#ifndef NDEBUG
1205namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001206/// Apply a less-than relation on the node order, which corresponds to the
1207/// instruction order prior to scheduling. IsReverse implements greater-than.
1208template<bool IsReverse>
1209struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001210 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00001211 if (IsReverse)
1212 return A->NodeNum > B->NodeNum;
1213 else
1214 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001215 }
1216};
1217
Andrew Trick96f678f2012-01-13 06:30:30 +00001218/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00001219class InstructionShuffler : public MachineSchedStrategy {
1220 bool IsAlternating;
1221 bool IsTopDown;
1222
1223 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
1224 // gives nodes with a higher number higher priority causing the latest
1225 // instructions to be scheduled first.
1226 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
1227 TopQ;
1228 // When scheduling bottom-up, use greater-than as the queue priority.
1229 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
1230 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00001231public:
Andrew Trick17d35e52012-03-14 04:00:41 +00001232 InstructionShuffler(bool alternate, bool topdown)
1233 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00001234
Andrew Trick17d35e52012-03-14 04:00:41 +00001235 virtual void initialize(ScheduleDAGMI *) {
1236 TopQ.clear();
1237 BottomQ.clear();
1238 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001239
Andrew Trick17d35e52012-03-14 04:00:41 +00001240 /// Implement MachineSchedStrategy interface.
1241 /// -----------------------------------------
1242
1243 virtual SUnit *pickNode(bool &IsTopNode) {
1244 SUnit *SU;
1245 if (IsTopDown) {
1246 do {
1247 if (TopQ.empty()) return NULL;
1248 SU = TopQ.top();
1249 TopQ.pop();
1250 } while (SU->isScheduled);
1251 IsTopNode = true;
1252 }
1253 else {
1254 do {
1255 if (BottomQ.empty()) return NULL;
1256 SU = BottomQ.top();
1257 BottomQ.pop();
1258 } while (SU->isScheduled);
1259 IsTopNode = false;
1260 }
1261 if (IsAlternating)
1262 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001263 return SU;
1264 }
1265
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001266 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
1267
Andrew Trick17d35e52012-03-14 04:00:41 +00001268 virtual void releaseTopNode(SUnit *SU) {
1269 TopQ.push(SU);
1270 }
1271 virtual void releaseBottomNode(SUnit *SU) {
1272 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00001273 }
1274};
1275} // namespace
1276
Andrew Trickc174eaf2012-03-08 01:41:12 +00001277static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00001278 bool Alternate = !ForceTopDown && !ForceBottomUp;
1279 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001280 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001281 "-misched-topdown incompatible with -misched-bottomup");
1282 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00001283}
Andrew Trick17d35e52012-03-14 04:00:41 +00001284static MachineSchedRegistry ShufflerRegistry(
1285 "shuffle", "Shuffle machine instructions alternating directions",
1286 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00001287#endif // !NDEBUG