blob: dbab6bae28e98db95339c412efcb6c42639e972c [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 Trick9b5caaa2012-11-12 19:40:10 +000061// Experimental heuristics
62static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
63 cl::desc("Enable load clustering."));
64
Andrew Trick5edf2f02012-01-14 02:17:06 +000065//===----------------------------------------------------------------------===//
66// Machine Instruction Scheduling Pass and Registry
67//===----------------------------------------------------------------------===//
68
Andrew Trick86b7e2a2012-04-24 20:36:19 +000069MachineSchedContext::MachineSchedContext():
70 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
71 RegClassInfo = new RegisterClassInfo();
72}
73
74MachineSchedContext::~MachineSchedContext() {
75 delete RegClassInfo;
76}
77
Andrew Trick96f678f2012-01-13 06:30:30 +000078namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000079/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000080class MachineScheduler : public MachineSchedContext,
81 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000082public:
Andrew Trick42b7a712012-01-17 06:55:03 +000083 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000084
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
86
87 virtual void releaseMemory() {}
88
89 virtual bool runOnMachineFunction(MachineFunction&);
90
91 virtual void print(raw_ostream &O, const Module* = 0) const;
92
93 static char ID; // Class identification, replacement for typeinfo
94};
95} // namespace
96
Andrew Trick42b7a712012-01-17 06:55:03 +000097char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000098
Andrew Trick42b7a712012-01-17 06:55:03 +000099char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000100
Andrew Trick42b7a712012-01-17 06:55:03 +0000101INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000102 "Machine Instruction Scheduler", false, false)
103INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
104INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
105INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000106INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000107 "Machine Instruction Scheduler", false, false)
108
Andrew Trick42b7a712012-01-17 06:55:03 +0000109MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000110: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000111 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000112}
113
Andrew Trick42b7a712012-01-17 06:55:03 +0000114void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000115 AU.setPreservesCFG();
116 AU.addRequiredID(MachineDominatorsID);
117 AU.addRequired<MachineLoopInfo>();
118 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000119 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000120 AU.addRequired<SlotIndexes>();
121 AU.addPreserved<SlotIndexes>();
122 AU.addRequired<LiveIntervals>();
123 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000124 MachineFunctionPass::getAnalysisUsage(AU);
125}
126
Andrew Trick96f678f2012-01-13 06:30:30 +0000127MachinePassRegistry MachineSchedRegistry::Registry;
128
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000129/// A dummy default scheduler factory indicates whether the scheduler
130/// is overridden on the command line.
131static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
132 return 0;
133}
Andrew Trick96f678f2012-01-13 06:30:30 +0000134
135/// MachineSchedOpt allows command line selection of the scheduler.
136static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
137 RegisterPassParser<MachineSchedRegistry> >
138MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000139 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000140 cl::desc("Machine instruction scheduler to use"));
141
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000142static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000143DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000144 useDefaultMachineSched);
145
Andrew Trick17d35e52012-03-14 04:00:41 +0000146/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000147/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000148static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000149
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000150
151/// Decrement this iterator until reaching the top or a non-debug instr.
152static MachineBasicBlock::iterator
153priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
154 assert(I != Beg && "reached the top of the region, cannot decrement");
155 while (--I != Beg) {
156 if (!I->isDebugValue())
157 break;
158 }
159 return I;
160}
161
162/// If this iterator is a debug value, increment until reaching the End or a
163/// non-debug instruction.
164static MachineBasicBlock::iterator
165nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000166 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000167 if (!I->isDebugValue())
168 break;
169 }
170 return I;
171}
172
Andrew Trickcb058d52012-03-14 04:00:38 +0000173/// Top-level MachineScheduler pass driver.
174///
175/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000176/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
177/// consistent with the DAG builder, which traverses the interior of the
178/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000179///
180/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000181/// simplifying the DAG builder's support for "special" target instructions.
182/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000183/// scheduling boundaries, for example to bundle the boudary instructions
184/// without reordering them. This creates complexity, because the target
185/// scheduler must update the RegionBegin and RegionEnd positions cached by
186/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
187/// design would be to split blocks at scheduling boundaries, but LLVM has a
188/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000189bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000190 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
191
Andrew Trick96f678f2012-01-13 06:30:30 +0000192 // Initialize the context of the pass.
193 MF = &mf;
194 MLI = &getAnalysis<MachineLoopInfo>();
195 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000196 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000197 AA = &getAnalysis<AliasAnalysis>();
198
Lang Hames907cc8f2012-01-27 22:36:19 +0000199 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000200 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000201
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000202 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000203
Andrew Trick96f678f2012-01-13 06:30:30 +0000204 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000205 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
206 if (Ctor == useDefaultMachineSched) {
207 // Get the default scheduler set by the target.
208 Ctor = MachineSchedRegistry::getDefault();
209 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000210 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000211 MachineSchedRegistry::setDefault(Ctor);
212 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000213 }
214 // Instantiate the selected scheduler.
215 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
216
217 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000218 //
219 // TODO: Visit blocks in global postorder or postorder within the bottom-up
220 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000221 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
222 MBB != MBBEnd; ++MBB) {
223
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000224 Scheduler->startBlock(MBB);
225
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000226 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000227 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000228 // boundary at the bottom of the region. The DAG does not include RegionEnd,
229 // but the region does (i.e. the next RegionEnd is above the previous
230 // RegionBegin). If the current block has no terminator then RegionEnd ==
231 // MBB->end() for the bottom region.
232 //
233 // The Scheduler may insert instructions during either schedule() or
234 // exitRegion(), even for empty regions. So the local iterators 'I' and
235 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000236 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000237 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000238 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000239
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000240 // Avoid decrementing RegionEnd for blocks with no terminator.
241 if (RegionEnd != MBB->end()
242 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
243 --RegionEnd;
244 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000245 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000246 }
247
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000248 // The next region starts above the previous region. Look backward in the
249 // instruction stream until we find the nearest boundary.
250 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000251 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000252 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
253 break;
254 }
Andrew Trick47c14452012-03-07 05:21:52 +0000255 // Notify the scheduler of the region, even if we may skip scheduling
256 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000257 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000258
259 // Skip empty scheduling regions (0 or 1 schedulable instructions).
260 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000261 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000262 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000263 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000264 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000265 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000266 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000267 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000268 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
269 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
270 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000271 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000272
Andrew Trickd24da972012-03-09 03:46:42 +0000273 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000274 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000275 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000276
277 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000278 Scheduler->exitRegion();
279
280 // Scheduling has invalidated the current iterator 'I'. Ask the
281 // scheduler for the top of it's scheduled region.
282 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000283 }
Andrew Trick22764532012-11-06 07:10:34 +0000284 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000285 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000286 }
Andrew Trick830da402012-04-01 07:24:23 +0000287 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000288 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000289 return true;
290}
291
Andrew Trick42b7a712012-01-17 06:55:03 +0000292void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000293 // unimplemented
294}
295
Manman Renb720be62012-09-11 22:23:19 +0000296#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000297void ReadyQueue::dump() {
298 dbgs() << Name << ": ";
299 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
300 dbgs() << Queue[i]->NodeNum << " ";
301 dbgs() << "\n";
302}
303#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000304
305//===----------------------------------------------------------------------===//
306// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
307// preservation.
308//===----------------------------------------------------------------------===//
309
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000310bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
311 // Do not use WillCreateCycle, it assumes SD scheduling.
312 // If Pred is reachable from Succ, then the edge creates a cycle.
313 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
314 return false;
315 Topo.AddPred(SuccSU, PredDep.getSUnit());
316 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
317 // Return true regardless of whether a new edge needed to be inserted.
318 return true;
319}
320
Andrew Trickc174eaf2012-03-08 01:41:12 +0000321/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
322/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000323///
324/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000325void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000326 SUnit *SuccSU = SuccEdge->getSUnit();
327
Andrew Trickae692f22012-11-12 19:28:57 +0000328 if (SuccEdge->isWeak()) {
329 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000330 if (SuccEdge->isCluster())
331 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000332 return;
333 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000334#ifndef NDEBUG
335 if (SuccSU->NumPredsLeft == 0) {
336 dbgs() << "*** Scheduling failed! ***\n";
337 SuccSU->dump(this);
338 dbgs() << " has been released too many times!\n";
339 llvm_unreachable(0);
340 }
341#endif
342 --SuccSU->NumPredsLeft;
343 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000344 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000345}
346
347/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000348void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000349 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
350 I != E; ++I) {
351 releaseSucc(SU, &*I);
352 }
353}
354
Andrew Trick17d35e52012-03-14 04:00:41 +0000355/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
356/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000357///
358/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000359void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
360 SUnit *PredSU = PredEdge->getSUnit();
361
Andrew Trickae692f22012-11-12 19:28:57 +0000362 if (PredEdge->isWeak()) {
363 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000364 if (PredEdge->isCluster())
365 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000366 return;
367 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000368#ifndef NDEBUG
369 if (PredSU->NumSuccsLeft == 0) {
370 dbgs() << "*** Scheduling failed! ***\n";
371 PredSU->dump(this);
372 dbgs() << " has been released too many times!\n";
373 llvm_unreachable(0);
374 }
375#endif
376 --PredSU->NumSuccsLeft;
377 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
378 SchedImpl->releaseBottomNode(PredSU);
379}
380
381/// releasePredecessors - Call releasePred on each of SU's predecessors.
382void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
383 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
384 I != E; ++I) {
385 releasePred(SU, &*I);
386 }
387}
388
389void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
390 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000391 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000392 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000393 ++RegionBegin;
394
395 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000396 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000397
398 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000399 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000400
401 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000402 if (RegionBegin == InsertPos)
403 RegionBegin = MI;
404}
405
Andrew Trick0b0d8992012-03-21 04:12:07 +0000406bool ScheduleDAGMI::checkSchedLimit() {
407#ifndef NDEBUG
408 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
409 CurrentTop = CurrentBottom;
410 return false;
411 }
412 ++NumInstrsScheduled;
413#endif
414 return true;
415}
416
Andrew Trick006e1ab2012-04-24 17:56:43 +0000417/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
418/// crossing a scheduling boundary. [begin, end) includes all instructions in
419/// the region, including the boundary itself and single-instruction regions
420/// that don't get scheduled.
421void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
422 MachineBasicBlock::iterator begin,
423 MachineBasicBlock::iterator end,
424 unsigned endcount)
425{
426 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000427
428 // For convenience remember the end of the liveness region.
429 LiveRegionEnd =
430 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
431}
432
433// Setup the register pressure trackers for the top scheduled top and bottom
434// scheduled regions.
435void ScheduleDAGMI::initRegPressure() {
436 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
437 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
438
439 // Close the RPTracker to finalize live ins.
440 RPTracker.closeRegion();
441
Andrew Trickbb0a2422012-05-24 22:11:14 +0000442 DEBUG(RPTracker.getPressure().dump(TRI));
443
Andrew Trick7f8ab782012-05-10 21:06:10 +0000444 // Initialize the live ins and live outs.
445 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
446 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
447
448 // Close one end of the tracker so we can call
449 // getMaxUpward/DownwardPressureDelta before advancing across any
450 // instructions. This converts currently live regs into live ins/outs.
451 TopRPTracker.closeTop();
452 BotRPTracker.closeBottom();
453
454 // Account for liveness generated by the region boundary.
455 if (LiveRegionEnd != RegionEnd)
456 BotRPTracker.recede();
457
458 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000459
460 // Cache the list of excess pressure sets in this region. This will also track
461 // the max pressure in the scheduled code for these sets.
462 RegionCriticalPSets.clear();
463 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
464 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
465 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000466 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
467 << "Limit " << Limit
468 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000469 if (RegionPressure[i] > Limit)
470 RegionCriticalPSets.push_back(PressureElement(i, 0));
471 }
472 DEBUG(dbgs() << "Excess PSets: ";
473 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
474 dbgs() << TRI->getRegPressureSetName(
475 RegionCriticalPSets[i].PSetID) << " ";
476 dbgs() << "\n");
477}
478
479// FIXME: When the pressure tracker deals in pressure differences then we won't
480// iterate over all RegionCriticalPSets[i].
481void ScheduleDAGMI::
482updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
483 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
484 unsigned ID = RegionCriticalPSets[i].PSetID;
485 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
486 if ((int)NewMaxPressure[ID] > MaxUnits)
487 MaxUnits = NewMaxPressure[ID];
488 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000489}
490
Andrew Trick17d35e52012-03-14 04:00:41 +0000491/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000492/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
493/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000494///
495/// This is a skeletal driver, with all the functionality pushed into helpers,
496/// so that it can be easilly extended by experimental schedulers. Generally,
497/// implementing MachineSchedStrategy should be sufficient to implement a new
498/// scheduling algorithm. However, if a scheduler further subclasses
499/// ScheduleDAGMI then it will want to override this virtual method in order to
500/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000501void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000502 buildDAGWithRegPressure();
503
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000504 Topo.InitDAGTopologicalSorting();
505
Andrew Trickd039b382012-09-14 17:22:42 +0000506 postprocessDAG();
507
Andrew Trick78e5efe2012-09-11 00:39:15 +0000508 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
509 SUnits[su].dumpAll(this));
510
511 if (ViewMISchedDAGs) viewGraph();
512
513 initQueues();
514
515 bool IsTopNode = false;
516 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000517 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000518 if (!checkSchedLimit())
519 break;
520
521 scheduleMI(SU, IsTopNode);
522
523 updateQueues(SU, IsTopNode);
524 }
525 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
526
527 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000528
529 DEBUG({
530 unsigned BBNum = top()->getParent()->getNumber();
531 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
532 dumpSchedule();
533 dbgs() << '\n';
534 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000535}
536
537/// Build the DAG and setup three register pressure trackers.
538void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000539 // Initialize the register pressure tracker used by buildSchedGraph.
540 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000541
Andrew Trick7f8ab782012-05-10 21:06:10 +0000542 // Account for liveness generate by the region boundary.
543 if (LiveRegionEnd != RegionEnd)
544 RPTracker.recede();
545
546 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000547 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000548 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000549
Andrew Trick7f8ab782012-05-10 21:06:10 +0000550 // Initialize top/bottom trackers after computing region pressure.
551 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000552}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000553
Andrew Trickd039b382012-09-14 17:22:42 +0000554/// Apply each ScheduleDAGMutation step in order.
555void ScheduleDAGMI::postprocessDAG() {
556 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
557 Mutations[i]->apply(this);
558 }
559}
560
Andrew Trick1e94e982012-10-15 18:02:27 +0000561// Release all DAG roots for scheduling.
Andrew Trickae692f22012-11-12 19:28:57 +0000562//
563// Nodes with unreleased weak edges can still be roots.
Andrew Trick1e94e982012-10-15 18:02:27 +0000564void ScheduleDAGMI::releaseRoots() {
565 SmallVector<SUnit*, 16> BotRoots;
566
567 for (std::vector<SUnit>::iterator
568 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000569 SUnit *SU = &(*I);
Andrew Trick1e94e982012-10-15 18:02:27 +0000570 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickae692f22012-11-12 19:28:57 +0000571 if (!I->NumPredsLeft && SU != &EntrySU)
572 SchedImpl->releaseTopNode(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000573 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trickae692f22012-11-12 19:28:57 +0000574 if (!I->NumSuccsLeft && SU != &ExitSU)
575 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000576 }
577 // Release bottom roots in reverse order so the higher priority nodes appear
578 // first. This is more natural and slightly more efficient.
579 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
580 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
581 SchedImpl->releaseBottomNode(*I);
582}
583
Andrew Trick78e5efe2012-09-11 00:39:15 +0000584/// Identify DAG roots and setup scheduler queues.
585void ScheduleDAGMI::initQueues() {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000586 NextClusterSucc = NULL;
587 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000588
Andrew Trick78e5efe2012-09-11 00:39:15 +0000589 // Initialize the strategy before modifying the DAG.
Andrew Trick17d35e52012-03-14 04:00:41 +0000590 SchedImpl->initialize(this);
591
Andrew Trickae692f22012-11-12 19:28:57 +0000592 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
593 releaseRoots();
594
Andrew Trickc174eaf2012-03-08 01:41:12 +0000595 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000596 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000597
Andrew Trick1e94e982012-10-15 18:02:27 +0000598 SchedImpl->registerRoots();
599
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000600 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000601 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000602}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000603
Andrew Trick78e5efe2012-09-11 00:39:15 +0000604/// Move an instruction and update register pressure.
605void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
606 // Move the instruction to its new location in the instruction stream.
607 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000608
Andrew Trick78e5efe2012-09-11 00:39:15 +0000609 if (IsTopNode) {
610 assert(SU->isTopReady() && "node still has unscheduled dependencies");
611 if (&*CurrentTop == MI)
612 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000613 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000614 moveInstruction(MI, CurrentTop);
615 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000616 }
Andrew Trick000b2502012-04-24 18:04:37 +0000617
Andrew Trick78e5efe2012-09-11 00:39:15 +0000618 // Update top scheduled pressure.
619 TopRPTracker.advance();
620 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
621 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
622 }
623 else {
624 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
625 MachineBasicBlock::iterator priorII =
626 priorNonDebug(CurrentBottom, CurrentTop);
627 if (&*priorII == MI)
628 CurrentBottom = priorII;
629 else {
630 if (&*CurrentTop == MI) {
631 CurrentTop = nextIfDebug(++CurrentTop, priorII);
632 TopRPTracker.setPos(CurrentTop);
633 }
634 moveInstruction(MI, CurrentBottom);
635 CurrentBottom = MI;
636 }
637 // Update bottom scheduled pressure.
638 BotRPTracker.recede();
639 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
640 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
641 }
642}
643
644/// Update scheduler queues after scheduling an instruction.
645void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
646 // Release dependent instructions for scheduling.
647 if (IsTopNode)
648 releaseSuccessors(SU);
649 else
650 releasePredecessors(SU);
651
652 SU->isScheduled = true;
653
654 // Notify the scheduling strategy after updating the DAG.
655 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000656}
657
658/// Reinsert any remaining debug_values, just like the PostRA scheduler.
659void ScheduleDAGMI::placeDebugValues() {
660 // If first instruction was a DBG_VALUE then put it back.
661 if (FirstDbgValue) {
662 BB->splice(RegionBegin, BB, FirstDbgValue);
663 RegionBegin = FirstDbgValue;
664 }
665
666 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
667 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
668 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
669 MachineInstr *DbgValue = P.first;
670 MachineBasicBlock::iterator OrigPrevMI = P.second;
671 BB->splice(++OrigPrevMI, BB, DbgValue);
672 if (OrigPrevMI == llvm::prior(RegionEnd))
673 RegionEnd = DbgValue;
674 }
675 DbgValues.clear();
676 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000677}
678
Andrew Trick3b87f622012-11-07 07:05:09 +0000679#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
680void ScheduleDAGMI::dumpSchedule() const {
681 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
682 if (SUnit *SU = getSUnit(&(*MI)))
683 SU->dump(this);
684 else
685 dbgs() << "Missing SUnit\n";
686 }
687}
688#endif
689
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000690namespace {
691/// \brief Post-process the DAG to create cluster edges between neighboring
692/// loads.
693class LoadClusterMutation : public ScheduleDAGMutation {
694 struct LoadInfo {
695 SUnit *SU;
696 unsigned BaseReg;
697 unsigned Offset;
698 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
699 : SU(su), BaseReg(reg), Offset(ofs) {}
700 };
701 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
702 const LoadClusterMutation::LoadInfo &RHS);
703
704 const TargetInstrInfo *TII;
705 const TargetRegisterInfo *TRI;
706public:
707 LoadClusterMutation(const TargetInstrInfo *tii,
708 const TargetRegisterInfo *tri)
709 : TII(tii), TRI(tri) {}
710
711 virtual void apply(ScheduleDAGMI *DAG);
712protected:
713 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
714};
715} // anonymous
716
717bool LoadClusterMutation::LoadInfoLess(
718 const LoadClusterMutation::LoadInfo &LHS,
719 const LoadClusterMutation::LoadInfo &RHS) {
720 if (LHS.BaseReg != RHS.BaseReg)
721 return LHS.BaseReg < RHS.BaseReg;
722 return LHS.Offset < RHS.Offset;
723}
724
725void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
726 ScheduleDAGMI *DAG) {
727 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
728 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
729 SUnit *SU = Loads[Idx];
730 unsigned BaseReg;
731 unsigned Offset;
732 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
733 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
734 }
735 if (LoadRecords.size() < 2)
736 return;
737 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
738 unsigned ClusterLength = 1;
739 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
740 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
741 ClusterLength = 1;
742 continue;
743 }
744
745 SUnit *SUa = LoadRecords[Idx].SU;
746 SUnit *SUb = LoadRecords[Idx+1].SU;
747 if (TII->shouldScheduleLoadsNear(SUa->getInstr(), SUb->getInstr(),
748 ClusterLength)
749 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
750
751 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
752 << SUb->NodeNum << ")\n");
753 // Copy successor edges from SUa to SUb. Interleaving computation
754 // dependent on SUa can prevent load combining due to register reuse.
755 // Predecessor edges do not need to be copied from SUb to SUa since nearby
756 // loads should have effectively the same inputs.
757 for (SUnit::const_succ_iterator
758 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
759 if (SI->getSUnit() == SUb)
760 continue;
761 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
762 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
763 }
764 ++ClusterLength;
765 }
766 else
767 ClusterLength = 1;
768 }
769}
770
771/// \brief Callback from DAG postProcessing to create cluster edges for loads.
772void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
773 // Map DAG NodeNum to store chain ID.
774 DenseMap<unsigned, unsigned> StoreChainIDs;
775 // Map each store chain to a set of dependent loads.
776 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
777 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
778 SUnit *SU = &DAG->SUnits[Idx];
779 if (!SU->getInstr()->mayLoad())
780 continue;
781 unsigned ChainPredID = DAG->SUnits.size();
782 for (SUnit::const_pred_iterator
783 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
784 if (PI->isCtrl()) {
785 ChainPredID = PI->getSUnit()->NodeNum;
786 break;
787 }
788 }
789 // Check if this chain-like pred has been seen
790 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
791 unsigned NumChains = StoreChainDependents.size();
792 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
793 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
794 if (Result.second)
795 StoreChainDependents.resize(NumChains + 1);
796 StoreChainDependents[Result.first->second].push_back(SU);
797 }
798 // Iterate over the store chains.
799 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
800 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
801}
802
Andrew Trickc174eaf2012-03-08 01:41:12 +0000803//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000804// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000805//===----------------------------------------------------------------------===//
806
807namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000808/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
809/// the schedule.
810class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000811public:
812 /// Represent the type of SchedCandidate found within a single queue.
813 /// pickNodeBidirectional depends on these listed by decreasing priority.
814 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000815 NoCand, SingleExcess, SingleCritical, Cluster,
816 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
817 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
818 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000819
820#ifndef NDEBUG
821 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
822#endif
823
824 /// Policy for scheduling the next instruction in the candidate's zone.
825 struct CandPolicy {
826 bool ReduceLatency;
827 unsigned ReduceResIdx;
828 unsigned DemandResIdx;
829
830 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
831 };
832
833 /// Status of an instruction's critical resource consumption.
834 struct SchedResourceDelta {
835 // Count critical resources in the scheduled region required by SU.
836 unsigned CritResources;
837
838 // Count critical resources from another region consumed by SU.
839 unsigned DemandedResources;
840
841 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
842
843 bool operator==(const SchedResourceDelta &RHS) const {
844 return CritResources == RHS.CritResources
845 && DemandedResources == RHS.DemandedResources;
846 }
847 bool operator!=(const SchedResourceDelta &RHS) const {
848 return !operator==(RHS);
849 }
850 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000851
852 /// Store the state used by ConvergingScheduler heuristics, required for the
853 /// lifetime of one invocation of pickNode().
854 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000855 CandPolicy Policy;
856
Andrew Trick7196a8f2012-05-10 21:06:16 +0000857 // The best SUnit candidate.
858 SUnit *SU;
859
Andrew Trick3b87f622012-11-07 07:05:09 +0000860 // The reason for this candidate.
861 CandReason Reason;
862
Andrew Trick7196a8f2012-05-10 21:06:16 +0000863 // Register pressure values for the best candidate.
864 RegPressureDelta RPDelta;
865
Andrew Trick3b87f622012-11-07 07:05:09 +0000866 // Critical resource consumption of the best candidate.
867 SchedResourceDelta ResDelta;
868
869 SchedCandidate(const CandPolicy &policy)
870 : Policy(policy), SU(NULL), Reason(NoCand) {}
871
872 bool isValid() const { return SU; }
873
874 // Copy the status of another candidate without changing policy.
875 void setBest(SchedCandidate &Best) {
876 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
877 SU = Best.SU;
878 Reason = Best.Reason;
879 RPDelta = Best.RPDelta;
880 ResDelta = Best.ResDelta;
881 }
882
883 void initResourceDelta(const ScheduleDAGMI *DAG,
884 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000885 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000886
887 /// Summarize the unscheduled region.
888 struct SchedRemainder {
889 // Critical path through the DAG in expected latency.
890 unsigned CriticalPath;
891
892 // Unscheduled resources
893 SmallVector<unsigned, 16> RemainingCounts;
894 // Critical resource for the unscheduled zone.
895 unsigned CritResIdx;
896 // Number of micro-ops left to schedule.
897 unsigned RemainingMicroOps;
898 // Is the unscheduled zone resource limited.
899 bool IsResourceLimited;
900
901 unsigned MaxRemainingCount;
902
903 void reset() {
904 CriticalPath = 0;
905 RemainingCounts.clear();
906 CritResIdx = 0;
907 RemainingMicroOps = 0;
908 IsResourceLimited = false;
909 MaxRemainingCount = 0;
910 }
911
912 SchedRemainder() { reset(); }
913
914 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
915 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000916
Andrew Trickf3234242012-05-24 22:11:12 +0000917 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +0000918 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +0000919 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000920 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000921 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000922 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +0000923 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000924
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000925 ReadyQueue Available;
926 ReadyQueue Pending;
927 bool CheckPending;
928
Andrew Trick3b87f622012-11-07 07:05:09 +0000929 // For heuristics, keep a list of the nodes that immediately depend on the
930 // most recently scheduled node.
931 SmallPtrSet<const SUnit*, 8> NextSUs;
932
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000933 ScheduleHazardRecognizer *HazardRec;
934
935 unsigned CurrCycle;
936 unsigned IssueCount;
937
938 /// MinReadyCycle - Cycle of the soonest available instruction.
939 unsigned MinReadyCycle;
940
Andrew Trick3b87f622012-11-07 07:05:09 +0000941 // The expected latency of the critical path in this scheduled zone.
942 unsigned ExpectedLatency;
943
944 // Resources used in the scheduled zone beyond this boundary.
945 SmallVector<unsigned, 16> ResourceCounts;
946
947 // Cache the critical resources ID in this scheduled zone.
948 unsigned CritResIdx;
949
950 // Is the scheduled region resource limited vs. latency limited.
951 bool IsResourceLimited;
952
953 unsigned ExpectedCount;
954
955 // Policy flag: attempt to find ILP until expected latency is covered.
956 bool ShouldIncreaseILP;
957
958#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +0000959 // Remember the greatest min operand latency.
960 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +0000961#endif
962
963 void reset() {
964 Available.clear();
965 Pending.clear();
966 CheckPending = false;
967 NextSUs.clear();
968 HazardRec = 0;
969 CurrCycle = 0;
970 IssueCount = 0;
971 MinReadyCycle = UINT_MAX;
972 ExpectedLatency = 0;
973 ResourceCounts.resize(1);
974 assert(!ResourceCounts[0] && "nonzero count for bad resource");
975 CritResIdx = 0;
976 IsResourceLimited = false;
977 ExpectedCount = 0;
978 ShouldIncreaseILP = false;
979#ifndef NDEBUG
980 MaxMinLatency = 0;
981#endif
982 // Reserve a zero-count for invalid CritResIdx.
983 ResourceCounts.resize(1);
984 }
Andrew Trickb7e02892012-06-05 21:11:27 +0000985
Andrew Trickf3234242012-05-24 22:11:12 +0000986 /// Pending queues extend the ready queues with the same ID and the
987 /// PendingFlag set.
988 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +0000989 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
990 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
991 reset();
992 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000993
994 ~SchedBoundary() { delete HazardRec; }
995
Andrew Trick3b87f622012-11-07 07:05:09 +0000996 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
997 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +0000998
Andrew Trickf3234242012-05-24 22:11:12 +0000999 bool isTop() const {
1000 return Available.getID() == ConvergingScheduler::TopQID;
1001 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001002
Andrew Trick3b87f622012-11-07 07:05:09 +00001003 unsigned getUnscheduledLatency(SUnit *SU) const {
1004 if (isTop())
1005 return SU->getHeight();
1006 return SU->getDepth();
1007 }
1008
1009 unsigned getCriticalCount() const {
1010 return ResourceCounts[CritResIdx];
1011 }
1012
Andrew Trick5559ffa2012-06-29 03:23:24 +00001013 bool checkHazard(SUnit *SU);
1014
Andrew Trick3b87f622012-11-07 07:05:09 +00001015 void checkILPPolicy();
1016
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001017 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1018
1019 void bumpCycle();
1020
Andrew Trick3b87f622012-11-07 07:05:09 +00001021 void countResource(unsigned PIdx, unsigned Cycles);
1022
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001023 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001024
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001025 void releasePending();
1026
1027 void removeReady(SUnit *SU);
1028
1029 SUnit *pickOnlyChoice();
1030 };
1031
Andrew Trick3b87f622012-11-07 07:05:09 +00001032private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001033 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001034 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001035 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001036
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001037 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001038 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001039 SchedBoundary Top;
1040 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001041
1042public:
Andrew Trickf3234242012-05-24 22:11:12 +00001043 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001044 enum {
1045 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001046 BotQID = 2,
1047 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001048 };
1049
Andrew Trickf3234242012-05-24 22:11:12 +00001050 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001051 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001052
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001053 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001054
Andrew Trick7196a8f2012-05-10 21:06:16 +00001055 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001056
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001057 virtual void schedNode(SUnit *SU, bool IsTopNode);
1058
1059 virtual void releaseTopNode(SUnit *SU);
1060
1061 virtual void releaseBottomNode(SUnit *SU);
1062
Andrew Trick3b87f622012-11-07 07:05:09 +00001063 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001064
Andrew Trick3b87f622012-11-07 07:05:09 +00001065protected:
1066 void balanceZones(
1067 ConvergingScheduler::SchedBoundary &CriticalZone,
1068 ConvergingScheduler::SchedCandidate &CriticalCand,
1069 ConvergingScheduler::SchedBoundary &OppositeZone,
1070 ConvergingScheduler::SchedCandidate &OppositeCand);
1071
1072 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1073 ConvergingScheduler::SchedCandidate &BotCand);
1074
1075 void tryCandidate(SchedCandidate &Cand,
1076 SchedCandidate &TryCand,
1077 SchedBoundary &Zone,
1078 const RegPressureTracker &RPTracker,
1079 RegPressureTracker &TempTracker);
1080
1081 SUnit *pickNodeBidirectional(bool &IsTopNode);
1082
1083 void pickNodeFromQueue(SchedBoundary &Zone,
1084 const RegPressureTracker &RPTracker,
1085 SchedCandidate &Candidate);
1086
Andrew Trick28ebc892012-05-10 21:06:19 +00001087#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001088 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001089#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001090};
1091} // namespace
1092
Andrew Trick3b87f622012-11-07 07:05:09 +00001093void ConvergingScheduler::SchedRemainder::
1094init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1095 reset();
1096 if (!SchedModel->hasInstrSchedModel())
1097 return;
1098 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1099 for (std::vector<SUnit>::iterator
1100 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1101 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1102 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1103 for (TargetSchedModel::ProcResIter
1104 PI = SchedModel->getWriteProcResBegin(SC),
1105 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1106 unsigned PIdx = PI->ProcResourceIdx;
1107 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1108 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1109 }
1110 }
1111}
1112
1113void ConvergingScheduler::SchedBoundary::
1114init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1115 reset();
1116 DAG = dag;
1117 SchedModel = smodel;
1118 Rem = rem;
1119 if (SchedModel->hasInstrSchedModel())
1120 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1121}
1122
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001123void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1124 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001125 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001126 TRI = DAG->TRI;
Andrew Trick3b87f622012-11-07 07:05:09 +00001127 Rem.init(DAG, SchedModel);
1128 Top.init(DAG, SchedModel, &Rem);
1129 Bot.init(DAG, SchedModel, &Rem);
1130
1131 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001132
Andrew Trick412cd2f2012-10-10 05:43:09 +00001133 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1134 // are disabled, then these HazardRecs will be disabled.
1135 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001136 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001137 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1138 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1139
1140 assert((!ForceTopDown || !ForceBottomUp) &&
1141 "-misched-topdown incompatible with -misched-bottomup");
1142}
1143
1144void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001145 if (SU->isScheduled)
1146 return;
1147
1148 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1149 I != E; ++I) {
1150 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001151 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001152#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001153 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001154#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001155 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1156 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001157 }
1158 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001159}
1160
1161void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001162 if (SU->isScheduled)
1163 return;
1164
1165 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1166
1167 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1168 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001169 if (I->isWeak())
1170 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001171 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001172 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001173#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001174 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001175#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001176 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1177 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001178 }
1179 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001180}
1181
Andrew Trick3b87f622012-11-07 07:05:09 +00001182void ConvergingScheduler::registerRoots() {
1183 Rem.CriticalPath = DAG->ExitSU.getDepth();
1184 // Some roots may not feed into ExitSU. Check all of them in case.
1185 for (std::vector<SUnit*>::const_iterator
1186 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1187 if ((*I)->getDepth() > Rem.CriticalPath)
1188 Rem.CriticalPath = (*I)->getDepth();
1189 }
1190 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1191}
1192
Andrew Trick5559ffa2012-06-29 03:23:24 +00001193/// Does this SU have a hazard within the current instruction group.
1194///
1195/// The scheduler supports two modes of hazard recognition. The first is the
1196/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1197/// supports highly complicated in-order reservation tables
1198/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1199///
1200/// The second is a streamlined mechanism that checks for hazards based on
1201/// simple counters that the scheduler itself maintains. It explicitly checks
1202/// for instruction dispatch limitations, including the number of micro-ops that
1203/// can dispatch per cycle.
1204///
1205/// TODO: Also check whether the SU must start a new group.
1206bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1207 if (HazardRec->isEnabled())
1208 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1209
Andrew Trick412cd2f2012-10-10 05:43:09 +00001210 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001211 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1212 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1213 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001214 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001215 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001216 return false;
1217}
1218
Andrew Trick3b87f622012-11-07 07:05:09 +00001219/// If expected latency is covered, disable ILP policy.
1220void ConvergingScheduler::SchedBoundary::checkILPPolicy() {
1221 if (ShouldIncreaseILP
1222 && (IsResourceLimited || ExpectedLatency <= CurrCycle)) {
1223 ShouldIncreaseILP = false;
1224 DEBUG(dbgs() << "Disable ILP: " << Available.getName() << '\n');
1225 }
1226}
1227
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001228void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1229 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001230
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001231 if (ReadyCycle < MinReadyCycle)
1232 MinReadyCycle = ReadyCycle;
1233
1234 // Check for interlocks first. For the purpose of other heuristics, an
1235 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001236 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001237 Pending.push(SU);
1238 else
1239 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001240
1241 // Record this node as an immediate dependent of the scheduled node.
1242 NextSUs.insert(SU);
1243
1244 // If CriticalPath has been computed, then check if the unscheduled nodes
1245 // exceed the ILP window. Before registerRoots, CriticalPath==0.
1246 if (Rem->CriticalPath && (ExpectedLatency + getUnscheduledLatency(SU)
1247 > Rem->CriticalPath + ILPWindow)) {
1248 ShouldIncreaseILP = true;
1249 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << " "
1250 << ExpectedLatency << " + " << getUnscheduledLatency(SU) << '\n');
1251 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001252}
1253
1254/// Move the boundary of scheduled code by one cycle.
1255void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001256 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001257 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001258
Andrew Trick3b87f622012-11-07 07:05:09 +00001259 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001260 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001261 if (MinReadyCycle > NextCycle) {
1262 IssueCount = 0;
1263 NextCycle = MinReadyCycle;
1264 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001265
1266 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001267 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001268 CurrCycle = NextCycle;
1269 }
1270 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001271 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001272 for (; CurrCycle != NextCycle; ++CurrCycle) {
1273 if (isTop())
1274 HazardRec->AdvanceCycle();
1275 else
1276 HazardRec->RecedeCycle();
1277 }
1278 }
1279 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001280 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001281
Andrew Trick3b87f622012-11-07 07:05:09 +00001282 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001283 << CurrCycle << '\n');
1284}
1285
Andrew Trick3b87f622012-11-07 07:05:09 +00001286/// Add the given processor resource to this scheduled zone.
1287void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1288 unsigned Cycles) {
1289 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1290 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1291 << " +(" << Cycles << "x" << Factor
1292 << ") / " << SchedModel->getLatencyFactor() << '\n');
1293
1294 unsigned Count = Factor * Cycles;
1295 ResourceCounts[PIdx] += Count;
1296 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1297 Rem->RemainingCounts[PIdx] -= Count;
1298
1299 // Reset MaxRemainingCount for sanity.
1300 Rem->MaxRemainingCount = 0;
1301
1302 // Check if this resource exceeds the current critical resource by a full
1303 // cycle. If so, it becomes the critical resource.
1304 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1305 >= (int)SchedModel->getLatencyFactor()) {
1306 CritResIdx = PIdx;
1307 DEBUG(dbgs() << " *** Critical resource "
1308 << SchedModel->getProcResource(PIdx)->Name << " x"
1309 << ResourceCounts[PIdx] << '\n');
1310 }
1311}
1312
Andrew Trickb7e02892012-06-05 21:11:27 +00001313/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001314void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001315 // Update the reservation table.
1316 if (HazardRec->isEnabled()) {
1317 if (!isTop() && SU->isCall) {
1318 // Calls are scheduled with their preceding instructions. For bottom-up
1319 // scheduling, clear the pipeline state before emitting.
1320 HazardRec->Reset();
1321 }
1322 HazardRec->EmitInstruction(SU);
1323 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001324 // Update resource counts and critical resource.
1325 if (SchedModel->hasInstrSchedModel()) {
1326 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1327 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1328 for (TargetSchedModel::ProcResIter
1329 PI = SchedModel->getWriteProcResBegin(SC),
1330 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1331 countResource(PI->ProcResourceIdx, PI->Cycles);
1332 }
1333 }
1334 if (isTop()) {
1335 if (SU->getDepth() > ExpectedLatency)
1336 ExpectedLatency = SU->getDepth();
1337 }
1338 else {
1339 if (SU->getHeight() > ExpectedLatency)
1340 ExpectedLatency = SU->getHeight();
1341 }
1342
1343 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1344
Andrew Trick5559ffa2012-06-29 03:23:24 +00001345 // Check the instruction group dispatch limit.
1346 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001347 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001348
1349 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1350 // issue width. However, we commonly reach the maximum. In this case
1351 // opportunistically bump the cycle to avoid uselessly checking everything in
1352 // the readyQ. Furthermore, a single instruction may produce more than one
1353 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001354 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001355 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001356 bumpCycle();
1357 }
1358}
1359
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001360/// Release pending ready nodes in to the available queue. This makes them
1361/// visible to heuristics.
1362void ConvergingScheduler::SchedBoundary::releasePending() {
1363 // If the available queue is empty, it is safe to reset MinReadyCycle.
1364 if (Available.empty())
1365 MinReadyCycle = UINT_MAX;
1366
1367 // Check to see if any of the pending instructions are ready to issue. If
1368 // so, add them to the available queue.
1369 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1370 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001371 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001372
1373 if (ReadyCycle < MinReadyCycle)
1374 MinReadyCycle = ReadyCycle;
1375
1376 if (ReadyCycle > CurrCycle)
1377 continue;
1378
Andrew Trick5559ffa2012-06-29 03:23:24 +00001379 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001380 continue;
1381
1382 Available.push(SU);
1383 Pending.remove(Pending.begin()+i);
1384 --i; --e;
1385 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001386 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001387 CheckPending = false;
1388}
1389
1390/// Remove SU from the ready set for this boundary.
1391void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1392 if (Available.isInQueue(SU))
1393 Available.remove(Available.find(SU));
1394 else {
1395 assert(Pending.isInQueue(SU) && "bad ready count");
1396 Pending.remove(Pending.find(SU));
1397 }
1398}
1399
1400/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001401/// defer any nodes that now hit a hazard, and advance the cycle until at least
1402/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001403SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1404 if (CheckPending)
1405 releasePending();
1406
Andrew Trick3b87f622012-11-07 07:05:09 +00001407 if (IssueCount > 0) {
1408 // Defer any ready instrs that now have a hazard.
1409 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1410 if (checkHazard(*I)) {
1411 Pending.push(*I);
1412 I = Available.remove(I);
1413 continue;
1414 }
1415 ++I;
1416 }
1417 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001418 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001419 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1420 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001421 bumpCycle();
1422 releasePending();
1423 }
1424 if (Available.size() == 1)
1425 return *Available.begin();
1426 return NULL;
1427}
1428
Andrew Trick3b87f622012-11-07 07:05:09 +00001429/// Record the candidate policy for opposite zones with different critical
1430/// resources.
1431///
1432/// If the CriticalZone is latency limited, don't force a policy for the
1433/// candidates here. Instead, When releasing each candidate, releaseNode
1434/// compares the region's critical path to the candidate's height or depth and
1435/// the scheduled zone's expected latency then sets ShouldIncreaseILP.
1436void ConvergingScheduler::balanceZones(
1437 ConvergingScheduler::SchedBoundary &CriticalZone,
1438 ConvergingScheduler::SchedCandidate &CriticalCand,
1439 ConvergingScheduler::SchedBoundary &OppositeZone,
1440 ConvergingScheduler::SchedCandidate &OppositeCand) {
1441
1442 if (!CriticalZone.IsResourceLimited)
1443 return;
1444
1445 SchedRemainder *Rem = CriticalZone.Rem;
1446
1447 // If the critical zone is overconsuming a resource relative to the
1448 // remainder, try to reduce it.
1449 unsigned RemainingCritCount =
1450 Rem->RemainingCounts[CriticalZone.CritResIdx];
1451 if ((int)(Rem->MaxRemainingCount - RemainingCritCount)
1452 > (int)SchedModel->getLatencyFactor()) {
1453 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1454 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1455 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1456 << '\n');
1457 }
1458 // If the other zone is underconsuming a resource relative to the full zone,
1459 // try to increase it.
1460 unsigned OppositeCount =
1461 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1462 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1463 > (int)SchedModel->getLatencyFactor()) {
1464 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1465 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1466 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1467 << '\n');
1468 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001469}
Andrew Trick3b87f622012-11-07 07:05:09 +00001470
1471/// Determine if the scheduled zones exceed resource limits or critical path and
1472/// set each candidate's ReduceHeight policy accordingly.
1473void ConvergingScheduler::checkResourceLimits(
1474 ConvergingScheduler::SchedCandidate &TopCand,
1475 ConvergingScheduler::SchedCandidate &BotCand) {
1476
1477 Bot.checkILPPolicy();
1478 Top.checkILPPolicy();
1479 if (Bot.ShouldIncreaseILP)
1480 BotCand.Policy.ReduceLatency = true;
1481 if (Top.ShouldIncreaseILP)
1482 TopCand.Policy.ReduceLatency = true;
1483
1484 // Handle resource-limited regions.
1485 if (Top.IsResourceLimited && Bot.IsResourceLimited
1486 && Top.CritResIdx == Bot.CritResIdx) {
1487 // If the scheduled critical resource in both zones is no longer the
1488 // critical remaining resource, attempt to reduce resource height both ways.
1489 if (Top.CritResIdx != Rem.CritResIdx) {
1490 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1491 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1492 DEBUG(dbgs() << "Reduce scheduled "
1493 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1494 }
1495 return;
1496 }
1497 // Handle latency-limited regions.
1498 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1499 // If the total scheduled expected latency exceeds the region's critical
1500 // path then reduce latency both ways.
1501 //
1502 // Just because a zone is not resource limited does not mean it is latency
1503 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1504 // to exceed expected latency.
1505 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1506 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1507 TopCand.Policy.ReduceLatency = true;
1508 BotCand.Policy.ReduceLatency = true;
1509 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1510 << " + " << Bot.ExpectedLatency << '\n');
1511 }
1512 return;
1513 }
1514 // The critical resource is different in each zone, so request balancing.
1515
1516 // Compute the cost of each zone.
1517 Rem.MaxRemainingCount = std::max(
1518 Rem.RemainingMicroOps * SchedModel->getMicroOpFactor(),
1519 Rem.RemainingCounts[Rem.CritResIdx]);
1520 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1521 Top.ExpectedCount = std::max(
1522 Top.getCriticalCount(),
1523 Top.ExpectedCount * SchedModel->getLatencyFactor());
1524 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1525 Bot.ExpectedCount = std::max(
1526 Bot.getCriticalCount(),
1527 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1528
1529 balanceZones(Top, TopCand, Bot, BotCand);
1530 balanceZones(Bot, BotCand, Top, TopCand);
1531}
1532
1533void ConvergingScheduler::SchedCandidate::
1534initResourceDelta(const ScheduleDAGMI *DAG,
1535 const TargetSchedModel *SchedModel) {
1536 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1537 return;
1538
1539 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1540 for (TargetSchedModel::ProcResIter
1541 PI = SchedModel->getWriteProcResBegin(SC),
1542 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1543 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1544 ResDelta.CritResources += PI->Cycles;
1545 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1546 ResDelta.DemandedResources += PI->Cycles;
1547 }
1548}
1549
1550/// Return true if this heuristic determines order.
1551static bool tryLess(unsigned TryVal, unsigned CandVal,
1552 ConvergingScheduler::SchedCandidate &TryCand,
1553 ConvergingScheduler::SchedCandidate &Cand,
1554 ConvergingScheduler::CandReason Reason) {
1555 if (TryVal < CandVal) {
1556 TryCand.Reason = Reason;
1557 return true;
1558 }
1559 if (TryVal > CandVal) {
1560 if (Cand.Reason > Reason)
1561 Cand.Reason = Reason;
1562 return true;
1563 }
1564 return false;
1565}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001566
Andrew Trick3b87f622012-11-07 07:05:09 +00001567static bool tryGreater(unsigned TryVal, unsigned CandVal,
1568 ConvergingScheduler::SchedCandidate &TryCand,
1569 ConvergingScheduler::SchedCandidate &Cand,
1570 ConvergingScheduler::CandReason Reason) {
1571 if (TryVal > CandVal) {
1572 TryCand.Reason = Reason;
1573 return true;
1574 }
1575 if (TryVal < CandVal) {
1576 if (Cand.Reason > Reason)
1577 Cand.Reason = Reason;
1578 return true;
1579 }
1580 return false;
1581}
1582
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001583static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1584 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1585}
1586
Andrew Trick3b87f622012-11-07 07:05:09 +00001587/// Apply a set of heursitics to a new candidate. Heuristics are currently
1588/// hierarchical. This may be more efficient than a graduated cost model because
1589/// we don't need to evaluate all aspects of the model for each node in the
1590/// queue. But it's really done to make the heuristics easier to debug and
1591/// statistically analyze.
1592///
1593/// \param Cand provides the policy and current best candidate.
1594/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1595/// \param Zone describes the scheduled zone that we are extending.
1596/// \param RPTracker describes reg pressure within the scheduled zone.
1597/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1598void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1599 SchedCandidate &TryCand,
1600 SchedBoundary &Zone,
1601 const RegPressureTracker &RPTracker,
1602 RegPressureTracker &TempTracker) {
1603
1604 // Always initialize TryCand's RPDelta.
1605 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1606 DAG->getRegionCriticalPSets(),
1607 DAG->getRegPressure().MaxSetPressure);
1608
1609 // Initialize the candidate if needed.
1610 if (!Cand.isValid()) {
1611 TryCand.Reason = NodeOrder;
1612 return;
1613 }
1614 // Avoid exceeding the target's limit.
1615 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1616 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1617 return;
1618 if (Cand.Reason == SingleExcess)
1619 Cand.Reason = MultiPressure;
1620
1621 // Avoid increasing the max critical pressure in the scheduled region.
1622 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1623 Cand.RPDelta.CriticalMax.UnitIncrease,
1624 TryCand, Cand, SingleCritical))
1625 return;
1626 if (Cand.Reason == SingleCritical)
1627 Cand.Reason = MultiPressure;
1628
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001629 // Keep clustered nodes together to encourage downstream peephole
1630 // optimizations which may reduce resource requirements.
1631 //
1632 // This is a best effort to set things up for a post-RA pass. Optimizations
1633 // like generating loads of multiple registers should ideally be done within
1634 // the scheduler pass by combining the loads during DAG postprocessing.
1635 const SUnit *NextClusterSU =
1636 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1637 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1638 TryCand, Cand, Cluster))
1639 return;
1640 // Currently, weak edges are for clustering, so we hard-code that reason.
1641 // However, deferring the current TryCand will not change Cand's reason.
1642 CandReason OrigReason = Cand.Reason;
1643 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1644 getWeakLeft(Cand.SU, Zone.isTop()),
1645 TryCand, Cand, Cluster)) {
1646 Cand.Reason = OrigReason;
1647 return;
1648 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001649 // Avoid critical resource consumption and balance the schedule.
1650 TryCand.initResourceDelta(DAG, SchedModel);
1651 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1652 TryCand, Cand, ResourceReduce))
1653 return;
1654 if (tryGreater(TryCand.ResDelta.DemandedResources,
1655 Cand.ResDelta.DemandedResources,
1656 TryCand, Cand, ResourceDemand))
1657 return;
1658
1659 // Avoid serializing long latency dependence chains.
1660 if (Cand.Policy.ReduceLatency) {
1661 if (Zone.isTop()) {
1662 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1663 > Zone.ExpectedCount) {
1664 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1665 TryCand, Cand, TopDepthReduce))
1666 return;
1667 }
1668 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1669 TryCand, Cand, TopPathReduce))
1670 return;
1671 }
1672 else {
1673 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1674 > Zone.ExpectedCount) {
1675 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1676 TryCand, Cand, BotHeightReduce))
1677 return;
1678 }
1679 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1680 TryCand, Cand, BotPathReduce))
1681 return;
1682 }
1683 }
1684
1685 // Avoid increasing the max pressure of the entire region.
1686 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1687 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1688 return;
1689 if (Cand.Reason == SingleMax)
1690 Cand.Reason = MultiPressure;
1691
1692 // Prefer immediate defs/users of the last scheduled instruction. This is a
1693 // nice pressure avoidance strategy that also conserves the processor's
1694 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001695 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1696 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001697 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001698
Andrew Trick3b87f622012-11-07 07:05:09 +00001699 // Fall through to original instruction order.
1700 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1701 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1702 TryCand.Reason = NodeOrder;
1703 }
1704}
Andrew Trick28ebc892012-05-10 21:06:19 +00001705
Andrew Trick5429a6b2012-05-17 22:37:09 +00001706/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1707/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001708static bool compareRPDelta(const RegPressureDelta &LHS,
1709 const RegPressureDelta &RHS) {
1710 // Compare each component of pressure in decreasing order of importance
1711 // without checking if any are valid. Invalid PressureElements are assumed to
1712 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001713
1714 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001715 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1716 DEBUG(dbgs() << "RP excess top - bot: "
1717 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001718 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001719 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001720 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001721 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1722 DEBUG(dbgs() << "RP critical top - bot: "
1723 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1724 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001725 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001726 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001727 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001728 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1729 DEBUG(dbgs() << "RP current top - bot: "
1730 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1731 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001732 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001733 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001734 return false;
1735}
1736
Andrew Trick3b87f622012-11-07 07:05:09 +00001737#ifndef NDEBUG
1738const char *ConvergingScheduler::getReasonStr(
1739 ConvergingScheduler::CandReason Reason) {
1740 switch (Reason) {
1741 case NoCand: return "NOCAND ";
1742 case SingleExcess: return "REG-EXCESS";
1743 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001744 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001745 case SingleMax: return "REG-MAX ";
1746 case MultiPressure: return "REG-MULTI ";
1747 case ResourceReduce: return "RES-REDUCE";
1748 case ResourceDemand: return "RES-DEMAND";
1749 case TopDepthReduce: return "TOP-DEPTH ";
1750 case TopPathReduce: return "TOP-PATH ";
1751 case BotHeightReduce:return "BOT-HEIGHT";
1752 case BotPathReduce: return "BOT-PATH ";
1753 case NextDefUse: return "DEF-USE ";
1754 case NodeOrder: return "ORDER ";
1755 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001756 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001757}
1758
1759void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1760 const SchedBoundary &Zone) {
1761 const char *Label = getReasonStr(Cand.Reason);
1762 PressureElement P;
1763 unsigned ResIdx = 0;
1764 unsigned Latency = 0;
1765 switch (Cand.Reason) {
1766 default:
1767 break;
1768 case SingleExcess:
1769 P = Cand.RPDelta.Excess;
1770 break;
1771 case SingleCritical:
1772 P = Cand.RPDelta.CriticalMax;
1773 break;
1774 case SingleMax:
1775 P = Cand.RPDelta.CurrentMax;
1776 break;
1777 case ResourceReduce:
1778 ResIdx = Cand.Policy.ReduceResIdx;
1779 break;
1780 case ResourceDemand:
1781 ResIdx = Cand.Policy.DemandResIdx;
1782 break;
1783 case TopDepthReduce:
1784 Latency = Cand.SU->getDepth();
1785 break;
1786 case TopPathReduce:
1787 Latency = Cand.SU->getHeight();
1788 break;
1789 case BotHeightReduce:
1790 Latency = Cand.SU->getHeight();
1791 break;
1792 case BotPathReduce:
1793 Latency = Cand.SU->getDepth();
1794 break;
1795 }
1796 dbgs() << Label << " " << Zone.Available.getName() << " ";
1797 if (P.isValid())
1798 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1799 << " ";
1800 else
1801 dbgs() << " ";
1802 if (ResIdx)
1803 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1804 else
1805 dbgs() << " ";
1806 if (Latency)
1807 dbgs() << Latency << " cycles ";
1808 else
1809 dbgs() << " ";
1810 Cand.SU->dump(DAG);
1811}
1812#endif
1813
Andrew Trick7196a8f2012-05-10 21:06:16 +00001814/// Pick the best candidate from the top queue.
1815///
1816/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1817/// DAG building. To adjust for the current scheduling location we need to
1818/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001819void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1820 const RegPressureTracker &RPTracker,
1821 SchedCandidate &Cand) {
1822 ReadyQueue &Q = Zone.Available;
1823
Andrew Trickf3234242012-05-24 22:11:12 +00001824 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001825
Andrew Trick7196a8f2012-05-10 21:06:16 +00001826 // getMaxPressureDelta temporarily modifies the tracker.
1827 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1828
Andrew Trick8c2d9212012-05-24 22:11:03 +00001829 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001830
Andrew Trick3b87f622012-11-07 07:05:09 +00001831 SchedCandidate TryCand(Cand.Policy);
1832 TryCand.SU = *I;
1833 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1834 if (TryCand.Reason != NoCand) {
1835 // Initialize resource delta if needed in case future heuristics query it.
1836 if (TryCand.ResDelta == SchedResourceDelta())
1837 TryCand.initResourceDelta(DAG, SchedModel);
1838 Cand.setBest(TryCand);
1839 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001840 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001841 TryCand.SU = *I;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001842 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001843}
1844
1845static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1846 bool IsTop) {
1847 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1848 << " SU(" << Cand.SU->NodeNum << ") "
1849 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001850}
1851
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001852/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001853SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001854 // Schedule as far as possible in the direction of no choice. This is most
1855 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001856 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001857 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001858 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001859 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001860 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001861 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001862 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001863 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001864 CandPolicy NoPolicy;
1865 SchedCandidate BotCand(NoPolicy);
1866 SchedCandidate TopCand(NoPolicy);
1867 checkResourceLimits(TopCand, BotCand);
1868
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001869 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001870 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1871 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001872
1873 // If either Q has a single candidate that provides the least increase in
1874 // Excess pressure, we can immediately schedule from that Q.
1875 //
1876 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1877 // affects picking from either Q. If scheduling in one direction must
1878 // increase pressure for one of the excess PSets, then schedule in that
1879 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001880 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001881 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001882 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001883 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001884 }
1885 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001886 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1887 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001888
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001889 // If either Q has a single candidate that minimizes pressure above the
1890 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001891 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1892 if (TopCand.Reason < BotCand.Reason) {
1893 IsTopNode = true;
1894 tracePick(TopCand, IsTopNode);
1895 return TopCand.SU;
1896 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001897 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001898 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001899 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001900 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001901 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001902 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001903 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001904 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001905 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001906 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001907 // Otherwise prefer the bottom candidate, in node order if all else failed.
1908 if (TopCand.Reason < BotCand.Reason) {
1909 IsTopNode = true;
1910 tracePick(TopCand, IsTopNode);
1911 return TopCand.SU;
1912 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001913 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001914 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001915 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001916}
1917
1918/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001919SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1920 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001921 assert(Top.Available.empty() && Top.Pending.empty() &&
1922 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001923 return NULL;
1924 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001925 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00001926 do {
1927 if (ForceTopDown) {
1928 SU = Top.pickOnlyChoice();
1929 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001930 CandPolicy NoPolicy;
1931 SchedCandidate TopCand(NoPolicy);
1932 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1933 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00001934 SU = TopCand.SU;
1935 }
1936 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001937 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001938 else if (ForceBottomUp) {
1939 SU = Bot.pickOnlyChoice();
1940 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001941 CandPolicy NoPolicy;
1942 SchedCandidate BotCand(NoPolicy);
1943 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1944 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00001945 SU = BotCand.SU;
1946 }
1947 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001948 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001949 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00001950 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00001951 }
1952 } while (SU->isScheduled);
1953
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001954 if (SU->isTopReady())
1955 Top.removeReady(SU);
1956 if (SU->isBottomReady())
1957 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00001958
1959 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1960 << " Scheduling Instruction in cycle "
1961 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1962 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001963 return SU;
1964}
1965
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001966/// Update the scheduler's state after scheduling a node. This is the same node
1967/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00001968/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001969void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001970 if (IsTopNode) {
1971 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001972 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001973 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001974 else {
1975 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001976 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001977 }
1978}
1979
Andrew Trick17d35e52012-03-14 04:00:41 +00001980/// Create the standard converging machine scheduler. This will be used as the
1981/// default scheduler if the target does not set a default.
1982static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001983 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001984 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001985 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
1986 // Register DAG post-processors.
1987 if (EnableLoadCluster)
1988 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
1989 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00001990}
1991static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00001992ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1993 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00001994
1995//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00001996// ILP Scheduler. Currently for experimental analysis of heuristics.
1997//===----------------------------------------------------------------------===//
1998
1999namespace {
2000/// \brief Order nodes by the ILP metric.
2001struct ILPOrder {
2002 ScheduleDAGILP *ILP;
2003 bool MaximizeILP;
2004
2005 ILPOrder(ScheduleDAGILP *ilp, bool MaxILP): ILP(ilp), MaximizeILP(MaxILP) {}
2006
2007 /// \brief Apply a less-than relation on node priority.
2008 bool operator()(const SUnit *A, const SUnit *B) const {
2009 // Return true if A comes after B in the Q.
2010 if (MaximizeILP)
2011 return ILP->getILP(A) < ILP->getILP(B);
2012 else
2013 return ILP->getILP(A) > ILP->getILP(B);
2014 }
2015};
2016
2017/// \brief Schedule based on the ILP metric.
2018class ILPScheduler : public MachineSchedStrategy {
2019 ScheduleDAGILP ILP;
2020 ILPOrder Cmp;
2021
2022 std::vector<SUnit*> ReadyQ;
2023public:
2024 ILPScheduler(bool MaximizeILP)
2025 : ILP(/*BottomUp=*/true), Cmp(&ILP, MaximizeILP) {}
2026
2027 virtual void initialize(ScheduleDAGMI *DAG) {
2028 ReadyQ.clear();
2029 ILP.resize(DAG->SUnits.size());
2030 }
2031
2032 virtual void registerRoots() {
2033 for (std::vector<SUnit*>::const_iterator
2034 I = ReadyQ.begin(), E = ReadyQ.end(); I != E; ++I) {
2035 ILP.computeILP(*I);
2036 }
2037 }
2038
2039 /// Implement MachineSchedStrategy interface.
2040 /// -----------------------------------------
2041
2042 virtual SUnit *pickNode(bool &IsTopNode) {
2043 if (ReadyQ.empty()) return NULL;
2044 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2045 SUnit *SU = ReadyQ.back();
2046 ReadyQ.pop_back();
2047 IsTopNode = false;
2048 DEBUG(dbgs() << "*** Scheduling " << *SU->getInstr()
2049 << " ILP: " << ILP.getILP(SU) << '\n');
2050 return SU;
2051 }
2052
2053 virtual void schedNode(SUnit *, bool) {}
2054
2055 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2056
2057 virtual void releaseBottomNode(SUnit *SU) {
2058 ReadyQ.push_back(SU);
2059 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2060 }
2061};
2062} // namespace
2063
2064static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2065 return new ScheduleDAGMI(C, new ILPScheduler(true));
2066}
2067static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2068 return new ScheduleDAGMI(C, new ILPScheduler(false));
2069}
2070static MachineSchedRegistry ILPMaxRegistry(
2071 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2072static MachineSchedRegistry ILPMinRegistry(
2073 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2074
2075//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002076// Machine Instruction Shuffler for Correctness Testing
2077//===----------------------------------------------------------------------===//
2078
Andrew Trick96f678f2012-01-13 06:30:30 +00002079#ifndef NDEBUG
2080namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002081/// Apply a less-than relation on the node order, which corresponds to the
2082/// instruction order prior to scheduling. IsReverse implements greater-than.
2083template<bool IsReverse>
2084struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002085 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002086 if (IsReverse)
2087 return A->NodeNum > B->NodeNum;
2088 else
2089 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002090 }
2091};
2092
Andrew Trick96f678f2012-01-13 06:30:30 +00002093/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002094class InstructionShuffler : public MachineSchedStrategy {
2095 bool IsAlternating;
2096 bool IsTopDown;
2097
2098 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2099 // gives nodes with a higher number higher priority causing the latest
2100 // instructions to be scheduled first.
2101 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2102 TopQ;
2103 // When scheduling bottom-up, use greater-than as the queue priority.
2104 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2105 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002106public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002107 InstructionShuffler(bool alternate, bool topdown)
2108 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002109
Andrew Trick17d35e52012-03-14 04:00:41 +00002110 virtual void initialize(ScheduleDAGMI *) {
2111 TopQ.clear();
2112 BottomQ.clear();
2113 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002114
Andrew Trick17d35e52012-03-14 04:00:41 +00002115 /// Implement MachineSchedStrategy interface.
2116 /// -----------------------------------------
2117
2118 virtual SUnit *pickNode(bool &IsTopNode) {
2119 SUnit *SU;
2120 if (IsTopDown) {
2121 do {
2122 if (TopQ.empty()) return NULL;
2123 SU = TopQ.top();
2124 TopQ.pop();
2125 } while (SU->isScheduled);
2126 IsTopNode = true;
2127 }
2128 else {
2129 do {
2130 if (BottomQ.empty()) return NULL;
2131 SU = BottomQ.top();
2132 BottomQ.pop();
2133 } while (SU->isScheduled);
2134 IsTopNode = false;
2135 }
2136 if (IsAlternating)
2137 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002138 return SU;
2139 }
2140
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002141 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2142
Andrew Trick17d35e52012-03-14 04:00:41 +00002143 virtual void releaseTopNode(SUnit *SU) {
2144 TopQ.push(SU);
2145 }
2146 virtual void releaseBottomNode(SUnit *SU) {
2147 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002148 }
2149};
2150} // namespace
2151
Andrew Trickc174eaf2012-03-08 01:41:12 +00002152static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002153 bool Alternate = !ForceTopDown && !ForceBottomUp;
2154 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002155 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002156 "-misched-topdown incompatible with -misched-bottomup");
2157 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002158}
Andrew Trick17d35e52012-03-14 04:00:41 +00002159static MachineSchedRegistry ShufflerRegistry(
2160 "shuffle", "Shuffle machine instructions alternating directions",
2161 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002162#endif // !NDEBUG