blob: 3e5935cca7227855cd9f8c043ba2b7313a1f7ac1 [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"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick78e5efe2012-09-11 00:39:15 +000034namespace llvm {
35cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39}
Andrew Trick17d35e52012-03-14 04:00:41 +000040
Andrew Trick0df7f882012-03-07 00:18:25 +000041#ifndef NDEBUG
42static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000044
45static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000047#else
48static bool ViewMISchedDAGs = false;
49#endif // NDEBUG
50
Andrew Trick9b5caaa2012-11-12 19:40:10 +000051// Experimental heuristics
52static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000053 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000054
Andrew Trick6996fd02012-11-12 19:52:20 +000055// Experimental heuristics
56static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000057 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000058
Andrew Trick178f7d02013-01-25 04:01:04 +000059// DAG subtrees must have at least this many nodes.
60static const unsigned MinSubtreeSize = 8;
61
Andrew Trick5edf2f02012-01-14 02:17:06 +000062//===----------------------------------------------------------------------===//
63// Machine Instruction Scheduling Pass and Registry
64//===----------------------------------------------------------------------===//
65
Andrew Trick86b7e2a2012-04-24 20:36:19 +000066MachineSchedContext::MachineSchedContext():
67 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
68 RegClassInfo = new RegisterClassInfo();
69}
70
71MachineSchedContext::~MachineSchedContext() {
72 delete RegClassInfo;
73}
74
Andrew Trick96f678f2012-01-13 06:30:30 +000075namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000076/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000077class MachineScheduler : public MachineSchedContext,
78 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000079public:
Andrew Trick42b7a712012-01-17 06:55:03 +000080 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000081
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
83
84 virtual void releaseMemory() {}
85
86 virtual bool runOnMachineFunction(MachineFunction&);
87
88 virtual void print(raw_ostream &O, const Module* = 0) const;
89
90 static char ID; // Class identification, replacement for typeinfo
91};
92} // namespace
93
Andrew Trick42b7a712012-01-17 06:55:03 +000094char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000095
Andrew Trick42b7a712012-01-17 06:55:03 +000096char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000097
Andrew Trick42b7a712012-01-17 06:55:03 +000098INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000099 "Machine Instruction Scheduler", false, false)
100INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
101INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
102INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000103INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000104 "Machine Instruction Scheduler", false, false)
105
Andrew Trick42b7a712012-01-17 06:55:03 +0000106MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000107: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000108 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000109}
110
Andrew Trick42b7a712012-01-17 06:55:03 +0000111void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000112 AU.setPreservesCFG();
113 AU.addRequiredID(MachineDominatorsID);
114 AU.addRequired<MachineLoopInfo>();
115 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000116 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000117 AU.addRequired<SlotIndexes>();
118 AU.addPreserved<SlotIndexes>();
119 AU.addRequired<LiveIntervals>();
120 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000121 MachineFunctionPass::getAnalysisUsage(AU);
122}
123
Andrew Trick96f678f2012-01-13 06:30:30 +0000124MachinePassRegistry MachineSchedRegistry::Registry;
125
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000126/// A dummy default scheduler factory indicates whether the scheduler
127/// is overridden on the command line.
128static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
129 return 0;
130}
Andrew Trick96f678f2012-01-13 06:30:30 +0000131
132/// MachineSchedOpt allows command line selection of the scheduler.
133static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
134 RegisterPassParser<MachineSchedRegistry> >
135MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000136 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000137 cl::desc("Machine instruction scheduler to use"));
138
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000139static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000140DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000141 useDefaultMachineSched);
142
Andrew Trick17d35e52012-03-14 04:00:41 +0000143/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000144/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000145static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000146
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000147
148/// Decrement this iterator until reaching the top or a non-debug instr.
149static MachineBasicBlock::iterator
150priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
151 assert(I != Beg && "reached the top of the region, cannot decrement");
152 while (--I != Beg) {
153 if (!I->isDebugValue())
154 break;
155 }
156 return I;
157}
158
159/// If this iterator is a debug value, increment until reaching the End or a
160/// non-debug instruction.
161static MachineBasicBlock::iterator
162nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000163 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000164 if (!I->isDebugValue())
165 break;
166 }
167 return I;
168}
169
Andrew Trickcb058d52012-03-14 04:00:38 +0000170/// Top-level MachineScheduler pass driver.
171///
172/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000173/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
174/// consistent with the DAG builder, which traverses the interior of the
175/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000176///
177/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000178/// simplifying the DAG builder's support for "special" target instructions.
179/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000180/// scheduling boundaries, for example to bundle the boudary instructions
181/// without reordering them. This creates complexity, because the target
182/// scheduler must update the RegionBegin and RegionEnd positions cached by
183/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
184/// design would be to split blocks at scheduling boundaries, but LLVM has a
185/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000186bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000187 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
188
Andrew Trick96f678f2012-01-13 06:30:30 +0000189 // Initialize the context of the pass.
190 MF = &mf;
191 MLI = &getAnalysis<MachineLoopInfo>();
192 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000193 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000194 AA = &getAnalysis<AliasAnalysis>();
195
Lang Hames907cc8f2012-01-27 22:36:19 +0000196 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000197 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000198
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000199 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000200
Andrew Trick96f678f2012-01-13 06:30:30 +0000201 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000202 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
203 if (Ctor == useDefaultMachineSched) {
204 // Get the default scheduler set by the target.
205 Ctor = MachineSchedRegistry::getDefault();
206 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000207 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000208 MachineSchedRegistry::setDefault(Ctor);
209 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000210 }
211 // Instantiate the selected scheduler.
212 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
213
214 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000215 //
216 // TODO: Visit blocks in global postorder or postorder within the bottom-up
217 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000218 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
219 MBB != MBBEnd; ++MBB) {
220
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000221 Scheduler->startBlock(MBB);
222
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000223 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000224 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000225 // boundary at the bottom of the region. The DAG does not include RegionEnd,
226 // but the region does (i.e. the next RegionEnd is above the previous
227 // RegionBegin). If the current block has no terminator then RegionEnd ==
228 // MBB->end() for the bottom region.
229 //
230 // The Scheduler may insert instructions during either schedule() or
231 // exitRegion(), even for empty regions. So the local iterators 'I' and
232 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000233 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000234 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000235 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000236
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000237 // Avoid decrementing RegionEnd for blocks with no terminator.
238 if (RegionEnd != MBB->end()
239 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
240 --RegionEnd;
241 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000242 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000243 }
244
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000245 // The next region starts above the previous region. Look backward in the
246 // instruction stream until we find the nearest boundary.
247 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000248 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000249 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
250 break;
251 }
Andrew Trick47c14452012-03-07 05:21:52 +0000252 // Notify the scheduler of the region, even if we may skip scheduling
253 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000254 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000255
256 // Skip empty scheduling regions (0 or 1 schedulable instructions).
257 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000258 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000259 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000260 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000261 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000262 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000263 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000264 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000265 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
266 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
267 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000268 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000269
Andrew Trickd24da972012-03-09 03:46:42 +0000270 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000271 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000272 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000273
274 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000275 Scheduler->exitRegion();
276
277 // Scheduling has invalidated the current iterator 'I'. Ask the
278 // scheduler for the top of it's scheduled region.
279 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000280 }
Andrew Trick22764532012-11-06 07:10:34 +0000281 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000282 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000283 }
Andrew Trick830da402012-04-01 07:24:23 +0000284 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000285 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000286 return true;
287}
288
Andrew Trick42b7a712012-01-17 06:55:03 +0000289void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000290 // unimplemented
291}
292
Manman Renb720be62012-09-11 22:23:19 +0000293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000294void ReadyQueue::dump() {
295 dbgs() << Name << ": ";
296 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
297 dbgs() << Queue[i]->NodeNum << " ";
298 dbgs() << "\n";
299}
300#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000301
302//===----------------------------------------------------------------------===//
303// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
304// preservation.
305//===----------------------------------------------------------------------===//
306
Andrew Trick178f7d02013-01-25 04:01:04 +0000307ScheduleDAGMI::~ScheduleDAGMI() {
308 delete DFSResult;
309 DeleteContainerPointers(Mutations);
310 delete SchedImpl;
311}
312
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000313bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000314 if (SuccSU != &ExitSU) {
315 // Do not use WillCreateCycle, it assumes SD scheduling.
316 // If Pred is reachable from Succ, then the edge creates a cycle.
317 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
318 return false;
319 Topo.AddPred(SuccSU, PredDep.getSUnit());
320 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000321 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
322 // Return true regardless of whether a new edge needed to be inserted.
323 return true;
324}
325
Andrew Trickc174eaf2012-03-08 01:41:12 +0000326/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
327/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000328///
329/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000330void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000331 SUnit *SuccSU = SuccEdge->getSUnit();
332
Andrew Trickae692f22012-11-12 19:28:57 +0000333 if (SuccEdge->isWeak()) {
334 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000335 if (SuccEdge->isCluster())
336 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000337 return;
338 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000339#ifndef NDEBUG
340 if (SuccSU->NumPredsLeft == 0) {
341 dbgs() << "*** Scheduling failed! ***\n";
342 SuccSU->dump(this);
343 dbgs() << " has been released too many times!\n";
344 llvm_unreachable(0);
345 }
346#endif
347 --SuccSU->NumPredsLeft;
348 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000349 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000350}
351
352/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000353void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000354 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
355 I != E; ++I) {
356 releaseSucc(SU, &*I);
357 }
358}
359
Andrew Trick17d35e52012-03-14 04:00:41 +0000360/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
361/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000362///
363/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000364void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
365 SUnit *PredSU = PredEdge->getSUnit();
366
Andrew Trickae692f22012-11-12 19:28:57 +0000367 if (PredEdge->isWeak()) {
368 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000369 if (PredEdge->isCluster())
370 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000371 return;
372 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000373#ifndef NDEBUG
374 if (PredSU->NumSuccsLeft == 0) {
375 dbgs() << "*** Scheduling failed! ***\n";
376 PredSU->dump(this);
377 dbgs() << " has been released too many times!\n";
378 llvm_unreachable(0);
379 }
380#endif
381 --PredSU->NumSuccsLeft;
382 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
383 SchedImpl->releaseBottomNode(PredSU);
384}
385
386/// releasePredecessors - Call releasePred on each of SU's predecessors.
387void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
388 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
389 I != E; ++I) {
390 releasePred(SU, &*I);
391 }
392}
393
394void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
395 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000396 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000397 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000398 ++RegionBegin;
399
400 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000401 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000402
403 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000404 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000405
406 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000407 if (RegionBegin == InsertPos)
408 RegionBegin = MI;
409}
410
Andrew Trick0b0d8992012-03-21 04:12:07 +0000411bool ScheduleDAGMI::checkSchedLimit() {
412#ifndef NDEBUG
413 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
414 CurrentTop = CurrentBottom;
415 return false;
416 }
417 ++NumInstrsScheduled;
418#endif
419 return true;
420}
421
Andrew Trick006e1ab2012-04-24 17:56:43 +0000422/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
423/// crossing a scheduling boundary. [begin, end) includes all instructions in
424/// the region, including the boundary itself and single-instruction regions
425/// that don't get scheduled.
426void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
427 MachineBasicBlock::iterator begin,
428 MachineBasicBlock::iterator end,
429 unsigned endcount)
430{
431 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000432
433 // For convenience remember the end of the liveness region.
434 LiveRegionEnd =
435 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
436}
437
438// Setup the register pressure trackers for the top scheduled top and bottom
439// scheduled regions.
440void ScheduleDAGMI::initRegPressure() {
441 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
442 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
443
444 // Close the RPTracker to finalize live ins.
445 RPTracker.closeRegion();
446
Andrew Trickbb0a2422012-05-24 22:11:14 +0000447 DEBUG(RPTracker.getPressure().dump(TRI));
448
Andrew Trick7f8ab782012-05-10 21:06:10 +0000449 // Initialize the live ins and live outs.
450 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
451 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
452
453 // Close one end of the tracker so we can call
454 // getMaxUpward/DownwardPressureDelta before advancing across any
455 // instructions. This converts currently live regs into live ins/outs.
456 TopRPTracker.closeTop();
457 BotRPTracker.closeBottom();
458
459 // Account for liveness generated by the region boundary.
460 if (LiveRegionEnd != RegionEnd)
461 BotRPTracker.recede();
462
463 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000464
465 // Cache the list of excess pressure sets in this region. This will also track
466 // the max pressure in the scheduled code for these sets.
467 RegionCriticalPSets.clear();
468 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
469 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
470 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000471 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
472 << "Limit " << Limit
473 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000474 if (RegionPressure[i] > Limit)
475 RegionCriticalPSets.push_back(PressureElement(i, 0));
476 }
477 DEBUG(dbgs() << "Excess PSets: ";
478 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
479 dbgs() << TRI->getRegPressureSetName(
480 RegionCriticalPSets[i].PSetID) << " ";
481 dbgs() << "\n");
482}
483
484// FIXME: When the pressure tracker deals in pressure differences then we won't
485// iterate over all RegionCriticalPSets[i].
486void ScheduleDAGMI::
487updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
488 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
489 unsigned ID = RegionCriticalPSets[i].PSetID;
490 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
491 if ((int)NewMaxPressure[ID] > MaxUnits)
492 MaxUnits = NewMaxPressure[ID];
493 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000494}
495
Andrew Trick17d35e52012-03-14 04:00:41 +0000496/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000497/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
498/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000499///
500/// This is a skeletal driver, with all the functionality pushed into helpers,
501/// so that it can be easilly extended by experimental schedulers. Generally,
502/// implementing MachineSchedStrategy should be sufficient to implement a new
503/// scheduling algorithm. However, if a scheduler further subclasses
504/// ScheduleDAGMI then it will want to override this virtual method in order to
505/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000506void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000507 buildDAGWithRegPressure();
508
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000509 Topo.InitDAGTopologicalSorting();
510
Andrew Trickd039b382012-09-14 17:22:42 +0000511 postprocessDAG();
512
Andrew Trick78e5efe2012-09-11 00:39:15 +0000513 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
514 SUnits[su].dumpAll(this));
515
Andrew Trick78e5efe2012-09-11 00:39:15 +0000516 initQueues();
517
518 bool IsTopNode = false;
519 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000520 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000521 if (!checkSchedLimit())
522 break;
523
524 scheduleMI(SU, IsTopNode);
525
526 updateQueues(SU, IsTopNode);
527 }
528 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
529
530 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000531
532 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000533 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000534 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
535 dumpSchedule();
536 dbgs() << '\n';
537 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000538}
539
540/// Build the DAG and setup three register pressure trackers.
541void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000542 // Initialize the register pressure tracker used by buildSchedGraph.
543 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000544
Andrew Trick7f8ab782012-05-10 21:06:10 +0000545 // Account for liveness generate by the region boundary.
546 if (LiveRegionEnd != RegionEnd)
547 RPTracker.recede();
548
549 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000550 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000551 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000552
Andrew Trick7f8ab782012-05-10 21:06:10 +0000553 // Initialize top/bottom trackers after computing region pressure.
554 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000555}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000556
Andrew Trickd039b382012-09-14 17:22:42 +0000557/// Apply each ScheduleDAGMutation step in order.
558void ScheduleDAGMI::postprocessDAG() {
559 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
560 Mutations[i]->apply(this);
561 }
562}
563
Andrew Trick178f7d02013-01-25 04:01:04 +0000564void ScheduleDAGMI::initDFSResult() {
565 if (!DFSResult)
566 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
567 DFSResult->clear();
568 DFSResult->resize(SUnits.size());
569 ScheduledTrees.clear();
570}
571
572void ScheduleDAGMI::computeDFSResult(ArrayRef<SUnit*> Roots) {
573 DFSResult->compute(Roots);
574 ScheduledTrees.resize(DFSResult->getNumSubtrees());
575}
576
Andrew Trick1e94e982012-10-15 18:02:27 +0000577// Release all DAG roots for scheduling.
Andrew Trickae692f22012-11-12 19:28:57 +0000578//
579// Nodes with unreleased weak edges can still be roots.
Andrew Trick1e94e982012-10-15 18:02:27 +0000580void ScheduleDAGMI::releaseRoots() {
581 SmallVector<SUnit*, 16> BotRoots;
582
583 for (std::vector<SUnit>::iterator
584 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000585 SUnit *SU = &(*I);
Andrew Trickdb417062013-01-24 02:09:57 +0000586
587 // Order predecessors so DFSResult follows the critical path.
588 SU->biasCriticalPath();
589
Andrew Trick1e94e982012-10-15 18:02:27 +0000590 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickae692f22012-11-12 19:28:57 +0000591 if (!I->NumPredsLeft && SU != &EntrySU)
592 SchedImpl->releaseTopNode(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000593 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trickae692f22012-11-12 19:28:57 +0000594 if (!I->NumSuccsLeft && SU != &ExitSU)
595 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000596 }
597 // Release bottom roots in reverse order so the higher priority nodes appear
598 // first. This is more natural and slightly more efficient.
599 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
600 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
601 SchedImpl->releaseBottomNode(*I);
602}
603
Andrew Trick78e5efe2012-09-11 00:39:15 +0000604/// Identify DAG roots and setup scheduler queues.
605void ScheduleDAGMI::initQueues() {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000606 NextClusterSucc = NULL;
607 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000608
Andrew Trick78e5efe2012-09-11 00:39:15 +0000609 // Initialize the strategy before modifying the DAG.
Andrew Trick17d35e52012-03-14 04:00:41 +0000610 SchedImpl->initialize(this);
611
Andrew Trickae692f22012-11-12 19:28:57 +0000612 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
613 releaseRoots();
614
Andrew Trickc174eaf2012-03-08 01:41:12 +0000615 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000616 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000617
Andrew Trick1e94e982012-10-15 18:02:27 +0000618 SchedImpl->registerRoots();
619
Andrew Trick657b75b2012-12-01 01:22:49 +0000620 // Advance past initial DebugValues.
621 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000622 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000623 TopRPTracker.setPos(CurrentTop);
624
Andrew Trick17d35e52012-03-14 04:00:41 +0000625 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000626}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000627
Andrew Trick78e5efe2012-09-11 00:39:15 +0000628/// Move an instruction and update register pressure.
629void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
630 // Move the instruction to its new location in the instruction stream.
631 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000632
Andrew Trick78e5efe2012-09-11 00:39:15 +0000633 if (IsTopNode) {
634 assert(SU->isTopReady() && "node still has unscheduled dependencies");
635 if (&*CurrentTop == MI)
636 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000637 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000638 moveInstruction(MI, CurrentTop);
639 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000640 }
Andrew Trick000b2502012-04-24 18:04:37 +0000641
Andrew Trick78e5efe2012-09-11 00:39:15 +0000642 // Update top scheduled pressure.
643 TopRPTracker.advance();
644 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
645 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
646 }
647 else {
648 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
649 MachineBasicBlock::iterator priorII =
650 priorNonDebug(CurrentBottom, CurrentTop);
651 if (&*priorII == MI)
652 CurrentBottom = priorII;
653 else {
654 if (&*CurrentTop == MI) {
655 CurrentTop = nextIfDebug(++CurrentTop, priorII);
656 TopRPTracker.setPos(CurrentTop);
657 }
658 moveInstruction(MI, CurrentBottom);
659 CurrentBottom = MI;
660 }
661 // Update bottom scheduled pressure.
662 BotRPTracker.recede();
663 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
664 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
665 }
666}
667
668/// Update scheduler queues after scheduling an instruction.
669void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
670 // Release dependent instructions for scheduling.
671 if (IsTopNode)
672 releaseSuccessors(SU);
673 else
674 releasePredecessors(SU);
675
676 SU->isScheduled = true;
677
Andrew Trick178f7d02013-01-25 04:01:04 +0000678 if (DFSResult) {
679 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
680 if (!ScheduledTrees.test(SubtreeID)) {
681 ScheduledTrees.set(SubtreeID);
682 DFSResult->scheduleTree(SubtreeID);
683 SchedImpl->scheduleTree(SubtreeID);
684 }
685 }
686
Andrew Trick78e5efe2012-09-11 00:39:15 +0000687 // Notify the scheduling strategy after updating the DAG.
688 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000689}
690
691/// Reinsert any remaining debug_values, just like the PostRA scheduler.
692void ScheduleDAGMI::placeDebugValues() {
693 // If first instruction was a DBG_VALUE then put it back.
694 if (FirstDbgValue) {
695 BB->splice(RegionBegin, BB, FirstDbgValue);
696 RegionBegin = FirstDbgValue;
697 }
698
699 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
700 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
701 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
702 MachineInstr *DbgValue = P.first;
703 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000704 if (&*RegionBegin == DbgValue)
705 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000706 BB->splice(++OrigPrevMI, BB, DbgValue);
707 if (OrigPrevMI == llvm::prior(RegionEnd))
708 RegionEnd = DbgValue;
709 }
710 DbgValues.clear();
711 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000712}
713
Andrew Trick3b87f622012-11-07 07:05:09 +0000714#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
715void ScheduleDAGMI::dumpSchedule() const {
716 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
717 if (SUnit *SU = getSUnit(&(*MI)))
718 SU->dump(this);
719 else
720 dbgs() << "Missing SUnit\n";
721 }
722}
723#endif
724
Andrew Trick6996fd02012-11-12 19:52:20 +0000725//===----------------------------------------------------------------------===//
726// LoadClusterMutation - DAG post-processing to cluster loads.
727//===----------------------------------------------------------------------===//
728
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000729namespace {
730/// \brief Post-process the DAG to create cluster edges between neighboring
731/// loads.
732class LoadClusterMutation : public ScheduleDAGMutation {
733 struct LoadInfo {
734 SUnit *SU;
735 unsigned BaseReg;
736 unsigned Offset;
737 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
738 : SU(su), BaseReg(reg), Offset(ofs) {}
739 };
740 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
741 const LoadClusterMutation::LoadInfo &RHS);
742
743 const TargetInstrInfo *TII;
744 const TargetRegisterInfo *TRI;
745public:
746 LoadClusterMutation(const TargetInstrInfo *tii,
747 const TargetRegisterInfo *tri)
748 : TII(tii), TRI(tri) {}
749
750 virtual void apply(ScheduleDAGMI *DAG);
751protected:
752 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
753};
754} // anonymous
755
756bool LoadClusterMutation::LoadInfoLess(
757 const LoadClusterMutation::LoadInfo &LHS,
758 const LoadClusterMutation::LoadInfo &RHS) {
759 if (LHS.BaseReg != RHS.BaseReg)
760 return LHS.BaseReg < RHS.BaseReg;
761 return LHS.Offset < RHS.Offset;
762}
763
764void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
765 ScheduleDAGMI *DAG) {
766 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
767 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
768 SUnit *SU = Loads[Idx];
769 unsigned BaseReg;
770 unsigned Offset;
771 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
772 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
773 }
774 if (LoadRecords.size() < 2)
775 return;
776 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
777 unsigned ClusterLength = 1;
778 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
779 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
780 ClusterLength = 1;
781 continue;
782 }
783
784 SUnit *SUa = LoadRecords[Idx].SU;
785 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000786 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000787 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
788
789 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
790 << SUb->NodeNum << ")\n");
791 // Copy successor edges from SUa to SUb. Interleaving computation
792 // dependent on SUa can prevent load combining due to register reuse.
793 // Predecessor edges do not need to be copied from SUb to SUa since nearby
794 // loads should have effectively the same inputs.
795 for (SUnit::const_succ_iterator
796 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
797 if (SI->getSUnit() == SUb)
798 continue;
799 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
800 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
801 }
802 ++ClusterLength;
803 }
804 else
805 ClusterLength = 1;
806 }
807}
808
809/// \brief Callback from DAG postProcessing to create cluster edges for loads.
810void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
811 // Map DAG NodeNum to store chain ID.
812 DenseMap<unsigned, unsigned> StoreChainIDs;
813 // Map each store chain to a set of dependent loads.
814 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
815 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
816 SUnit *SU = &DAG->SUnits[Idx];
817 if (!SU->getInstr()->mayLoad())
818 continue;
819 unsigned ChainPredID = DAG->SUnits.size();
820 for (SUnit::const_pred_iterator
821 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
822 if (PI->isCtrl()) {
823 ChainPredID = PI->getSUnit()->NodeNum;
824 break;
825 }
826 }
827 // Check if this chain-like pred has been seen
828 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
829 unsigned NumChains = StoreChainDependents.size();
830 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
831 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
832 if (Result.second)
833 StoreChainDependents.resize(NumChains + 1);
834 StoreChainDependents[Result.first->second].push_back(SU);
835 }
836 // Iterate over the store chains.
837 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
838 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
839}
840
Andrew Trickc174eaf2012-03-08 01:41:12 +0000841//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000842// MacroFusion - DAG post-processing to encourage fusion of macro ops.
843//===----------------------------------------------------------------------===//
844
845namespace {
846/// \brief Post-process the DAG to create cluster edges between instructions
847/// that may be fused by the processor into a single operation.
848class MacroFusion : public ScheduleDAGMutation {
849 const TargetInstrInfo *TII;
850public:
851 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
852
853 virtual void apply(ScheduleDAGMI *DAG);
854};
855} // anonymous
856
857/// \brief Callback from DAG postProcessing to create cluster edges to encourage
858/// fused operations.
859void MacroFusion::apply(ScheduleDAGMI *DAG) {
860 // For now, assume targets can only fuse with the branch.
861 MachineInstr *Branch = DAG->ExitSU.getInstr();
862 if (!Branch)
863 return;
864
865 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
866 SUnit *SU = &DAG->SUnits[--Idx];
867 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
868 continue;
869
870 // Create a single weak edge from SU to ExitSU. The only effect is to cause
871 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
872 // need to copy predecessor edges from ExitSU to SU, since top-down
873 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
874 // of SU, we could create an artificial edge from the deepest root, but it
875 // hasn't been needed yet.
876 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
877 (void)Success;
878 assert(Success && "No DAG nodes should be reachable from ExitSU");
879
880 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
881 break;
882 }
883}
884
885//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000886// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000887//===----------------------------------------------------------------------===//
888
889namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000890/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
891/// the schedule.
892class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000893public:
894 /// Represent the type of SchedCandidate found within a single queue.
895 /// pickNodeBidirectional depends on these listed by decreasing priority.
896 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000897 NoCand, SingleExcess, SingleCritical, Cluster,
898 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
899 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
900 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000901
902#ifndef NDEBUG
903 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
904#endif
905
906 /// Policy for scheduling the next instruction in the candidate's zone.
907 struct CandPolicy {
908 bool ReduceLatency;
909 unsigned ReduceResIdx;
910 unsigned DemandResIdx;
911
912 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
913 };
914
915 /// Status of an instruction's critical resource consumption.
916 struct SchedResourceDelta {
917 // Count critical resources in the scheduled region required by SU.
918 unsigned CritResources;
919
920 // Count critical resources from another region consumed by SU.
921 unsigned DemandedResources;
922
923 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
924
925 bool operator==(const SchedResourceDelta &RHS) const {
926 return CritResources == RHS.CritResources
927 && DemandedResources == RHS.DemandedResources;
928 }
929 bool operator!=(const SchedResourceDelta &RHS) const {
930 return !operator==(RHS);
931 }
932 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000933
934 /// Store the state used by ConvergingScheduler heuristics, required for the
935 /// lifetime of one invocation of pickNode().
936 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000937 CandPolicy Policy;
938
Andrew Trick7196a8f2012-05-10 21:06:16 +0000939 // The best SUnit candidate.
940 SUnit *SU;
941
Andrew Trick3b87f622012-11-07 07:05:09 +0000942 // The reason for this candidate.
943 CandReason Reason;
944
Andrew Trick7196a8f2012-05-10 21:06:16 +0000945 // Register pressure values for the best candidate.
946 RegPressureDelta RPDelta;
947
Andrew Trick3b87f622012-11-07 07:05:09 +0000948 // Critical resource consumption of the best candidate.
949 SchedResourceDelta ResDelta;
950
951 SchedCandidate(const CandPolicy &policy)
952 : Policy(policy), SU(NULL), Reason(NoCand) {}
953
954 bool isValid() const { return SU; }
955
956 // Copy the status of another candidate without changing policy.
957 void setBest(SchedCandidate &Best) {
958 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
959 SU = Best.SU;
960 Reason = Best.Reason;
961 RPDelta = Best.RPDelta;
962 ResDelta = Best.ResDelta;
963 }
964
965 void initResourceDelta(const ScheduleDAGMI *DAG,
966 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000967 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000968
969 /// Summarize the unscheduled region.
970 struct SchedRemainder {
971 // Critical path through the DAG in expected latency.
972 unsigned CriticalPath;
973
974 // Unscheduled resources
975 SmallVector<unsigned, 16> RemainingCounts;
976 // Critical resource for the unscheduled zone.
977 unsigned CritResIdx;
978 // Number of micro-ops left to schedule.
979 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +0000980
Andrew Trick3b87f622012-11-07 07:05:09 +0000981 void reset() {
982 CriticalPath = 0;
983 RemainingCounts.clear();
984 CritResIdx = 0;
985 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +0000986 }
987
988 SchedRemainder() { reset(); }
989
990 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +0000991
992 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
993 if (!SchedModel->hasInstrSchedModel())
994 return 0;
995
996 return std::max(
997 RemainingMicroOps * SchedModel->getMicroOpFactor(),
998 RemainingCounts[CritResIdx]);
999 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001000 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001001
Andrew Trickf3234242012-05-24 22:11:12 +00001002 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001003 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001004 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001005 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001006 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001007 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001008 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001009
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001010 ReadyQueue Available;
1011 ReadyQueue Pending;
1012 bool CheckPending;
1013
Andrew Trick3b87f622012-11-07 07:05:09 +00001014 // For heuristics, keep a list of the nodes that immediately depend on the
1015 // most recently scheduled node.
1016 SmallPtrSet<const SUnit*, 8> NextSUs;
1017
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001018 ScheduleHazardRecognizer *HazardRec;
1019
1020 unsigned CurrCycle;
1021 unsigned IssueCount;
1022
1023 /// MinReadyCycle - Cycle of the soonest available instruction.
1024 unsigned MinReadyCycle;
1025
Andrew Trick3b87f622012-11-07 07:05:09 +00001026 // The expected latency of the critical path in this scheduled zone.
1027 unsigned ExpectedLatency;
1028
1029 // Resources used in the scheduled zone beyond this boundary.
1030 SmallVector<unsigned, 16> ResourceCounts;
1031
1032 // Cache the critical resources ID in this scheduled zone.
1033 unsigned CritResIdx;
1034
1035 // Is the scheduled region resource limited vs. latency limited.
1036 bool IsResourceLimited;
1037
1038 unsigned ExpectedCount;
1039
Andrew Trick3b87f622012-11-07 07:05:09 +00001040#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001041 // Remember the greatest min operand latency.
1042 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001043#endif
1044
1045 void reset() {
1046 Available.clear();
1047 Pending.clear();
1048 CheckPending = false;
1049 NextSUs.clear();
1050 HazardRec = 0;
1051 CurrCycle = 0;
1052 IssueCount = 0;
1053 MinReadyCycle = UINT_MAX;
1054 ExpectedLatency = 0;
1055 ResourceCounts.resize(1);
1056 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1057 CritResIdx = 0;
1058 IsResourceLimited = false;
1059 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001060#ifndef NDEBUG
1061 MaxMinLatency = 0;
1062#endif
1063 // Reserve a zero-count for invalid CritResIdx.
1064 ResourceCounts.resize(1);
1065 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001066
Andrew Trickf3234242012-05-24 22:11:12 +00001067 /// Pending queues extend the ready queues with the same ID and the
1068 /// PendingFlag set.
1069 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001070 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1071 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1072 reset();
1073 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001074
1075 ~SchedBoundary() { delete HazardRec; }
1076
Andrew Trick3b87f622012-11-07 07:05:09 +00001077 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1078 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001079
Andrew Trickf3234242012-05-24 22:11:12 +00001080 bool isTop() const {
1081 return Available.getID() == ConvergingScheduler::TopQID;
1082 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001083
Andrew Trick3b87f622012-11-07 07:05:09 +00001084 unsigned getUnscheduledLatency(SUnit *SU) const {
1085 if (isTop())
1086 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001087 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001088 }
1089
1090 unsigned getCriticalCount() const {
1091 return ResourceCounts[CritResIdx];
1092 }
1093
Andrew Trick5559ffa2012-06-29 03:23:24 +00001094 bool checkHazard(SUnit *SU);
1095
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001096 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001097
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001098 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1099
1100 void bumpCycle();
1101
Andrew Trick3b87f622012-11-07 07:05:09 +00001102 void countResource(unsigned PIdx, unsigned Cycles);
1103
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001104 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001105
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001106 void releasePending();
1107
1108 void removeReady(SUnit *SU);
1109
1110 SUnit *pickOnlyChoice();
1111 };
1112
Andrew Trick3b87f622012-11-07 07:05:09 +00001113private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001114 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001115 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001116 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001117
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001118 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001119 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001120 SchedBoundary Top;
1121 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001122
1123public:
Andrew Trickf3234242012-05-24 22:11:12 +00001124 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001125 enum {
1126 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001127 BotQID = 2,
1128 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001129 };
1130
Andrew Trickf3234242012-05-24 22:11:12 +00001131 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001132 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001133
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001134 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001135
Andrew Trick7196a8f2012-05-10 21:06:16 +00001136 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001137
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001138 virtual void schedNode(SUnit *SU, bool IsTopNode);
1139
1140 virtual void releaseTopNode(SUnit *SU);
1141
1142 virtual void releaseBottomNode(SUnit *SU);
1143
Andrew Trick3b87f622012-11-07 07:05:09 +00001144 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001145
Andrew Trick3b87f622012-11-07 07:05:09 +00001146protected:
1147 void balanceZones(
1148 ConvergingScheduler::SchedBoundary &CriticalZone,
1149 ConvergingScheduler::SchedCandidate &CriticalCand,
1150 ConvergingScheduler::SchedBoundary &OppositeZone,
1151 ConvergingScheduler::SchedCandidate &OppositeCand);
1152
1153 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1154 ConvergingScheduler::SchedCandidate &BotCand);
1155
1156 void tryCandidate(SchedCandidate &Cand,
1157 SchedCandidate &TryCand,
1158 SchedBoundary &Zone,
1159 const RegPressureTracker &RPTracker,
1160 RegPressureTracker &TempTracker);
1161
1162 SUnit *pickNodeBidirectional(bool &IsTopNode);
1163
1164 void pickNodeFromQueue(SchedBoundary &Zone,
1165 const RegPressureTracker &RPTracker,
1166 SchedCandidate &Candidate);
1167
Andrew Trick28ebc892012-05-10 21:06:19 +00001168#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001169 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001170#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001171};
1172} // namespace
1173
Andrew Trick3b87f622012-11-07 07:05:09 +00001174void ConvergingScheduler::SchedRemainder::
1175init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1176 reset();
1177 if (!SchedModel->hasInstrSchedModel())
1178 return;
1179 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1180 for (std::vector<SUnit>::iterator
1181 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1182 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1183 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1184 for (TargetSchedModel::ProcResIter
1185 PI = SchedModel->getWriteProcResBegin(SC),
1186 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1187 unsigned PIdx = PI->ProcResourceIdx;
1188 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1189 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1190 }
1191 }
Andrew Trick071966f2012-12-18 20:52:49 +00001192 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1193 PIdx != PEnd; ++PIdx) {
1194 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1195 >= (int)SchedModel->getLatencyFactor()) {
1196 CritResIdx = PIdx;
1197 }
1198 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001199}
1200
1201void ConvergingScheduler::SchedBoundary::
1202init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1203 reset();
1204 DAG = dag;
1205 SchedModel = smodel;
1206 Rem = rem;
1207 if (SchedModel->hasInstrSchedModel())
1208 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1209}
1210
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001211void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1212 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001213 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001214 TRI = DAG->TRI;
Andrew Trick3b87f622012-11-07 07:05:09 +00001215 Rem.init(DAG, SchedModel);
1216 Top.init(DAG, SchedModel, &Rem);
1217 Bot.init(DAG, SchedModel, &Rem);
1218
Andrew Trick178f7d02013-01-25 04:01:04 +00001219 DAG->initDFSResult();
1220
Andrew Trick3b87f622012-11-07 07:05:09 +00001221 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001222
Andrew Trick412cd2f2012-10-10 05:43:09 +00001223 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1224 // are disabled, then these HazardRecs will be disabled.
1225 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001226 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001227 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1228 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1229
1230 assert((!ForceTopDown || !ForceBottomUp) &&
1231 "-misched-topdown incompatible with -misched-bottomup");
1232}
1233
1234void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001235 if (SU->isScheduled)
1236 return;
1237
Andrew Trickd4539602012-12-18 20:52:52 +00001238 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001239 I != E; ++I) {
1240 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001241 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001242#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001243 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001244#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001245 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1246 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001247 }
1248 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001249}
1250
1251void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001252 if (SU->isScheduled)
1253 return;
1254
1255 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1256
1257 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1258 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001259 if (I->isWeak())
1260 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001261 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001262 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001263#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001264 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001265#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001266 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1267 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001268 }
1269 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001270}
1271
Andrew Trick3b87f622012-11-07 07:05:09 +00001272void ConvergingScheduler::registerRoots() {
1273 Rem.CriticalPath = DAG->ExitSU.getDepth();
1274 // Some roots may not feed into ExitSU. Check all of them in case.
1275 for (std::vector<SUnit*>::const_iterator
1276 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1277 if ((*I)->getDepth() > Rem.CriticalPath)
1278 Rem.CriticalPath = (*I)->getDepth();
1279 }
1280 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
Andrew Trick178f7d02013-01-25 04:01:04 +00001281
1282 DAG->computeDFSResult(Bot.Available.elements());
Andrew Trick3b87f622012-11-07 07:05:09 +00001283}
1284
Andrew Trick5559ffa2012-06-29 03:23:24 +00001285/// Does this SU have a hazard within the current instruction group.
1286///
1287/// The scheduler supports two modes of hazard recognition. The first is the
1288/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1289/// supports highly complicated in-order reservation tables
1290/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1291///
1292/// The second is a streamlined mechanism that checks for hazards based on
1293/// simple counters that the scheduler itself maintains. It explicitly checks
1294/// for instruction dispatch limitations, including the number of micro-ops that
1295/// can dispatch per cycle.
1296///
1297/// TODO: Also check whether the SU must start a new group.
1298bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1299 if (HazardRec->isEnabled())
1300 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1301
Andrew Trick412cd2f2012-10-10 05:43:09 +00001302 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001303 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1304 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1305 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001306 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001307 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001308 return false;
1309}
1310
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001311/// Compute the remaining latency to determine whether ILP should be increased.
1312void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1313 // FIXME: compile time. In all, we visit four queues here one we should only
1314 // need to visit the one that was last popped if we cache the result.
1315 unsigned RemLatency = 0;
1316 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1317 I != E; ++I) {
1318 unsigned L = getUnscheduledLatency(*I);
1319 if (L > RemLatency)
1320 RemLatency = L;
1321 }
1322 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1323 I != E; ++I) {
1324 unsigned L = getUnscheduledLatency(*I);
1325 if (L > RemLatency)
1326 RemLatency = L;
1327 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001328 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1329 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001330 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1331 Policy.ReduceLatency = true;
1332 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001333 }
1334}
1335
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001336void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1337 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001338
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001339 if (ReadyCycle < MinReadyCycle)
1340 MinReadyCycle = ReadyCycle;
1341
1342 // Check for interlocks first. For the purpose of other heuristics, an
1343 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001344 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001345 Pending.push(SU);
1346 else
1347 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001348
1349 // Record this node as an immediate dependent of the scheduled node.
1350 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001351}
1352
1353/// Move the boundary of scheduled code by one cycle.
1354void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001355 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001356 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001357
Andrew Trick3b87f622012-11-07 07:05:09 +00001358 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001359 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001360 if (MinReadyCycle > NextCycle) {
1361 IssueCount = 0;
1362 NextCycle = MinReadyCycle;
1363 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001364
1365 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001366 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001367 CurrCycle = NextCycle;
1368 }
1369 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001370 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001371 for (; CurrCycle != NextCycle; ++CurrCycle) {
1372 if (isTop())
1373 HazardRec->AdvanceCycle();
1374 else
1375 HazardRec->RecedeCycle();
1376 }
1377 }
1378 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001379 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001380
Andrew Trick3b87f622012-11-07 07:05:09 +00001381 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001382 << CurrCycle << '\n');
1383}
1384
Andrew Trick3b87f622012-11-07 07:05:09 +00001385/// Add the given processor resource to this scheduled zone.
1386void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1387 unsigned Cycles) {
1388 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1389 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1390 << " +(" << Cycles << "x" << Factor
1391 << ") / " << SchedModel->getLatencyFactor() << '\n');
1392
1393 unsigned Count = Factor * Cycles;
1394 ResourceCounts[PIdx] += Count;
1395 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1396 Rem->RemainingCounts[PIdx] -= Count;
1397
Andrew Trick3b87f622012-11-07 07:05:09 +00001398 // Check if this resource exceeds the current critical resource by a full
1399 // cycle. If so, it becomes the critical resource.
1400 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1401 >= (int)SchedModel->getLatencyFactor()) {
1402 CritResIdx = PIdx;
1403 DEBUG(dbgs() << " *** Critical resource "
1404 << SchedModel->getProcResource(PIdx)->Name << " x"
1405 << ResourceCounts[PIdx] << '\n');
1406 }
1407}
1408
Andrew Trickb7e02892012-06-05 21:11:27 +00001409/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001410void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001411 // Update the reservation table.
1412 if (HazardRec->isEnabled()) {
1413 if (!isTop() && SU->isCall) {
1414 // Calls are scheduled with their preceding instructions. For bottom-up
1415 // scheduling, clear the pipeline state before emitting.
1416 HazardRec->Reset();
1417 }
1418 HazardRec->EmitInstruction(SU);
1419 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001420 // Update resource counts and critical resource.
1421 if (SchedModel->hasInstrSchedModel()) {
1422 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1423 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1424 for (TargetSchedModel::ProcResIter
1425 PI = SchedModel->getWriteProcResBegin(SC),
1426 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1427 countResource(PI->ProcResourceIdx, PI->Cycles);
1428 }
1429 }
1430 if (isTop()) {
1431 if (SU->getDepth() > ExpectedLatency)
1432 ExpectedLatency = SU->getDepth();
1433 }
1434 else {
1435 if (SU->getHeight() > ExpectedLatency)
1436 ExpectedLatency = SU->getHeight();
1437 }
1438
1439 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1440
Andrew Trick5559ffa2012-06-29 03:23:24 +00001441 // Check the instruction group dispatch limit.
1442 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001443 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001444
1445 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1446 // issue width. However, we commonly reach the maximum. In this case
1447 // opportunistically bump the cycle to avoid uselessly checking everything in
1448 // the readyQ. Furthermore, a single instruction may produce more than one
1449 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001450 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001451 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001452 bumpCycle();
1453 }
1454}
1455
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001456/// Release pending ready nodes in to the available queue. This makes them
1457/// visible to heuristics.
1458void ConvergingScheduler::SchedBoundary::releasePending() {
1459 // If the available queue is empty, it is safe to reset MinReadyCycle.
1460 if (Available.empty())
1461 MinReadyCycle = UINT_MAX;
1462
1463 // Check to see if any of the pending instructions are ready to issue. If
1464 // so, add them to the available queue.
1465 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1466 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001467 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001468
1469 if (ReadyCycle < MinReadyCycle)
1470 MinReadyCycle = ReadyCycle;
1471
1472 if (ReadyCycle > CurrCycle)
1473 continue;
1474
Andrew Trick5559ffa2012-06-29 03:23:24 +00001475 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001476 continue;
1477
1478 Available.push(SU);
1479 Pending.remove(Pending.begin()+i);
1480 --i; --e;
1481 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001482 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001483 CheckPending = false;
1484}
1485
1486/// Remove SU from the ready set for this boundary.
1487void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1488 if (Available.isInQueue(SU))
1489 Available.remove(Available.find(SU));
1490 else {
1491 assert(Pending.isInQueue(SU) && "bad ready count");
1492 Pending.remove(Pending.find(SU));
1493 }
1494}
1495
1496/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001497/// defer any nodes that now hit a hazard, and advance the cycle until at least
1498/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001499SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1500 if (CheckPending)
1501 releasePending();
1502
Andrew Trick3b87f622012-11-07 07:05:09 +00001503 if (IssueCount > 0) {
1504 // Defer any ready instrs that now have a hazard.
1505 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1506 if (checkHazard(*I)) {
1507 Pending.push(*I);
1508 I = Available.remove(I);
1509 continue;
1510 }
1511 ++I;
1512 }
1513 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001514 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001515 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1516 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001517 bumpCycle();
1518 releasePending();
1519 }
1520 if (Available.size() == 1)
1521 return *Available.begin();
1522 return NULL;
1523}
1524
Andrew Trick3b87f622012-11-07 07:05:09 +00001525/// Record the candidate policy for opposite zones with different critical
1526/// resources.
1527///
1528/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001529/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001530void ConvergingScheduler::balanceZones(
1531 ConvergingScheduler::SchedBoundary &CriticalZone,
1532 ConvergingScheduler::SchedCandidate &CriticalCand,
1533 ConvergingScheduler::SchedBoundary &OppositeZone,
1534 ConvergingScheduler::SchedCandidate &OppositeCand) {
1535
1536 if (!CriticalZone.IsResourceLimited)
1537 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001538 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001539
1540 SchedRemainder *Rem = CriticalZone.Rem;
1541
1542 // If the critical zone is overconsuming a resource relative to the
1543 // remainder, try to reduce it.
1544 unsigned RemainingCritCount =
1545 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001546 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001547 > (int)SchedModel->getLatencyFactor()) {
1548 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1549 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1550 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1551 << '\n');
1552 }
1553 // If the other zone is underconsuming a resource relative to the full zone,
1554 // try to increase it.
1555 unsigned OppositeCount =
1556 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1557 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1558 > (int)SchedModel->getLatencyFactor()) {
1559 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1560 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1561 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1562 << '\n');
1563 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001564}
Andrew Trick3b87f622012-11-07 07:05:09 +00001565
1566/// Determine if the scheduled zones exceed resource limits or critical path and
1567/// set each candidate's ReduceHeight policy accordingly.
1568void ConvergingScheduler::checkResourceLimits(
1569 ConvergingScheduler::SchedCandidate &TopCand,
1570 ConvergingScheduler::SchedCandidate &BotCand) {
1571
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001572 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001573 Bot.setLatencyPolicy(BotCand.Policy);
1574 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001575
1576 // Handle resource-limited regions.
1577 if (Top.IsResourceLimited && Bot.IsResourceLimited
1578 && Top.CritResIdx == Bot.CritResIdx) {
1579 // If the scheduled critical resource in both zones is no longer the
1580 // critical remaining resource, attempt to reduce resource height both ways.
1581 if (Top.CritResIdx != Rem.CritResIdx) {
1582 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1583 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1584 DEBUG(dbgs() << "Reduce scheduled "
1585 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1586 }
1587 return;
1588 }
1589 // Handle latency-limited regions.
1590 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1591 // If the total scheduled expected latency exceeds the region's critical
1592 // path then reduce latency both ways.
1593 //
1594 // Just because a zone is not resource limited does not mean it is latency
1595 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1596 // to exceed expected latency.
1597 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1598 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1599 TopCand.Policy.ReduceLatency = true;
1600 BotCand.Policy.ReduceLatency = true;
1601 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1602 << " + " << Bot.ExpectedLatency << '\n');
1603 }
1604 return;
1605 }
1606 // The critical resource is different in each zone, so request balancing.
1607
1608 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001609 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1610 Top.ExpectedCount = std::max(
1611 Top.getCriticalCount(),
1612 Top.ExpectedCount * SchedModel->getLatencyFactor());
1613 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1614 Bot.ExpectedCount = std::max(
1615 Bot.getCriticalCount(),
1616 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1617
1618 balanceZones(Top, TopCand, Bot, BotCand);
1619 balanceZones(Bot, BotCand, Top, TopCand);
1620}
1621
1622void ConvergingScheduler::SchedCandidate::
1623initResourceDelta(const ScheduleDAGMI *DAG,
1624 const TargetSchedModel *SchedModel) {
1625 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1626 return;
1627
1628 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1629 for (TargetSchedModel::ProcResIter
1630 PI = SchedModel->getWriteProcResBegin(SC),
1631 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1632 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1633 ResDelta.CritResources += PI->Cycles;
1634 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1635 ResDelta.DemandedResources += PI->Cycles;
1636 }
1637}
1638
1639/// Return true if this heuristic determines order.
1640static bool tryLess(unsigned TryVal, unsigned CandVal,
1641 ConvergingScheduler::SchedCandidate &TryCand,
1642 ConvergingScheduler::SchedCandidate &Cand,
1643 ConvergingScheduler::CandReason Reason) {
1644 if (TryVal < CandVal) {
1645 TryCand.Reason = Reason;
1646 return true;
1647 }
1648 if (TryVal > CandVal) {
1649 if (Cand.Reason > Reason)
1650 Cand.Reason = Reason;
1651 return true;
1652 }
1653 return false;
1654}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001655
Andrew Trick3b87f622012-11-07 07:05:09 +00001656static bool tryGreater(unsigned TryVal, unsigned CandVal,
1657 ConvergingScheduler::SchedCandidate &TryCand,
1658 ConvergingScheduler::SchedCandidate &Cand,
1659 ConvergingScheduler::CandReason Reason) {
1660 if (TryVal > CandVal) {
1661 TryCand.Reason = Reason;
1662 return true;
1663 }
1664 if (TryVal < CandVal) {
1665 if (Cand.Reason > Reason)
1666 Cand.Reason = Reason;
1667 return true;
1668 }
1669 return false;
1670}
1671
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001672static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1673 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1674}
1675
Andrew Trick3b87f622012-11-07 07:05:09 +00001676/// Apply a set of heursitics to a new candidate. Heuristics are currently
1677/// hierarchical. This may be more efficient than a graduated cost model because
1678/// we don't need to evaluate all aspects of the model for each node in the
1679/// queue. But it's really done to make the heuristics easier to debug and
1680/// statistically analyze.
1681///
1682/// \param Cand provides the policy and current best candidate.
1683/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1684/// \param Zone describes the scheduled zone that we are extending.
1685/// \param RPTracker describes reg pressure within the scheduled zone.
1686/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1687void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1688 SchedCandidate &TryCand,
1689 SchedBoundary &Zone,
1690 const RegPressureTracker &RPTracker,
1691 RegPressureTracker &TempTracker) {
1692
1693 // Always initialize TryCand's RPDelta.
1694 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1695 DAG->getRegionCriticalPSets(),
1696 DAG->getRegPressure().MaxSetPressure);
1697
1698 // Initialize the candidate if needed.
1699 if (!Cand.isValid()) {
1700 TryCand.Reason = NodeOrder;
1701 return;
1702 }
1703 // Avoid exceeding the target's limit.
1704 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1705 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1706 return;
1707 if (Cand.Reason == SingleExcess)
1708 Cand.Reason = MultiPressure;
1709
1710 // Avoid increasing the max critical pressure in the scheduled region.
1711 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1712 Cand.RPDelta.CriticalMax.UnitIncrease,
1713 TryCand, Cand, SingleCritical))
1714 return;
1715 if (Cand.Reason == SingleCritical)
1716 Cand.Reason = MultiPressure;
1717
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001718 // Keep clustered nodes together to encourage downstream peephole
1719 // optimizations which may reduce resource requirements.
1720 //
1721 // This is a best effort to set things up for a post-RA pass. Optimizations
1722 // like generating loads of multiple registers should ideally be done within
1723 // the scheduler pass by combining the loads during DAG postprocessing.
1724 const SUnit *NextClusterSU =
1725 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1726 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1727 TryCand, Cand, Cluster))
1728 return;
1729 // Currently, weak edges are for clustering, so we hard-code that reason.
1730 // However, deferring the current TryCand will not change Cand's reason.
1731 CandReason OrigReason = Cand.Reason;
1732 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1733 getWeakLeft(Cand.SU, Zone.isTop()),
1734 TryCand, Cand, Cluster)) {
1735 Cand.Reason = OrigReason;
1736 return;
1737 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001738 // Avoid critical resource consumption and balance the schedule.
1739 TryCand.initResourceDelta(DAG, SchedModel);
1740 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1741 TryCand, Cand, ResourceReduce))
1742 return;
1743 if (tryGreater(TryCand.ResDelta.DemandedResources,
1744 Cand.ResDelta.DemandedResources,
1745 TryCand, Cand, ResourceDemand))
1746 return;
1747
1748 // Avoid serializing long latency dependence chains.
1749 if (Cand.Policy.ReduceLatency) {
1750 if (Zone.isTop()) {
1751 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1752 > Zone.ExpectedCount) {
1753 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1754 TryCand, Cand, TopDepthReduce))
1755 return;
1756 }
1757 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1758 TryCand, Cand, TopPathReduce))
1759 return;
1760 }
1761 else {
1762 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1763 > Zone.ExpectedCount) {
1764 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1765 TryCand, Cand, BotHeightReduce))
1766 return;
1767 }
1768 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1769 TryCand, Cand, BotPathReduce))
1770 return;
1771 }
1772 }
1773
1774 // Avoid increasing the max pressure of the entire region.
1775 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1776 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1777 return;
1778 if (Cand.Reason == SingleMax)
1779 Cand.Reason = MultiPressure;
1780
1781 // Prefer immediate defs/users of the last scheduled instruction. This is a
1782 // nice pressure avoidance strategy that also conserves the processor's
1783 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001784 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1785 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001786 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001787
Andrew Trick3b87f622012-11-07 07:05:09 +00001788 // Fall through to original instruction order.
1789 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1790 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1791 TryCand.Reason = NodeOrder;
1792 }
1793}
Andrew Trick28ebc892012-05-10 21:06:19 +00001794
Andrew Trick5429a6b2012-05-17 22:37:09 +00001795/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1796/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001797static bool compareRPDelta(const RegPressureDelta &LHS,
1798 const RegPressureDelta &RHS) {
1799 // Compare each component of pressure in decreasing order of importance
1800 // without checking if any are valid. Invalid PressureElements are assumed to
1801 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001802
1803 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001804 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1805 DEBUG(dbgs() << "RP excess top - bot: "
1806 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001807 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001808 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001809 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001810 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1811 DEBUG(dbgs() << "RP critical top - bot: "
1812 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1813 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001814 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001815 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001816 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001817 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1818 DEBUG(dbgs() << "RP current top - bot: "
1819 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1820 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001821 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001822 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001823 return false;
1824}
1825
Andrew Trick3b87f622012-11-07 07:05:09 +00001826#ifndef NDEBUG
1827const char *ConvergingScheduler::getReasonStr(
1828 ConvergingScheduler::CandReason Reason) {
1829 switch (Reason) {
1830 case NoCand: return "NOCAND ";
1831 case SingleExcess: return "REG-EXCESS";
1832 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001833 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001834 case SingleMax: return "REG-MAX ";
1835 case MultiPressure: return "REG-MULTI ";
1836 case ResourceReduce: return "RES-REDUCE";
1837 case ResourceDemand: return "RES-DEMAND";
1838 case TopDepthReduce: return "TOP-DEPTH ";
1839 case TopPathReduce: return "TOP-PATH ";
1840 case BotHeightReduce:return "BOT-HEIGHT";
1841 case BotPathReduce: return "BOT-PATH ";
1842 case NextDefUse: return "DEF-USE ";
1843 case NodeOrder: return "ORDER ";
1844 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001845 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001846}
1847
1848void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1849 const SchedBoundary &Zone) {
1850 const char *Label = getReasonStr(Cand.Reason);
1851 PressureElement P;
1852 unsigned ResIdx = 0;
1853 unsigned Latency = 0;
1854 switch (Cand.Reason) {
1855 default:
1856 break;
1857 case SingleExcess:
1858 P = Cand.RPDelta.Excess;
1859 break;
1860 case SingleCritical:
1861 P = Cand.RPDelta.CriticalMax;
1862 break;
1863 case SingleMax:
1864 P = Cand.RPDelta.CurrentMax;
1865 break;
1866 case ResourceReduce:
1867 ResIdx = Cand.Policy.ReduceResIdx;
1868 break;
1869 case ResourceDemand:
1870 ResIdx = Cand.Policy.DemandResIdx;
1871 break;
1872 case TopDepthReduce:
1873 Latency = Cand.SU->getDepth();
1874 break;
1875 case TopPathReduce:
1876 Latency = Cand.SU->getHeight();
1877 break;
1878 case BotHeightReduce:
1879 Latency = Cand.SU->getHeight();
1880 break;
1881 case BotPathReduce:
1882 Latency = Cand.SU->getDepth();
1883 break;
1884 }
1885 dbgs() << Label << " " << Zone.Available.getName() << " ";
1886 if (P.isValid())
1887 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1888 << " ";
1889 else
1890 dbgs() << " ";
1891 if (ResIdx)
1892 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1893 else
1894 dbgs() << " ";
1895 if (Latency)
1896 dbgs() << Latency << " cycles ";
1897 else
1898 dbgs() << " ";
1899 Cand.SU->dump(DAG);
1900}
1901#endif
1902
Andrew Trick7196a8f2012-05-10 21:06:16 +00001903/// Pick the best candidate from the top queue.
1904///
1905/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1906/// DAG building. To adjust for the current scheduling location we need to
1907/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001908void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1909 const RegPressureTracker &RPTracker,
1910 SchedCandidate &Cand) {
1911 ReadyQueue &Q = Zone.Available;
1912
Andrew Trickf3234242012-05-24 22:11:12 +00001913 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001914
Andrew Trick7196a8f2012-05-10 21:06:16 +00001915 // getMaxPressureDelta temporarily modifies the tracker.
1916 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1917
Andrew Trick8c2d9212012-05-24 22:11:03 +00001918 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001919
Andrew Trick3b87f622012-11-07 07:05:09 +00001920 SchedCandidate TryCand(Cand.Policy);
1921 TryCand.SU = *I;
1922 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1923 if (TryCand.Reason != NoCand) {
1924 // Initialize resource delta if needed in case future heuristics query it.
1925 if (TryCand.ResDelta == SchedResourceDelta())
1926 TryCand.initResourceDelta(DAG, SchedModel);
1927 Cand.setBest(TryCand);
1928 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001929 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001930 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001931}
1932
1933static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1934 bool IsTop) {
1935 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1936 << " SU(" << Cand.SU->NodeNum << ") "
1937 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001938}
1939
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001940/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001941SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001942 // Schedule as far as possible in the direction of no choice. This is most
1943 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001944 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001945 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001946 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001947 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001948 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001949 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001950 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001951 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001952 CandPolicy NoPolicy;
1953 SchedCandidate BotCand(NoPolicy);
1954 SchedCandidate TopCand(NoPolicy);
1955 checkResourceLimits(TopCand, BotCand);
1956
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001957 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001958 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1959 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001960
1961 // If either Q has a single candidate that provides the least increase in
1962 // Excess pressure, we can immediately schedule from that Q.
1963 //
1964 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1965 // affects picking from either Q. If scheduling in one direction must
1966 // increase pressure for one of the excess PSets, then schedule in that
1967 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001968 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001969 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001970 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001971 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001972 }
1973 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001974 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1975 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001976
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001977 // If either Q has a single candidate that minimizes pressure above the
1978 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001979 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1980 if (TopCand.Reason < BotCand.Reason) {
1981 IsTopNode = true;
1982 tracePick(TopCand, IsTopNode);
1983 return TopCand.SU;
1984 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001985 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001986 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001987 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001988 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001989 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001990 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001991 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001992 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001993 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001994 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001995 // Otherwise prefer the bottom candidate, in node order if all else failed.
1996 if (TopCand.Reason < BotCand.Reason) {
1997 IsTopNode = true;
1998 tracePick(TopCand, IsTopNode);
1999 return TopCand.SU;
2000 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002001 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002002 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002003 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002004}
2005
2006/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002007SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2008 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002009 assert(Top.Available.empty() && Top.Pending.empty() &&
2010 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002011 return NULL;
2012 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002013 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002014 do {
2015 if (ForceTopDown) {
2016 SU = Top.pickOnlyChoice();
2017 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002018 CandPolicy NoPolicy;
2019 SchedCandidate TopCand(NoPolicy);
2020 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2021 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002022 SU = TopCand.SU;
2023 }
2024 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002025 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002026 else if (ForceBottomUp) {
2027 SU = Bot.pickOnlyChoice();
2028 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002029 CandPolicy NoPolicy;
2030 SchedCandidate BotCand(NoPolicy);
2031 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2032 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002033 SU = BotCand.SU;
2034 }
2035 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002036 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002037 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002038 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002039 }
2040 } while (SU->isScheduled);
2041
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002042 if (SU->isTopReady())
2043 Top.removeReady(SU);
2044 if (SU->isBottomReady())
2045 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002046
2047 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2048 << " Scheduling Instruction in cycle "
2049 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2050 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00002051 return SU;
2052}
2053
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002054/// Update the scheduler's state after scheduling a node. This is the same node
2055/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002056/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002057void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002058 if (IsTopNode) {
2059 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002060 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002061 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002062 else {
2063 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002064 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002065 }
2066}
2067
Andrew Trick17d35e52012-03-14 04:00:41 +00002068/// Create the standard converging machine scheduler. This will be used as the
2069/// default scheduler if the target does not set a default.
2070static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002071 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002072 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002073 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2074 // Register DAG post-processors.
2075 if (EnableLoadCluster)
2076 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002077 if (EnableMacroFusion)
2078 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002079 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002080}
2081static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002082ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2083 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002084
2085//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002086// ILP Scheduler. Currently for experimental analysis of heuristics.
2087//===----------------------------------------------------------------------===//
2088
2089namespace {
2090/// \brief Order nodes by the ILP metric.
2091struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002092 const SchedDFSResult *DFSResult;
2093 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002094 bool MaximizeILP;
2095
Andrew Trick178f7d02013-01-25 04:01:04 +00002096 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002097
2098 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002099 ///
2100 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002101 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002102 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2103 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2104 if (SchedTreeA != SchedTreeB) {
2105 // Unscheduled trees have lower priority.
2106 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2107 return ScheduledTrees->test(SchedTreeB);
2108
2109 // Trees with shallower connections have have lower priority.
2110 if (DFSResult->getSubtreeLevel(SchedTreeA)
2111 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2112 return DFSResult->getSubtreeLevel(SchedTreeA)
2113 < DFSResult->getSubtreeLevel(SchedTreeB);
2114 }
2115 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002116 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002117 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002118 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002119 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002120 }
2121};
2122
2123/// \brief Schedule based on the ILP metric.
2124class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002125 /// In case all subtrees are eventually connected to a common root through
2126 /// data dependence (e.g. reduction), place an upper limit on their size.
2127 ///
2128 /// FIXME: A subtree limit is generally good, but in the situation commented
2129 /// above, where multiple similar subtrees feed a common root, we should
2130 /// only split at a point where the resulting subtrees will be balanced.
2131 /// (a motivating test case must be found).
2132 static const unsigned SubtreeLimit = 16;
2133
Andrew Trick178f7d02013-01-25 04:01:04 +00002134 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002135 ILPOrder Cmp;
2136
2137 std::vector<SUnit*> ReadyQ;
2138public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002139 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002140
Andrew Trick178f7d02013-01-25 04:01:04 +00002141 virtual void initialize(ScheduleDAGMI *dag) {
2142 DAG = dag;
2143 DAG->initDFSResult();
2144 Cmp.DFSResult = DAG->getDFSResult();
2145 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002146 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002147 }
2148
2149 virtual void registerRoots() {
Andrew Trick178f7d02013-01-25 04:01:04 +00002150 DAG->computeDFSResult(ReadyQ);
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002151 // Restore the heap in ReadyQ with the updated DFS results.
2152 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002153 }
2154
2155 /// Implement MachineSchedStrategy interface.
2156 /// -----------------------------------------
2157
Andrew Trick8b1496c2012-11-28 05:13:28 +00002158 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002159 virtual SUnit *pickNode(bool &IsTopNode) {
2160 if (ReadyQ.empty()) return NULL;
2161 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2162 SUnit *SU = ReadyQ.back();
2163 ReadyQ.pop_back();
2164 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002165 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2166 << *SU->getInstr()
Andrew Trick178f7d02013-01-25 04:01:04 +00002167 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2168 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2169 << DAG->getDFSResult()->getSubtreeLevel(
2170 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002171 return SU;
2172 }
2173
Andrew Trick178f7d02013-01-25 04:01:04 +00002174 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2175 virtual void scheduleTree(unsigned SubtreeID) {
2176 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2177 }
2178
Andrew Trick8b1496c2012-11-28 05:13:28 +00002179 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2180 /// DFSResults, and resort the priority Q.
2181 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2182 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002183 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002184
2185 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2186
2187 virtual void releaseBottomNode(SUnit *SU) {
2188 ReadyQ.push_back(SU);
2189 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2190 }
2191};
2192} // namespace
2193
2194static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2195 return new ScheduleDAGMI(C, new ILPScheduler(true));
2196}
2197static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2198 return new ScheduleDAGMI(C, new ILPScheduler(false));
2199}
2200static MachineSchedRegistry ILPMaxRegistry(
2201 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2202static MachineSchedRegistry ILPMinRegistry(
2203 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2204
2205//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002206// Machine Instruction Shuffler for Correctness Testing
2207//===----------------------------------------------------------------------===//
2208
Andrew Trick96f678f2012-01-13 06:30:30 +00002209#ifndef NDEBUG
2210namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002211/// Apply a less-than relation on the node order, which corresponds to the
2212/// instruction order prior to scheduling. IsReverse implements greater-than.
2213template<bool IsReverse>
2214struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002215 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002216 if (IsReverse)
2217 return A->NodeNum > B->NodeNum;
2218 else
2219 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002220 }
2221};
2222
Andrew Trick96f678f2012-01-13 06:30:30 +00002223/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002224class InstructionShuffler : public MachineSchedStrategy {
2225 bool IsAlternating;
2226 bool IsTopDown;
2227
2228 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2229 // gives nodes with a higher number higher priority causing the latest
2230 // instructions to be scheduled first.
2231 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2232 TopQ;
2233 // When scheduling bottom-up, use greater-than as the queue priority.
2234 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2235 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002236public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002237 InstructionShuffler(bool alternate, bool topdown)
2238 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002239
Andrew Trick17d35e52012-03-14 04:00:41 +00002240 virtual void initialize(ScheduleDAGMI *) {
2241 TopQ.clear();
2242 BottomQ.clear();
2243 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002244
Andrew Trick17d35e52012-03-14 04:00:41 +00002245 /// Implement MachineSchedStrategy interface.
2246 /// -----------------------------------------
2247
2248 virtual SUnit *pickNode(bool &IsTopNode) {
2249 SUnit *SU;
2250 if (IsTopDown) {
2251 do {
2252 if (TopQ.empty()) return NULL;
2253 SU = TopQ.top();
2254 TopQ.pop();
2255 } while (SU->isScheduled);
2256 IsTopNode = true;
2257 }
2258 else {
2259 do {
2260 if (BottomQ.empty()) return NULL;
2261 SU = BottomQ.top();
2262 BottomQ.pop();
2263 } while (SU->isScheduled);
2264 IsTopNode = false;
2265 }
2266 if (IsAlternating)
2267 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002268 return SU;
2269 }
2270
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002271 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2272
Andrew Trick17d35e52012-03-14 04:00:41 +00002273 virtual void releaseTopNode(SUnit *SU) {
2274 TopQ.push(SU);
2275 }
2276 virtual void releaseBottomNode(SUnit *SU) {
2277 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002278 }
2279};
2280} // namespace
2281
Andrew Trickc174eaf2012-03-08 01:41:12 +00002282static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002283 bool Alternate = !ForceTopDown && !ForceBottomUp;
2284 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002285 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002286 "-misched-topdown incompatible with -misched-bottomup");
2287 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002288}
Andrew Trick17d35e52012-03-14 04:00:41 +00002289static MachineSchedRegistry ShufflerRegistry(
2290 "shuffle", "Shuffle machine instructions alternating directions",
2291 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002292#endif // !NDEBUG