blob: c621ca96bf5d5be7265a5ba7e031e47be4db5282 [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 Trickc174eaf2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/PriorityQueue.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszak760fa5d2013-03-10 13:11:23 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000024#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000025#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000026#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000027#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/ErrorHandling.h"
Andrew Trick30849792013-01-25 07:45:29 +000031#include "llvm/Support/GraphWriter.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000032#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000033#include <queue>
34
Andrew Trick96f678f2012-01-13 06:30:30 +000035using namespace llvm;
36
Andrew Trick78e5efe2012-09-11 00:39:15 +000037namespace llvm {
38cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
39 cl::desc("Force top-down list scheduling"));
40cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
41 cl::desc("Force bottom-up list scheduling"));
42}
Andrew Trick17d35e52012-03-14 04:00:41 +000043
Andrew Trick0df7f882012-03-07 00:18:25 +000044#ifndef NDEBUG
45static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
46 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000047
48static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
49 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000050#else
51static bool ViewMISchedDAGs = false;
52#endif // NDEBUG
53
Andrew Trick9b5caaa2012-11-12 19:40:10 +000054// Experimental heuristics
55static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000056 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000057
Andrew Trick6996fd02012-11-12 19:52:20 +000058// Experimental heuristics
59static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000060 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000061
Andrew Trickfff2d3a2013-03-08 05:40:34 +000062static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
63 cl::desc("Verify machine instrs before and after machine scheduling"));
64
Andrew Trick178f7d02013-01-25 04:01:04 +000065// DAG subtrees must have at least this many nodes.
66static const unsigned MinSubtreeSize = 8;
67
Andrew Trick5edf2f02012-01-14 02:17:06 +000068//===----------------------------------------------------------------------===//
69// Machine Instruction Scheduling Pass and Registry
70//===----------------------------------------------------------------------===//
71
Andrew Trick86b7e2a2012-04-24 20:36:19 +000072MachineSchedContext::MachineSchedContext():
73 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
74 RegClassInfo = new RegisterClassInfo();
75}
76
77MachineSchedContext::~MachineSchedContext() {
78 delete RegClassInfo;
79}
80
Andrew Trick96f678f2012-01-13 06:30:30 +000081namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000082/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000083class MachineScheduler : public MachineSchedContext,
84 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000085public:
Andrew Trick42b7a712012-01-17 06:55:03 +000086 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000087
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
89
90 virtual void releaseMemory() {}
91
92 virtual bool runOnMachineFunction(MachineFunction&);
93
94 virtual void print(raw_ostream &O, const Module* = 0) const;
95
96 static char ID; // Class identification, replacement for typeinfo
97};
98} // namespace
99
Andrew Trick42b7a712012-01-17 06:55:03 +0000100char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +0000101
Andrew Trick42b7a712012-01-17 06:55:03 +0000102char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000103
Andrew Trick42b7a712012-01-17 06:55:03 +0000104INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000105 "Machine Instruction Scheduler", false, false)
106INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
107INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
108INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000109INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000110 "Machine Instruction Scheduler", false, false)
111
Andrew Trick42b7a712012-01-17 06:55:03 +0000112MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000113: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000114 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000115}
116
Andrew Trick42b7a712012-01-17 06:55:03 +0000117void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000118 AU.setPreservesCFG();
119 AU.addRequiredID(MachineDominatorsID);
120 AU.addRequired<MachineLoopInfo>();
121 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000122 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000123 AU.addRequired<SlotIndexes>();
124 AU.addPreserved<SlotIndexes>();
125 AU.addRequired<LiveIntervals>();
126 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000127 MachineFunctionPass::getAnalysisUsage(AU);
128}
129
Andrew Trick96f678f2012-01-13 06:30:30 +0000130MachinePassRegistry MachineSchedRegistry::Registry;
131
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000132/// A dummy default scheduler factory indicates whether the scheduler
133/// is overridden on the command line.
134static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
135 return 0;
136}
Andrew Trick96f678f2012-01-13 06:30:30 +0000137
138/// MachineSchedOpt allows command line selection of the scheduler.
139static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
140 RegisterPassParser<MachineSchedRegistry> >
141MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000142 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000143 cl::desc("Machine instruction scheduler to use"));
144
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000145static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000146DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000147 useDefaultMachineSched);
148
Andrew Trick17d35e52012-03-14 04:00:41 +0000149/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000150/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000151static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000152
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000153
154/// Decrement this iterator until reaching the top or a non-debug instr.
155static MachineBasicBlock::iterator
156priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
157 assert(I != Beg && "reached the top of the region, cannot decrement");
158 while (--I != Beg) {
159 if (!I->isDebugValue())
160 break;
161 }
162 return I;
163}
164
165/// If this iterator is a debug value, increment until reaching the End or a
166/// non-debug instruction.
167static MachineBasicBlock::iterator
168nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000169 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000170 if (!I->isDebugValue())
171 break;
172 }
173 return I;
174}
175
Andrew Trickcb058d52012-03-14 04:00:38 +0000176/// Top-level MachineScheduler pass driver.
177///
178/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000179/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
180/// consistent with the DAG builder, which traverses the interior of the
181/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000182///
183/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000184/// simplifying the DAG builder's support for "special" target instructions.
185/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000186/// scheduling boundaries, for example to bundle the boudary instructions
187/// without reordering them. This creates complexity, because the target
188/// scheduler must update the RegionBegin and RegionEnd positions cached by
189/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
190/// design would be to split blocks at scheduling boundaries, but LLVM has a
191/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000192bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000193 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
194
Andrew Trick96f678f2012-01-13 06:30:30 +0000195 // Initialize the context of the pass.
196 MF = &mf;
197 MLI = &getAnalysis<MachineLoopInfo>();
198 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000199 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000200 AA = &getAnalysis<AliasAnalysis>();
201
Lang Hames907cc8f2012-01-27 22:36:19 +0000202 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000203 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000204
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000205 if (VerifyScheduling) {
206 DEBUG(LIS->print(dbgs()));
207 MF->verify(this, "Before machine scheduling.");
208 }
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000209 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000210
Andrew Trick96f678f2012-01-13 06:30:30 +0000211 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000212 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
213 if (Ctor == useDefaultMachineSched) {
214 // Get the default scheduler set by the target.
215 Ctor = MachineSchedRegistry::getDefault();
216 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000217 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000218 MachineSchedRegistry::setDefault(Ctor);
219 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000220 }
221 // Instantiate the selected scheduler.
222 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
223
224 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000225 //
226 // TODO: Visit blocks in global postorder or postorder within the bottom-up
227 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000228 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
229 MBB != MBBEnd; ++MBB) {
230
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000231 Scheduler->startBlock(MBB);
232
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000233 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000234 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000235 // boundary at the bottom of the region. The DAG does not include RegionEnd,
236 // but the region does (i.e. the next RegionEnd is above the previous
237 // RegionBegin). If the current block has no terminator then RegionEnd ==
238 // MBB->end() for the bottom region.
239 //
240 // The Scheduler may insert instructions during either schedule() or
241 // exitRegion(), even for empty regions. So the local iterators 'I' and
242 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000243 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000244 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000245 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000246
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000247 // Avoid decrementing RegionEnd for blocks with no terminator.
248 if (RegionEnd != MBB->end()
249 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
250 --RegionEnd;
251 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000252 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000253 }
254
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000255 // The next region starts above the previous region. Look backward in the
256 // instruction stream until we find the nearest boundary.
257 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000258 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000259 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
260 break;
261 }
Andrew Trick47c14452012-03-07 05:21:52 +0000262 // Notify the scheduler of the region, even if we may skip scheduling
263 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000264 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000265
266 // Skip empty scheduling regions (0 or 1 schedulable instructions).
267 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000268 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000269 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000270 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000271 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000272 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000273 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000274 DEBUG(dbgs() << MF->getName()
Andrew Trickc8554232013-01-25 07:45:31 +0000275 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
276 << "\n From: " << *I << " To: ";
Andrew Trick291411c2012-02-08 02:17:21 +0000277 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
278 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000279 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000280
Andrew Trickd24da972012-03-09 03:46:42 +0000281 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000282 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000283 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000284
285 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000286 Scheduler->exitRegion();
287
288 // Scheduling has invalidated the current iterator 'I'. Ask the
289 // scheduler for the top of it's scheduled region.
290 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000291 }
Andrew Trick22764532012-11-06 07:10:34 +0000292 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000293 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000294 }
Andrew Trick830da402012-04-01 07:24:23 +0000295 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000296 DEBUG(LIS->print(dbgs()));
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000297 if (VerifyScheduling)
298 MF->verify(this, "After machine scheduling.");
Andrew Trick96f678f2012-01-13 06:30:30 +0000299 return true;
300}
301
Andrew Trick42b7a712012-01-17 06:55:03 +0000302void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000303 // unimplemented
304}
305
Manman Renb720be62012-09-11 22:23:19 +0000306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000307void ReadyQueue::dump() {
Andrew Trick11189f72013-04-05 00:31:29 +0000308 dbgs() << " " << Name << ": ";
Andrew Trick78e5efe2012-09-11 00:39:15 +0000309 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
310 dbgs() << Queue[i]->NodeNum << " ";
311 dbgs() << "\n";
312}
313#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000314
315//===----------------------------------------------------------------------===//
316// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
317// preservation.
318//===----------------------------------------------------------------------===//
319
Andrew Trick178f7d02013-01-25 04:01:04 +0000320ScheduleDAGMI::~ScheduleDAGMI() {
321 delete DFSResult;
322 DeleteContainerPointers(Mutations);
323 delete SchedImpl;
324}
325
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000326bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000327 if (SuccSU != &ExitSU) {
328 // Do not use WillCreateCycle, it assumes SD scheduling.
329 // If Pred is reachable from Succ, then the edge creates a cycle.
330 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
331 return false;
332 Topo.AddPred(SuccSU, PredDep.getSUnit());
333 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000334 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
335 // Return true regardless of whether a new edge needed to be inserted.
336 return true;
337}
338
Andrew Trickc174eaf2012-03-08 01:41:12 +0000339/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
340/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000341///
342/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000343void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000344 SUnit *SuccSU = SuccEdge->getSUnit();
345
Andrew Trickae692f22012-11-12 19:28:57 +0000346 if (SuccEdge->isWeak()) {
347 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000348 if (SuccEdge->isCluster())
349 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000350 return;
351 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000352#ifndef NDEBUG
353 if (SuccSU->NumPredsLeft == 0) {
354 dbgs() << "*** Scheduling failed! ***\n";
355 SuccSU->dump(this);
356 dbgs() << " has been released too many times!\n";
357 llvm_unreachable(0);
358 }
359#endif
360 --SuccSU->NumPredsLeft;
361 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000362 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000363}
364
365/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000366void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000367 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
368 I != E; ++I) {
369 releaseSucc(SU, &*I);
370 }
371}
372
Andrew Trick17d35e52012-03-14 04:00:41 +0000373/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
374/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000375///
376/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000377void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
378 SUnit *PredSU = PredEdge->getSUnit();
379
Andrew Trickae692f22012-11-12 19:28:57 +0000380 if (PredEdge->isWeak()) {
381 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000382 if (PredEdge->isCluster())
383 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000384 return;
385 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000386#ifndef NDEBUG
387 if (PredSU->NumSuccsLeft == 0) {
388 dbgs() << "*** Scheduling failed! ***\n";
389 PredSU->dump(this);
390 dbgs() << " has been released too many times!\n";
391 llvm_unreachable(0);
392 }
393#endif
394 --PredSU->NumSuccsLeft;
395 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
396 SchedImpl->releaseBottomNode(PredSU);
397}
398
399/// releasePredecessors - Call releasePred on each of SU's predecessors.
400void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
401 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
402 I != E; ++I) {
403 releasePred(SU, &*I);
404 }
405}
406
407void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
408 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000409 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000410 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000411 ++RegionBegin;
412
413 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000414 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000415
416 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000417 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000418
419 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000420 if (RegionBegin == InsertPos)
421 RegionBegin = MI;
422}
423
Andrew Trick0b0d8992012-03-21 04:12:07 +0000424bool ScheduleDAGMI::checkSchedLimit() {
425#ifndef NDEBUG
426 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
427 CurrentTop = CurrentBottom;
428 return false;
429 }
430 ++NumInstrsScheduled;
431#endif
432 return true;
433}
434
Andrew Trick006e1ab2012-04-24 17:56:43 +0000435/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
436/// crossing a scheduling boundary. [begin, end) includes all instructions in
437/// the region, including the boundary itself and single-instruction regions
438/// that don't get scheduled.
439void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
440 MachineBasicBlock::iterator begin,
441 MachineBasicBlock::iterator end,
442 unsigned endcount)
443{
444 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000445
446 // For convenience remember the end of the liveness region.
447 LiveRegionEnd =
448 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
449}
450
451// Setup the register pressure trackers for the top scheduled top and bottom
452// scheduled regions.
453void ScheduleDAGMI::initRegPressure() {
454 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
455 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
456
457 // Close the RPTracker to finalize live ins.
458 RPTracker.closeRegion();
459
Andrew Trickbb0a2422012-05-24 22:11:14 +0000460 DEBUG(RPTracker.getPressure().dump(TRI));
461
Andrew Trick7f8ab782012-05-10 21:06:10 +0000462 // Initialize the live ins and live outs.
463 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
464 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
465
466 // Close one end of the tracker so we can call
467 // getMaxUpward/DownwardPressureDelta before advancing across any
468 // instructions. This converts currently live regs into live ins/outs.
469 TopRPTracker.closeTop();
470 BotRPTracker.closeBottom();
471
472 // Account for liveness generated by the region boundary.
473 if (LiveRegionEnd != RegionEnd)
474 BotRPTracker.recede();
475
476 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000477
478 // Cache the list of excess pressure sets in this region. This will also track
479 // the max pressure in the scheduled code for these sets.
480 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +0000481 const std::vector<unsigned> &RegionPressure =
482 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000483 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
484 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000485 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
486 << "Limit " << Limit
487 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000488 if (RegionPressure[i] > Limit)
489 RegionCriticalPSets.push_back(PressureElement(i, 0));
490 }
491 DEBUG(dbgs() << "Excess PSets: ";
492 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
493 dbgs() << TRI->getRegPressureSetName(
494 RegionCriticalPSets[i].PSetID) << " ";
495 dbgs() << "\n");
496}
497
498// FIXME: When the pressure tracker deals in pressure differences then we won't
499// iterate over all RegionCriticalPSets[i].
500void ScheduleDAGMI::
Jakub Staszakb717a502013-02-16 15:47:26 +0000501updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000502 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
503 unsigned ID = RegionCriticalPSets[i].PSetID;
504 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
505 if ((int)NewMaxPressure[ID] > MaxUnits)
506 MaxUnits = NewMaxPressure[ID];
507 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000508}
509
Andrew Trick17d35e52012-03-14 04:00:41 +0000510/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000511/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
512/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000513///
514/// This is a skeletal driver, with all the functionality pushed into helpers,
515/// so that it can be easilly extended by experimental schedulers. Generally,
516/// implementing MachineSchedStrategy should be sufficient to implement a new
517/// scheduling algorithm. However, if a scheduler further subclasses
518/// ScheduleDAGMI then it will want to override this virtual method in order to
519/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000520void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000521 buildDAGWithRegPressure();
522
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000523 Topo.InitDAGTopologicalSorting();
524
Andrew Trickd039b382012-09-14 17:22:42 +0000525 postprocessDAG();
526
Andrew Trick4e1fb182013-01-25 06:33:57 +0000527 SmallVector<SUnit*, 8> TopRoots, BotRoots;
528 findRootsAndBiasEdges(TopRoots, BotRoots);
529
530 // Initialize the strategy before modifying the DAG.
531 // This may initialize a DFSResult to be used for queue priority.
532 SchedImpl->initialize(this);
533
Andrew Trick78e5efe2012-09-11 00:39:15 +0000534 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
535 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000536 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000537
Andrew Trick4e1fb182013-01-25 06:33:57 +0000538 // Initialize ready queues now that the DAG and priority data are finalized.
539 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000540
541 bool IsTopNode = false;
542 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000543 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000544 if (!checkSchedLimit())
545 break;
546
547 scheduleMI(SU, IsTopNode);
548
549 updateQueues(SU, IsTopNode);
550 }
551 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
552
553 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000554
555 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000556 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000557 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
558 dumpSchedule();
559 dbgs() << '\n';
560 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000561}
562
563/// Build the DAG and setup three register pressure trackers.
564void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000565 // Initialize the register pressure tracker used by buildSchedGraph.
566 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000567
Andrew Trick7f8ab782012-05-10 21:06:10 +0000568 // Account for liveness generate by the region boundary.
569 if (LiveRegionEnd != RegionEnd)
570 RPTracker.recede();
571
572 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000573 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000574
Andrew Trick7f8ab782012-05-10 21:06:10 +0000575 // Initialize top/bottom trackers after computing region pressure.
576 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000577}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000578
Andrew Trickd039b382012-09-14 17:22:42 +0000579/// Apply each ScheduleDAGMutation step in order.
580void ScheduleDAGMI::postprocessDAG() {
581 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
582 Mutations[i]->apply(this);
583 }
584}
585
Andrew Trick4e1fb182013-01-25 06:33:57 +0000586void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000587 if (!DFSResult)
588 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
589 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000590 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000591 DFSResult->resize(SUnits.size());
592 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000593 ScheduledTrees.resize(DFSResult->getNumSubtrees());
594}
595
Andrew Trick4e1fb182013-01-25 06:33:57 +0000596void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
597 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000598 for (std::vector<SUnit>::iterator
599 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000600 SUnit *SU = &(*I);
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000601 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickdb417062013-01-24 02:09:57 +0000602
603 // Order predecessors so DFSResult follows the critical path.
604 SU->biasCriticalPath();
605
Andrew Trick1e94e982012-10-15 18:02:27 +0000606 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000607 if (!I->NumPredsLeft)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000608 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000609 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000610 if (!I->NumSuccsLeft)
Andrew Trickae692f22012-11-12 19:28:57 +0000611 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000612 }
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000613 ExitSU.biasCriticalPath();
Andrew Trick1e94e982012-10-15 18:02:27 +0000614}
615
Andrew Trick78e5efe2012-09-11 00:39:15 +0000616/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000617void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
618 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000619 NextClusterSucc = NULL;
620 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000621
Andrew Trickae692f22012-11-12 19:28:57 +0000622 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000623 //
624 // Nodes with unreleased weak edges can still be roots.
625 // Release top roots in forward order.
626 for (SmallVectorImpl<SUnit*>::const_iterator
627 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
628 SchedImpl->releaseTopNode(*I);
629 }
630 // Release bottom roots in reverse order so the higher priority nodes appear
631 // first. This is more natural and slightly more efficient.
632 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
633 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
634 SchedImpl->releaseBottomNode(*I);
635 }
Andrew Trickae692f22012-11-12 19:28:57 +0000636
Andrew Trickc174eaf2012-03-08 01:41:12 +0000637 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000638 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000639
Andrew Trick1e94e982012-10-15 18:02:27 +0000640 SchedImpl->registerRoots();
641
Andrew Trick657b75b2012-12-01 01:22:49 +0000642 // Advance past initial DebugValues.
643 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000644 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000645 TopRPTracker.setPos(CurrentTop);
646
Andrew Trick17d35e52012-03-14 04:00:41 +0000647 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000648}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000649
Andrew Trick78e5efe2012-09-11 00:39:15 +0000650/// Move an instruction and update register pressure.
651void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
652 // Move the instruction to its new location in the instruction stream.
653 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000654
Andrew Trick78e5efe2012-09-11 00:39:15 +0000655 if (IsTopNode) {
656 assert(SU->isTopReady() && "node still has unscheduled dependencies");
657 if (&*CurrentTop == MI)
658 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000659 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000660 moveInstruction(MI, CurrentTop);
661 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000662 }
Andrew Trick000b2502012-04-24 18:04:37 +0000663
Andrew Trick78e5efe2012-09-11 00:39:15 +0000664 // Update top scheduled pressure.
665 TopRPTracker.advance();
666 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
667 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
668 }
669 else {
670 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
671 MachineBasicBlock::iterator priorII =
672 priorNonDebug(CurrentBottom, CurrentTop);
673 if (&*priorII == MI)
674 CurrentBottom = priorII;
675 else {
676 if (&*CurrentTop == MI) {
677 CurrentTop = nextIfDebug(++CurrentTop, priorII);
678 TopRPTracker.setPos(CurrentTop);
679 }
680 moveInstruction(MI, CurrentBottom);
681 CurrentBottom = MI;
682 }
683 // Update bottom scheduled pressure.
684 BotRPTracker.recede();
685 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
686 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
687 }
688}
689
690/// Update scheduler queues after scheduling an instruction.
691void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
692 // Release dependent instructions for scheduling.
693 if (IsTopNode)
694 releaseSuccessors(SU);
695 else
696 releasePredecessors(SU);
697
698 SU->isScheduled = true;
699
Andrew Trick178f7d02013-01-25 04:01:04 +0000700 if (DFSResult) {
701 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
702 if (!ScheduledTrees.test(SubtreeID)) {
703 ScheduledTrees.set(SubtreeID);
704 DFSResult->scheduleTree(SubtreeID);
705 SchedImpl->scheduleTree(SubtreeID);
706 }
707 }
708
Andrew Trick78e5efe2012-09-11 00:39:15 +0000709 // Notify the scheduling strategy after updating the DAG.
710 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000711}
712
713/// Reinsert any remaining debug_values, just like the PostRA scheduler.
714void ScheduleDAGMI::placeDebugValues() {
715 // If first instruction was a DBG_VALUE then put it back.
716 if (FirstDbgValue) {
717 BB->splice(RegionBegin, BB, FirstDbgValue);
718 RegionBegin = FirstDbgValue;
719 }
720
721 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
722 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
723 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
724 MachineInstr *DbgValue = P.first;
725 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000726 if (&*RegionBegin == DbgValue)
727 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000728 BB->splice(++OrigPrevMI, BB, DbgValue);
729 if (OrigPrevMI == llvm::prior(RegionEnd))
730 RegionEnd = DbgValue;
731 }
732 DbgValues.clear();
733 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000734}
735
Andrew Trick3b87f622012-11-07 07:05:09 +0000736#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
737void ScheduleDAGMI::dumpSchedule() const {
738 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
739 if (SUnit *SU = getSUnit(&(*MI)))
740 SU->dump(this);
741 else
742 dbgs() << "Missing SUnit\n";
743 }
744}
745#endif
746
Andrew Trick6996fd02012-11-12 19:52:20 +0000747//===----------------------------------------------------------------------===//
748// LoadClusterMutation - DAG post-processing to cluster loads.
749//===----------------------------------------------------------------------===//
750
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000751namespace {
752/// \brief Post-process the DAG to create cluster edges between neighboring
753/// loads.
754class LoadClusterMutation : public ScheduleDAGMutation {
755 struct LoadInfo {
756 SUnit *SU;
757 unsigned BaseReg;
758 unsigned Offset;
759 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
760 : SU(su), BaseReg(reg), Offset(ofs) {}
761 };
762 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
763 const LoadClusterMutation::LoadInfo &RHS);
764
765 const TargetInstrInfo *TII;
766 const TargetRegisterInfo *TRI;
767public:
768 LoadClusterMutation(const TargetInstrInfo *tii,
769 const TargetRegisterInfo *tri)
770 : TII(tii), TRI(tri) {}
771
772 virtual void apply(ScheduleDAGMI *DAG);
773protected:
774 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
775};
776} // anonymous
777
778bool LoadClusterMutation::LoadInfoLess(
779 const LoadClusterMutation::LoadInfo &LHS,
780 const LoadClusterMutation::LoadInfo &RHS) {
781 if (LHS.BaseReg != RHS.BaseReg)
782 return LHS.BaseReg < RHS.BaseReg;
783 return LHS.Offset < RHS.Offset;
784}
785
786void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
787 ScheduleDAGMI *DAG) {
788 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
789 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
790 SUnit *SU = Loads[Idx];
791 unsigned BaseReg;
792 unsigned Offset;
793 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
794 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
795 }
796 if (LoadRecords.size() < 2)
797 return;
798 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
799 unsigned ClusterLength = 1;
800 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
801 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
802 ClusterLength = 1;
803 continue;
804 }
805
806 SUnit *SUa = LoadRecords[Idx].SU;
807 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000808 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000809 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
810
811 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
812 << SUb->NodeNum << ")\n");
813 // Copy successor edges from SUa to SUb. Interleaving computation
814 // dependent on SUa can prevent load combining due to register reuse.
815 // Predecessor edges do not need to be copied from SUb to SUa since nearby
816 // loads should have effectively the same inputs.
817 for (SUnit::const_succ_iterator
818 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
819 if (SI->getSUnit() == SUb)
820 continue;
821 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
822 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
823 }
824 ++ClusterLength;
825 }
826 else
827 ClusterLength = 1;
828 }
829}
830
831/// \brief Callback from DAG postProcessing to create cluster edges for loads.
832void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
833 // Map DAG NodeNum to store chain ID.
834 DenseMap<unsigned, unsigned> StoreChainIDs;
835 // Map each store chain to a set of dependent loads.
836 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
837 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
838 SUnit *SU = &DAG->SUnits[Idx];
839 if (!SU->getInstr()->mayLoad())
840 continue;
841 unsigned ChainPredID = DAG->SUnits.size();
842 for (SUnit::const_pred_iterator
843 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
844 if (PI->isCtrl()) {
845 ChainPredID = PI->getSUnit()->NodeNum;
846 break;
847 }
848 }
849 // Check if this chain-like pred has been seen
850 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
851 unsigned NumChains = StoreChainDependents.size();
852 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
853 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
854 if (Result.second)
855 StoreChainDependents.resize(NumChains + 1);
856 StoreChainDependents[Result.first->second].push_back(SU);
857 }
858 // Iterate over the store chains.
859 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
860 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
861}
862
Andrew Trickc174eaf2012-03-08 01:41:12 +0000863//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000864// MacroFusion - DAG post-processing to encourage fusion of macro ops.
865//===----------------------------------------------------------------------===//
866
867namespace {
868/// \brief Post-process the DAG to create cluster edges between instructions
869/// that may be fused by the processor into a single operation.
870class MacroFusion : public ScheduleDAGMutation {
871 const TargetInstrInfo *TII;
872public:
873 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
874
875 virtual void apply(ScheduleDAGMI *DAG);
876};
877} // anonymous
878
879/// \brief Callback from DAG postProcessing to create cluster edges to encourage
880/// fused operations.
881void MacroFusion::apply(ScheduleDAGMI *DAG) {
882 // For now, assume targets can only fuse with the branch.
883 MachineInstr *Branch = DAG->ExitSU.getInstr();
884 if (!Branch)
885 return;
886
887 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
888 SUnit *SU = &DAG->SUnits[--Idx];
889 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
890 continue;
891
892 // Create a single weak edge from SU to ExitSU. The only effect is to cause
893 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
894 // need to copy predecessor edges from ExitSU to SU, since top-down
895 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
896 // of SU, we could create an artificial edge from the deepest root, but it
897 // hasn't been needed yet.
898 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
899 (void)Success;
900 assert(Success && "No DAG nodes should be reachable from ExitSU");
901
902 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
903 break;
904 }
905}
906
907//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000908// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000909//===----------------------------------------------------------------------===//
910
911namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000912/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
913/// the schedule.
914class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000915public:
916 /// Represent the type of SchedCandidate found within a single queue.
917 /// pickNodeBidirectional depends on these listed by decreasing priority.
918 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000919 NoCand, SingleExcess, SingleCritical, Cluster,
920 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
921 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
922 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000923
924#ifndef NDEBUG
925 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
926#endif
927
928 /// Policy for scheduling the next instruction in the candidate's zone.
929 struct CandPolicy {
930 bool ReduceLatency;
931 unsigned ReduceResIdx;
932 unsigned DemandResIdx;
933
934 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
935 };
936
937 /// Status of an instruction's critical resource consumption.
938 struct SchedResourceDelta {
939 // Count critical resources in the scheduled region required by SU.
940 unsigned CritResources;
941
942 // Count critical resources from another region consumed by SU.
943 unsigned DemandedResources;
944
945 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
946
947 bool operator==(const SchedResourceDelta &RHS) const {
948 return CritResources == RHS.CritResources
949 && DemandedResources == RHS.DemandedResources;
950 }
951 bool operator!=(const SchedResourceDelta &RHS) const {
952 return !operator==(RHS);
953 }
954 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000955
956 /// Store the state used by ConvergingScheduler heuristics, required for the
957 /// lifetime of one invocation of pickNode().
958 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000959 CandPolicy Policy;
960
Andrew Trick7196a8f2012-05-10 21:06:16 +0000961 // The best SUnit candidate.
962 SUnit *SU;
963
Andrew Trick3b87f622012-11-07 07:05:09 +0000964 // The reason for this candidate.
965 CandReason Reason;
966
Andrew Trick7196a8f2012-05-10 21:06:16 +0000967 // Register pressure values for the best candidate.
968 RegPressureDelta RPDelta;
969
Andrew Trick3b87f622012-11-07 07:05:09 +0000970 // Critical resource consumption of the best candidate.
971 SchedResourceDelta ResDelta;
972
973 SchedCandidate(const CandPolicy &policy)
974 : Policy(policy), SU(NULL), Reason(NoCand) {}
975
976 bool isValid() const { return SU; }
977
978 // Copy the status of another candidate without changing policy.
979 void setBest(SchedCandidate &Best) {
980 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
981 SU = Best.SU;
982 Reason = Best.Reason;
983 RPDelta = Best.RPDelta;
984 ResDelta = Best.ResDelta;
985 }
986
987 void initResourceDelta(const ScheduleDAGMI *DAG,
988 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000989 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000990
991 /// Summarize the unscheduled region.
992 struct SchedRemainder {
993 // Critical path through the DAG in expected latency.
994 unsigned CriticalPath;
995
996 // Unscheduled resources
997 SmallVector<unsigned, 16> RemainingCounts;
998 // Critical resource for the unscheduled zone.
999 unsigned CritResIdx;
1000 // Number of micro-ops left to schedule.
1001 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +00001002
Andrew Trick3b87f622012-11-07 07:05:09 +00001003 void reset() {
1004 CriticalPath = 0;
1005 RemainingCounts.clear();
1006 CritResIdx = 0;
1007 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001008 }
1009
1010 SchedRemainder() { reset(); }
1011
1012 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001013
1014 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1015 if (!SchedModel->hasInstrSchedModel())
1016 return 0;
1017
1018 return std::max(
1019 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1020 RemainingCounts[CritResIdx]);
1021 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001022 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001023
Andrew Trickf3234242012-05-24 22:11:12 +00001024 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001025 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001026 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001027 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001028 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001029 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001030 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001031
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001032 ReadyQueue Available;
1033 ReadyQueue Pending;
1034 bool CheckPending;
1035
Andrew Trick3b87f622012-11-07 07:05:09 +00001036 // For heuristics, keep a list of the nodes that immediately depend on the
1037 // most recently scheduled node.
1038 SmallPtrSet<const SUnit*, 8> NextSUs;
1039
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001040 ScheduleHazardRecognizer *HazardRec;
1041
1042 unsigned CurrCycle;
1043 unsigned IssueCount;
1044
1045 /// MinReadyCycle - Cycle of the soonest available instruction.
1046 unsigned MinReadyCycle;
1047
Andrew Trick3b87f622012-11-07 07:05:09 +00001048 // The expected latency of the critical path in this scheduled zone.
1049 unsigned ExpectedLatency;
1050
1051 // Resources used in the scheduled zone beyond this boundary.
1052 SmallVector<unsigned, 16> ResourceCounts;
1053
1054 // Cache the critical resources ID in this scheduled zone.
1055 unsigned CritResIdx;
1056
1057 // Is the scheduled region resource limited vs. latency limited.
1058 bool IsResourceLimited;
1059
1060 unsigned ExpectedCount;
1061
Andrew Trick3b87f622012-11-07 07:05:09 +00001062#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001063 // Remember the greatest min operand latency.
1064 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001065#endif
1066
1067 void reset() {
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001068 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1069 delete HazardRec;
1070
Andrew Trick3b87f622012-11-07 07:05:09 +00001071 Available.clear();
1072 Pending.clear();
1073 CheckPending = false;
1074 NextSUs.clear();
1075 HazardRec = 0;
1076 CurrCycle = 0;
1077 IssueCount = 0;
1078 MinReadyCycle = UINT_MAX;
1079 ExpectedLatency = 0;
1080 ResourceCounts.resize(1);
1081 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1082 CritResIdx = 0;
1083 IsResourceLimited = false;
1084 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001085#ifndef NDEBUG
1086 MaxMinLatency = 0;
1087#endif
1088 // Reserve a zero-count for invalid CritResIdx.
1089 ResourceCounts.resize(1);
1090 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001091
Andrew Trickf3234242012-05-24 22:11:12 +00001092 /// Pending queues extend the ready queues with the same ID and the
1093 /// PendingFlag set.
1094 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001095 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001096 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1097 HazardRec(0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001098 reset();
1099 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001100
1101 ~SchedBoundary() { delete HazardRec; }
1102
Andrew Trick3b87f622012-11-07 07:05:09 +00001103 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1104 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001105
Andrew Trickf3234242012-05-24 22:11:12 +00001106 bool isTop() const {
1107 return Available.getID() == ConvergingScheduler::TopQID;
1108 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001109
Andrew Trick3b87f622012-11-07 07:05:09 +00001110 unsigned getUnscheduledLatency(SUnit *SU) const {
1111 if (isTop())
1112 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001113 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001114 }
1115
1116 unsigned getCriticalCount() const {
1117 return ResourceCounts[CritResIdx];
1118 }
1119
Andrew Trick5559ffa2012-06-29 03:23:24 +00001120 bool checkHazard(SUnit *SU);
1121
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001122 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001123
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001124 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1125
1126 void bumpCycle();
1127
Andrew Trick3b87f622012-11-07 07:05:09 +00001128 void countResource(unsigned PIdx, unsigned Cycles);
1129
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001130 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001131
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001132 void releasePending();
1133
1134 void removeReady(SUnit *SU);
1135
1136 SUnit *pickOnlyChoice();
1137 };
1138
Andrew Trick3b87f622012-11-07 07:05:09 +00001139private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001140 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001141 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001142 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001143
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001144 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001145 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001146 SchedBoundary Top;
1147 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001148
1149public:
Andrew Trickf3234242012-05-24 22:11:12 +00001150 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001151 enum {
1152 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001153 BotQID = 2,
1154 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001155 };
1156
Andrew Trickf3234242012-05-24 22:11:12 +00001157 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001158 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001159
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001160 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001161
Andrew Trick7196a8f2012-05-10 21:06:16 +00001162 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001163
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001164 virtual void schedNode(SUnit *SU, bool IsTopNode);
1165
1166 virtual void releaseTopNode(SUnit *SU);
1167
1168 virtual void releaseBottomNode(SUnit *SU);
1169
Andrew Trick3b87f622012-11-07 07:05:09 +00001170 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001171
Andrew Trick3b87f622012-11-07 07:05:09 +00001172protected:
1173 void balanceZones(
1174 ConvergingScheduler::SchedBoundary &CriticalZone,
1175 ConvergingScheduler::SchedCandidate &CriticalCand,
1176 ConvergingScheduler::SchedBoundary &OppositeZone,
1177 ConvergingScheduler::SchedCandidate &OppositeCand);
1178
1179 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1180 ConvergingScheduler::SchedCandidate &BotCand);
1181
1182 void tryCandidate(SchedCandidate &Cand,
1183 SchedCandidate &TryCand,
1184 SchedBoundary &Zone,
1185 const RegPressureTracker &RPTracker,
1186 RegPressureTracker &TempTracker);
1187
1188 SUnit *pickNodeBidirectional(bool &IsTopNode);
1189
1190 void pickNodeFromQueue(SchedBoundary &Zone,
1191 const RegPressureTracker &RPTracker,
1192 SchedCandidate &Candidate);
1193
Andrew Trick28ebc892012-05-10 21:06:19 +00001194#ifndef NDEBUG
Andrew Trick11189f72013-04-05 00:31:29 +00001195 void traceCandidate(const SchedCandidate &Cand);
Andrew Trick28ebc892012-05-10 21:06:19 +00001196#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001197};
1198} // namespace
1199
Andrew Trick3b87f622012-11-07 07:05:09 +00001200void ConvergingScheduler::SchedRemainder::
1201init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1202 reset();
1203 if (!SchedModel->hasInstrSchedModel())
1204 return;
1205 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1206 for (std::vector<SUnit>::iterator
1207 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1208 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1209 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1210 for (TargetSchedModel::ProcResIter
1211 PI = SchedModel->getWriteProcResBegin(SC),
1212 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1213 unsigned PIdx = PI->ProcResourceIdx;
1214 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1215 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1216 }
1217 }
Andrew Trick071966f2012-12-18 20:52:49 +00001218 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1219 PIdx != PEnd; ++PIdx) {
1220 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1221 >= (int)SchedModel->getLatencyFactor()) {
1222 CritResIdx = PIdx;
1223 }
1224 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001225}
1226
1227void ConvergingScheduler::SchedBoundary::
1228init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1229 reset();
1230 DAG = dag;
1231 SchedModel = smodel;
1232 Rem = rem;
1233 if (SchedModel->hasInstrSchedModel())
1234 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1235}
1236
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001237void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1238 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001239 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001240 TRI = DAG->TRI;
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001241
Andrew Trick3b87f622012-11-07 07:05:09 +00001242 Rem.init(DAG, SchedModel);
1243 Top.init(DAG, SchedModel, &Rem);
1244 Bot.init(DAG, SchedModel, &Rem);
1245
Andrew Trick4e1fb182013-01-25 06:33:57 +00001246 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00001247
Andrew Trick3b87f622012-11-07 07:05:09 +00001248 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001249
Andrew Trick412cd2f2012-10-10 05:43:09 +00001250 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1251 // are disabled, then these HazardRecs will be disabled.
1252 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001253 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001254 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1255 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1256
1257 assert((!ForceTopDown || !ForceBottomUp) &&
1258 "-misched-topdown incompatible with -misched-bottomup");
1259}
1260
1261void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001262 if (SU->isScheduled)
1263 return;
1264
Andrew Trickd4539602012-12-18 20:52:52 +00001265 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001266 I != E; ++I) {
1267 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001268 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001269#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001270 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001271#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001272 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1273 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001274 }
1275 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001276}
1277
1278void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001279 if (SU->isScheduled)
1280 return;
1281
1282 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1283
1284 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1285 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001286 if (I->isWeak())
1287 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001288 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001289 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001290#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001291 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001292#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001293 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1294 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001295 }
1296 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001297}
1298
Andrew Trick3b87f622012-11-07 07:05:09 +00001299void ConvergingScheduler::registerRoots() {
1300 Rem.CriticalPath = DAG->ExitSU.getDepth();
1301 // Some roots may not feed into ExitSU. Check all of them in case.
1302 for (std::vector<SUnit*>::const_iterator
1303 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1304 if ((*I)->getDepth() > Rem.CriticalPath)
1305 Rem.CriticalPath = (*I)->getDepth();
1306 }
1307 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1308}
1309
Andrew Trick5559ffa2012-06-29 03:23:24 +00001310/// Does this SU have a hazard within the current instruction group.
1311///
1312/// The scheduler supports two modes of hazard recognition. The first is the
1313/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1314/// supports highly complicated in-order reservation tables
1315/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1316///
1317/// The second is a streamlined mechanism that checks for hazards based on
1318/// simple counters that the scheduler itself maintains. It explicitly checks
1319/// for instruction dispatch limitations, including the number of micro-ops that
1320/// can dispatch per cycle.
1321///
1322/// TODO: Also check whether the SU must start a new group.
1323bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1324 if (HazardRec->isEnabled())
1325 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1326
Andrew Trick412cd2f2012-10-10 05:43:09 +00001327 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001328 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1329 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1330 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001331 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001332 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001333 return false;
1334}
1335
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001336/// Compute the remaining latency to determine whether ILP should be increased.
1337void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1338 // FIXME: compile time. In all, we visit four queues here one we should only
1339 // need to visit the one that was last popped if we cache the result.
1340 unsigned RemLatency = 0;
1341 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1342 I != E; ++I) {
1343 unsigned L = getUnscheduledLatency(*I);
1344 if (L > RemLatency)
1345 RemLatency = L;
1346 }
1347 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1348 I != E; ++I) {
1349 unsigned L = getUnscheduledLatency(*I);
1350 if (L > RemLatency)
1351 RemLatency = L;
1352 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001353 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1354 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001355 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1356 Policy.ReduceLatency = true;
1357 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001358 }
1359}
1360
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001361void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1362 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001363
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001364 if (ReadyCycle < MinReadyCycle)
1365 MinReadyCycle = ReadyCycle;
1366
1367 // Check for interlocks first. For the purpose of other heuristics, an
1368 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001369 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001370 Pending.push(SU);
1371 else
1372 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001373
1374 // Record this node as an immediate dependent of the scheduled node.
1375 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001376}
1377
1378/// Move the boundary of scheduled code by one cycle.
1379void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001380 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001381 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001382
Andrew Trick3b87f622012-11-07 07:05:09 +00001383 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001384 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001385 if (MinReadyCycle > NextCycle) {
1386 IssueCount = 0;
1387 NextCycle = MinReadyCycle;
1388 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001389
1390 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001391 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001392 CurrCycle = NextCycle;
1393 }
1394 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001395 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001396 for (; CurrCycle != NextCycle; ++CurrCycle) {
1397 if (isTop())
1398 HazardRec->AdvanceCycle();
1399 else
1400 HazardRec->RecedeCycle();
1401 }
1402 }
1403 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001404 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001405
Andrew Trick11189f72013-04-05 00:31:29 +00001406 DEBUG(dbgs() << " " << Available.getName()
1407 << " Cycle: " << CurrCycle << '\n');
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001408}
1409
Andrew Trick3b87f622012-11-07 07:05:09 +00001410/// Add the given processor resource to this scheduled zone.
1411void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1412 unsigned Cycles) {
1413 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1414 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1415 << " +(" << Cycles << "x" << Factor
1416 << ") / " << SchedModel->getLatencyFactor() << '\n');
1417
1418 unsigned Count = Factor * Cycles;
1419 ResourceCounts[PIdx] += Count;
1420 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1421 Rem->RemainingCounts[PIdx] -= Count;
1422
Andrew Trick3b87f622012-11-07 07:05:09 +00001423 // Check if this resource exceeds the current critical resource by a full
1424 // cycle. If so, it becomes the critical resource.
1425 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1426 >= (int)SchedModel->getLatencyFactor()) {
1427 CritResIdx = PIdx;
1428 DEBUG(dbgs() << " *** Critical resource "
1429 << SchedModel->getProcResource(PIdx)->Name << " x"
1430 << ResourceCounts[PIdx] << '\n');
1431 }
1432}
1433
Andrew Trickb7e02892012-06-05 21:11:27 +00001434/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001435void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001436 // Update the reservation table.
1437 if (HazardRec->isEnabled()) {
1438 if (!isTop() && SU->isCall) {
1439 // Calls are scheduled with their preceding instructions. For bottom-up
1440 // scheduling, clear the pipeline state before emitting.
1441 HazardRec->Reset();
1442 }
1443 HazardRec->EmitInstruction(SU);
1444 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001445 // Update resource counts and critical resource.
1446 if (SchedModel->hasInstrSchedModel()) {
1447 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1448 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1449 for (TargetSchedModel::ProcResIter
1450 PI = SchedModel->getWriteProcResBegin(SC),
1451 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1452 countResource(PI->ProcResourceIdx, PI->Cycles);
1453 }
1454 }
1455 if (isTop()) {
1456 if (SU->getDepth() > ExpectedLatency)
1457 ExpectedLatency = SU->getDepth();
1458 }
1459 else {
1460 if (SU->getHeight() > ExpectedLatency)
1461 ExpectedLatency = SU->getHeight();
1462 }
1463
1464 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1465
Andrew Trick5559ffa2012-06-29 03:23:24 +00001466 // Check the instruction group dispatch limit.
1467 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001468 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001469
1470 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1471 // issue width. However, we commonly reach the maximum. In this case
1472 // opportunistically bump the cycle to avoid uselessly checking everything in
1473 // the readyQ. Furthermore, a single instruction may produce more than one
1474 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001475 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001476 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001477 bumpCycle();
1478 }
1479}
1480
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001481/// Release pending ready nodes in to the available queue. This makes them
1482/// visible to heuristics.
1483void ConvergingScheduler::SchedBoundary::releasePending() {
1484 // If the available queue is empty, it is safe to reset MinReadyCycle.
1485 if (Available.empty())
1486 MinReadyCycle = UINT_MAX;
1487
1488 // Check to see if any of the pending instructions are ready to issue. If
1489 // so, add them to the available queue.
1490 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1491 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001492 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001493
1494 if (ReadyCycle < MinReadyCycle)
1495 MinReadyCycle = ReadyCycle;
1496
1497 if (ReadyCycle > CurrCycle)
1498 continue;
1499
Andrew Trick5559ffa2012-06-29 03:23:24 +00001500 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001501 continue;
1502
1503 Available.push(SU);
1504 Pending.remove(Pending.begin()+i);
1505 --i; --e;
1506 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001507 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001508 CheckPending = false;
1509}
1510
1511/// Remove SU from the ready set for this boundary.
1512void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1513 if (Available.isInQueue(SU))
1514 Available.remove(Available.find(SU));
1515 else {
1516 assert(Pending.isInQueue(SU) && "bad ready count");
1517 Pending.remove(Pending.find(SU));
1518 }
1519}
1520
1521/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001522/// defer any nodes that now hit a hazard, and advance the cycle until at least
1523/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001524SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1525 if (CheckPending)
1526 releasePending();
1527
Andrew Trick3b87f622012-11-07 07:05:09 +00001528 if (IssueCount > 0) {
1529 // Defer any ready instrs that now have a hazard.
1530 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1531 if (checkHazard(*I)) {
1532 Pending.push(*I);
1533 I = Available.remove(I);
1534 continue;
1535 }
1536 ++I;
1537 }
1538 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001539 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001540 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1541 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001542 bumpCycle();
1543 releasePending();
1544 }
1545 if (Available.size() == 1)
1546 return *Available.begin();
1547 return NULL;
1548}
1549
Andrew Trick3b87f622012-11-07 07:05:09 +00001550/// Record the candidate policy for opposite zones with different critical
1551/// resources.
1552///
1553/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001554/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001555void ConvergingScheduler::balanceZones(
1556 ConvergingScheduler::SchedBoundary &CriticalZone,
1557 ConvergingScheduler::SchedCandidate &CriticalCand,
1558 ConvergingScheduler::SchedBoundary &OppositeZone,
1559 ConvergingScheduler::SchedCandidate &OppositeCand) {
1560
1561 if (!CriticalZone.IsResourceLimited)
1562 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001563 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001564
1565 SchedRemainder *Rem = CriticalZone.Rem;
1566
1567 // If the critical zone is overconsuming a resource relative to the
1568 // remainder, try to reduce it.
1569 unsigned RemainingCritCount =
1570 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001571 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001572 > (int)SchedModel->getLatencyFactor()) {
1573 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1574 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1575 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1576 << '\n');
1577 }
1578 // If the other zone is underconsuming a resource relative to the full zone,
1579 // try to increase it.
1580 unsigned OppositeCount =
1581 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1582 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1583 > (int)SchedModel->getLatencyFactor()) {
1584 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1585 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1586 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1587 << '\n');
1588 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001589}
Andrew Trick3b87f622012-11-07 07:05:09 +00001590
1591/// Determine if the scheduled zones exceed resource limits or critical path and
1592/// set each candidate's ReduceHeight policy accordingly.
1593void ConvergingScheduler::checkResourceLimits(
1594 ConvergingScheduler::SchedCandidate &TopCand,
1595 ConvergingScheduler::SchedCandidate &BotCand) {
1596
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001597 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001598 Bot.setLatencyPolicy(BotCand.Policy);
1599 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001600
1601 // Handle resource-limited regions.
1602 if (Top.IsResourceLimited && Bot.IsResourceLimited
1603 && Top.CritResIdx == Bot.CritResIdx) {
1604 // If the scheduled critical resource in both zones is no longer the
1605 // critical remaining resource, attempt to reduce resource height both ways.
1606 if (Top.CritResIdx != Rem.CritResIdx) {
1607 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1608 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1609 DEBUG(dbgs() << "Reduce scheduled "
1610 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1611 }
1612 return;
1613 }
1614 // Handle latency-limited regions.
1615 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1616 // If the total scheduled expected latency exceeds the region's critical
1617 // path then reduce latency both ways.
1618 //
1619 // Just because a zone is not resource limited does not mean it is latency
1620 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1621 // to exceed expected latency.
1622 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1623 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1624 TopCand.Policy.ReduceLatency = true;
1625 BotCand.Policy.ReduceLatency = true;
1626 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1627 << " + " << Bot.ExpectedLatency << '\n');
1628 }
1629 return;
1630 }
1631 // The critical resource is different in each zone, so request balancing.
1632
1633 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001634 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1635 Top.ExpectedCount = std::max(
1636 Top.getCriticalCount(),
1637 Top.ExpectedCount * SchedModel->getLatencyFactor());
1638 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1639 Bot.ExpectedCount = std::max(
1640 Bot.getCriticalCount(),
1641 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1642
1643 balanceZones(Top, TopCand, Bot, BotCand);
1644 balanceZones(Bot, BotCand, Top, TopCand);
1645}
1646
1647void ConvergingScheduler::SchedCandidate::
1648initResourceDelta(const ScheduleDAGMI *DAG,
1649 const TargetSchedModel *SchedModel) {
1650 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1651 return;
1652
1653 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1654 for (TargetSchedModel::ProcResIter
1655 PI = SchedModel->getWriteProcResBegin(SC),
1656 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1657 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1658 ResDelta.CritResources += PI->Cycles;
1659 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1660 ResDelta.DemandedResources += PI->Cycles;
1661 }
1662}
1663
1664/// Return true if this heuristic determines order.
1665static bool tryLess(unsigned TryVal, unsigned CandVal,
1666 ConvergingScheduler::SchedCandidate &TryCand,
1667 ConvergingScheduler::SchedCandidate &Cand,
1668 ConvergingScheduler::CandReason Reason) {
1669 if (TryVal < CandVal) {
1670 TryCand.Reason = Reason;
1671 return true;
1672 }
1673 if (TryVal > CandVal) {
1674 if (Cand.Reason > Reason)
1675 Cand.Reason = Reason;
1676 return true;
1677 }
1678 return false;
1679}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001680
Andrew Trick3b87f622012-11-07 07:05:09 +00001681static bool tryGreater(unsigned TryVal, unsigned CandVal,
1682 ConvergingScheduler::SchedCandidate &TryCand,
1683 ConvergingScheduler::SchedCandidate &Cand,
1684 ConvergingScheduler::CandReason Reason) {
1685 if (TryVal > CandVal) {
1686 TryCand.Reason = Reason;
1687 return true;
1688 }
1689 if (TryVal < CandVal) {
1690 if (Cand.Reason > Reason)
1691 Cand.Reason = Reason;
1692 return true;
1693 }
1694 return false;
1695}
1696
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001697static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1698 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1699}
1700
Andrew Trick3b87f622012-11-07 07:05:09 +00001701/// Apply a set of heursitics to a new candidate. Heuristics are currently
1702/// hierarchical. This may be more efficient than a graduated cost model because
1703/// we don't need to evaluate all aspects of the model for each node in the
1704/// queue. But it's really done to make the heuristics easier to debug and
1705/// statistically analyze.
1706///
1707/// \param Cand provides the policy and current best candidate.
1708/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1709/// \param Zone describes the scheduled zone that we are extending.
1710/// \param RPTracker describes reg pressure within the scheduled zone.
1711/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1712void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1713 SchedCandidate &TryCand,
1714 SchedBoundary &Zone,
1715 const RegPressureTracker &RPTracker,
1716 RegPressureTracker &TempTracker) {
1717
1718 // Always initialize TryCand's RPDelta.
1719 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1720 DAG->getRegionCriticalPSets(),
1721 DAG->getRegPressure().MaxSetPressure);
1722
1723 // Initialize the candidate if needed.
1724 if (!Cand.isValid()) {
1725 TryCand.Reason = NodeOrder;
1726 return;
1727 }
1728 // Avoid exceeding the target's limit.
1729 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1730 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1731 return;
1732 if (Cand.Reason == SingleExcess)
1733 Cand.Reason = MultiPressure;
1734
1735 // Avoid increasing the max critical pressure in the scheduled region.
1736 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1737 Cand.RPDelta.CriticalMax.UnitIncrease,
1738 TryCand, Cand, SingleCritical))
1739 return;
1740 if (Cand.Reason == SingleCritical)
1741 Cand.Reason = MultiPressure;
1742
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001743 // Keep clustered nodes together to encourage downstream peephole
1744 // optimizations which may reduce resource requirements.
1745 //
1746 // This is a best effort to set things up for a post-RA pass. Optimizations
1747 // like generating loads of multiple registers should ideally be done within
1748 // the scheduler pass by combining the loads during DAG postprocessing.
1749 const SUnit *NextClusterSU =
1750 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1751 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1752 TryCand, Cand, Cluster))
1753 return;
1754 // Currently, weak edges are for clustering, so we hard-code that reason.
1755 // However, deferring the current TryCand will not change Cand's reason.
1756 CandReason OrigReason = Cand.Reason;
1757 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1758 getWeakLeft(Cand.SU, Zone.isTop()),
1759 TryCand, Cand, Cluster)) {
1760 Cand.Reason = OrigReason;
1761 return;
1762 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001763 // Avoid critical resource consumption and balance the schedule.
1764 TryCand.initResourceDelta(DAG, SchedModel);
1765 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1766 TryCand, Cand, ResourceReduce))
1767 return;
1768 if (tryGreater(TryCand.ResDelta.DemandedResources,
1769 Cand.ResDelta.DemandedResources,
1770 TryCand, Cand, ResourceDemand))
1771 return;
1772
1773 // Avoid serializing long latency dependence chains.
1774 if (Cand.Policy.ReduceLatency) {
1775 if (Zone.isTop()) {
1776 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1777 > Zone.ExpectedCount) {
1778 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1779 TryCand, Cand, TopDepthReduce))
1780 return;
1781 }
1782 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1783 TryCand, Cand, TopPathReduce))
1784 return;
1785 }
1786 else {
1787 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1788 > Zone.ExpectedCount) {
1789 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1790 TryCand, Cand, BotHeightReduce))
1791 return;
1792 }
1793 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1794 TryCand, Cand, BotPathReduce))
1795 return;
1796 }
1797 }
1798
1799 // Avoid increasing the max pressure of the entire region.
1800 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1801 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1802 return;
1803 if (Cand.Reason == SingleMax)
1804 Cand.Reason = MultiPressure;
1805
1806 // Prefer immediate defs/users of the last scheduled instruction. This is a
1807 // nice pressure avoidance strategy that also conserves the processor's
1808 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001809 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1810 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001811 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001812
Andrew Trick3b87f622012-11-07 07:05:09 +00001813 // Fall through to original instruction order.
1814 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1815 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1816 TryCand.Reason = NodeOrder;
1817 }
1818}
Andrew Trick28ebc892012-05-10 21:06:19 +00001819
Andrew Trick5429a6b2012-05-17 22:37:09 +00001820/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1821/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001822static bool compareRPDelta(const RegPressureDelta &LHS,
1823 const RegPressureDelta &RHS) {
1824 // Compare each component of pressure in decreasing order of importance
1825 // without checking if any are valid. Invalid PressureElements are assumed to
1826 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001827
1828 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001829 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1830 DEBUG(dbgs() << "RP excess top - bot: "
1831 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001832 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001833 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001834 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001835 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1836 DEBUG(dbgs() << "RP critical top - bot: "
1837 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1838 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001839 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001840 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001841 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001842 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1843 DEBUG(dbgs() << "RP current top - bot: "
1844 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1845 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001846 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001847 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001848 return false;
1849}
1850
Andrew Trick3b87f622012-11-07 07:05:09 +00001851#ifndef NDEBUG
1852const char *ConvergingScheduler::getReasonStr(
1853 ConvergingScheduler::CandReason Reason) {
1854 switch (Reason) {
1855 case NoCand: return "NOCAND ";
1856 case SingleExcess: return "REG-EXCESS";
1857 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001858 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001859 case SingleMax: return "REG-MAX ";
1860 case MultiPressure: return "REG-MULTI ";
1861 case ResourceReduce: return "RES-REDUCE";
1862 case ResourceDemand: return "RES-DEMAND";
1863 case TopDepthReduce: return "TOP-DEPTH ";
1864 case TopPathReduce: return "TOP-PATH ";
1865 case BotHeightReduce:return "BOT-HEIGHT";
1866 case BotPathReduce: return "BOT-PATH ";
1867 case NextDefUse: return "DEF-USE ";
1868 case NodeOrder: return "ORDER ";
1869 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001870 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001871}
1872
Andrew Trick11189f72013-04-05 00:31:29 +00001873void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001874 PressureElement P;
1875 unsigned ResIdx = 0;
1876 unsigned Latency = 0;
1877 switch (Cand.Reason) {
1878 default:
1879 break;
1880 case SingleExcess:
1881 P = Cand.RPDelta.Excess;
1882 break;
1883 case SingleCritical:
1884 P = Cand.RPDelta.CriticalMax;
1885 break;
1886 case SingleMax:
1887 P = Cand.RPDelta.CurrentMax;
1888 break;
1889 case ResourceReduce:
1890 ResIdx = Cand.Policy.ReduceResIdx;
1891 break;
1892 case ResourceDemand:
1893 ResIdx = Cand.Policy.DemandResIdx;
1894 break;
1895 case TopDepthReduce:
1896 Latency = Cand.SU->getDepth();
1897 break;
1898 case TopPathReduce:
1899 Latency = Cand.SU->getHeight();
1900 break;
1901 case BotHeightReduce:
1902 Latency = Cand.SU->getHeight();
1903 break;
1904 case BotPathReduce:
1905 Latency = Cand.SU->getDepth();
1906 break;
1907 }
Andrew Trick11189f72013-04-05 00:31:29 +00001908 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00001909 if (P.isValid())
Andrew Trick11189f72013-04-05 00:31:29 +00001910 dbgs() << " " << TRI->getRegPressureSetName(P.PSetID)
1911 << ":" << P.UnitIncrease << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001912 else
Andrew Trick11189f72013-04-05 00:31:29 +00001913 dbgs() << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001914 if (ResIdx)
Andrew Trick11189f72013-04-05 00:31:29 +00001915 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001916 else
1917 dbgs() << " ";
Andrew Trick11189f72013-04-05 00:31:29 +00001918 if (Latency)
1919 dbgs() << " " << Latency << " cycles ";
1920 else
1921 dbgs() << " ";
1922 dbgs() << '\n';
Andrew Trick3b87f622012-11-07 07:05:09 +00001923}
1924#endif
1925
Andrew Trick7196a8f2012-05-10 21:06:16 +00001926/// Pick the best candidate from the top queue.
1927///
1928/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1929/// DAG building. To adjust for the current scheduling location we need to
1930/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001931void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1932 const RegPressureTracker &RPTracker,
1933 SchedCandidate &Cand) {
1934 ReadyQueue &Q = Zone.Available;
1935
Andrew Trickf3234242012-05-24 22:11:12 +00001936 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001937
Andrew Trick7196a8f2012-05-10 21:06:16 +00001938 // getMaxPressureDelta temporarily modifies the tracker.
1939 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1940
Andrew Trick8c2d9212012-05-24 22:11:03 +00001941 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001942
Andrew Trick3b87f622012-11-07 07:05:09 +00001943 SchedCandidate TryCand(Cand.Policy);
1944 TryCand.SU = *I;
1945 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1946 if (TryCand.Reason != NoCand) {
1947 // Initialize resource delta if needed in case future heuristics query it.
1948 if (TryCand.ResDelta == SchedResourceDelta())
1949 TryCand.initResourceDelta(DAG, SchedModel);
1950 Cand.setBest(TryCand);
Andrew Trick11189f72013-04-05 00:31:29 +00001951 DEBUG(traceCandidate(Cand));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001952 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001953 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001954}
1955
1956static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1957 bool IsTop) {
Andrew Trick11189f72013-04-05 00:31:29 +00001958 DEBUG(dbgs() << "Pick " << (IsTop ? "Top" : "Bot")
Andrew Trick3b87f622012-11-07 07:05:09 +00001959 << " SU(" << Cand.SU->NodeNum << ") "
1960 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001961}
1962
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001963/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001964SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001965 // Schedule as far as possible in the direction of no choice. This is most
1966 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001967 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001968 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001969 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001970 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001971 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001972 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001973 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001974 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001975 CandPolicy NoPolicy;
1976 SchedCandidate BotCand(NoPolicy);
1977 SchedCandidate TopCand(NoPolicy);
1978 checkResourceLimits(TopCand, BotCand);
1979
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001980 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001981 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1982 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001983
1984 // If either Q has a single candidate that provides the least increase in
1985 // Excess pressure, we can immediately schedule from that Q.
1986 //
1987 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1988 // affects picking from either Q. If scheduling in one direction must
1989 // increase pressure for one of the excess PSets, then schedule in that
1990 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001991 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001992 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001993 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001994 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001995 }
1996 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001997 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1998 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001999
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002000 // If either Q has a single candidate that minimizes pressure above the
2001 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00002002 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
2003 if (TopCand.Reason < BotCand.Reason) {
2004 IsTopNode = true;
2005 tracePick(TopCand, IsTopNode);
2006 return TopCand.SU;
2007 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002008 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002009 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002010 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002011 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002012 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002013 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002014 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00002015 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002016 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002017 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002018 // Otherwise prefer the bottom candidate, in node order if all else failed.
2019 if (TopCand.Reason < BotCand.Reason) {
2020 IsTopNode = true;
2021 tracePick(TopCand, IsTopNode);
2022 return TopCand.SU;
2023 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002024 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002025 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002026 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002027}
2028
2029/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002030SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2031 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002032 assert(Top.Available.empty() && Top.Pending.empty() &&
2033 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002034 return NULL;
2035 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002036 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002037 do {
2038 if (ForceTopDown) {
2039 SU = Top.pickOnlyChoice();
2040 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002041 CandPolicy NoPolicy;
2042 SchedCandidate TopCand(NoPolicy);
2043 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2044 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002045 SU = TopCand.SU;
2046 }
2047 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002048 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002049 else if (ForceBottomUp) {
2050 SU = Bot.pickOnlyChoice();
2051 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002052 CandPolicy NoPolicy;
2053 SchedCandidate BotCand(NoPolicy);
2054 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2055 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002056 SU = BotCand.SU;
2057 }
2058 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002059 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002060 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002061 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002062 }
2063 } while (SU->isScheduled);
2064
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002065 if (SU->isTopReady())
2066 Top.removeReady(SU);
2067 if (SU->isBottomReady())
2068 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002069
Andrew Trick11189f72013-04-05 00:31:29 +00002070 DEBUG(dbgs() << "Scheduling " << *SU->getInstr());
Andrew Trick7196a8f2012-05-10 21:06:16 +00002071 return SU;
2072}
2073
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002074/// Update the scheduler's state after scheduling a node. This is the same node
2075/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002076/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002077void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002078 if (IsTopNode) {
2079 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002080 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002081 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002082 else {
2083 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002084 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002085 }
2086}
2087
Andrew Trick17d35e52012-03-14 04:00:41 +00002088/// Create the standard converging machine scheduler. This will be used as the
2089/// default scheduler if the target does not set a default.
2090static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002091 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002092 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002093 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2094 // Register DAG post-processors.
2095 if (EnableLoadCluster)
2096 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002097 if (EnableMacroFusion)
2098 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002099 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002100}
2101static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002102ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2103 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002104
2105//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002106// ILP Scheduler. Currently for experimental analysis of heuristics.
2107//===----------------------------------------------------------------------===//
2108
2109namespace {
2110/// \brief Order nodes by the ILP metric.
2111struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002112 const SchedDFSResult *DFSResult;
2113 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002114 bool MaximizeILP;
2115
Andrew Trick178f7d02013-01-25 04:01:04 +00002116 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002117
2118 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002119 ///
2120 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002121 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002122 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2123 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2124 if (SchedTreeA != SchedTreeB) {
2125 // Unscheduled trees have lower priority.
2126 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2127 return ScheduledTrees->test(SchedTreeB);
2128
2129 // Trees with shallower connections have have lower priority.
2130 if (DFSResult->getSubtreeLevel(SchedTreeA)
2131 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2132 return DFSResult->getSubtreeLevel(SchedTreeA)
2133 < DFSResult->getSubtreeLevel(SchedTreeB);
2134 }
2135 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002136 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002137 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002138 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002139 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002140 }
2141};
2142
2143/// \brief Schedule based on the ILP metric.
2144class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002145 /// In case all subtrees are eventually connected to a common root through
2146 /// data dependence (e.g. reduction), place an upper limit on their size.
2147 ///
2148 /// FIXME: A subtree limit is generally good, but in the situation commented
2149 /// above, where multiple similar subtrees feed a common root, we should
2150 /// only split at a point where the resulting subtrees will be balanced.
2151 /// (a motivating test case must be found).
2152 static const unsigned SubtreeLimit = 16;
2153
Andrew Trick178f7d02013-01-25 04:01:04 +00002154 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002155 ILPOrder Cmp;
2156
2157 std::vector<SUnit*> ReadyQ;
2158public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002159 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002160
Andrew Trick178f7d02013-01-25 04:01:04 +00002161 virtual void initialize(ScheduleDAGMI *dag) {
2162 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002163 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002164 Cmp.DFSResult = DAG->getDFSResult();
2165 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002166 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002167 }
2168
2169 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002170 // Restore the heap in ReadyQ with the updated DFS results.
2171 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002172 }
2173
2174 /// Implement MachineSchedStrategy interface.
2175 /// -----------------------------------------
2176
Andrew Trick8b1496c2012-11-28 05:13:28 +00002177 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002178 virtual SUnit *pickNode(bool &IsTopNode) {
2179 if (ReadyQ.empty()) return NULL;
Matt Arsenault26c417b2013-03-21 00:57:21 +00002180 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002181 SUnit *SU = ReadyQ.back();
2182 ReadyQ.pop_back();
2183 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002184 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2185 << *SU->getInstr()
Andrew Trick178f7d02013-01-25 04:01:04 +00002186 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2187 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2188 << DAG->getDFSResult()->getSubtreeLevel(
2189 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002190 return SU;
2191 }
2192
Andrew Trick178f7d02013-01-25 04:01:04 +00002193 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2194 virtual void scheduleTree(unsigned SubtreeID) {
2195 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2196 }
2197
Andrew Trick8b1496c2012-11-28 05:13:28 +00002198 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2199 /// DFSResults, and resort the priority Q.
2200 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2201 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002202 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002203
2204 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2205
2206 virtual void releaseBottomNode(SUnit *SU) {
2207 ReadyQ.push_back(SU);
2208 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2209 }
2210};
2211} // namespace
2212
2213static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2214 return new ScheduleDAGMI(C, new ILPScheduler(true));
2215}
2216static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2217 return new ScheduleDAGMI(C, new ILPScheduler(false));
2218}
2219static MachineSchedRegistry ILPMaxRegistry(
2220 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2221static MachineSchedRegistry ILPMinRegistry(
2222 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2223
2224//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002225// Machine Instruction Shuffler for Correctness Testing
2226//===----------------------------------------------------------------------===//
2227
Andrew Trick96f678f2012-01-13 06:30:30 +00002228#ifndef NDEBUG
2229namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002230/// Apply a less-than relation on the node order, which corresponds to the
2231/// instruction order prior to scheduling. IsReverse implements greater-than.
2232template<bool IsReverse>
2233struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002234 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002235 if (IsReverse)
2236 return A->NodeNum > B->NodeNum;
2237 else
2238 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002239 }
2240};
2241
Andrew Trick96f678f2012-01-13 06:30:30 +00002242/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002243class InstructionShuffler : public MachineSchedStrategy {
2244 bool IsAlternating;
2245 bool IsTopDown;
2246
2247 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2248 // gives nodes with a higher number higher priority causing the latest
2249 // instructions to be scheduled first.
2250 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2251 TopQ;
2252 // When scheduling bottom-up, use greater-than as the queue priority.
2253 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2254 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002255public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002256 InstructionShuffler(bool alternate, bool topdown)
2257 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002258
Andrew Trick17d35e52012-03-14 04:00:41 +00002259 virtual void initialize(ScheduleDAGMI *) {
2260 TopQ.clear();
2261 BottomQ.clear();
2262 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002263
Andrew Trick17d35e52012-03-14 04:00:41 +00002264 /// Implement MachineSchedStrategy interface.
2265 /// -----------------------------------------
2266
2267 virtual SUnit *pickNode(bool &IsTopNode) {
2268 SUnit *SU;
2269 if (IsTopDown) {
2270 do {
2271 if (TopQ.empty()) return NULL;
2272 SU = TopQ.top();
2273 TopQ.pop();
2274 } while (SU->isScheduled);
2275 IsTopNode = true;
2276 }
2277 else {
2278 do {
2279 if (BottomQ.empty()) return NULL;
2280 SU = BottomQ.top();
2281 BottomQ.pop();
2282 } while (SU->isScheduled);
2283 IsTopNode = false;
2284 }
2285 if (IsAlternating)
2286 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002287 return SU;
2288 }
2289
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002290 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2291
Andrew Trick17d35e52012-03-14 04:00:41 +00002292 virtual void releaseTopNode(SUnit *SU) {
2293 TopQ.push(SU);
2294 }
2295 virtual void releaseBottomNode(SUnit *SU) {
2296 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002297 }
2298};
2299} // namespace
2300
Andrew Trickc174eaf2012-03-08 01:41:12 +00002301static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002302 bool Alternate = !ForceTopDown && !ForceBottomUp;
2303 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002304 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002305 "-misched-topdown incompatible with -misched-bottomup");
2306 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002307}
Andrew Trick17d35e52012-03-14 04:00:41 +00002308static MachineSchedRegistry ShufflerRegistry(
2309 "shuffle", "Shuffle machine instructions alternating directions",
2310 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002311#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00002312
2313//===----------------------------------------------------------------------===//
2314// GraphWriter support for ScheduleDAGMI.
2315//===----------------------------------------------------------------------===//
2316
2317#ifndef NDEBUG
2318namespace llvm {
2319
2320template<> struct GraphTraits<
2321 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2322
2323template<>
2324struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2325
2326 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2327
2328 static std::string getGraphName(const ScheduleDAG *G) {
2329 return G->MF.getName();
2330 }
2331
2332 static bool renderGraphFromBottomUp() {
2333 return true;
2334 }
2335
2336 static bool isNodeHidden(const SUnit *Node) {
2337 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2338 }
2339
2340 static bool hasNodeAddressLabel(const SUnit *Node,
2341 const ScheduleDAG *Graph) {
2342 return false;
2343 }
2344
2345 /// If you want to override the dot attributes printed for a particular
2346 /// edge, override this method.
2347 static std::string getEdgeAttributes(const SUnit *Node,
2348 SUnitIterator EI,
2349 const ScheduleDAG *Graph) {
2350 if (EI.isArtificialDep())
2351 return "color=cyan,style=dashed";
2352 if (EI.isCtrlDep())
2353 return "color=blue,style=dashed";
2354 return "";
2355 }
2356
2357 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2358 std::string Str;
2359 raw_string_ostream SS(Str);
2360 SS << "SU(" << SU->NodeNum << ')';
2361 return SS.str();
2362 }
2363 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2364 return G->getGraphNodeLabel(SU);
2365 }
2366
2367 static std::string getNodeAttributes(const SUnit *N,
2368 const ScheduleDAG *Graph) {
2369 std::string Str("shape=Mrecord");
2370 const SchedDFSResult *DFS =
2371 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2372 if (DFS) {
2373 Str += ",style=filled,fillcolor=\"#";
2374 Str += DOT::getColorString(DFS->getSubtreeID(N));
2375 Str += '"';
2376 }
2377 return Str;
2378 }
2379};
2380} // namespace llvm
2381#endif // NDEBUG
2382
2383/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2384/// rendered using 'dot'.
2385///
2386void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2387#ifndef NDEBUG
2388 ViewGraph(this, Name, false, Title);
2389#else
2390 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2391 << "systems with Graphviz or gv!\n";
2392#endif // NDEBUG
2393}
2394
2395/// Out-of-line implementation with no arguments is handy for gdb.
2396void ScheduleDAGMI::viewGraph() {
2397 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
2398}