blob: 71cc072d47e4664358d02f683e911ceaeb9f746d [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 Trick1e94e982012-10-15 18:02:27 +000021#include "llvm/CodeGen/ScheduleDAGILP.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000022#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trickb7e02892012-06-05 21:11:27 +000023#include "llvm/Analysis/AliasAnalysis.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 Trick78e5efe2012-09-11 00:39:15 +000035namespace llvm {
36cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
40}
Andrew Trick17d35e52012-03-14 04:00:41 +000041
Andrew Trick0df7f882012-03-07 00:18:25 +000042#ifndef NDEBUG
43static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
44 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000045
46static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
47 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000048#else
49static bool ViewMISchedDAGs = false;
50#endif // NDEBUG
51
Andrew Trick3b87f622012-11-07 07:05:09 +000052// Threshold to very roughly model an out-of-order processor's instruction
53// buffers. If the actual value of this threshold matters much in practice, then
54// it can be specified by the machine model. For now, it's an experimental
55// tuning knob to determine when and if it matters.
56static cl::opt<unsigned> ILPWindow("ilp-window", cl::Hidden,
57 cl::desc("Allow expected latency to exceed the critical path by N cycles "
58 "before attempting to balance ILP"),
59 cl::init(10U));
60
Andrew Trick5edf2f02012-01-14 02:17:06 +000061//===----------------------------------------------------------------------===//
62// Machine Instruction Scheduling Pass and Registry
63//===----------------------------------------------------------------------===//
64
Andrew Trick86b7e2a2012-04-24 20:36:19 +000065MachineSchedContext::MachineSchedContext():
66 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
67 RegClassInfo = new RegisterClassInfo();
68}
69
70MachineSchedContext::~MachineSchedContext() {
71 delete RegClassInfo;
72}
73
Andrew Trick96f678f2012-01-13 06:30:30 +000074namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000075/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000076class MachineScheduler : public MachineSchedContext,
77 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000078public:
Andrew Trick42b7a712012-01-17 06:55:03 +000079 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000080
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
82
83 virtual void releaseMemory() {}
84
85 virtual bool runOnMachineFunction(MachineFunction&);
86
87 virtual void print(raw_ostream &O, const Module* = 0) const;
88
89 static char ID; // Class identification, replacement for typeinfo
90};
91} // namespace
92
Andrew Trick42b7a712012-01-17 06:55:03 +000093char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000094
Andrew Trick42b7a712012-01-17 06:55:03 +000095char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000096
Andrew Trick42b7a712012-01-17 06:55:03 +000097INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000098 "Machine Instruction Scheduler", false, false)
99INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
100INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
101INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000102INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000103 "Machine Instruction Scheduler", false, false)
104
Andrew Trick42b7a712012-01-17 06:55:03 +0000105MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000106: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000107 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000108}
109
Andrew Trick42b7a712012-01-17 06:55:03 +0000110void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000111 AU.setPreservesCFG();
112 AU.addRequiredID(MachineDominatorsID);
113 AU.addRequired<MachineLoopInfo>();
114 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000115 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000116 AU.addRequired<SlotIndexes>();
117 AU.addPreserved<SlotIndexes>();
118 AU.addRequired<LiveIntervals>();
119 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000120 MachineFunctionPass::getAnalysisUsage(AU);
121}
122
Andrew Trick96f678f2012-01-13 06:30:30 +0000123MachinePassRegistry MachineSchedRegistry::Registry;
124
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000125/// A dummy default scheduler factory indicates whether the scheduler
126/// is overridden on the command line.
127static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
128 return 0;
129}
Andrew Trick96f678f2012-01-13 06:30:30 +0000130
131/// MachineSchedOpt allows command line selection of the scheduler.
132static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
133 RegisterPassParser<MachineSchedRegistry> >
134MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000135 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000136 cl::desc("Machine instruction scheduler to use"));
137
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000138static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000139DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000140 useDefaultMachineSched);
141
Andrew Trick17d35e52012-03-14 04:00:41 +0000142/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000143/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000144static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000145
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000146
147/// Decrement this iterator until reaching the top or a non-debug instr.
148static MachineBasicBlock::iterator
149priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
150 assert(I != Beg && "reached the top of the region, cannot decrement");
151 while (--I != Beg) {
152 if (!I->isDebugValue())
153 break;
154 }
155 return I;
156}
157
158/// If this iterator is a debug value, increment until reaching the End or a
159/// non-debug instruction.
160static MachineBasicBlock::iterator
161nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000162 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000163 if (!I->isDebugValue())
164 break;
165 }
166 return I;
167}
168
Andrew Trickcb058d52012-03-14 04:00:38 +0000169/// Top-level MachineScheduler pass driver.
170///
171/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000172/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
173/// consistent with the DAG builder, which traverses the interior of the
174/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000175///
176/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000177/// simplifying the DAG builder's support for "special" target instructions.
178/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000179/// scheduling boundaries, for example to bundle the boudary instructions
180/// without reordering them. This creates complexity, because the target
181/// scheduler must update the RegionBegin and RegionEnd positions cached by
182/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
183/// design would be to split blocks at scheduling boundaries, but LLVM has a
184/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000185bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000186 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
187
Andrew Trick96f678f2012-01-13 06:30:30 +0000188 // Initialize the context of the pass.
189 MF = &mf;
190 MLI = &getAnalysis<MachineLoopInfo>();
191 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000192 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000193 AA = &getAnalysis<AliasAnalysis>();
194
Lang Hames907cc8f2012-01-27 22:36:19 +0000195 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000196 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000197
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000198 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000199
Andrew Trick96f678f2012-01-13 06:30:30 +0000200 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000201 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
202 if (Ctor == useDefaultMachineSched) {
203 // Get the default scheduler set by the target.
204 Ctor = MachineSchedRegistry::getDefault();
205 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000206 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000207 MachineSchedRegistry::setDefault(Ctor);
208 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000209 }
210 // Instantiate the selected scheduler.
211 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
212
213 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000214 //
215 // TODO: Visit blocks in global postorder or postorder within the bottom-up
216 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000217 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
218 MBB != MBBEnd; ++MBB) {
219
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000220 Scheduler->startBlock(MBB);
221
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000222 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000223 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000224 // boundary at the bottom of the region. The DAG does not include RegionEnd,
225 // but the region does (i.e. the next RegionEnd is above the previous
226 // RegionBegin). If the current block has no terminator then RegionEnd ==
227 // MBB->end() for the bottom region.
228 //
229 // The Scheduler may insert instructions during either schedule() or
230 // exitRegion(), even for empty regions. So the local iterators 'I' and
231 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000232 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000233 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000234 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000235
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000236 // Avoid decrementing RegionEnd for blocks with no terminator.
237 if (RegionEnd != MBB->end()
238 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
239 --RegionEnd;
240 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000241 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000242 }
243
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000244 // The next region starts above the previous region. Look backward in the
245 // instruction stream until we find the nearest boundary.
246 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000247 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000248 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
249 break;
250 }
Andrew Trick47c14452012-03-07 05:21:52 +0000251 // Notify the scheduler of the region, even if we may skip scheduling
252 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000253 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000254
255 // Skip empty scheduling regions (0 or 1 schedulable instructions).
256 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000257 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000258 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000259 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000260 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000261 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000262 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000263 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000264 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
265 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
266 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000267 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000268
Andrew Trickd24da972012-03-09 03:46:42 +0000269 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000270 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000271 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000272
273 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000274 Scheduler->exitRegion();
275
276 // Scheduling has invalidated the current iterator 'I'. Ask the
277 // scheduler for the top of it's scheduled region.
278 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000279 }
Andrew Trick22764532012-11-06 07:10:34 +0000280 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000281 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000282 }
Andrew Trick830da402012-04-01 07:24:23 +0000283 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000284 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000285 return true;
286}
287
Andrew Trick42b7a712012-01-17 06:55:03 +0000288void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000289 // unimplemented
290}
291
Manman Renb720be62012-09-11 22:23:19 +0000292#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000293void ReadyQueue::dump() {
294 dbgs() << Name << ": ";
295 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
296 dbgs() << Queue[i]->NodeNum << " ";
297 dbgs() << "\n";
298}
299#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000300
301//===----------------------------------------------------------------------===//
302// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
303// preservation.
304//===----------------------------------------------------------------------===//
305
Andrew Trickc174eaf2012-03-08 01:41:12 +0000306/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
307/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000308///
309/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000310void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000311 SUnit *SuccSU = SuccEdge->getSUnit();
312
Andrew Trickae692f22012-11-12 19:28:57 +0000313 if (SuccEdge->isWeak()) {
314 --SuccSU->WeakPredsLeft;
315 return;
316 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000317#ifndef NDEBUG
318 if (SuccSU->NumPredsLeft == 0) {
319 dbgs() << "*** Scheduling failed! ***\n";
320 SuccSU->dump(this);
321 dbgs() << " has been released too many times!\n";
322 llvm_unreachable(0);
323 }
324#endif
325 --SuccSU->NumPredsLeft;
326 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000327 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000328}
329
330/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000331void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000332 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
333 I != E; ++I) {
334 releaseSucc(SU, &*I);
335 }
336}
337
Andrew Trick17d35e52012-03-14 04:00:41 +0000338/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
339/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000340///
341/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000342void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
343 SUnit *PredSU = PredEdge->getSUnit();
344
Andrew Trickae692f22012-11-12 19:28:57 +0000345 if (PredEdge->isWeak()) {
346 --PredSU->WeakSuccsLeft;
347 return;
348 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000349#ifndef NDEBUG
350 if (PredSU->NumSuccsLeft == 0) {
351 dbgs() << "*** Scheduling failed! ***\n";
352 PredSU->dump(this);
353 dbgs() << " has been released too many times!\n";
354 llvm_unreachable(0);
355 }
356#endif
357 --PredSU->NumSuccsLeft;
358 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
359 SchedImpl->releaseBottomNode(PredSU);
360}
361
362/// releasePredecessors - Call releasePred on each of SU's predecessors.
363void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
364 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
365 I != E; ++I) {
366 releasePred(SU, &*I);
367 }
368}
369
370void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
371 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000372 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000373 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000374 ++RegionBegin;
375
376 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000377 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000378
379 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000380 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000381
382 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000383 if (RegionBegin == InsertPos)
384 RegionBegin = MI;
385}
386
Andrew Trick0b0d8992012-03-21 04:12:07 +0000387bool ScheduleDAGMI::checkSchedLimit() {
388#ifndef NDEBUG
389 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
390 CurrentTop = CurrentBottom;
391 return false;
392 }
393 ++NumInstrsScheduled;
394#endif
395 return true;
396}
397
Andrew Trick006e1ab2012-04-24 17:56:43 +0000398/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
399/// crossing a scheduling boundary. [begin, end) includes all instructions in
400/// the region, including the boundary itself and single-instruction regions
401/// that don't get scheduled.
402void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
403 MachineBasicBlock::iterator begin,
404 MachineBasicBlock::iterator end,
405 unsigned endcount)
406{
407 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000408
409 // For convenience remember the end of the liveness region.
410 LiveRegionEnd =
411 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
412}
413
414// Setup the register pressure trackers for the top scheduled top and bottom
415// scheduled regions.
416void ScheduleDAGMI::initRegPressure() {
417 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
418 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
419
420 // Close the RPTracker to finalize live ins.
421 RPTracker.closeRegion();
422
Andrew Trickbb0a2422012-05-24 22:11:14 +0000423 DEBUG(RPTracker.getPressure().dump(TRI));
424
Andrew Trick7f8ab782012-05-10 21:06:10 +0000425 // Initialize the live ins and live outs.
426 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
427 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
428
429 // Close one end of the tracker so we can call
430 // getMaxUpward/DownwardPressureDelta before advancing across any
431 // instructions. This converts currently live regs into live ins/outs.
432 TopRPTracker.closeTop();
433 BotRPTracker.closeBottom();
434
435 // Account for liveness generated by the region boundary.
436 if (LiveRegionEnd != RegionEnd)
437 BotRPTracker.recede();
438
439 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000440
441 // Cache the list of excess pressure sets in this region. This will also track
442 // the max pressure in the scheduled code for these sets.
443 RegionCriticalPSets.clear();
444 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
445 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
446 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000447 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
448 << "Limit " << Limit
449 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000450 if (RegionPressure[i] > Limit)
451 RegionCriticalPSets.push_back(PressureElement(i, 0));
452 }
453 DEBUG(dbgs() << "Excess PSets: ";
454 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
455 dbgs() << TRI->getRegPressureSetName(
456 RegionCriticalPSets[i].PSetID) << " ";
457 dbgs() << "\n");
458}
459
460// FIXME: When the pressure tracker deals in pressure differences then we won't
461// iterate over all RegionCriticalPSets[i].
462void ScheduleDAGMI::
463updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
464 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
465 unsigned ID = RegionCriticalPSets[i].PSetID;
466 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
467 if ((int)NewMaxPressure[ID] > MaxUnits)
468 MaxUnits = NewMaxPressure[ID];
469 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000470}
471
Andrew Trick17d35e52012-03-14 04:00:41 +0000472/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000473/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
474/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000475///
476/// This is a skeletal driver, with all the functionality pushed into helpers,
477/// so that it can be easilly extended by experimental schedulers. Generally,
478/// implementing MachineSchedStrategy should be sufficient to implement a new
479/// scheduling algorithm. However, if a scheduler further subclasses
480/// ScheduleDAGMI then it will want to override this virtual method in order to
481/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000482void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000483 buildDAGWithRegPressure();
484
Andrew Trickd039b382012-09-14 17:22:42 +0000485 postprocessDAG();
486
Andrew Trick78e5efe2012-09-11 00:39:15 +0000487 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
488 SUnits[su].dumpAll(this));
489
490 if (ViewMISchedDAGs) viewGraph();
491
492 initQueues();
493
494 bool IsTopNode = false;
495 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000496 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000497 if (!checkSchedLimit())
498 break;
499
500 scheduleMI(SU, IsTopNode);
501
502 updateQueues(SU, IsTopNode);
503 }
504 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
505
506 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000507
508 DEBUG({
509 unsigned BBNum = top()->getParent()->getNumber();
510 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
511 dumpSchedule();
512 dbgs() << '\n';
513 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000514}
515
516/// Build the DAG and setup three register pressure trackers.
517void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000518 // Initialize the register pressure tracker used by buildSchedGraph.
519 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000520
Andrew Trick7f8ab782012-05-10 21:06:10 +0000521 // Account for liveness generate by the region boundary.
522 if (LiveRegionEnd != RegionEnd)
523 RPTracker.recede();
524
525 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000526 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000527 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000528
Andrew Trick7f8ab782012-05-10 21:06:10 +0000529 // Initialize top/bottom trackers after computing region pressure.
530 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000531}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000532
Andrew Trickd039b382012-09-14 17:22:42 +0000533/// Apply each ScheduleDAGMutation step in order.
534void ScheduleDAGMI::postprocessDAG() {
535 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
536 Mutations[i]->apply(this);
537 }
538}
539
Andrew Trick1e94e982012-10-15 18:02:27 +0000540// Release all DAG roots for scheduling.
Andrew Trickae692f22012-11-12 19:28:57 +0000541//
542// Nodes with unreleased weak edges can still be roots.
Andrew Trick1e94e982012-10-15 18:02:27 +0000543void ScheduleDAGMI::releaseRoots() {
544 SmallVector<SUnit*, 16> BotRoots;
545
546 for (std::vector<SUnit>::iterator
547 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000548 SUnit *SU = &(*I);
Andrew Trick1e94e982012-10-15 18:02:27 +0000549 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickae692f22012-11-12 19:28:57 +0000550 if (!I->NumPredsLeft && SU != &EntrySU)
551 SchedImpl->releaseTopNode(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000552 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trickae692f22012-11-12 19:28:57 +0000553 if (!I->NumSuccsLeft && SU != &ExitSU)
554 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000555 }
556 // Release bottom roots in reverse order so the higher priority nodes appear
557 // first. This is more natural and slightly more efficient.
558 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
559 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
560 SchedImpl->releaseBottomNode(*I);
561}
562
Andrew Trick78e5efe2012-09-11 00:39:15 +0000563/// Identify DAG roots and setup scheduler queues.
564void ScheduleDAGMI::initQueues() {
Andrew Trick1e94e982012-10-15 18:02:27 +0000565
Andrew Trick78e5efe2012-09-11 00:39:15 +0000566 // Initialize the strategy before modifying the DAG.
Andrew Trick17d35e52012-03-14 04:00:41 +0000567 SchedImpl->initialize(this);
568
Andrew Trickae692f22012-11-12 19:28:57 +0000569 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
570 releaseRoots();
571
Andrew Trickc174eaf2012-03-08 01:41:12 +0000572 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000573 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000574
Andrew Trick1e94e982012-10-15 18:02:27 +0000575 SchedImpl->registerRoots();
576
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000577 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000578 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000579}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000580
Andrew Trick78e5efe2012-09-11 00:39:15 +0000581/// Move an instruction and update register pressure.
582void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
583 // Move the instruction to its new location in the instruction stream.
584 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000585
Andrew Trick78e5efe2012-09-11 00:39:15 +0000586 if (IsTopNode) {
587 assert(SU->isTopReady() && "node still has unscheduled dependencies");
588 if (&*CurrentTop == MI)
589 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000590 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000591 moveInstruction(MI, CurrentTop);
592 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000593 }
Andrew Trick000b2502012-04-24 18:04:37 +0000594
Andrew Trick78e5efe2012-09-11 00:39:15 +0000595 // Update top scheduled pressure.
596 TopRPTracker.advance();
597 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
598 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
599 }
600 else {
601 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
602 MachineBasicBlock::iterator priorII =
603 priorNonDebug(CurrentBottom, CurrentTop);
604 if (&*priorII == MI)
605 CurrentBottom = priorII;
606 else {
607 if (&*CurrentTop == MI) {
608 CurrentTop = nextIfDebug(++CurrentTop, priorII);
609 TopRPTracker.setPos(CurrentTop);
610 }
611 moveInstruction(MI, CurrentBottom);
612 CurrentBottom = MI;
613 }
614 // Update bottom scheduled pressure.
615 BotRPTracker.recede();
616 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
617 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
618 }
619}
620
621/// Update scheduler queues after scheduling an instruction.
622void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
623 // Release dependent instructions for scheduling.
624 if (IsTopNode)
625 releaseSuccessors(SU);
626 else
627 releasePredecessors(SU);
628
629 SU->isScheduled = true;
630
631 // Notify the scheduling strategy after updating the DAG.
632 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000633}
634
635/// Reinsert any remaining debug_values, just like the PostRA scheduler.
636void ScheduleDAGMI::placeDebugValues() {
637 // If first instruction was a DBG_VALUE then put it back.
638 if (FirstDbgValue) {
639 BB->splice(RegionBegin, BB, FirstDbgValue);
640 RegionBegin = FirstDbgValue;
641 }
642
643 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
644 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
645 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
646 MachineInstr *DbgValue = P.first;
647 MachineBasicBlock::iterator OrigPrevMI = P.second;
648 BB->splice(++OrigPrevMI, BB, DbgValue);
649 if (OrigPrevMI == llvm::prior(RegionEnd))
650 RegionEnd = DbgValue;
651 }
652 DbgValues.clear();
653 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000654}
655
Andrew Trick3b87f622012-11-07 07:05:09 +0000656#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
657void ScheduleDAGMI::dumpSchedule() const {
658 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
659 if (SUnit *SU = getSUnit(&(*MI)))
660 SU->dump(this);
661 else
662 dbgs() << "Missing SUnit\n";
663 }
664}
665#endif
666
Andrew Trickc174eaf2012-03-08 01:41:12 +0000667//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000668// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000669//===----------------------------------------------------------------------===//
670
671namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000672/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
673/// the schedule.
674class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000675public:
676 /// Represent the type of SchedCandidate found within a single queue.
677 /// pickNodeBidirectional depends on these listed by decreasing priority.
678 enum CandReason {
679 NoCand, SingleExcess, SingleCritical, ResourceReduce, ResourceDemand,
680 BotHeightReduce, BotPathReduce, TopDepthReduce, TopPathReduce,
681 SingleMax, MultiPressure, NextDefUse, NodeOrder};
682
683#ifndef NDEBUG
684 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
685#endif
686
687 /// Policy for scheduling the next instruction in the candidate's zone.
688 struct CandPolicy {
689 bool ReduceLatency;
690 unsigned ReduceResIdx;
691 unsigned DemandResIdx;
692
693 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
694 };
695
696 /// Status of an instruction's critical resource consumption.
697 struct SchedResourceDelta {
698 // Count critical resources in the scheduled region required by SU.
699 unsigned CritResources;
700
701 // Count critical resources from another region consumed by SU.
702 unsigned DemandedResources;
703
704 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
705
706 bool operator==(const SchedResourceDelta &RHS) const {
707 return CritResources == RHS.CritResources
708 && DemandedResources == RHS.DemandedResources;
709 }
710 bool operator!=(const SchedResourceDelta &RHS) const {
711 return !operator==(RHS);
712 }
713 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000714
715 /// Store the state used by ConvergingScheduler heuristics, required for the
716 /// lifetime of one invocation of pickNode().
717 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000718 CandPolicy Policy;
719
Andrew Trick7196a8f2012-05-10 21:06:16 +0000720 // The best SUnit candidate.
721 SUnit *SU;
722
Andrew Trick3b87f622012-11-07 07:05:09 +0000723 // The reason for this candidate.
724 CandReason Reason;
725
Andrew Trick7196a8f2012-05-10 21:06:16 +0000726 // Register pressure values for the best candidate.
727 RegPressureDelta RPDelta;
728
Andrew Trick3b87f622012-11-07 07:05:09 +0000729 // Critical resource consumption of the best candidate.
730 SchedResourceDelta ResDelta;
731
732 SchedCandidate(const CandPolicy &policy)
733 : Policy(policy), SU(NULL), Reason(NoCand) {}
734
735 bool isValid() const { return SU; }
736
737 // Copy the status of another candidate without changing policy.
738 void setBest(SchedCandidate &Best) {
739 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
740 SU = Best.SU;
741 Reason = Best.Reason;
742 RPDelta = Best.RPDelta;
743 ResDelta = Best.ResDelta;
744 }
745
746 void initResourceDelta(const ScheduleDAGMI *DAG,
747 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000748 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000749
750 /// Summarize the unscheduled region.
751 struct SchedRemainder {
752 // Critical path through the DAG in expected latency.
753 unsigned CriticalPath;
754
755 // Unscheduled resources
756 SmallVector<unsigned, 16> RemainingCounts;
757 // Critical resource for the unscheduled zone.
758 unsigned CritResIdx;
759 // Number of micro-ops left to schedule.
760 unsigned RemainingMicroOps;
761 // Is the unscheduled zone resource limited.
762 bool IsResourceLimited;
763
764 unsigned MaxRemainingCount;
765
766 void reset() {
767 CriticalPath = 0;
768 RemainingCounts.clear();
769 CritResIdx = 0;
770 RemainingMicroOps = 0;
771 IsResourceLimited = false;
772 MaxRemainingCount = 0;
773 }
774
775 SchedRemainder() { reset(); }
776
777 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
778 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000779
Andrew Trickf3234242012-05-24 22:11:12 +0000780 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +0000781 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +0000782 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000783 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000784 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000785 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +0000786 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000787
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000788 ReadyQueue Available;
789 ReadyQueue Pending;
790 bool CheckPending;
791
Andrew Trick3b87f622012-11-07 07:05:09 +0000792 // For heuristics, keep a list of the nodes that immediately depend on the
793 // most recently scheduled node.
794 SmallPtrSet<const SUnit*, 8> NextSUs;
795
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000796 ScheduleHazardRecognizer *HazardRec;
797
798 unsigned CurrCycle;
799 unsigned IssueCount;
800
801 /// MinReadyCycle - Cycle of the soonest available instruction.
802 unsigned MinReadyCycle;
803
Andrew Trick3b87f622012-11-07 07:05:09 +0000804 // The expected latency of the critical path in this scheduled zone.
805 unsigned ExpectedLatency;
806
807 // Resources used in the scheduled zone beyond this boundary.
808 SmallVector<unsigned, 16> ResourceCounts;
809
810 // Cache the critical resources ID in this scheduled zone.
811 unsigned CritResIdx;
812
813 // Is the scheduled region resource limited vs. latency limited.
814 bool IsResourceLimited;
815
816 unsigned ExpectedCount;
817
818 // Policy flag: attempt to find ILP until expected latency is covered.
819 bool ShouldIncreaseILP;
820
821#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +0000822 // Remember the greatest min operand latency.
823 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +0000824#endif
825
826 void reset() {
827 Available.clear();
828 Pending.clear();
829 CheckPending = false;
830 NextSUs.clear();
831 HazardRec = 0;
832 CurrCycle = 0;
833 IssueCount = 0;
834 MinReadyCycle = UINT_MAX;
835 ExpectedLatency = 0;
836 ResourceCounts.resize(1);
837 assert(!ResourceCounts[0] && "nonzero count for bad resource");
838 CritResIdx = 0;
839 IsResourceLimited = false;
840 ExpectedCount = 0;
841 ShouldIncreaseILP = false;
842#ifndef NDEBUG
843 MaxMinLatency = 0;
844#endif
845 // Reserve a zero-count for invalid CritResIdx.
846 ResourceCounts.resize(1);
847 }
Andrew Trickb7e02892012-06-05 21:11:27 +0000848
Andrew Trickf3234242012-05-24 22:11:12 +0000849 /// Pending queues extend the ready queues with the same ID and the
850 /// PendingFlag set.
851 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +0000852 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
853 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
854 reset();
855 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000856
857 ~SchedBoundary() { delete HazardRec; }
858
Andrew Trick3b87f622012-11-07 07:05:09 +0000859 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
860 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +0000861
Andrew Trickf3234242012-05-24 22:11:12 +0000862 bool isTop() const {
863 return Available.getID() == ConvergingScheduler::TopQID;
864 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000865
Andrew Trick3b87f622012-11-07 07:05:09 +0000866 unsigned getUnscheduledLatency(SUnit *SU) const {
867 if (isTop())
868 return SU->getHeight();
869 return SU->getDepth();
870 }
871
872 unsigned getCriticalCount() const {
873 return ResourceCounts[CritResIdx];
874 }
875
Andrew Trick5559ffa2012-06-29 03:23:24 +0000876 bool checkHazard(SUnit *SU);
877
Andrew Trick3b87f622012-11-07 07:05:09 +0000878 void checkILPPolicy();
879
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000880 void releaseNode(SUnit *SU, unsigned ReadyCycle);
881
882 void bumpCycle();
883
Andrew Trick3b87f622012-11-07 07:05:09 +0000884 void countResource(unsigned PIdx, unsigned Cycles);
885
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000886 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +0000887
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000888 void releasePending();
889
890 void removeReady(SUnit *SU);
891
892 SUnit *pickOnlyChoice();
893 };
894
Andrew Trick3b87f622012-11-07 07:05:09 +0000895private:
Andrew Trick17d35e52012-03-14 04:00:41 +0000896 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000897 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000898 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +0000899
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000900 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +0000901 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000902 SchedBoundary Top;
903 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +0000904
905public:
Andrew Trickf3234242012-05-24 22:11:12 +0000906 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +0000907 enum {
908 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +0000909 BotQID = 2,
910 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +0000911 };
912
Andrew Trickf3234242012-05-24 22:11:12 +0000913 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +0000914 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000915
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000916 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +0000917
Andrew Trick7196a8f2012-05-10 21:06:16 +0000918 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +0000919
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000920 virtual void schedNode(SUnit *SU, bool IsTopNode);
921
922 virtual void releaseTopNode(SUnit *SU);
923
924 virtual void releaseBottomNode(SUnit *SU);
925
Andrew Trick3b87f622012-11-07 07:05:09 +0000926 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000927
Andrew Trick3b87f622012-11-07 07:05:09 +0000928protected:
929 void balanceZones(
930 ConvergingScheduler::SchedBoundary &CriticalZone,
931 ConvergingScheduler::SchedCandidate &CriticalCand,
932 ConvergingScheduler::SchedBoundary &OppositeZone,
933 ConvergingScheduler::SchedCandidate &OppositeCand);
934
935 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
936 ConvergingScheduler::SchedCandidate &BotCand);
937
938 void tryCandidate(SchedCandidate &Cand,
939 SchedCandidate &TryCand,
940 SchedBoundary &Zone,
941 const RegPressureTracker &RPTracker,
942 RegPressureTracker &TempTracker);
943
944 SUnit *pickNodeBidirectional(bool &IsTopNode);
945
946 void pickNodeFromQueue(SchedBoundary &Zone,
947 const RegPressureTracker &RPTracker,
948 SchedCandidate &Candidate);
949
Andrew Trick28ebc892012-05-10 21:06:19 +0000950#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +0000951 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +0000952#endif
Andrew Trick42b7a712012-01-17 06:55:03 +0000953};
954} // namespace
955
Andrew Trick3b87f622012-11-07 07:05:09 +0000956void ConvergingScheduler::SchedRemainder::
957init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
958 reset();
959 if (!SchedModel->hasInstrSchedModel())
960 return;
961 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
962 for (std::vector<SUnit>::iterator
963 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
964 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
965 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
966 for (TargetSchedModel::ProcResIter
967 PI = SchedModel->getWriteProcResBegin(SC),
968 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
969 unsigned PIdx = PI->ProcResourceIdx;
970 unsigned Factor = SchedModel->getResourceFactor(PIdx);
971 RemainingCounts[PIdx] += (Factor * PI->Cycles);
972 }
973 }
974}
975
976void ConvergingScheduler::SchedBoundary::
977init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
978 reset();
979 DAG = dag;
980 SchedModel = smodel;
981 Rem = rem;
982 if (SchedModel->hasInstrSchedModel())
983 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
984}
985
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000986void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
987 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000988 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000989 TRI = DAG->TRI;
Andrew Trick3b87f622012-11-07 07:05:09 +0000990 Rem.init(DAG, SchedModel);
991 Top.init(DAG, SchedModel, &Rem);
992 Bot.init(DAG, SchedModel, &Rem);
993
994 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000995
Andrew Trick412cd2f2012-10-10 05:43:09 +0000996 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
997 // are disabled, then these HazardRecs will be disabled.
998 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000999 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001000 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1001 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1002
1003 assert((!ForceTopDown || !ForceBottomUp) &&
1004 "-misched-topdown incompatible with -misched-bottomup");
1005}
1006
1007void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001008 if (SU->isScheduled)
1009 return;
1010
1011 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1012 I != E; ++I) {
1013 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001014 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001015#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001016 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001017#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001018 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1019 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001020 }
1021 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001022}
1023
1024void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001025 if (SU->isScheduled)
1026 return;
1027
1028 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1029
1030 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1031 I != E; ++I) {
1032 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001033 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001034#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001035 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001036#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001037 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1038 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001039 }
1040 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001041}
1042
Andrew Trick3b87f622012-11-07 07:05:09 +00001043void ConvergingScheduler::registerRoots() {
1044 Rem.CriticalPath = DAG->ExitSU.getDepth();
1045 // Some roots may not feed into ExitSU. Check all of them in case.
1046 for (std::vector<SUnit*>::const_iterator
1047 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1048 if ((*I)->getDepth() > Rem.CriticalPath)
1049 Rem.CriticalPath = (*I)->getDepth();
1050 }
1051 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1052}
1053
Andrew Trick5559ffa2012-06-29 03:23:24 +00001054/// Does this SU have a hazard within the current instruction group.
1055///
1056/// The scheduler supports two modes of hazard recognition. The first is the
1057/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1058/// supports highly complicated in-order reservation tables
1059/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1060///
1061/// The second is a streamlined mechanism that checks for hazards based on
1062/// simple counters that the scheduler itself maintains. It explicitly checks
1063/// for instruction dispatch limitations, including the number of micro-ops that
1064/// can dispatch per cycle.
1065///
1066/// TODO: Also check whether the SU must start a new group.
1067bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1068 if (HazardRec->isEnabled())
1069 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1070
Andrew Trick412cd2f2012-10-10 05:43:09 +00001071 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001072 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1073 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1074 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001075 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001076 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001077 return false;
1078}
1079
Andrew Trick3b87f622012-11-07 07:05:09 +00001080/// If expected latency is covered, disable ILP policy.
1081void ConvergingScheduler::SchedBoundary::checkILPPolicy() {
1082 if (ShouldIncreaseILP
1083 && (IsResourceLimited || ExpectedLatency <= CurrCycle)) {
1084 ShouldIncreaseILP = false;
1085 DEBUG(dbgs() << "Disable ILP: " << Available.getName() << '\n');
1086 }
1087}
1088
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001089void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1090 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001091
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001092 if (ReadyCycle < MinReadyCycle)
1093 MinReadyCycle = ReadyCycle;
1094
1095 // Check for interlocks first. For the purpose of other heuristics, an
1096 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001097 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001098 Pending.push(SU);
1099 else
1100 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001101
1102 // Record this node as an immediate dependent of the scheduled node.
1103 NextSUs.insert(SU);
1104
1105 // If CriticalPath has been computed, then check if the unscheduled nodes
1106 // exceed the ILP window. Before registerRoots, CriticalPath==0.
1107 if (Rem->CriticalPath && (ExpectedLatency + getUnscheduledLatency(SU)
1108 > Rem->CriticalPath + ILPWindow)) {
1109 ShouldIncreaseILP = true;
1110 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << " "
1111 << ExpectedLatency << " + " << getUnscheduledLatency(SU) << '\n');
1112 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001113}
1114
1115/// Move the boundary of scheduled code by one cycle.
1116void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001117 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001118 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001119
Andrew Trick3b87f622012-11-07 07:05:09 +00001120 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001121 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001122 if (MinReadyCycle > NextCycle) {
1123 IssueCount = 0;
1124 NextCycle = MinReadyCycle;
1125 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001126
1127 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001128 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001129 CurrCycle = NextCycle;
1130 }
1131 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001132 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001133 for (; CurrCycle != NextCycle; ++CurrCycle) {
1134 if (isTop())
1135 HazardRec->AdvanceCycle();
1136 else
1137 HazardRec->RecedeCycle();
1138 }
1139 }
1140 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001141 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001142
Andrew Trick3b87f622012-11-07 07:05:09 +00001143 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001144 << CurrCycle << '\n');
1145}
1146
Andrew Trick3b87f622012-11-07 07:05:09 +00001147/// Add the given processor resource to this scheduled zone.
1148void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1149 unsigned Cycles) {
1150 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1151 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1152 << " +(" << Cycles << "x" << Factor
1153 << ") / " << SchedModel->getLatencyFactor() << '\n');
1154
1155 unsigned Count = Factor * Cycles;
1156 ResourceCounts[PIdx] += Count;
1157 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1158 Rem->RemainingCounts[PIdx] -= Count;
1159
1160 // Reset MaxRemainingCount for sanity.
1161 Rem->MaxRemainingCount = 0;
1162
1163 // Check if this resource exceeds the current critical resource by a full
1164 // cycle. If so, it becomes the critical resource.
1165 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1166 >= (int)SchedModel->getLatencyFactor()) {
1167 CritResIdx = PIdx;
1168 DEBUG(dbgs() << " *** Critical resource "
1169 << SchedModel->getProcResource(PIdx)->Name << " x"
1170 << ResourceCounts[PIdx] << '\n');
1171 }
1172}
1173
Andrew Trickb7e02892012-06-05 21:11:27 +00001174/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001175void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001176 // Update the reservation table.
1177 if (HazardRec->isEnabled()) {
1178 if (!isTop() && SU->isCall) {
1179 // Calls are scheduled with their preceding instructions. For bottom-up
1180 // scheduling, clear the pipeline state before emitting.
1181 HazardRec->Reset();
1182 }
1183 HazardRec->EmitInstruction(SU);
1184 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001185 // Update resource counts and critical resource.
1186 if (SchedModel->hasInstrSchedModel()) {
1187 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1188 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1189 for (TargetSchedModel::ProcResIter
1190 PI = SchedModel->getWriteProcResBegin(SC),
1191 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1192 countResource(PI->ProcResourceIdx, PI->Cycles);
1193 }
1194 }
1195 if (isTop()) {
1196 if (SU->getDepth() > ExpectedLatency)
1197 ExpectedLatency = SU->getDepth();
1198 }
1199 else {
1200 if (SU->getHeight() > ExpectedLatency)
1201 ExpectedLatency = SU->getHeight();
1202 }
1203
1204 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1205
Andrew Trick5559ffa2012-06-29 03:23:24 +00001206 // Check the instruction group dispatch limit.
1207 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001208 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001209
1210 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1211 // issue width. However, we commonly reach the maximum. In this case
1212 // opportunistically bump the cycle to avoid uselessly checking everything in
1213 // the readyQ. Furthermore, a single instruction may produce more than one
1214 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001215 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001216 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001217 bumpCycle();
1218 }
1219}
1220
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001221/// Release pending ready nodes in to the available queue. This makes them
1222/// visible to heuristics.
1223void ConvergingScheduler::SchedBoundary::releasePending() {
1224 // If the available queue is empty, it is safe to reset MinReadyCycle.
1225 if (Available.empty())
1226 MinReadyCycle = UINT_MAX;
1227
1228 // Check to see if any of the pending instructions are ready to issue. If
1229 // so, add them to the available queue.
1230 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1231 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001232 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001233
1234 if (ReadyCycle < MinReadyCycle)
1235 MinReadyCycle = ReadyCycle;
1236
1237 if (ReadyCycle > CurrCycle)
1238 continue;
1239
Andrew Trick5559ffa2012-06-29 03:23:24 +00001240 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001241 continue;
1242
1243 Available.push(SU);
1244 Pending.remove(Pending.begin()+i);
1245 --i; --e;
1246 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001247 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001248 CheckPending = false;
1249}
1250
1251/// Remove SU from the ready set for this boundary.
1252void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1253 if (Available.isInQueue(SU))
1254 Available.remove(Available.find(SU));
1255 else {
1256 assert(Pending.isInQueue(SU) && "bad ready count");
1257 Pending.remove(Pending.find(SU));
1258 }
1259}
1260
1261/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001262/// defer any nodes that now hit a hazard, and advance the cycle until at least
1263/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001264SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1265 if (CheckPending)
1266 releasePending();
1267
Andrew Trick3b87f622012-11-07 07:05:09 +00001268 if (IssueCount > 0) {
1269 // Defer any ready instrs that now have a hazard.
1270 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1271 if (checkHazard(*I)) {
1272 Pending.push(*I);
1273 I = Available.remove(I);
1274 continue;
1275 }
1276 ++I;
1277 }
1278 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001279 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001280 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1281 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001282 bumpCycle();
1283 releasePending();
1284 }
1285 if (Available.size() == 1)
1286 return *Available.begin();
1287 return NULL;
1288}
1289
Andrew Trick3b87f622012-11-07 07:05:09 +00001290/// Record the candidate policy for opposite zones with different critical
1291/// resources.
1292///
1293/// If the CriticalZone is latency limited, don't force a policy for the
1294/// candidates here. Instead, When releasing each candidate, releaseNode
1295/// compares the region's critical path to the candidate's height or depth and
1296/// the scheduled zone's expected latency then sets ShouldIncreaseILP.
1297void ConvergingScheduler::balanceZones(
1298 ConvergingScheduler::SchedBoundary &CriticalZone,
1299 ConvergingScheduler::SchedCandidate &CriticalCand,
1300 ConvergingScheduler::SchedBoundary &OppositeZone,
1301 ConvergingScheduler::SchedCandidate &OppositeCand) {
1302
1303 if (!CriticalZone.IsResourceLimited)
1304 return;
1305
1306 SchedRemainder *Rem = CriticalZone.Rem;
1307
1308 // If the critical zone is overconsuming a resource relative to the
1309 // remainder, try to reduce it.
1310 unsigned RemainingCritCount =
1311 Rem->RemainingCounts[CriticalZone.CritResIdx];
1312 if ((int)(Rem->MaxRemainingCount - RemainingCritCount)
1313 > (int)SchedModel->getLatencyFactor()) {
1314 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1315 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1316 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1317 << '\n');
1318 }
1319 // If the other zone is underconsuming a resource relative to the full zone,
1320 // try to increase it.
1321 unsigned OppositeCount =
1322 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1323 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1324 > (int)SchedModel->getLatencyFactor()) {
1325 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1326 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1327 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1328 << '\n');
1329 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001330}
Andrew Trick3b87f622012-11-07 07:05:09 +00001331
1332/// Determine if the scheduled zones exceed resource limits or critical path and
1333/// set each candidate's ReduceHeight policy accordingly.
1334void ConvergingScheduler::checkResourceLimits(
1335 ConvergingScheduler::SchedCandidate &TopCand,
1336 ConvergingScheduler::SchedCandidate &BotCand) {
1337
1338 Bot.checkILPPolicy();
1339 Top.checkILPPolicy();
1340 if (Bot.ShouldIncreaseILP)
1341 BotCand.Policy.ReduceLatency = true;
1342 if (Top.ShouldIncreaseILP)
1343 TopCand.Policy.ReduceLatency = true;
1344
1345 // Handle resource-limited regions.
1346 if (Top.IsResourceLimited && Bot.IsResourceLimited
1347 && Top.CritResIdx == Bot.CritResIdx) {
1348 // If the scheduled critical resource in both zones is no longer the
1349 // critical remaining resource, attempt to reduce resource height both ways.
1350 if (Top.CritResIdx != Rem.CritResIdx) {
1351 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1352 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1353 DEBUG(dbgs() << "Reduce scheduled "
1354 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1355 }
1356 return;
1357 }
1358 // Handle latency-limited regions.
1359 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1360 // If the total scheduled expected latency exceeds the region's critical
1361 // path then reduce latency both ways.
1362 //
1363 // Just because a zone is not resource limited does not mean it is latency
1364 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1365 // to exceed expected latency.
1366 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1367 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1368 TopCand.Policy.ReduceLatency = true;
1369 BotCand.Policy.ReduceLatency = true;
1370 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1371 << " + " << Bot.ExpectedLatency << '\n');
1372 }
1373 return;
1374 }
1375 // The critical resource is different in each zone, so request balancing.
1376
1377 // Compute the cost of each zone.
1378 Rem.MaxRemainingCount = std::max(
1379 Rem.RemainingMicroOps * SchedModel->getMicroOpFactor(),
1380 Rem.RemainingCounts[Rem.CritResIdx]);
1381 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1382 Top.ExpectedCount = std::max(
1383 Top.getCriticalCount(),
1384 Top.ExpectedCount * SchedModel->getLatencyFactor());
1385 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1386 Bot.ExpectedCount = std::max(
1387 Bot.getCriticalCount(),
1388 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1389
1390 balanceZones(Top, TopCand, Bot, BotCand);
1391 balanceZones(Bot, BotCand, Top, TopCand);
1392}
1393
1394void ConvergingScheduler::SchedCandidate::
1395initResourceDelta(const ScheduleDAGMI *DAG,
1396 const TargetSchedModel *SchedModel) {
1397 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1398 return;
1399
1400 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1401 for (TargetSchedModel::ProcResIter
1402 PI = SchedModel->getWriteProcResBegin(SC),
1403 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1404 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1405 ResDelta.CritResources += PI->Cycles;
1406 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1407 ResDelta.DemandedResources += PI->Cycles;
1408 }
1409}
1410
1411/// Return true if this heuristic determines order.
1412static bool tryLess(unsigned TryVal, unsigned CandVal,
1413 ConvergingScheduler::SchedCandidate &TryCand,
1414 ConvergingScheduler::SchedCandidate &Cand,
1415 ConvergingScheduler::CandReason Reason) {
1416 if (TryVal < CandVal) {
1417 TryCand.Reason = Reason;
1418 return true;
1419 }
1420 if (TryVal > CandVal) {
1421 if (Cand.Reason > Reason)
1422 Cand.Reason = Reason;
1423 return true;
1424 }
1425 return false;
1426}
1427static bool tryGreater(unsigned TryVal, unsigned CandVal,
1428 ConvergingScheduler::SchedCandidate &TryCand,
1429 ConvergingScheduler::SchedCandidate &Cand,
1430 ConvergingScheduler::CandReason Reason) {
1431 if (TryVal > CandVal) {
1432 TryCand.Reason = Reason;
1433 return true;
1434 }
1435 if (TryVal < CandVal) {
1436 if (Cand.Reason > Reason)
1437 Cand.Reason = Reason;
1438 return true;
1439 }
1440 return false;
1441}
1442
1443/// Apply a set of heursitics to a new candidate. Heuristics are currently
1444/// hierarchical. This may be more efficient than a graduated cost model because
1445/// we don't need to evaluate all aspects of the model for each node in the
1446/// queue. But it's really done to make the heuristics easier to debug and
1447/// statistically analyze.
1448///
1449/// \param Cand provides the policy and current best candidate.
1450/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1451/// \param Zone describes the scheduled zone that we are extending.
1452/// \param RPTracker describes reg pressure within the scheduled zone.
1453/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1454void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1455 SchedCandidate &TryCand,
1456 SchedBoundary &Zone,
1457 const RegPressureTracker &RPTracker,
1458 RegPressureTracker &TempTracker) {
1459
1460 // Always initialize TryCand's RPDelta.
1461 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1462 DAG->getRegionCriticalPSets(),
1463 DAG->getRegPressure().MaxSetPressure);
1464
1465 // Initialize the candidate if needed.
1466 if (!Cand.isValid()) {
1467 TryCand.Reason = NodeOrder;
1468 return;
1469 }
1470 // Avoid exceeding the target's limit.
1471 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1472 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1473 return;
1474 if (Cand.Reason == SingleExcess)
1475 Cand.Reason = MultiPressure;
1476
1477 // Avoid increasing the max critical pressure in the scheduled region.
1478 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1479 Cand.RPDelta.CriticalMax.UnitIncrease,
1480 TryCand, Cand, SingleCritical))
1481 return;
1482 if (Cand.Reason == SingleCritical)
1483 Cand.Reason = MultiPressure;
1484
1485 // Avoid critical resource consumption and balance the schedule.
1486 TryCand.initResourceDelta(DAG, SchedModel);
1487 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1488 TryCand, Cand, ResourceReduce))
1489 return;
1490 if (tryGreater(TryCand.ResDelta.DemandedResources,
1491 Cand.ResDelta.DemandedResources,
1492 TryCand, Cand, ResourceDemand))
1493 return;
1494
1495 // Avoid serializing long latency dependence chains.
1496 if (Cand.Policy.ReduceLatency) {
1497 if (Zone.isTop()) {
1498 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1499 > Zone.ExpectedCount) {
1500 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1501 TryCand, Cand, TopDepthReduce))
1502 return;
1503 }
1504 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1505 TryCand, Cand, TopPathReduce))
1506 return;
1507 }
1508 else {
1509 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1510 > Zone.ExpectedCount) {
1511 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1512 TryCand, Cand, BotHeightReduce))
1513 return;
1514 }
1515 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1516 TryCand, Cand, BotPathReduce))
1517 return;
1518 }
1519 }
1520
1521 // Avoid increasing the max pressure of the entire region.
1522 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1523 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1524 return;
1525 if (Cand.Reason == SingleMax)
1526 Cand.Reason = MultiPressure;
1527
1528 // Prefer immediate defs/users of the last scheduled instruction. This is a
1529 // nice pressure avoidance strategy that also conserves the processor's
1530 // register renaming resources and keeps the machine code readable.
1531 if (Zone.NextSUs.count(TryCand.SU) && !Zone.NextSUs.count(Cand.SU)) {
1532 TryCand.Reason = NextDefUse;
1533 return;
1534 }
1535 if (!Zone.NextSUs.count(TryCand.SU) && Zone.NextSUs.count(Cand.SU)) {
1536 if (Cand.Reason > NextDefUse)
1537 Cand.Reason = NextDefUse;
1538 return;
1539 }
1540 // Fall through to original instruction order.
1541 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1542 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1543 TryCand.Reason = NodeOrder;
1544 }
1545}
Andrew Trick28ebc892012-05-10 21:06:19 +00001546
Andrew Trick5429a6b2012-05-17 22:37:09 +00001547/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1548/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001549static bool compareRPDelta(const RegPressureDelta &LHS,
1550 const RegPressureDelta &RHS) {
1551 // Compare each component of pressure in decreasing order of importance
1552 // without checking if any are valid. Invalid PressureElements are assumed to
1553 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001554
1555 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001556 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1557 DEBUG(dbgs() << "RP excess top - bot: "
1558 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001559 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001560 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001561 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001562 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1563 DEBUG(dbgs() << "RP critical top - bot: "
1564 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1565 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001566 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001567 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001568 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001569 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1570 DEBUG(dbgs() << "RP current top - bot: "
1571 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1572 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001573 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001574 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001575 return false;
1576}
1577
Andrew Trick3b87f622012-11-07 07:05:09 +00001578#ifndef NDEBUG
1579const char *ConvergingScheduler::getReasonStr(
1580 ConvergingScheduler::CandReason Reason) {
1581 switch (Reason) {
1582 case NoCand: return "NOCAND ";
1583 case SingleExcess: return "REG-EXCESS";
1584 case SingleCritical: return "REG-CRIT ";
1585 case SingleMax: return "REG-MAX ";
1586 case MultiPressure: return "REG-MULTI ";
1587 case ResourceReduce: return "RES-REDUCE";
1588 case ResourceDemand: return "RES-DEMAND";
1589 case TopDepthReduce: return "TOP-DEPTH ";
1590 case TopPathReduce: return "TOP-PATH ";
1591 case BotHeightReduce:return "BOT-HEIGHT";
1592 case BotPathReduce: return "BOT-PATH ";
1593 case NextDefUse: return "DEF-USE ";
1594 case NodeOrder: return "ORDER ";
1595 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001596 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001597}
1598
1599void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1600 const SchedBoundary &Zone) {
1601 const char *Label = getReasonStr(Cand.Reason);
1602 PressureElement P;
1603 unsigned ResIdx = 0;
1604 unsigned Latency = 0;
1605 switch (Cand.Reason) {
1606 default:
1607 break;
1608 case SingleExcess:
1609 P = Cand.RPDelta.Excess;
1610 break;
1611 case SingleCritical:
1612 P = Cand.RPDelta.CriticalMax;
1613 break;
1614 case SingleMax:
1615 P = Cand.RPDelta.CurrentMax;
1616 break;
1617 case ResourceReduce:
1618 ResIdx = Cand.Policy.ReduceResIdx;
1619 break;
1620 case ResourceDemand:
1621 ResIdx = Cand.Policy.DemandResIdx;
1622 break;
1623 case TopDepthReduce:
1624 Latency = Cand.SU->getDepth();
1625 break;
1626 case TopPathReduce:
1627 Latency = Cand.SU->getHeight();
1628 break;
1629 case BotHeightReduce:
1630 Latency = Cand.SU->getHeight();
1631 break;
1632 case BotPathReduce:
1633 Latency = Cand.SU->getDepth();
1634 break;
1635 }
1636 dbgs() << Label << " " << Zone.Available.getName() << " ";
1637 if (P.isValid())
1638 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1639 << " ";
1640 else
1641 dbgs() << " ";
1642 if (ResIdx)
1643 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1644 else
1645 dbgs() << " ";
1646 if (Latency)
1647 dbgs() << Latency << " cycles ";
1648 else
1649 dbgs() << " ";
1650 Cand.SU->dump(DAG);
1651}
1652#endif
1653
Andrew Trick7196a8f2012-05-10 21:06:16 +00001654/// Pick the best candidate from the top queue.
1655///
1656/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1657/// DAG building. To adjust for the current scheduling location we need to
1658/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001659void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1660 const RegPressureTracker &RPTracker,
1661 SchedCandidate &Cand) {
1662 ReadyQueue &Q = Zone.Available;
1663
Andrew Trickf3234242012-05-24 22:11:12 +00001664 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001665
Andrew Trick7196a8f2012-05-10 21:06:16 +00001666 // getMaxPressureDelta temporarily modifies the tracker.
1667 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1668
Andrew Trick8c2d9212012-05-24 22:11:03 +00001669 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001670
Andrew Trick3b87f622012-11-07 07:05:09 +00001671 SchedCandidate TryCand(Cand.Policy);
1672 TryCand.SU = *I;
1673 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1674 if (TryCand.Reason != NoCand) {
1675 // Initialize resource delta if needed in case future heuristics query it.
1676 if (TryCand.ResDelta == SchedResourceDelta())
1677 TryCand.initResourceDelta(DAG, SchedModel);
1678 Cand.setBest(TryCand);
1679 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001680 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001681 TryCand.SU = *I;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001682 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001683}
1684
1685static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1686 bool IsTop) {
1687 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1688 << " SU(" << Cand.SU->NodeNum << ") "
1689 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001690}
1691
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001692/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001693SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001694 // Schedule as far as possible in the direction of no choice. This is most
1695 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001696 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001697 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001698 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001699 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001700 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001701 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001702 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001703 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001704 CandPolicy NoPolicy;
1705 SchedCandidate BotCand(NoPolicy);
1706 SchedCandidate TopCand(NoPolicy);
1707 checkResourceLimits(TopCand, BotCand);
1708
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001709 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001710 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1711 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001712
1713 // If either Q has a single candidate that provides the least increase in
1714 // Excess pressure, we can immediately schedule from that Q.
1715 //
1716 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1717 // affects picking from either Q. If scheduling in one direction must
1718 // increase pressure for one of the excess PSets, then schedule in that
1719 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001720 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001721 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001722 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001723 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001724 }
1725 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001726 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1727 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001728
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001729 // If either Q has a single candidate that minimizes pressure above the
1730 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001731 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1732 if (TopCand.Reason < BotCand.Reason) {
1733 IsTopNode = true;
1734 tracePick(TopCand, IsTopNode);
1735 return TopCand.SU;
1736 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001737 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001738 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001739 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001740 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001741 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001742 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001743 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001744 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001745 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001746 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001747 // Otherwise prefer the bottom candidate, in node order if all else failed.
1748 if (TopCand.Reason < BotCand.Reason) {
1749 IsTopNode = true;
1750 tracePick(TopCand, IsTopNode);
1751 return TopCand.SU;
1752 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001753 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001754 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001755 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001756}
1757
1758/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001759SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1760 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001761 assert(Top.Available.empty() && Top.Pending.empty() &&
1762 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001763 return NULL;
1764 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001765 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00001766 do {
1767 if (ForceTopDown) {
1768 SU = Top.pickOnlyChoice();
1769 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001770 CandPolicy NoPolicy;
1771 SchedCandidate TopCand(NoPolicy);
1772 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1773 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00001774 SU = TopCand.SU;
1775 }
1776 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001777 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001778 else if (ForceBottomUp) {
1779 SU = Bot.pickOnlyChoice();
1780 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001781 CandPolicy NoPolicy;
1782 SchedCandidate BotCand(NoPolicy);
1783 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1784 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00001785 SU = BotCand.SU;
1786 }
1787 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001788 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001789 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00001790 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00001791 }
1792 } while (SU->isScheduled);
1793
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001794 if (SU->isTopReady())
1795 Top.removeReady(SU);
1796 if (SU->isBottomReady())
1797 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00001798
1799 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1800 << " Scheduling Instruction in cycle "
1801 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1802 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001803 return SU;
1804}
1805
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001806/// Update the scheduler's state after scheduling a node. This is the same node
1807/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00001808/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001809void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001810 if (IsTopNode) {
1811 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001812 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001813 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001814 else {
1815 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001816 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001817 }
1818}
1819
Andrew Trick17d35e52012-03-14 04:00:41 +00001820/// Create the standard converging machine scheduler. This will be used as the
1821/// default scheduler if the target does not set a default.
1822static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001823 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001824 "-misched-topdown incompatible with -misched-bottomup");
1825 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +00001826}
1827static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00001828ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1829 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00001830
1831//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00001832// ILP Scheduler. Currently for experimental analysis of heuristics.
1833//===----------------------------------------------------------------------===//
1834
1835namespace {
1836/// \brief Order nodes by the ILP metric.
1837struct ILPOrder {
1838 ScheduleDAGILP *ILP;
1839 bool MaximizeILP;
1840
1841 ILPOrder(ScheduleDAGILP *ilp, bool MaxILP): ILP(ilp), MaximizeILP(MaxILP) {}
1842
1843 /// \brief Apply a less-than relation on node priority.
1844 bool operator()(const SUnit *A, const SUnit *B) const {
1845 // Return true if A comes after B in the Q.
1846 if (MaximizeILP)
1847 return ILP->getILP(A) < ILP->getILP(B);
1848 else
1849 return ILP->getILP(A) > ILP->getILP(B);
1850 }
1851};
1852
1853/// \brief Schedule based on the ILP metric.
1854class ILPScheduler : public MachineSchedStrategy {
1855 ScheduleDAGILP ILP;
1856 ILPOrder Cmp;
1857
1858 std::vector<SUnit*> ReadyQ;
1859public:
1860 ILPScheduler(bool MaximizeILP)
1861 : ILP(/*BottomUp=*/true), Cmp(&ILP, MaximizeILP) {}
1862
1863 virtual void initialize(ScheduleDAGMI *DAG) {
1864 ReadyQ.clear();
1865 ILP.resize(DAG->SUnits.size());
1866 }
1867
1868 virtual void registerRoots() {
1869 for (std::vector<SUnit*>::const_iterator
1870 I = ReadyQ.begin(), E = ReadyQ.end(); I != E; ++I) {
1871 ILP.computeILP(*I);
1872 }
1873 }
1874
1875 /// Implement MachineSchedStrategy interface.
1876 /// -----------------------------------------
1877
1878 virtual SUnit *pickNode(bool &IsTopNode) {
1879 if (ReadyQ.empty()) return NULL;
1880 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
1881 SUnit *SU = ReadyQ.back();
1882 ReadyQ.pop_back();
1883 IsTopNode = false;
1884 DEBUG(dbgs() << "*** Scheduling " << *SU->getInstr()
1885 << " ILP: " << ILP.getILP(SU) << '\n');
1886 return SU;
1887 }
1888
1889 virtual void schedNode(SUnit *, bool) {}
1890
1891 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
1892
1893 virtual void releaseBottomNode(SUnit *SU) {
1894 ReadyQ.push_back(SU);
1895 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
1896 }
1897};
1898} // namespace
1899
1900static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
1901 return new ScheduleDAGMI(C, new ILPScheduler(true));
1902}
1903static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
1904 return new ScheduleDAGMI(C, new ILPScheduler(false));
1905}
1906static MachineSchedRegistry ILPMaxRegistry(
1907 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
1908static MachineSchedRegistry ILPMinRegistry(
1909 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
1910
1911//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00001912// Machine Instruction Shuffler for Correctness Testing
1913//===----------------------------------------------------------------------===//
1914
Andrew Trick96f678f2012-01-13 06:30:30 +00001915#ifndef NDEBUG
1916namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001917/// Apply a less-than relation on the node order, which corresponds to the
1918/// instruction order prior to scheduling. IsReverse implements greater-than.
1919template<bool IsReverse>
1920struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001921 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00001922 if (IsReverse)
1923 return A->NodeNum > B->NodeNum;
1924 else
1925 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001926 }
1927};
1928
Andrew Trick96f678f2012-01-13 06:30:30 +00001929/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00001930class InstructionShuffler : public MachineSchedStrategy {
1931 bool IsAlternating;
1932 bool IsTopDown;
1933
1934 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
1935 // gives nodes with a higher number higher priority causing the latest
1936 // instructions to be scheduled first.
1937 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
1938 TopQ;
1939 // When scheduling bottom-up, use greater-than as the queue priority.
1940 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
1941 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00001942public:
Andrew Trick17d35e52012-03-14 04:00:41 +00001943 InstructionShuffler(bool alternate, bool topdown)
1944 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00001945
Andrew Trick17d35e52012-03-14 04:00:41 +00001946 virtual void initialize(ScheduleDAGMI *) {
1947 TopQ.clear();
1948 BottomQ.clear();
1949 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001950
Andrew Trick17d35e52012-03-14 04:00:41 +00001951 /// Implement MachineSchedStrategy interface.
1952 /// -----------------------------------------
1953
1954 virtual SUnit *pickNode(bool &IsTopNode) {
1955 SUnit *SU;
1956 if (IsTopDown) {
1957 do {
1958 if (TopQ.empty()) return NULL;
1959 SU = TopQ.top();
1960 TopQ.pop();
1961 } while (SU->isScheduled);
1962 IsTopNode = true;
1963 }
1964 else {
1965 do {
1966 if (BottomQ.empty()) return NULL;
1967 SU = BottomQ.top();
1968 BottomQ.pop();
1969 } while (SU->isScheduled);
1970 IsTopNode = false;
1971 }
1972 if (IsAlternating)
1973 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001974 return SU;
1975 }
1976
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001977 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
1978
Andrew Trick17d35e52012-03-14 04:00:41 +00001979 virtual void releaseTopNode(SUnit *SU) {
1980 TopQ.push(SU);
1981 }
1982 virtual void releaseBottomNode(SUnit *SU) {
1983 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00001984 }
1985};
1986} // namespace
1987
Andrew Trickc174eaf2012-03-08 01:41:12 +00001988static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00001989 bool Alternate = !ForceTopDown && !ForceBottomUp;
1990 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001991 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001992 "-misched-topdown incompatible with -misched-bottomup");
1993 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00001994}
Andrew Trick17d35e52012-03-14 04:00:41 +00001995static MachineSchedRegistry ShufflerRegistry(
1996 "shuffle", "Shuffle machine instructions alternating directions",
1997 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00001998#endif // !NDEBUG