blob: da6920575dbcd25b728dcb14a5346b5882393391 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
Andrew Trickc174eaf2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/PriorityQueue.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszak760fa5d2013-03-10 13:11:23 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick1f8b48a2013-06-21 18:32:58 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000025#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000026#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000027#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000028#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
Andrew Trick30849792013-01-25 07:45:29 +000032#include "llvm/Support/GraphWriter.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000033#include "llvm/Support/raw_ostream.h"
Jakub Staszak38084db2013-06-14 00:00:13 +000034#include "llvm/Target/TargetInstrInfo.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000035#include <queue>
36
Andrew Trick96f678f2012-01-13 06:30:30 +000037using namespace llvm;
38
Andrew Trick78e5efe2012-09-11 00:39:15 +000039namespace llvm {
40cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41 cl::desc("Force top-down list scheduling"));
42cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43 cl::desc("Force bottom-up list scheduling"));
44}
Andrew Trick17d35e52012-03-14 04:00:41 +000045
Andrew Trick0df7f882012-03-07 00:18:25 +000046#ifndef NDEBUG
47static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000049
50static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000052#else
53static bool ViewMISchedDAGs = false;
54#endif // NDEBUG
55
Andrew Trick9b5caaa2012-11-12 19:40:10 +000056static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000057 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000058
Andrew Trick6996fd02012-11-12 19:52:20 +000059// Experimental heuristics
60static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000061 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000062
Andrew Trickfff2d3a2013-03-08 05:40:34 +000063static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
64 cl::desc("Verify machine instrs before and after machine scheduling"));
65
Andrew Trick178f7d02013-01-25 04:01:04 +000066// DAG subtrees must have at least this many nodes.
67static const unsigned MinSubtreeSize = 8;
68
Andrew Trick5edf2f02012-01-14 02:17:06 +000069//===----------------------------------------------------------------------===//
70// Machine Instruction Scheduling Pass and Registry
71//===----------------------------------------------------------------------===//
72
Andrew Trick86b7e2a2012-04-24 20:36:19 +000073MachineSchedContext::MachineSchedContext():
74 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
75 RegClassInfo = new RegisterClassInfo();
76}
77
78MachineSchedContext::~MachineSchedContext() {
79 delete RegClassInfo;
80}
81
Andrew Trick96f678f2012-01-13 06:30:30 +000082namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000083/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000084class MachineScheduler : public MachineSchedContext,
85 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000086public:
Andrew Trick42b7a712012-01-17 06:55:03 +000087 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000088
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
90
91 virtual void releaseMemory() {}
92
93 virtual bool runOnMachineFunction(MachineFunction&);
94
95 virtual void print(raw_ostream &O, const Module* = 0) const;
96
97 static char ID; // Class identification, replacement for typeinfo
98};
99} // namespace
100
Andrew Trick42b7a712012-01-17 06:55:03 +0000101char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +0000102
Andrew Trick42b7a712012-01-17 06:55:03 +0000103char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000104
Andrew Trick42b7a712012-01-17 06:55:03 +0000105INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000106 "Machine Instruction Scheduler", false, false)
107INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
108INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
109INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000110INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000111 "Machine Instruction Scheduler", false, false)
112
Andrew Trick42b7a712012-01-17 06:55:03 +0000113MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000114: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000115 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000116}
117
Andrew Trick42b7a712012-01-17 06:55:03 +0000118void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000119 AU.setPreservesCFG();
120 AU.addRequiredID(MachineDominatorsID);
121 AU.addRequired<MachineLoopInfo>();
122 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000123 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000124 AU.addRequired<SlotIndexes>();
125 AU.addPreserved<SlotIndexes>();
126 AU.addRequired<LiveIntervals>();
127 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000128 MachineFunctionPass::getAnalysisUsage(AU);
129}
130
Andrew Trick96f678f2012-01-13 06:30:30 +0000131MachinePassRegistry MachineSchedRegistry::Registry;
132
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000133/// A dummy default scheduler factory indicates whether the scheduler
134/// is overridden on the command line.
135static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
136 return 0;
137}
Andrew Trick96f678f2012-01-13 06:30:30 +0000138
139/// MachineSchedOpt allows command line selection of the scheduler.
140static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
141 RegisterPassParser<MachineSchedRegistry> >
142MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000143 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000144 cl::desc("Machine instruction scheduler to use"));
145
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000146static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000147DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000148 useDefaultMachineSched);
149
Andrew Trick17d35e52012-03-14 04:00:41 +0000150/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000151/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000152static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000153
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000154
155/// Decrement this iterator until reaching the top or a non-debug instr.
156static MachineBasicBlock::iterator
157priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
158 assert(I != Beg && "reached the top of the region, cannot decrement");
159 while (--I != Beg) {
160 if (!I->isDebugValue())
161 break;
162 }
163 return I;
164}
165
166/// If this iterator is a debug value, increment until reaching the End or a
167/// non-debug instruction.
168static MachineBasicBlock::iterator
169nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000170 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000171 if (!I->isDebugValue())
172 break;
173 }
174 return I;
175}
176
Andrew Trickcb058d52012-03-14 04:00:38 +0000177/// Top-level MachineScheduler pass driver.
178///
179/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000180/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
181/// consistent with the DAG builder, which traverses the interior of the
182/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000183///
184/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000185/// simplifying the DAG builder's support for "special" target instructions.
186/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000187/// scheduling boundaries, for example to bundle the boudary instructions
188/// without reordering them. This creates complexity, because the target
189/// scheduler must update the RegionBegin and RegionEnd positions cached by
190/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
191/// design would be to split blocks at scheduling boundaries, but LLVM has a
192/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000193bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000194 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
195
Andrew Trick96f678f2012-01-13 06:30:30 +0000196 // Initialize the context of the pass.
197 MF = &mf;
198 MLI = &getAnalysis<MachineLoopInfo>();
199 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000200 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000201 AA = &getAnalysis<AliasAnalysis>();
202
Lang Hames907cc8f2012-01-27 22:36:19 +0000203 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000204 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000205
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000206 if (VerifyScheduling) {
Andrew Trick5dca6132013-07-25 07:26:26 +0000207 DEBUG(LIS->dump());
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000208 MF->verify(this, "Before machine scheduling.");
209 }
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000210 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000211
Andrew Trick96f678f2012-01-13 06:30:30 +0000212 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000213 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
214 if (Ctor == useDefaultMachineSched) {
215 // Get the default scheduler set by the target.
216 Ctor = MachineSchedRegistry::getDefault();
217 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000218 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000219 MachineSchedRegistry::setDefault(Ctor);
220 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000221 }
222 // Instantiate the selected scheduler.
223 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
224
225 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000226 //
227 // TODO: Visit blocks in global postorder or postorder within the bottom-up
228 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000229 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
230 MBB != MBBEnd; ++MBB) {
231
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000232 Scheduler->startBlock(MBB);
233
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000234 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000235 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000236 // boundary at the bottom of the region. The DAG does not include RegionEnd,
237 // but the region does (i.e. the next RegionEnd is above the previous
238 // RegionBegin). If the current block has no terminator then RegionEnd ==
239 // MBB->end() for the bottom region.
240 //
241 // The Scheduler may insert instructions during either schedule() or
242 // exitRegion(), even for empty regions. So the local iterators 'I' and
243 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000244 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000245 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000246 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000247
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000248 // Avoid decrementing RegionEnd for blocks with no terminator.
249 if (RegionEnd != MBB->end()
250 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
251 --RegionEnd;
252 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000253 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000254 }
255
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000256 // The next region starts above the previous region. Look backward in the
257 // instruction stream until we find the nearest boundary.
Andrew Trickd2763f62013-08-23 17:48:33 +0000258 unsigned NumRegionInstrs = 0;
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000259 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trickd2763f62013-08-23 17:48:33 +0000260 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000261 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
262 break;
263 }
Andrew Trick47c14452012-03-07 05:21:52 +0000264 // Notify the scheduler of the region, even if we may skip scheduling
265 // it. Perhaps it still needs to be bundled.
Andrew Trickd2763f62013-08-23 17:48:33 +0000266 Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000267
268 // Skip empty scheduling regions (0 or 1 schedulable instructions).
269 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000270 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000271 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000272 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000273 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000274 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000275 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000276 DEBUG(dbgs() << MF->getName()
Andrew Trickc8554232013-01-25 07:45:31 +0000277 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
278 << "\n From: " << *I << " To: ";
Andrew Trick291411c2012-02-08 02:17:21 +0000279 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
280 else dbgs() << "End";
Andrew Trickd2763f62013-08-23 17:48:33 +0000281 dbgs() << " RegionInstrs: " << NumRegionInstrs
282 << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000283
Andrew Trickd24da972012-03-09 03:46:42 +0000284 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000285 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000286 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000287
288 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000289 Scheduler->exitRegion();
290
291 // Scheduling has invalidated the current iterator 'I'. Ask the
292 // scheduler for the top of it's scheduled region.
293 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000294 }
Andrew Trick22764532012-11-06 07:10:34 +0000295 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000296 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000297 }
Andrew Trick830da402012-04-01 07:24:23 +0000298 Scheduler->finalizeSchedule();
Andrew Trick5dca6132013-07-25 07:26:26 +0000299 DEBUG(LIS->dump());
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000300 if (VerifyScheduling)
301 MF->verify(this, "After machine scheduling.");
Andrew Trick96f678f2012-01-13 06:30:30 +0000302 return true;
303}
304
Andrew Trick42b7a712012-01-17 06:55:03 +0000305void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000306 // unimplemented
307}
308
Manman Renb720be62012-09-11 22:23:19 +0000309#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000310void ReadyQueue::dump() {
Andrew Tricke52d5022013-06-17 21:45:05 +0000311 dbgs() << Name << ": ";
Andrew Trick78e5efe2012-09-11 00:39:15 +0000312 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
313 dbgs() << Queue[i]->NodeNum << " ";
314 dbgs() << "\n";
315}
316#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000317
318//===----------------------------------------------------------------------===//
319// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
320// preservation.
321//===----------------------------------------------------------------------===//
322
Andrew Trick178f7d02013-01-25 04:01:04 +0000323ScheduleDAGMI::~ScheduleDAGMI() {
324 delete DFSResult;
325 DeleteContainerPointers(Mutations);
326 delete SchedImpl;
327}
328
Andrew Tricke38afe12013-04-24 15:54:43 +0000329bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
330 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
331}
332
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000333bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000334 if (SuccSU != &ExitSU) {
335 // Do not use WillCreateCycle, it assumes SD scheduling.
336 // If Pred is reachable from Succ, then the edge creates a cycle.
337 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
338 return false;
339 Topo.AddPred(SuccSU, PredDep.getSUnit());
340 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000341 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
342 // Return true regardless of whether a new edge needed to be inserted.
343 return true;
344}
345
Andrew Trickc174eaf2012-03-08 01:41:12 +0000346/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
347/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000348///
349/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000350void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000351 SUnit *SuccSU = SuccEdge->getSUnit();
352
Andrew Trickae692f22012-11-12 19:28:57 +0000353 if (SuccEdge->isWeak()) {
354 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000355 if (SuccEdge->isCluster())
356 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000357 return;
358 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000359#ifndef NDEBUG
360 if (SuccSU->NumPredsLeft == 0) {
361 dbgs() << "*** Scheduling failed! ***\n";
362 SuccSU->dump(this);
363 dbgs() << " has been released too many times!\n";
364 llvm_unreachable(0);
365 }
366#endif
367 --SuccSU->NumPredsLeft;
368 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000369 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000370}
371
372/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000373void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000374 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
375 I != E; ++I) {
376 releaseSucc(SU, &*I);
377 }
378}
379
Andrew Trick17d35e52012-03-14 04:00:41 +0000380/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
381/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000382///
383/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000384void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
385 SUnit *PredSU = PredEdge->getSUnit();
386
Andrew Trickae692f22012-11-12 19:28:57 +0000387 if (PredEdge->isWeak()) {
388 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000389 if (PredEdge->isCluster())
390 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000391 return;
392 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000393#ifndef NDEBUG
394 if (PredSU->NumSuccsLeft == 0) {
395 dbgs() << "*** Scheduling failed! ***\n";
396 PredSU->dump(this);
397 dbgs() << " has been released too many times!\n";
398 llvm_unreachable(0);
399 }
400#endif
401 --PredSU->NumSuccsLeft;
402 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
403 SchedImpl->releaseBottomNode(PredSU);
404}
405
406/// releasePredecessors - Call releasePred on each of SU's predecessors.
407void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
408 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
409 I != E; ++I) {
410 releasePred(SU, &*I);
411 }
412}
413
Andrew Trick4392f0f2013-04-13 06:07:40 +0000414/// This is normally called from the main scheduler loop but may also be invoked
415/// by the scheduling strategy to perform additional code motion.
Andrew Trick17d35e52012-03-14 04:00:41 +0000416void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
417 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000418 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000419 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000420 ++RegionBegin;
421
422 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000423 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000424
425 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000426 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000427
428 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000429 if (RegionBegin == InsertPos)
430 RegionBegin = MI;
431}
432
Andrew Trick0b0d8992012-03-21 04:12:07 +0000433bool ScheduleDAGMI::checkSchedLimit() {
434#ifndef NDEBUG
435 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
436 CurrentTop = CurrentBottom;
437 return false;
438 }
439 ++NumInstrsScheduled;
440#endif
441 return true;
442}
443
Andrew Trick006e1ab2012-04-24 17:56:43 +0000444/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
445/// crossing a scheduling boundary. [begin, end) includes all instructions in
446/// the region, including the boundary itself and single-instruction regions
447/// that don't get scheduled.
448void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
449 MachineBasicBlock::iterator begin,
450 MachineBasicBlock::iterator end,
Andrew Trickd2763f62013-08-23 17:48:33 +0000451 unsigned regioninstrs)
Andrew Trick006e1ab2012-04-24 17:56:43 +0000452{
Andrew Trickd2763f62013-08-23 17:48:33 +0000453 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000454
455 // For convenience remember the end of the liveness region.
456 LiveRegionEnd =
457 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
458}
459
460// Setup the register pressure trackers for the top scheduled top and bottom
461// scheduled regions.
462void ScheduleDAGMI::initRegPressure() {
463 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
464 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
465
466 // Close the RPTracker to finalize live ins.
467 RPTracker.closeRegion();
468
Andrew Trickd71efff2013-07-30 19:59:12 +0000469 DEBUG(RPTracker.dump());
Andrew Trickbb0a2422012-05-24 22:11:14 +0000470
Andrew Trick7f8ab782012-05-10 21:06:10 +0000471 // Initialize the live ins and live outs.
472 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
473 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
474
475 // Close one end of the tracker so we can call
476 // getMaxUpward/DownwardPressureDelta before advancing across any
477 // instructions. This converts currently live regs into live ins/outs.
478 TopRPTracker.closeTop();
479 BotRPTracker.closeBottom();
480
Andrew Trickd71efff2013-07-30 19:59:12 +0000481 BotRPTracker.initLiveThru(RPTracker);
482 if (!BotRPTracker.getLiveThru().empty()) {
483 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
484 DEBUG(dbgs() << "Live Thru: ";
485 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
486 };
487
Andrew Trick7f8ab782012-05-10 21:06:10 +0000488 // Account for liveness generated by the region boundary.
489 if (LiveRegionEnd != RegionEnd)
490 BotRPTracker.recede();
491
492 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000493
494 // Cache the list of excess pressure sets in this region. This will also track
495 // the max pressure in the scheduled code for these sets.
496 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +0000497 const std::vector<unsigned> &RegionPressure =
498 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000499 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick1f8b48a2013-06-21 18:32:58 +0000500 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trick3bf23302013-06-21 18:33:01 +0000501 if (RegionPressure[i] > Limit) {
502 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
503 << " Limit " << Limit
504 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000505 RegionCriticalPSets.push_back(PressureElement(i, 0));
Andrew Trick3bf23302013-06-21 18:33:01 +0000506 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000507 }
508 DEBUG(dbgs() << "Excess PSets: ";
509 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
510 dbgs() << TRI->getRegPressureSetName(
511 RegionCriticalPSets[i].PSetID) << " ";
512 dbgs() << "\n");
513}
514
515// FIXME: When the pressure tracker deals in pressure differences then we won't
516// iterate over all RegionCriticalPSets[i].
517void ScheduleDAGMI::
Jakub Staszakb717a502013-02-16 15:47:26 +0000518updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000519 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
520 unsigned ID = RegionCriticalPSets[i].PSetID;
521 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
522 if ((int)NewMaxPressure[ID] > MaxUnits)
523 MaxUnits = NewMaxPressure[ID];
524 }
Andrew Trick811a3722013-04-24 15:54:36 +0000525 DEBUG(
526 for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
Andrew Trick1f8b48a2013-06-21 18:32:58 +0000527 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trick811a3722013-04-24 15:54:36 +0000528 if (NewMaxPressure[i] > Limit ) {
529 dbgs() << " " << TRI->getRegPressureSetName(i) << ": "
530 << NewMaxPressure[i] << " > " << Limit << "\n";
531 }
532 });
Andrew Trick006e1ab2012-04-24 17:56:43 +0000533}
534
Andrew Trick17d35e52012-03-14 04:00:41 +0000535/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000536/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
537/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000538///
539/// This is a skeletal driver, with all the functionality pushed into helpers,
540/// so that it can be easilly extended by experimental schedulers. Generally,
541/// implementing MachineSchedStrategy should be sufficient to implement a new
542/// scheduling algorithm. However, if a scheduler further subclasses
543/// ScheduleDAGMI then it will want to override this virtual method in order to
544/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000545void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000546 buildDAGWithRegPressure();
547
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000548 Topo.InitDAGTopologicalSorting();
549
Andrew Trickd039b382012-09-14 17:22:42 +0000550 postprocessDAG();
551
Andrew Trick4e1fb182013-01-25 06:33:57 +0000552 SmallVector<SUnit*, 8> TopRoots, BotRoots;
553 findRootsAndBiasEdges(TopRoots, BotRoots);
554
555 // Initialize the strategy before modifying the DAG.
556 // This may initialize a DFSResult to be used for queue priority.
557 SchedImpl->initialize(this);
558
Andrew Trick78e5efe2012-09-11 00:39:15 +0000559 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
560 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000561 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000562
Andrew Trick4e1fb182013-01-25 06:33:57 +0000563 // Initialize ready queues now that the DAG and priority data are finalized.
564 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000565
566 bool IsTopNode = false;
567 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000568 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000569 if (!checkSchedLimit())
570 break;
571
572 scheduleMI(SU, IsTopNode);
573
574 updateQueues(SU, IsTopNode);
575 }
576 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
577
578 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000579
580 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000581 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000582 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
583 dumpSchedule();
584 dbgs() << '\n';
585 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000586}
587
588/// Build the DAG and setup three register pressure trackers.
589void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000590 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trickd71efff2013-07-30 19:59:12 +0000591 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
592 /*TrackUntiedDefs=*/true);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000593
Andrew Trick7f8ab782012-05-10 21:06:10 +0000594 // Account for liveness generate by the region boundary.
595 if (LiveRegionEnd != RegionEnd)
596 RPTracker.recede();
597
598 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000599 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000600
Andrew Trick7f8ab782012-05-10 21:06:10 +0000601 // Initialize top/bottom trackers after computing region pressure.
602 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000603}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000604
Andrew Trickd039b382012-09-14 17:22:42 +0000605/// Apply each ScheduleDAGMutation step in order.
606void ScheduleDAGMI::postprocessDAG() {
607 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
608 Mutations[i]->apply(this);
609 }
610}
611
Andrew Trick4e1fb182013-01-25 06:33:57 +0000612void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000613 if (!DFSResult)
614 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
615 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000616 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000617 DFSResult->resize(SUnits.size());
618 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000619 ScheduledTrees.resize(DFSResult->getNumSubtrees());
620}
621
Andrew Trick4e1fb182013-01-25 06:33:57 +0000622void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
623 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000624 for (std::vector<SUnit>::iterator
625 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000626 SUnit *SU = &(*I);
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000627 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickdb417062013-01-24 02:09:57 +0000628
629 // Order predecessors so DFSResult follows the critical path.
630 SU->biasCriticalPath();
631
Andrew Trick1e94e982012-10-15 18:02:27 +0000632 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000633 if (!I->NumPredsLeft)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000634 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000635 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000636 if (!I->NumSuccsLeft)
Andrew Trickae692f22012-11-12 19:28:57 +0000637 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000638 }
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000639 ExitSU.biasCriticalPath();
Andrew Trick1e94e982012-10-15 18:02:27 +0000640}
641
Andrew Trick78e5efe2012-09-11 00:39:15 +0000642/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000643void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
644 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000645 NextClusterSucc = NULL;
646 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000647
Andrew Trickae692f22012-11-12 19:28:57 +0000648 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000649 //
650 // Nodes with unreleased weak edges can still be roots.
651 // Release top roots in forward order.
652 for (SmallVectorImpl<SUnit*>::const_iterator
653 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
654 SchedImpl->releaseTopNode(*I);
655 }
656 // Release bottom roots in reverse order so the higher priority nodes appear
657 // first. This is more natural and slightly more efficient.
658 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
659 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
660 SchedImpl->releaseBottomNode(*I);
661 }
Andrew Trickae692f22012-11-12 19:28:57 +0000662
Andrew Trickc174eaf2012-03-08 01:41:12 +0000663 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000664 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000665
Andrew Trick1e94e982012-10-15 18:02:27 +0000666 SchedImpl->registerRoots();
667
Andrew Trick657b75b2012-12-01 01:22:49 +0000668 // Advance past initial DebugValues.
669 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000670 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000671 TopRPTracker.setPos(CurrentTop);
672
Andrew Trick17d35e52012-03-14 04:00:41 +0000673 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000674}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000675
Andrew Trick78e5efe2012-09-11 00:39:15 +0000676/// Move an instruction and update register pressure.
677void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
678 // Move the instruction to its new location in the instruction stream.
679 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000680
Andrew Trick78e5efe2012-09-11 00:39:15 +0000681 if (IsTopNode) {
682 assert(SU->isTopReady() && "node still has unscheduled dependencies");
683 if (&*CurrentTop == MI)
684 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000685 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000686 moveInstruction(MI, CurrentTop);
687 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000688 }
Andrew Trick000b2502012-04-24 18:04:37 +0000689
Andrew Trick78e5efe2012-09-11 00:39:15 +0000690 // Update top scheduled pressure.
691 TopRPTracker.advance();
692 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
693 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
694 }
695 else {
696 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
697 MachineBasicBlock::iterator priorII =
698 priorNonDebug(CurrentBottom, CurrentTop);
699 if (&*priorII == MI)
700 CurrentBottom = priorII;
701 else {
702 if (&*CurrentTop == MI) {
703 CurrentTop = nextIfDebug(++CurrentTop, priorII);
704 TopRPTracker.setPos(CurrentTop);
705 }
706 moveInstruction(MI, CurrentBottom);
707 CurrentBottom = MI;
708 }
709 // Update bottom scheduled pressure.
710 BotRPTracker.recede();
711 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
712 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
713 }
714}
715
716/// Update scheduler queues after scheduling an instruction.
717void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
718 // Release dependent instructions for scheduling.
719 if (IsTopNode)
720 releaseSuccessors(SU);
721 else
722 releasePredecessors(SU);
723
724 SU->isScheduled = true;
725
Andrew Trick178f7d02013-01-25 04:01:04 +0000726 if (DFSResult) {
727 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
728 if (!ScheduledTrees.test(SubtreeID)) {
729 ScheduledTrees.set(SubtreeID);
730 DFSResult->scheduleTree(SubtreeID);
731 SchedImpl->scheduleTree(SubtreeID);
732 }
733 }
734
Andrew Trick78e5efe2012-09-11 00:39:15 +0000735 // Notify the scheduling strategy after updating the DAG.
736 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000737}
738
739/// Reinsert any remaining debug_values, just like the PostRA scheduler.
740void ScheduleDAGMI::placeDebugValues() {
741 // If first instruction was a DBG_VALUE then put it back.
742 if (FirstDbgValue) {
743 BB->splice(RegionBegin, BB, FirstDbgValue);
744 RegionBegin = FirstDbgValue;
745 }
746
747 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
748 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
749 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
750 MachineInstr *DbgValue = P.first;
751 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000752 if (&*RegionBegin == DbgValue)
753 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000754 BB->splice(++OrigPrevMI, BB, DbgValue);
755 if (OrigPrevMI == llvm::prior(RegionEnd))
756 RegionEnd = DbgValue;
757 }
758 DbgValues.clear();
759 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000760}
761
Andrew Trick3b87f622012-11-07 07:05:09 +0000762#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
763void ScheduleDAGMI::dumpSchedule() const {
764 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
765 if (SUnit *SU = getSUnit(&(*MI)))
766 SU->dump(this);
767 else
768 dbgs() << "Missing SUnit\n";
769 }
770}
771#endif
772
Andrew Trick6996fd02012-11-12 19:52:20 +0000773//===----------------------------------------------------------------------===//
774// LoadClusterMutation - DAG post-processing to cluster loads.
775//===----------------------------------------------------------------------===//
776
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000777namespace {
778/// \brief Post-process the DAG to create cluster edges between neighboring
779/// loads.
780class LoadClusterMutation : public ScheduleDAGMutation {
781 struct LoadInfo {
782 SUnit *SU;
783 unsigned BaseReg;
784 unsigned Offset;
785 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
786 : SU(su), BaseReg(reg), Offset(ofs) {}
787 };
788 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
789 const LoadClusterMutation::LoadInfo &RHS);
790
791 const TargetInstrInfo *TII;
792 const TargetRegisterInfo *TRI;
793public:
794 LoadClusterMutation(const TargetInstrInfo *tii,
795 const TargetRegisterInfo *tri)
796 : TII(tii), TRI(tri) {}
797
798 virtual void apply(ScheduleDAGMI *DAG);
799protected:
800 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
801};
802} // anonymous
803
804bool LoadClusterMutation::LoadInfoLess(
805 const LoadClusterMutation::LoadInfo &LHS,
806 const LoadClusterMutation::LoadInfo &RHS) {
807 if (LHS.BaseReg != RHS.BaseReg)
808 return LHS.BaseReg < RHS.BaseReg;
809 return LHS.Offset < RHS.Offset;
810}
811
812void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
813 ScheduleDAGMI *DAG) {
814 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
815 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
816 SUnit *SU = Loads[Idx];
817 unsigned BaseReg;
818 unsigned Offset;
819 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
820 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
821 }
822 if (LoadRecords.size() < 2)
823 return;
824 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
825 unsigned ClusterLength = 1;
826 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
827 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
828 ClusterLength = 1;
829 continue;
830 }
831
832 SUnit *SUa = LoadRecords[Idx].SU;
833 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000834 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000835 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
836
837 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
838 << SUb->NodeNum << ")\n");
839 // Copy successor edges from SUa to SUb. Interleaving computation
840 // dependent on SUa can prevent load combining due to register reuse.
841 // Predecessor edges do not need to be copied from SUb to SUa since nearby
842 // loads should have effectively the same inputs.
843 for (SUnit::const_succ_iterator
844 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
845 if (SI->getSUnit() == SUb)
846 continue;
847 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
848 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
849 }
850 ++ClusterLength;
851 }
852 else
853 ClusterLength = 1;
854 }
855}
856
857/// \brief Callback from DAG postProcessing to create cluster edges for loads.
858void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
859 // Map DAG NodeNum to store chain ID.
860 DenseMap<unsigned, unsigned> StoreChainIDs;
861 // Map each store chain to a set of dependent loads.
862 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
863 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
864 SUnit *SU = &DAG->SUnits[Idx];
865 if (!SU->getInstr()->mayLoad())
866 continue;
867 unsigned ChainPredID = DAG->SUnits.size();
868 for (SUnit::const_pred_iterator
869 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
870 if (PI->isCtrl()) {
871 ChainPredID = PI->getSUnit()->NodeNum;
872 break;
873 }
874 }
875 // Check if this chain-like pred has been seen
876 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
877 unsigned NumChains = StoreChainDependents.size();
878 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
879 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
880 if (Result.second)
881 StoreChainDependents.resize(NumChains + 1);
882 StoreChainDependents[Result.first->second].push_back(SU);
883 }
884 // Iterate over the store chains.
885 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
886 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
887}
888
Andrew Trickc174eaf2012-03-08 01:41:12 +0000889//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000890// MacroFusion - DAG post-processing to encourage fusion of macro ops.
891//===----------------------------------------------------------------------===//
892
893namespace {
894/// \brief Post-process the DAG to create cluster edges between instructions
895/// that may be fused by the processor into a single operation.
896class MacroFusion : public ScheduleDAGMutation {
897 const TargetInstrInfo *TII;
898public:
899 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
900
901 virtual void apply(ScheduleDAGMI *DAG);
902};
903} // anonymous
904
905/// \brief Callback from DAG postProcessing to create cluster edges to encourage
906/// fused operations.
907void MacroFusion::apply(ScheduleDAGMI *DAG) {
908 // For now, assume targets can only fuse with the branch.
909 MachineInstr *Branch = DAG->ExitSU.getInstr();
910 if (!Branch)
911 return;
912
913 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
914 SUnit *SU = &DAG->SUnits[--Idx];
915 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
916 continue;
917
918 // Create a single weak edge from SU to ExitSU. The only effect is to cause
919 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
920 // need to copy predecessor edges from ExitSU to SU, since top-down
921 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
922 // of SU, we could create an artificial edge from the deepest root, but it
923 // hasn't been needed yet.
924 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
925 (void)Success;
926 assert(Success && "No DAG nodes should be reachable from ExitSU");
927
928 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
929 break;
930 }
931}
932
933//===----------------------------------------------------------------------===//
Andrew Tricke38afe12013-04-24 15:54:43 +0000934// CopyConstrain - DAG post-processing to encourage copy elimination.
935//===----------------------------------------------------------------------===//
936
937namespace {
938/// \brief Post-process the DAG to create weak edges from all uses of a copy to
939/// the one use that defines the copy's source vreg, most likely an induction
940/// variable increment.
941class CopyConstrain : public ScheduleDAGMutation {
942 // Transient state.
943 SlotIndex RegionBeginIdx;
Andrew Tricka264a202013-04-24 23:19:56 +0000944 // RegionEndIdx is the slot index of the last non-debug instruction in the
945 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Tricke38afe12013-04-24 15:54:43 +0000946 SlotIndex RegionEndIdx;
947public:
948 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
949
950 virtual void apply(ScheduleDAGMI *DAG);
951
952protected:
953 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
954};
955} // anonymous
956
957/// constrainLocalCopy handles two possibilities:
958/// 1) Local src:
959/// I0: = dst
960/// I1: src = ...
961/// I2: = dst
962/// I3: dst = src (copy)
963/// (create pred->succ edges I0->I1, I2->I1)
964///
965/// 2) Local copy:
966/// I0: dst = src (copy)
967/// I1: = dst
968/// I2: src = ...
969/// I3: = dst
970/// (create pred->succ edges I1->I2, I3->I2)
971///
972/// Although the MachineScheduler is currently constrained to single blocks,
973/// this algorithm should handle extended blocks. An EBB is a set of
974/// contiguously numbered blocks such that the previous block in the EBB is
975/// always the single predecessor.
976void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
977 LiveIntervals *LIS = DAG->getLIS();
978 MachineInstr *Copy = CopySU->getInstr();
979
980 // Check for pure vreg copies.
981 unsigned SrcReg = Copy->getOperand(1).getReg();
982 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
983 return;
984
985 unsigned DstReg = Copy->getOperand(0).getReg();
986 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
987 return;
988
989 // Check if either the dest or source is local. If it's live across a back
990 // edge, it's not local. Note that if both vregs are live across the back
991 // edge, we cannot successfully contrain the copy without cyclic scheduling.
992 unsigned LocalReg = DstReg;
993 unsigned GlobalReg = SrcReg;
994 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
995 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
996 LocalReg = SrcReg;
997 GlobalReg = DstReg;
998 LocalLI = &LIS->getInterval(LocalReg);
999 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1000 return;
1001 }
1002 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1003
1004 // Find the global segment after the start of the local LI.
1005 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1006 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1007 // local live range. We could create edges from other global uses to the local
1008 // start, but the coalescer should have already eliminated these cases, so
1009 // don't bother dealing with it.
1010 if (GlobalSegment == GlobalLI->end())
1011 return;
1012
1013 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1014 // returned the next global segment. But if GlobalSegment overlaps with
1015 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1016 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1017 if (GlobalSegment->contains(LocalLI->beginIndex()))
1018 ++GlobalSegment;
1019
1020 if (GlobalSegment == GlobalLI->end())
1021 return;
1022
1023 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1024 if (GlobalSegment != GlobalLI->begin()) {
1025 // Two address defs have no hole.
1026 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1027 GlobalSegment->start)) {
1028 return;
1029 }
Andrew Trick1e46fcd2013-07-30 19:59:08 +00001030 // If the prior global segment may be defined by the same two-address
1031 // instruction that also defines LocalLI, then can't make a hole here.
1032 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1033 LocalLI->beginIndex())) {
1034 return;
1035 }
Andrew Tricke38afe12013-04-24 15:54:43 +00001036 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1037 // it would be a disconnected component in the live range.
1038 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1039 "Disconnected LRG within the scheduling region.");
1040 }
1041 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1042 if (!GlobalDef)
1043 return;
1044
1045 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1046 if (!GlobalSU)
1047 return;
1048
1049 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1050 // constraining the uses of the last local def to precede GlobalDef.
1051 SmallVector<SUnit*,8> LocalUses;
1052 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1053 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1054 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1055 for (SUnit::const_succ_iterator
1056 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1057 I != E; ++I) {
1058 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1059 continue;
1060 if (I->getSUnit() == GlobalSU)
1061 continue;
1062 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1063 return;
1064 LocalUses.push_back(I->getSUnit());
1065 }
1066 // Open the top of the GlobalLI hole by constraining any earlier global uses
1067 // to precede the start of LocalLI.
1068 SmallVector<SUnit*,8> GlobalUses;
1069 MachineInstr *FirstLocalDef =
1070 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1071 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1072 for (SUnit::const_pred_iterator
1073 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1074 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1075 continue;
1076 if (I->getSUnit() == FirstLocalSU)
1077 continue;
1078 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1079 return;
1080 GlobalUses.push_back(I->getSUnit());
1081 }
1082 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1083 // Add the weak edges.
1084 for (SmallVectorImpl<SUnit*>::const_iterator
1085 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1086 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1087 << GlobalSU->NodeNum << ")\n");
1088 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1089 }
1090 for (SmallVectorImpl<SUnit*>::const_iterator
1091 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1092 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1093 << FirstLocalSU->NodeNum << ")\n");
1094 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1095 }
1096}
1097
1098/// \brief Callback from DAG postProcessing to create weak edges to encourage
1099/// copy elimination.
1100void CopyConstrain::apply(ScheduleDAGMI *DAG) {
Andrew Tricka264a202013-04-24 23:19:56 +00001101 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1102 if (FirstPos == DAG->end())
1103 return;
1104 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
Andrew Tricke38afe12013-04-24 15:54:43 +00001105 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1106 &*priorNonDebug(DAG->end(), DAG->begin()));
1107
1108 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1109 SUnit *SU = &DAG->SUnits[Idx];
1110 if (!SU->getInstr()->isCopy())
1111 continue;
1112
1113 constrainLocalCopy(SU, DAG);
1114 }
1115}
1116
1117//===----------------------------------------------------------------------===//
Andrew Trickfa989e72013-06-15 05:39:19 +00001118// ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +00001119//===----------------------------------------------------------------------===//
1120
1121namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001122/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
1123/// the schedule.
1124class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +00001125public:
1126 /// Represent the type of SchedCandidate found within a single queue.
1127 /// pickNodeBidirectional depends on these listed by decreasing priority.
1128 enum CandReason {
Andrew Tricka626f502013-06-17 21:45:13 +00001129 NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001130 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
Andrew Tricka626f502013-06-17 21:45:13 +00001131 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +00001132
1133#ifndef NDEBUG
1134 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
1135#endif
1136
1137 /// Policy for scheduling the next instruction in the candidate's zone.
1138 struct CandPolicy {
1139 bool ReduceLatency;
1140 unsigned ReduceResIdx;
1141 unsigned DemandResIdx;
1142
1143 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
1144 };
1145
1146 /// Status of an instruction's critical resource consumption.
1147 struct SchedResourceDelta {
1148 // Count critical resources in the scheduled region required by SU.
1149 unsigned CritResources;
1150
1151 // Count critical resources from another region consumed by SU.
1152 unsigned DemandedResources;
1153
1154 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
1155
1156 bool operator==(const SchedResourceDelta &RHS) const {
1157 return CritResources == RHS.CritResources
1158 && DemandedResources == RHS.DemandedResources;
1159 }
1160 bool operator!=(const SchedResourceDelta &RHS) const {
1161 return !operator==(RHS);
1162 }
1163 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001164
1165 /// Store the state used by ConvergingScheduler heuristics, required for the
1166 /// lifetime of one invocation of pickNode().
1167 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +00001168 CandPolicy Policy;
1169
Andrew Trick7196a8f2012-05-10 21:06:16 +00001170 // The best SUnit candidate.
1171 SUnit *SU;
1172
Andrew Trick3b87f622012-11-07 07:05:09 +00001173 // The reason for this candidate.
1174 CandReason Reason;
1175
Andrew Tricke52d5022013-06-17 21:45:05 +00001176 // Set of reasons that apply to multiple candidates.
1177 uint32_t RepeatReasonSet;
1178
Andrew Trick7196a8f2012-05-10 21:06:16 +00001179 // Register pressure values for the best candidate.
1180 RegPressureDelta RPDelta;
1181
Andrew Trick3b87f622012-11-07 07:05:09 +00001182 // Critical resource consumption of the best candidate.
1183 SchedResourceDelta ResDelta;
1184
1185 SchedCandidate(const CandPolicy &policy)
Andrew Tricke52d5022013-06-17 21:45:05 +00001186 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
Andrew Trick3b87f622012-11-07 07:05:09 +00001187
1188 bool isValid() const { return SU; }
1189
1190 // Copy the status of another candidate without changing policy.
1191 void setBest(SchedCandidate &Best) {
1192 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
1193 SU = Best.SU;
1194 Reason = Best.Reason;
1195 RPDelta = Best.RPDelta;
1196 ResDelta = Best.ResDelta;
1197 }
1198
Andrew Tricke52d5022013-06-17 21:45:05 +00001199 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
1200 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
1201
Andrew Trick3b87f622012-11-07 07:05:09 +00001202 void initResourceDelta(const ScheduleDAGMI *DAG,
1203 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001204 };
Andrew Trick3b87f622012-11-07 07:05:09 +00001205
1206 /// Summarize the unscheduled region.
1207 struct SchedRemainder {
1208 // Critical path through the DAG in expected latency.
1209 unsigned CriticalPath;
1210
Andrew Trickfa989e72013-06-15 05:39:19 +00001211 // Scaled count of micro-ops left to schedule.
1212 unsigned RemIssueCount;
1213
Andrew Trick3b87f622012-11-07 07:05:09 +00001214 // Unscheduled resources
1215 SmallVector<unsigned, 16> RemainingCounts;
Andrew Trick3b87f622012-11-07 07:05:09 +00001216
Andrew Trick3b87f622012-11-07 07:05:09 +00001217 void reset() {
1218 CriticalPath = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001219 RemIssueCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001220 RemainingCounts.clear();
Andrew Trick3b87f622012-11-07 07:05:09 +00001221 }
1222
1223 SchedRemainder() { reset(); }
1224
1225 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1226 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001227
Andrew Trickf3234242012-05-24 22:11:12 +00001228 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001229 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001230 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001231 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001232 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001233 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001234 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001235
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001236 ReadyQueue Available;
1237 ReadyQueue Pending;
1238 bool CheckPending;
1239
Andrew Trick3b87f622012-11-07 07:05:09 +00001240 // For heuristics, keep a list of the nodes that immediately depend on the
1241 // most recently scheduled node.
1242 SmallPtrSet<const SUnit*, 8> NextSUs;
1243
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001244 ScheduleHazardRecognizer *HazardRec;
1245
Andrew Trickfa989e72013-06-15 05:39:19 +00001246 /// Number of cycles it takes to issue the instructions scheduled in this
1247 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
1248 /// See getStalls().
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001249 unsigned CurrCycle;
Andrew Trickfa989e72013-06-15 05:39:19 +00001250
1251 /// Micro-ops issued in the current cycle
Andrew Trickbacb2492013-06-15 04:49:49 +00001252 unsigned CurrMOps;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001253
1254 /// MinReadyCycle - Cycle of the soonest available instruction.
1255 unsigned MinReadyCycle;
1256
Andrew Trick3b87f622012-11-07 07:05:09 +00001257 // The expected latency of the critical path in this scheduled zone.
1258 unsigned ExpectedLatency;
1259
Andrew Trick2c465a32013-06-15 04:49:44 +00001260 // The latency of dependence chains leading into this zone.
Andrew Trickcc47c122013-08-07 17:20:32 +00001261 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
Andrew Trick2c465a32013-06-15 04:49:44 +00001262 // For each cycle scheduled: DLat -= 1.
1263 unsigned DependentLatency;
1264
Andrew Trickfa989e72013-06-15 05:39:19 +00001265 /// Count the scheduled (issued) micro-ops that can be retired by
1266 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
1267 unsigned RetiredMOps;
1268
1269 // Count scheduled resources that have been executed. Resources are
1270 // considered executed if they become ready in the time that it takes to
1271 // saturate any resource including the one in question. Counts are scaled
Andrew Trick4e389802013-07-19 00:20:07 +00001272 // for direct comparison with other resources. Counts can be compared with
Andrew Trickfa989e72013-06-15 05:39:19 +00001273 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
1274 SmallVector<unsigned, 16> ExecutedResCounts;
1275
1276 /// Cache the max count for a single resource.
1277 unsigned MaxExecutedResCount;
Andrew Trick3b87f622012-11-07 07:05:09 +00001278
1279 // Cache the critical resources ID in this scheduled zone.
Andrew Trickfa989e72013-06-15 05:39:19 +00001280 unsigned ZoneCritResIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001281
1282 // Is the scheduled region resource limited vs. latency limited.
1283 bool IsResourceLimited;
1284
Andrew Trick3b87f622012-11-07 07:05:09 +00001285#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001286 // Remember the greatest operand latency as an upper bound on the number of
1287 // times we should retry the pending queue because of a hazard.
1288 unsigned MaxObservedLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001289#endif
1290
1291 void reset() {
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001292 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1293 delete HazardRec;
1294
Andrew Trick3b87f622012-11-07 07:05:09 +00001295 Available.clear();
1296 Pending.clear();
1297 CheckPending = false;
1298 NextSUs.clear();
1299 HazardRec = 0;
1300 CurrCycle = 0;
Andrew Trickbacb2492013-06-15 04:49:49 +00001301 CurrMOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001302 MinReadyCycle = UINT_MAX;
1303 ExpectedLatency = 0;
Andrew Trick2c465a32013-06-15 04:49:44 +00001304 DependentLatency = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001305 RetiredMOps = 0;
1306 MaxExecutedResCount = 0;
1307 ZoneCritResIdx = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001308 IsResourceLimited = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001309#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001310 MaxObservedLatency = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001311#endif
1312 // Reserve a zero-count for invalid CritResIdx.
Andrew Trickfa989e72013-06-15 05:39:19 +00001313 ExecutedResCounts.resize(1);
1314 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
Andrew Trick3b87f622012-11-07 07:05:09 +00001315 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001316
Andrew Trickf3234242012-05-24 22:11:12 +00001317 /// Pending queues extend the ready queues with the same ID and the
1318 /// PendingFlag set.
1319 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001320 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001321 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1322 HazardRec(0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001323 reset();
1324 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001325
1326 ~SchedBoundary() { delete HazardRec; }
1327
Andrew Trick3b87f622012-11-07 07:05:09 +00001328 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1329 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001330
Andrew Trickf3234242012-05-24 22:11:12 +00001331 bool isTop() const {
1332 return Available.getID() == ConvergingScheduler::TopQID;
1333 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001334
Andrew Trickaaaae512013-06-15 05:46:47 +00001335#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00001336 const char *getResourceName(unsigned PIdx) {
1337 if (!PIdx)
1338 return "MOps";
1339 return SchedModel->getProcResource(PIdx)->Name;
Andrew Trick3b87f622012-11-07 07:05:09 +00001340 }
Andrew Trickaaaae512013-06-15 05:46:47 +00001341#endif
Andrew Trick3b87f622012-11-07 07:05:09 +00001342
Andrew Trickfa989e72013-06-15 05:39:19 +00001343 /// Get the number of latency cycles "covered" by the scheduled
1344 /// instructions. This is the larger of the critical path within the zone
1345 /// and the number of cycles required to issue the instructions.
1346 unsigned getScheduledLatency() const {
1347 return std::max(ExpectedLatency, CurrCycle);
1348 }
1349
1350 unsigned getUnscheduledLatency(SUnit *SU) const {
1351 return isTop() ? SU->getHeight() : SU->getDepth();
1352 }
1353
1354 unsigned getResourceCount(unsigned ResIdx) const {
1355 return ExecutedResCounts[ResIdx];
1356 }
1357
1358 /// Get the scaled count of scheduled micro-ops and resources, including
1359 /// executed resources.
Andrew Trick3b87f622012-11-07 07:05:09 +00001360 unsigned getCriticalCount() const {
Andrew Trickfa989e72013-06-15 05:39:19 +00001361 if (!ZoneCritResIdx)
1362 return RetiredMOps * SchedModel->getMicroOpFactor();
1363 return getResourceCount(ZoneCritResIdx);
1364 }
1365
1366 /// Get a scaled count for the minimum execution time of the scheduled
1367 /// micro-ops that are ready to execute by getExecutedCount. Notice the
1368 /// feedback loop.
1369 unsigned getExecutedCount() const {
1370 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
1371 MaxExecutedResCount);
Andrew Trick3b87f622012-11-07 07:05:09 +00001372 }
1373
Andrew Trick5559ffa2012-06-29 03:23:24 +00001374 bool checkHazard(SUnit *SU);
1375
Andrew Trickfa989e72013-06-15 05:39:19 +00001376 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
1377
1378 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
1379
1380 void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
Andrew Trick3b87f622012-11-07 07:05:09 +00001381
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001382 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1383
Andrew Trickfa989e72013-06-15 05:39:19 +00001384 void bumpCycle(unsigned NextCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001385
Andrew Trickfa989e72013-06-15 05:39:19 +00001386 void incExecutedResources(unsigned PIdx, unsigned Count);
1387
1388 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
Andrew Trick3b87f622012-11-07 07:05:09 +00001389
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001390 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001391
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001392 void releasePending();
1393
1394 void removeReady(SUnit *SU);
1395
1396 SUnit *pickOnlyChoice();
Andrew Trickfa989e72013-06-15 05:39:19 +00001397
Andrew Trickaaaae512013-06-15 05:46:47 +00001398#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00001399 void dumpScheduledState();
Andrew Trickaaaae512013-06-15 05:46:47 +00001400#endif
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001401 };
1402
Andrew Trick3b87f622012-11-07 07:05:09 +00001403private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001404 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001405 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001406 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001407
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001408 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001409 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001410 SchedBoundary Top;
1411 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001412
1413public:
Andrew Trickf3234242012-05-24 22:11:12 +00001414 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001415 enum {
1416 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001417 BotQID = 2,
1418 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001419 };
1420
Andrew Trickf3234242012-05-24 22:11:12 +00001421 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001422 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001423
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001424 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001425
Andrew Trick7196a8f2012-05-10 21:06:16 +00001426 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001427
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001428 virtual void schedNode(SUnit *SU, bool IsTopNode);
1429
1430 virtual void releaseTopNode(SUnit *SU);
1431
1432 virtual void releaseBottomNode(SUnit *SU);
1433
Andrew Trick3b87f622012-11-07 07:05:09 +00001434 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001435
Andrew Trick3b87f622012-11-07 07:05:09 +00001436protected:
Andrew Trick3b87f622012-11-07 07:05:09 +00001437 void tryCandidate(SchedCandidate &Cand,
1438 SchedCandidate &TryCand,
1439 SchedBoundary &Zone,
1440 const RegPressureTracker &RPTracker,
1441 RegPressureTracker &TempTracker);
1442
1443 SUnit *pickNodeBidirectional(bool &IsTopNode);
1444
1445 void pickNodeFromQueue(SchedBoundary &Zone,
1446 const RegPressureTracker &RPTracker,
1447 SchedCandidate &Candidate);
1448
Andrew Trick4392f0f2013-04-13 06:07:40 +00001449 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1450
Andrew Trick28ebc892012-05-10 21:06:19 +00001451#ifndef NDEBUG
Andrew Trick11189f72013-04-05 00:31:29 +00001452 void traceCandidate(const SchedCandidate &Cand);
Andrew Trick28ebc892012-05-10 21:06:19 +00001453#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001454};
1455} // namespace
1456
Andrew Trick3b87f622012-11-07 07:05:09 +00001457void ConvergingScheduler::SchedRemainder::
1458init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1459 reset();
1460 if (!SchedModel->hasInstrSchedModel())
1461 return;
1462 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1463 for (std::vector<SUnit>::iterator
1464 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1465 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickfa989e72013-06-15 05:39:19 +00001466 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1467 * SchedModel->getMicroOpFactor();
Andrew Trick3b87f622012-11-07 07:05:09 +00001468 for (TargetSchedModel::ProcResIter
1469 PI = SchedModel->getWriteProcResBegin(SC),
1470 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1471 unsigned PIdx = PI->ProcResourceIdx;
1472 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1473 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1474 }
1475 }
1476}
1477
1478void ConvergingScheduler::SchedBoundary::
1479init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1480 reset();
1481 DAG = dag;
1482 SchedModel = smodel;
1483 Rem = rem;
1484 if (SchedModel->hasInstrSchedModel())
Andrew Trickfa989e72013-06-15 05:39:19 +00001485 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick3b87f622012-11-07 07:05:09 +00001486}
1487
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001488void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1489 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001490 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001491 TRI = DAG->TRI;
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001492
Andrew Trick3b87f622012-11-07 07:05:09 +00001493 Rem.init(DAG, SchedModel);
1494 Top.init(DAG, SchedModel, &Rem);
1495 Bot.init(DAG, SchedModel, &Rem);
1496
1497 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001498
Andrew Trick412cd2f2012-10-10 05:43:09 +00001499 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1500 // are disabled, then these HazardRecs will be disabled.
1501 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001502 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001503 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1504 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1505
1506 assert((!ForceTopDown || !ForceBottomUp) &&
1507 "-misched-topdown incompatible with -misched-bottomup");
1508}
1509
1510void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001511 if (SU->isScheduled)
1512 return;
1513
Andrew Trickd4539602012-12-18 20:52:52 +00001514 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001515 I != E; ++I) {
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001516 if (I->isWeak())
1517 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001518 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001519 unsigned Latency = I->getLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001520#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001521 Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001522#endif
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001523 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1524 SU->TopReadyCycle = PredReadyCycle + Latency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001525 }
1526 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001527}
1528
1529void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001530 if (SU->isScheduled)
1531 return;
1532
1533 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1534
1535 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1536 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001537 if (I->isWeak())
1538 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001539 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001540 unsigned Latency = I->getLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001541#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001542 Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001543#endif
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001544 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1545 SU->BotReadyCycle = SuccReadyCycle + Latency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001546 }
1547 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001548}
1549
Andrew Trick3b87f622012-11-07 07:05:09 +00001550void ConvergingScheduler::registerRoots() {
1551 Rem.CriticalPath = DAG->ExitSU.getDepth();
1552 // Some roots may not feed into ExitSU. Check all of them in case.
1553 for (std::vector<SUnit*>::const_iterator
1554 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1555 if ((*I)->getDepth() > Rem.CriticalPath)
1556 Rem.CriticalPath = (*I)->getDepth();
1557 }
1558 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1559}
1560
Andrew Trick5559ffa2012-06-29 03:23:24 +00001561/// Does this SU have a hazard within the current instruction group.
1562///
1563/// The scheduler supports two modes of hazard recognition. The first is the
1564/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1565/// supports highly complicated in-order reservation tables
1566/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1567///
1568/// The second is a streamlined mechanism that checks for hazards based on
1569/// simple counters that the scheduler itself maintains. It explicitly checks
1570/// for instruction dispatch limitations, including the number of micro-ops that
1571/// can dispatch per cycle.
1572///
1573/// TODO: Also check whether the SU must start a new group.
1574bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1575 if (HazardRec->isEnabled())
1576 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1577
Andrew Trick412cd2f2012-10-10 05:43:09 +00001578 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trickbacb2492013-06-15 04:49:49 +00001579 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001580 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1581 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001582 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001583 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001584 return false;
1585}
1586
Andrew Trickfa989e72013-06-15 05:39:19 +00001587// Find the unscheduled node in ReadySUs with the highest latency.
1588unsigned ConvergingScheduler::SchedBoundary::
1589findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1590 SUnit *LateSU = 0;
1591 unsigned RemLatency = 0;
1592 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001593 I != E; ++I) {
1594 unsigned L = getUnscheduledLatency(*I);
Andrew Trick2c465a32013-06-15 04:49:44 +00001595 if (L > RemLatency) {
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001596 RemLatency = L;
Andrew Trickfa989e72013-06-15 05:39:19 +00001597 LateSU = *I;
Andrew Trick2c465a32013-06-15 04:49:44 +00001598 }
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001599 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001600 if (LateSU) {
1601 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1602 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001603 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001604 return RemLatency;
1605}
Andrew Trick2c465a32013-06-15 04:49:44 +00001606
Andrew Trickfa989e72013-06-15 05:39:19 +00001607// Count resources in this zone and the remaining unscheduled
1608// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1609// resource index, or zero if the zone is issue limited.
1610unsigned ConvergingScheduler::SchedBoundary::
1611getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov86dc6f92013-07-19 08:55:18 +00001612 OtherCritIdx = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001613 if (!SchedModel->hasInstrSchedModel())
1614 return 0;
1615
1616 unsigned OtherCritCount = Rem->RemIssueCount
1617 + (RetiredMOps * SchedModel->getMicroOpFactor());
1618 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1619 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickfa989e72013-06-15 05:39:19 +00001620 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1621 PIdx != PEnd; ++PIdx) {
1622 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1623 if (OtherCount > OtherCritCount) {
1624 OtherCritCount = OtherCount;
1625 OtherCritIdx = PIdx;
1626 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001627 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001628 if (OtherCritIdx) {
1629 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1630 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1631 << " " << getResourceName(OtherCritIdx) << "\n");
1632 }
1633 return OtherCritCount;
1634}
1635
1636/// Set the CandPolicy for this zone given the current resources and latencies
1637/// inside and outside the zone.
1638void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
1639 SchedBoundary &OtherZone) {
1640 // Now that potential stalls have been considered, apply preemptive heuristics
1641 // based on the the total latency and resources inside and outside this
1642 // zone.
1643
1644 // Compute remaining latency. We need this both to determine whether the
1645 // overall schedule has become latency-limited and whether the instructions
1646 // outside this zone are resource or latency limited.
1647 //
1648 // The "dependent" latency is updated incrementally during scheduling as the
1649 // max height/depth of scheduled nodes minus the cycles since it was
1650 // scheduled:
1651 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
1652 //
1653 // The "independent" latency is the max ready queue depth:
1654 // ILat = max N.depth for N in Available|Pending
1655 //
1656 // RemainingLatency is the greater of independent and dependent latency.
1657 unsigned RemLatency = DependentLatency;
1658 RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
1659 RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
1660
1661 // Compute the critical resource outside the zone.
1662 unsigned OtherCritIdx;
1663 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
1664
1665 bool OtherResLimited = false;
1666 if (SchedModel->hasInstrSchedModel()) {
1667 unsigned LFactor = SchedModel->getLatencyFactor();
1668 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
1669 }
1670 if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
1671 Policy.ReduceLatency |= true;
1672 DEBUG(dbgs() << " " << Available.getName() << " RemainingLatency "
1673 << RemLatency << " + " << CurrCycle << "c > CritPath "
1674 << Rem->CriticalPath << "\n");
1675 }
1676 // If the same resource is limiting inside and outside the zone, do nothing.
Andrew Trick4e389802013-07-19 00:20:07 +00001677 if (ZoneCritResIdx == OtherCritIdx)
Andrew Trickfa989e72013-06-15 05:39:19 +00001678 return;
1679
1680 DEBUG(
1681 if (IsResourceLimited) {
1682 dbgs() << " " << Available.getName() << " ResourceLimited: "
1683 << getResourceName(ZoneCritResIdx) << "\n";
1684 }
1685 if (OtherResLimited)
Andrew Trick3bf23302013-06-21 18:33:01 +00001686 dbgs() << " RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
Andrew Trickfa989e72013-06-15 05:39:19 +00001687 if (!IsResourceLimited && !OtherResLimited)
1688 dbgs() << " Latency limited both directions.\n");
1689
1690 if (IsResourceLimited && !Policy.ReduceResIdx)
1691 Policy.ReduceResIdx = ZoneCritResIdx;
1692
1693 if (OtherResLimited)
1694 Policy.DemandResIdx = OtherCritIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001695}
1696
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001697void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1698 unsigned ReadyCycle) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001699 if (ReadyCycle < MinReadyCycle)
1700 MinReadyCycle = ReadyCycle;
1701
1702 // Check for interlocks first. For the purpose of other heuristics, an
1703 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickfa989e72013-06-15 05:39:19 +00001704 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1705 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001706 Pending.push(SU);
1707 else
1708 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001709
1710 // Record this node as an immediate dependent of the scheduled node.
1711 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001712}
1713
1714/// Move the boundary of scheduled code by one cycle.
Andrew Trickfa989e72013-06-15 05:39:19 +00001715void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
1716 if (SchedModel->getMicroOpBufferSize() == 0) {
1717 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1718 if (MinReadyCycle > NextCycle)
1719 NextCycle = MinReadyCycle;
Andrew Trick3b87f622012-11-07 07:05:09 +00001720 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001721 // Update the current micro-ops, which will issue in the next cycle.
1722 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1723 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1724
1725 // Decrement DependentLatency based on the next cycle.
Andrew Trick2c465a32013-06-15 04:49:44 +00001726 if ((NextCycle - CurrCycle) > DependentLatency)
1727 DependentLatency = 0;
1728 else
1729 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001730
1731 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001732 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001733 CurrCycle = NextCycle;
1734 }
1735 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001736 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001737 for (; CurrCycle != NextCycle; ++CurrCycle) {
1738 if (isTop())
1739 HazardRec->AdvanceCycle();
1740 else
1741 HazardRec->RecedeCycle();
1742 }
1743 }
1744 CheckPending = true;
Andrew Trickfa989e72013-06-15 05:39:19 +00001745 unsigned LFactor = SchedModel->getLatencyFactor();
1746 IsResourceLimited =
1747 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1748 > (int)LFactor;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001749
Andrew Trickfa989e72013-06-15 05:39:19 +00001750 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1751}
1752
1753void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
1754 unsigned Count) {
1755 ExecutedResCounts[PIdx] += Count;
1756 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1757 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001758}
1759
Andrew Trick3b87f622012-11-07 07:05:09 +00001760/// Add the given processor resource to this scheduled zone.
Andrew Trickfa989e72013-06-15 05:39:19 +00001761///
1762/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1763/// during which this resource is consumed.
1764///
1765/// \return the next cycle at which the instruction may execute without
1766/// oversubscribing resources.
1767unsigned ConvergingScheduler::SchedBoundary::
1768countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001769 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3b87f622012-11-07 07:05:09 +00001770 unsigned Count = Factor * Cycles;
Andrew Trickfa989e72013-06-15 05:39:19 +00001771 DEBUG(dbgs() << " " << getResourceName(PIdx)
1772 << " +" << Cycles << "x" << Factor << "u\n");
1773
1774 // Update Executed resources counts.
1775 incExecutedResources(PIdx, Count);
Andrew Trick3b87f622012-11-07 07:05:09 +00001776 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1777 Rem->RemainingCounts[PIdx] -= Count;
1778
Andrew Trick4e389802013-07-19 00:20:07 +00001779 // Check if this resource exceeds the current critical resource. If so, it
1780 // becomes the critical resource.
1781 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickfa989e72013-06-15 05:39:19 +00001782 ZoneCritResIdx = PIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001783 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfa989e72013-06-15 05:39:19 +00001784 << getResourceName(PIdx) << ": "
1785 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3b87f622012-11-07 07:05:09 +00001786 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001787 // TODO: We don't yet model reserved resources. It's not hard though.
1788 return CurrCycle;
Andrew Trick3b87f622012-11-07 07:05:09 +00001789}
1790
Andrew Trickb7e02892012-06-05 21:11:27 +00001791/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001792void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001793 // Update the reservation table.
1794 if (HazardRec->isEnabled()) {
1795 if (!isTop() && SU->isCall) {
1796 // Calls are scheduled with their preceding instructions. For bottom-up
1797 // scheduling, clear the pipeline state before emitting.
1798 HazardRec->Reset();
1799 }
1800 HazardRec->EmitInstruction(SU);
1801 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001802 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1803 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1804 CurrMOps += IncMOps;
Andrew Trick3b87f622012-11-07 07:05:09 +00001805 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1806 // issue width. However, we commonly reach the maximum. In this case
1807 // opportunistically bump the cycle to avoid uselessly checking everything in
1808 // the readyQ. Furthermore, a single instruction may produce more than one
1809 // cycle's worth of micro-ops.
Andrew Trickfa989e72013-06-15 05:39:19 +00001810 //
1811 // TODO: Also check if this SU must end a dispatch group.
1812 unsigned NextCycle = CurrCycle;
Andrew Trickbacb2492013-06-15 04:49:49 +00001813 if (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trickfa989e72013-06-15 05:39:19 +00001814 ++NextCycle;
1815 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1816 << " at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001817 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001818 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1819 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1820
1821 switch (SchedModel->getMicroOpBufferSize()) {
1822 case 0:
1823 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1824 break;
1825 case 1:
1826 if (ReadyCycle > NextCycle) {
1827 NextCycle = ReadyCycle;
1828 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1829 }
1830 break;
1831 default:
1832 // We don't currently model the OOO reorder buffer, so consider all
1833 // scheduled MOps to be "retired".
1834 break;
1835 }
1836 RetiredMOps += IncMOps;
1837
1838 // Update resource counts and critical resource.
1839 if (SchedModel->hasInstrSchedModel()) {
1840 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1841 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1842 Rem->RemIssueCount -= DecRemIssue;
1843 if (ZoneCritResIdx) {
1844 // Scale scheduled micro-ops for comparing with the critical resource.
1845 unsigned ScaledMOps =
1846 RetiredMOps * SchedModel->getMicroOpFactor();
1847
1848 // If scaled micro-ops are now more than the previous critical resource by
1849 // a full cycle, then micro-ops issue becomes critical.
1850 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1851 >= (int)SchedModel->getLatencyFactor()) {
1852 ZoneCritResIdx = 0;
1853 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1854 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1855 }
1856 }
1857 for (TargetSchedModel::ProcResIter
1858 PI = SchedModel->getWriteProcResBegin(SC),
1859 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1860 unsigned RCycle =
1861 countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
1862 if (RCycle > NextCycle)
1863 NextCycle = RCycle;
1864 }
1865 }
1866 // Update ExpectedLatency and DependentLatency.
1867 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1868 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1869 if (SU->getDepth() > TopLatency) {
1870 TopLatency = SU->getDepth();
1871 DEBUG(dbgs() << " " << Available.getName()
1872 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1873 }
1874 if (SU->getHeight() > BotLatency) {
1875 BotLatency = SU->getHeight();
1876 DEBUG(dbgs() << " " << Available.getName()
1877 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1878 }
1879 // If we stall for any reason, bump the cycle.
1880 if (NextCycle > CurrCycle) {
1881 bumpCycle(NextCycle);
1882 }
1883 else {
1884 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1885 // resource limited. If a stall occured, bumpCycle does this.
1886 unsigned LFactor = SchedModel->getLatencyFactor();
1887 IsResourceLimited =
1888 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1889 > (int)LFactor;
1890 }
1891 DEBUG(dumpScheduledState());
Andrew Trickb7e02892012-06-05 21:11:27 +00001892}
1893
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001894/// Release pending ready nodes in to the available queue. This makes them
1895/// visible to heuristics.
1896void ConvergingScheduler::SchedBoundary::releasePending() {
1897 // If the available queue is empty, it is safe to reset MinReadyCycle.
1898 if (Available.empty())
1899 MinReadyCycle = UINT_MAX;
1900
1901 // Check to see if any of the pending instructions are ready to issue. If
1902 // so, add them to the available queue.
Andrew Trickfa989e72013-06-15 05:39:19 +00001903 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001904 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1905 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001906 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001907
1908 if (ReadyCycle < MinReadyCycle)
1909 MinReadyCycle = ReadyCycle;
1910
Andrew Trickfa989e72013-06-15 05:39:19 +00001911 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001912 continue;
1913
Andrew Trick5559ffa2012-06-29 03:23:24 +00001914 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001915 continue;
1916
1917 Available.push(SU);
1918 Pending.remove(Pending.begin()+i);
1919 --i; --e;
1920 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001921 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001922 CheckPending = false;
1923}
1924
1925/// Remove SU from the ready set for this boundary.
1926void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1927 if (Available.isInQueue(SU))
1928 Available.remove(Available.find(SU));
1929 else {
1930 assert(Pending.isInQueue(SU) && "bad ready count");
1931 Pending.remove(Pending.find(SU));
1932 }
1933}
1934
1935/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001936/// defer any nodes that now hit a hazard, and advance the cycle until at least
1937/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001938SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1939 if (CheckPending)
1940 releasePending();
1941
Andrew Trickbacb2492013-06-15 04:49:49 +00001942 if (CurrMOps > 0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001943 // Defer any ready instrs that now have a hazard.
1944 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1945 if (checkHazard(*I)) {
1946 Pending.push(*I);
1947 I = Available.remove(I);
1948 continue;
1949 }
1950 ++I;
1951 }
1952 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001953 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001954 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
Andrew Trickb7e02892012-06-05 21:11:27 +00001955 "permanent hazard"); (void)i;
Andrew Trickfa989e72013-06-15 05:39:19 +00001956 bumpCycle(CurrCycle + 1);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001957 releasePending();
1958 }
1959 if (Available.size() == 1)
1960 return *Available.begin();
1961 return NULL;
1962}
1963
Andrew Trickaaaae512013-06-15 05:46:47 +00001964#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00001965// This is useful information to dump after bumpNode.
1966// Note that the Queue contents are more useful before pickNodeFromQueue.
1967void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
1968 unsigned ResFactor;
1969 unsigned ResCount;
1970 if (ZoneCritResIdx) {
1971 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
1972 ResCount = getResourceCount(ZoneCritResIdx);
Andrew Trick3b87f622012-11-07 07:05:09 +00001973 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001974 else {
1975 ResFactor = SchedModel->getMicroOpFactor();
1976 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3b87f622012-11-07 07:05:09 +00001977 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001978 unsigned LFactor = SchedModel->getLatencyFactor();
1979 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
1980 << " Retired: " << RetiredMOps;
1981 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
1982 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
1983 << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
1984 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
1985 << (IsResourceLimited ? " - Resource" : " - Latency")
1986 << " limited.\n";
Andrew Trick3b87f622012-11-07 07:05:09 +00001987}
Andrew Trickaaaae512013-06-15 05:46:47 +00001988#endif
Andrew Trick3b87f622012-11-07 07:05:09 +00001989
1990void ConvergingScheduler::SchedCandidate::
1991initResourceDelta(const ScheduleDAGMI *DAG,
1992 const TargetSchedModel *SchedModel) {
1993 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1994 return;
1995
1996 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1997 for (TargetSchedModel::ProcResIter
1998 PI = SchedModel->getWriteProcResBegin(SC),
1999 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2000 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2001 ResDelta.CritResources += PI->Cycles;
2002 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2003 ResDelta.DemandedResources += PI->Cycles;
2004 }
2005}
2006
Andrew Tricke52d5022013-06-17 21:45:05 +00002007
Andrew Trick3b87f622012-11-07 07:05:09 +00002008/// Return true if this heuristic determines order.
Andrew Trick614dacc2013-04-05 00:31:34 +00002009static bool tryLess(int TryVal, int CandVal,
Andrew Trick3b87f622012-11-07 07:05:09 +00002010 ConvergingScheduler::SchedCandidate &TryCand,
2011 ConvergingScheduler::SchedCandidate &Cand,
2012 ConvergingScheduler::CandReason Reason) {
2013 if (TryVal < CandVal) {
2014 TryCand.Reason = Reason;
2015 return true;
2016 }
2017 if (TryVal > CandVal) {
2018 if (Cand.Reason > Reason)
2019 Cand.Reason = Reason;
2020 return true;
2021 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002022 Cand.setRepeat(Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002023 return false;
2024}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002025
Andrew Trick614dacc2013-04-05 00:31:34 +00002026static bool tryGreater(int TryVal, int CandVal,
Andrew Trick3b87f622012-11-07 07:05:09 +00002027 ConvergingScheduler::SchedCandidate &TryCand,
2028 ConvergingScheduler::SchedCandidate &Cand,
2029 ConvergingScheduler::CandReason Reason) {
2030 if (TryVal > CandVal) {
2031 TryCand.Reason = Reason;
2032 return true;
2033 }
2034 if (TryVal < CandVal) {
2035 if (Cand.Reason > Reason)
2036 Cand.Reason = Reason;
2037 return true;
2038 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002039 Cand.setRepeat(Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002040 return false;
2041}
2042
Andrew Trick13372882013-07-25 07:26:35 +00002043static bool tryPressure(const PressureElement &TryP,
2044 const PressureElement &CandP,
2045 ConvergingScheduler::SchedCandidate &TryCand,
2046 ConvergingScheduler::SchedCandidate &Cand,
2047 ConvergingScheduler::CandReason Reason) {
2048 // If both candidates affect the same set, go with the smallest increase.
2049 if (TryP.PSetID == CandP.PSetID) {
2050 return tryLess(TryP.UnitIncrease, CandP.UnitIncrease, TryCand, Cand,
2051 Reason);
2052 }
2053 // If one candidate decreases and the other increases, go with it.
2054 if (tryLess(TryP.UnitIncrease < 0, CandP.UnitIncrease < 0, TryCand, Cand,
2055 Reason)) {
2056 return true;
2057 }
2058 // If TryP has lower Rank, it has a higher priority.
2059 int TryRank = TryP.PSetRank();
2060 int CandRank = CandP.PSetRank();
2061 // If the candidates are decreasing pressure, reverse priority.
2062 if (TryP.UnitIncrease < 0)
2063 std::swap(TryRank, CandRank);
2064 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2065}
2066
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002067static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2068 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2069}
2070
Andrew Trick4392f0f2013-04-13 06:07:40 +00002071/// Minimize physical register live ranges. Regalloc wants them adjacent to
2072/// their physreg def/use.
2073///
2074/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2075/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2076/// with the operation that produces or consumes the physreg. We'll do this when
2077/// regalloc has support for parallel copies.
2078static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2079 const MachineInstr *MI = SU->getInstr();
2080 if (!MI->isCopy())
2081 return 0;
2082
2083 unsigned ScheduledOper = isTop ? 1 : 0;
2084 unsigned UnscheduledOper = isTop ? 0 : 1;
2085 // If we have already scheduled the physreg produce/consumer, immediately
2086 // schedule the copy.
2087 if (TargetRegisterInfo::isPhysicalRegister(
2088 MI->getOperand(ScheduledOper).getReg()))
2089 return 1;
2090 // If the physreg is at the boundary, defer it. Otherwise schedule it
2091 // immediately to free the dependent. We can hoist the copy later.
2092 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2093 if (TargetRegisterInfo::isPhysicalRegister(
2094 MI->getOperand(UnscheduledOper).getReg()))
2095 return AtBoundary ? -1 : 1;
2096 return 0;
2097}
2098
Andrew Trick3b87f622012-11-07 07:05:09 +00002099/// Apply a set of heursitics to a new candidate. Heuristics are currently
2100/// hierarchical. This may be more efficient than a graduated cost model because
2101/// we don't need to evaluate all aspects of the model for each node in the
2102/// queue. But it's really done to make the heuristics easier to debug and
2103/// statistically analyze.
2104///
2105/// \param Cand provides the policy and current best candidate.
2106/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2107/// \param Zone describes the scheduled zone that we are extending.
2108/// \param RPTracker describes reg pressure within the scheduled zone.
2109/// \param TempTracker is a scratch pressure tracker to reuse in queries.
2110void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
2111 SchedCandidate &TryCand,
2112 SchedBoundary &Zone,
2113 const RegPressureTracker &RPTracker,
2114 RegPressureTracker &TempTracker) {
2115
2116 // Always initialize TryCand's RPDelta.
2117 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
2118 DAG->getRegionCriticalPSets(),
2119 DAG->getRegPressure().MaxSetPressure);
2120
2121 // Initialize the candidate if needed.
2122 if (!Cand.isValid()) {
2123 TryCand.Reason = NodeOrder;
2124 return;
2125 }
Andrew Trick4392f0f2013-04-13 06:07:40 +00002126
2127 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2128 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2129 TryCand, Cand, PhysRegCopy))
2130 return;
2131
Andrew Trick13372882013-07-25 07:26:35 +00002132 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2133 // invalid; convert it to INT_MAX to give it lowest priority.
2134 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
2135 RegExcess))
Andrew Trick3b87f622012-11-07 07:05:09 +00002136 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002137
2138 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick13372882013-07-25 07:26:35 +00002139 if (tryPressure(TryCand.RPDelta.CriticalMax, Cand.RPDelta.CriticalMax,
2140 TryCand, Cand, RegCritical))
Andrew Trick3b87f622012-11-07 07:05:09 +00002141 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002142
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002143 // Keep clustered nodes together to encourage downstream peephole
2144 // optimizations which may reduce resource requirements.
2145 //
2146 // This is a best effort to set things up for a post-RA pass. Optimizations
2147 // like generating loads of multiple registers should ideally be done within
2148 // the scheduler pass by combining the loads during DAG postprocessing.
2149 const SUnit *NextClusterSU =
2150 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2151 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2152 TryCand, Cand, Cluster))
2153 return;
Andrew Tricke38afe12013-04-24 15:54:43 +00002154
2155 // Weak edges are for clustering and other constraints.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002156 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2157 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Tricke38afe12013-04-24 15:54:43 +00002158 TryCand, Cand, Weak)) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002159 return;
2160 }
Andrew Tricka626f502013-06-17 21:45:13 +00002161 // Avoid increasing the max pressure of the entire region.
Andrew Trick13372882013-07-25 07:26:35 +00002162 if (tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax,
2163 TryCand, Cand, RegMax))
Andrew Tricka626f502013-06-17 21:45:13 +00002164 return;
2165
Andrew Trick3b87f622012-11-07 07:05:09 +00002166 // Avoid critical resource consumption and balance the schedule.
2167 TryCand.initResourceDelta(DAG, SchedModel);
2168 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2169 TryCand, Cand, ResourceReduce))
2170 return;
2171 if (tryGreater(TryCand.ResDelta.DemandedResources,
2172 Cand.ResDelta.DemandedResources,
2173 TryCand, Cand, ResourceDemand))
2174 return;
2175
2176 // Avoid serializing long latency dependence chains.
2177 if (Cand.Policy.ReduceLatency) {
2178 if (Zone.isTop()) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002179 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002180 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2181 TryCand, Cand, TopDepthReduce))
2182 return;
2183 }
2184 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2185 TryCand, Cand, TopPathReduce))
2186 return;
2187 }
2188 else {
Andrew Trickfa989e72013-06-15 05:39:19 +00002189 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002190 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2191 TryCand, Cand, BotHeightReduce))
2192 return;
2193 }
2194 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2195 TryCand, Cand, BotPathReduce))
2196 return;
2197 }
2198 }
2199
Andrew Trick3b87f622012-11-07 07:05:09 +00002200 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickfa989e72013-06-15 05:39:19 +00002201 // local pressure avoidance strategy that also makes the machine code
2202 // readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002203 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
2204 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00002205 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002206
Andrew Trick3b87f622012-11-07 07:05:09 +00002207 // Fall through to original instruction order.
2208 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2209 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2210 TryCand.Reason = NodeOrder;
2211 }
2212}
Andrew Trick28ebc892012-05-10 21:06:19 +00002213
Andrew Trick3b87f622012-11-07 07:05:09 +00002214#ifndef NDEBUG
2215const char *ConvergingScheduler::getReasonStr(
2216 ConvergingScheduler::CandReason Reason) {
2217 switch (Reason) {
2218 case NoCand: return "NOCAND ";
Andrew Trick4392f0f2013-04-13 06:07:40 +00002219 case PhysRegCopy: return "PREG-COPY";
Andrew Tricke52d5022013-06-17 21:45:05 +00002220 case RegExcess: return "REG-EXCESS";
2221 case RegCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002222 case Cluster: return "CLUSTER ";
Andrew Tricke38afe12013-04-24 15:54:43 +00002223 case Weak: return "WEAK ";
Andrew Tricka626f502013-06-17 21:45:13 +00002224 case RegMax: return "REG-MAX ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002225 case ResourceReduce: return "RES-REDUCE";
2226 case ResourceDemand: return "RES-DEMAND";
2227 case TopDepthReduce: return "TOP-DEPTH ";
2228 case TopPathReduce: return "TOP-PATH ";
2229 case BotHeightReduce:return "BOT-HEIGHT";
2230 case BotPathReduce: return "BOT-PATH ";
2231 case NextDefUse: return "DEF-USE ";
2232 case NodeOrder: return "ORDER ";
2233 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00002234 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00002235}
2236
Andrew Trick11189f72013-04-05 00:31:29 +00002237void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002238 PressureElement P;
2239 unsigned ResIdx = 0;
2240 unsigned Latency = 0;
2241 switch (Cand.Reason) {
2242 default:
2243 break;
Andrew Tricke52d5022013-06-17 21:45:05 +00002244 case RegExcess:
Andrew Trick3b87f622012-11-07 07:05:09 +00002245 P = Cand.RPDelta.Excess;
2246 break;
Andrew Tricke52d5022013-06-17 21:45:05 +00002247 case RegCritical:
Andrew Trick3b87f622012-11-07 07:05:09 +00002248 P = Cand.RPDelta.CriticalMax;
2249 break;
Andrew Tricka626f502013-06-17 21:45:13 +00002250 case RegMax:
Andrew Trick3b87f622012-11-07 07:05:09 +00002251 P = Cand.RPDelta.CurrentMax;
2252 break;
2253 case ResourceReduce:
2254 ResIdx = Cand.Policy.ReduceResIdx;
2255 break;
2256 case ResourceDemand:
2257 ResIdx = Cand.Policy.DemandResIdx;
2258 break;
2259 case TopDepthReduce:
2260 Latency = Cand.SU->getDepth();
2261 break;
2262 case TopPathReduce:
2263 Latency = Cand.SU->getHeight();
2264 break;
2265 case BotHeightReduce:
2266 Latency = Cand.SU->getHeight();
2267 break;
2268 case BotPathReduce:
2269 Latency = Cand.SU->getDepth();
2270 break;
2271 }
Andrew Trick11189f72013-04-05 00:31:29 +00002272 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002273 if (P.isValid())
Andrew Trick11189f72013-04-05 00:31:29 +00002274 dbgs() << " " << TRI->getRegPressureSetName(P.PSetID)
2275 << ":" << P.UnitIncrease << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002276 else
Andrew Trick11189f72013-04-05 00:31:29 +00002277 dbgs() << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002278 if (ResIdx)
Andrew Trick11189f72013-04-05 00:31:29 +00002279 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002280 else
2281 dbgs() << " ";
Andrew Trick11189f72013-04-05 00:31:29 +00002282 if (Latency)
2283 dbgs() << " " << Latency << " cycles ";
2284 else
2285 dbgs() << " ";
2286 dbgs() << '\n';
Andrew Trick3b87f622012-11-07 07:05:09 +00002287}
2288#endif
2289
Andrew Trick7196a8f2012-05-10 21:06:16 +00002290/// Pick the best candidate from the top queue.
2291///
2292/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2293/// DAG building. To adjust for the current scheduling location we need to
2294/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00002295void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2296 const RegPressureTracker &RPTracker,
2297 SchedCandidate &Cand) {
2298 ReadyQueue &Q = Zone.Available;
2299
Andrew Trickf3234242012-05-24 22:11:12 +00002300 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002301
Andrew Trick7196a8f2012-05-10 21:06:16 +00002302 // getMaxPressureDelta temporarily modifies the tracker.
2303 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2304
Andrew Trick8c2d9212012-05-24 22:11:03 +00002305 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00002306
Andrew Trick3b87f622012-11-07 07:05:09 +00002307 SchedCandidate TryCand(Cand.Policy);
2308 TryCand.SU = *I;
2309 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2310 if (TryCand.Reason != NoCand) {
2311 // Initialize resource delta if needed in case future heuristics query it.
2312 if (TryCand.ResDelta == SchedResourceDelta())
2313 TryCand.initResourceDelta(DAG, SchedModel);
2314 Cand.setBest(TryCand);
Andrew Trick11189f72013-04-05 00:31:29 +00002315 DEBUG(traceCandidate(Cand));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002316 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002317 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002318}
2319
2320static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2321 bool IsTop) {
Andrew Trickbaedcd72013-04-13 06:07:49 +00002322 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
Andrew Trick3b87f622012-11-07 07:05:09 +00002323 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00002324}
2325
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002326/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00002327SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002328 // Schedule as far as possible in the direction of no choice. This is most
2329 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002330 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002331 IsTopNode = false;
Andrew Trickfa989e72013-06-15 05:39:19 +00002332 DEBUG(dbgs() << "Pick Bot NOCAND\n");
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002333 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002334 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002335 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002336 IsTopNode = true;
Andrew Trickfa989e72013-06-15 05:39:19 +00002337 DEBUG(dbgs() << "Pick Top NOCAND\n");
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002338 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002339 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002340 CandPolicy NoPolicy;
2341 SchedCandidate BotCand(NoPolicy);
2342 SchedCandidate TopCand(NoPolicy);
Andrew Trickfa989e72013-06-15 05:39:19 +00002343 Bot.setPolicy(BotCand.Policy, Top);
2344 Top.setPolicy(TopCand.Policy, Bot);
Andrew Trick3b87f622012-11-07 07:05:09 +00002345
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002346 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00002347 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2348 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002349
2350 // If either Q has a single candidate that provides the least increase in
2351 // Excess pressure, we can immediately schedule from that Q.
2352 //
2353 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2354 // affects picking from either Q. If scheduling in one direction must
2355 // increase pressure for one of the excess PSets, then schedule in that
2356 // direction first to provide more freedom in the other direction.
Andrew Tricke52d5022013-06-17 21:45:05 +00002357 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2358 || (BotCand.Reason == RegCritical
2359 && !BotCand.isRepeat(RegCritical)))
2360 {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002361 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002362 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002363 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002364 }
2365 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00002366 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2367 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002368
Andrew Tricke52d5022013-06-17 21:45:05 +00002369 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3b87f622012-11-07 07:05:09 +00002370 if (TopCand.Reason < BotCand.Reason) {
2371 IsTopNode = true;
2372 tracePick(TopCand, IsTopNode);
2373 return TopCand.SU;
2374 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002375 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002376 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002377 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002378 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002379}
2380
2381/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002382SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2383 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002384 assert(Top.Available.empty() && Top.Pending.empty() &&
2385 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002386 return NULL;
2387 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002388 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002389 do {
2390 if (ForceTopDown) {
2391 SU = Top.pickOnlyChoice();
2392 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002393 CandPolicy NoPolicy;
2394 SchedCandidate TopCand(NoPolicy);
2395 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2396 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002397 SU = TopCand.SU;
2398 }
2399 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002400 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002401 else if (ForceBottomUp) {
2402 SU = Bot.pickOnlyChoice();
2403 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002404 CandPolicy NoPolicy;
2405 SchedCandidate BotCand(NoPolicy);
2406 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2407 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002408 SU = BotCand.SU;
2409 }
2410 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002411 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002412 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002413 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002414 }
2415 } while (SU->isScheduled);
2416
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002417 if (SU->isTopReady())
2418 Top.removeReady(SU);
2419 if (SU->isBottomReady())
2420 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002421
Andrew Trickbaedcd72013-04-13 06:07:49 +00002422 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7196a8f2012-05-10 21:06:16 +00002423 return SU;
2424}
2425
Andrew Trick4392f0f2013-04-13 06:07:40 +00002426void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2427
2428 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2429 if (!isTop)
2430 ++InsertPos;
2431 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2432
2433 // Find already scheduled copies with a single physreg dependence and move
2434 // them just above the scheduled instruction.
2435 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2436 I != E; ++I) {
2437 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2438 continue;
2439 SUnit *DepSU = I->getSUnit();
2440 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2441 continue;
2442 MachineInstr *Copy = DepSU->getInstr();
2443 if (!Copy->isCopy())
2444 continue;
2445 DEBUG(dbgs() << " Rescheduling physreg copy ";
2446 I->getSUnit()->dump(DAG));
2447 DAG->moveInstruction(Copy, InsertPos);
2448 }
2449}
2450
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002451/// Update the scheduler's state after scheduling a node. This is the same node
2452/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002453/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick4392f0f2013-04-13 06:07:40 +00002454///
2455/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2456/// them here. See comments in biasPhysRegCopy.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002457void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002458 if (IsTopNode) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002459 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002460 Top.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00002461 if (SU->hasPhysRegUses)
2462 reschedulePhysRegCopies(SU, true);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002463 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002464 else {
Andrew Trickfa989e72013-06-15 05:39:19 +00002465 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002466 Bot.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00002467 if (SU->hasPhysRegDefs)
2468 reschedulePhysRegCopies(SU, false);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002469 }
2470}
2471
Andrew Trick17d35e52012-03-14 04:00:41 +00002472/// Create the standard converging machine scheduler. This will be used as the
2473/// default scheduler if the target does not set a default.
2474static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002475 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002476 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002477 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2478 // Register DAG post-processors.
Andrew Tricke38afe12013-04-24 15:54:43 +00002479 //
2480 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2481 // data and pass it to later mutations. Have a single mutation that gathers
2482 // the interesting nodes in one pass.
Andrew Trick63a8d822013-06-15 04:49:46 +00002483 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002484 if (EnableLoadCluster)
2485 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002486 if (EnableMacroFusion)
2487 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002488 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002489}
2490static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002491ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2492 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002493
2494//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002495// ILP Scheduler. Currently for experimental analysis of heuristics.
2496//===----------------------------------------------------------------------===//
2497
2498namespace {
2499/// \brief Order nodes by the ILP metric.
2500struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002501 const SchedDFSResult *DFSResult;
2502 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002503 bool MaximizeILP;
2504
Andrew Trick178f7d02013-01-25 04:01:04 +00002505 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002506
2507 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002508 ///
2509 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002510 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002511 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2512 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2513 if (SchedTreeA != SchedTreeB) {
2514 // Unscheduled trees have lower priority.
2515 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2516 return ScheduledTrees->test(SchedTreeB);
2517
2518 // Trees with shallower connections have have lower priority.
2519 if (DFSResult->getSubtreeLevel(SchedTreeA)
2520 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2521 return DFSResult->getSubtreeLevel(SchedTreeA)
2522 < DFSResult->getSubtreeLevel(SchedTreeB);
2523 }
2524 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002525 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002526 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002527 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002528 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002529 }
2530};
2531
2532/// \brief Schedule based on the ILP metric.
2533class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002534 /// In case all subtrees are eventually connected to a common root through
2535 /// data dependence (e.g. reduction), place an upper limit on their size.
2536 ///
2537 /// FIXME: A subtree limit is generally good, but in the situation commented
2538 /// above, where multiple similar subtrees feed a common root, we should
2539 /// only split at a point where the resulting subtrees will be balanced.
2540 /// (a motivating test case must be found).
2541 static const unsigned SubtreeLimit = 16;
2542
Andrew Trick178f7d02013-01-25 04:01:04 +00002543 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002544 ILPOrder Cmp;
2545
2546 std::vector<SUnit*> ReadyQ;
2547public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002548 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002549
Andrew Trick178f7d02013-01-25 04:01:04 +00002550 virtual void initialize(ScheduleDAGMI *dag) {
2551 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002552 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002553 Cmp.DFSResult = DAG->getDFSResult();
2554 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002555 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002556 }
2557
2558 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002559 // Restore the heap in ReadyQ with the updated DFS results.
2560 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002561 }
2562
2563 /// Implement MachineSchedStrategy interface.
2564 /// -----------------------------------------
2565
Andrew Trick8b1496c2012-11-28 05:13:28 +00002566 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002567 virtual SUnit *pickNode(bool &IsTopNode) {
2568 if (ReadyQ.empty()) return NULL;
Matt Arsenault26c417b2013-03-21 00:57:21 +00002569 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002570 SUnit *SU = ReadyQ.back();
2571 ReadyQ.pop_back();
2572 IsTopNode = false;
Andrew Trickbaedcd72013-04-13 06:07:49 +00002573 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick178f7d02013-01-25 04:01:04 +00002574 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2575 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2576 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trickbaedcd72013-04-13 06:07:49 +00002577 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2578 << "Scheduling " << *SU->getInstr());
Andrew Trick1e94e982012-10-15 18:02:27 +00002579 return SU;
2580 }
2581
Andrew Trick178f7d02013-01-25 04:01:04 +00002582 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2583 virtual void scheduleTree(unsigned SubtreeID) {
2584 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2585 }
2586
Andrew Trick8b1496c2012-11-28 05:13:28 +00002587 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2588 /// DFSResults, and resort the priority Q.
2589 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2590 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002591 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002592
2593 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2594
2595 virtual void releaseBottomNode(SUnit *SU) {
2596 ReadyQ.push_back(SU);
2597 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2598 }
2599};
2600} // namespace
2601
2602static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2603 return new ScheduleDAGMI(C, new ILPScheduler(true));
2604}
2605static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2606 return new ScheduleDAGMI(C, new ILPScheduler(false));
2607}
2608static MachineSchedRegistry ILPMaxRegistry(
2609 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2610static MachineSchedRegistry ILPMinRegistry(
2611 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2612
2613//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002614// Machine Instruction Shuffler for Correctness Testing
2615//===----------------------------------------------------------------------===//
2616
Andrew Trick96f678f2012-01-13 06:30:30 +00002617#ifndef NDEBUG
2618namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002619/// Apply a less-than relation on the node order, which corresponds to the
2620/// instruction order prior to scheduling. IsReverse implements greater-than.
2621template<bool IsReverse>
2622struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002623 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002624 if (IsReverse)
2625 return A->NodeNum > B->NodeNum;
2626 else
2627 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002628 }
2629};
2630
Andrew Trick96f678f2012-01-13 06:30:30 +00002631/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002632class InstructionShuffler : public MachineSchedStrategy {
2633 bool IsAlternating;
2634 bool IsTopDown;
2635
2636 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2637 // gives nodes with a higher number higher priority causing the latest
2638 // instructions to be scheduled first.
2639 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2640 TopQ;
2641 // When scheduling bottom-up, use greater-than as the queue priority.
2642 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2643 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002644public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002645 InstructionShuffler(bool alternate, bool topdown)
2646 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002647
Andrew Trick17d35e52012-03-14 04:00:41 +00002648 virtual void initialize(ScheduleDAGMI *) {
2649 TopQ.clear();
2650 BottomQ.clear();
2651 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002652
Andrew Trick17d35e52012-03-14 04:00:41 +00002653 /// Implement MachineSchedStrategy interface.
2654 /// -----------------------------------------
2655
2656 virtual SUnit *pickNode(bool &IsTopNode) {
2657 SUnit *SU;
2658 if (IsTopDown) {
2659 do {
2660 if (TopQ.empty()) return NULL;
2661 SU = TopQ.top();
2662 TopQ.pop();
2663 } while (SU->isScheduled);
2664 IsTopNode = true;
2665 }
2666 else {
2667 do {
2668 if (BottomQ.empty()) return NULL;
2669 SU = BottomQ.top();
2670 BottomQ.pop();
2671 } while (SU->isScheduled);
2672 IsTopNode = false;
2673 }
2674 if (IsAlternating)
2675 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002676 return SU;
2677 }
2678
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002679 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2680
Andrew Trick17d35e52012-03-14 04:00:41 +00002681 virtual void releaseTopNode(SUnit *SU) {
2682 TopQ.push(SU);
2683 }
2684 virtual void releaseBottomNode(SUnit *SU) {
2685 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002686 }
2687};
2688} // namespace
2689
Andrew Trickc174eaf2012-03-08 01:41:12 +00002690static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002691 bool Alternate = !ForceTopDown && !ForceBottomUp;
2692 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002693 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002694 "-misched-topdown incompatible with -misched-bottomup");
2695 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002696}
Andrew Trick17d35e52012-03-14 04:00:41 +00002697static MachineSchedRegistry ShufflerRegistry(
2698 "shuffle", "Shuffle machine instructions alternating directions",
2699 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002700#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00002701
2702//===----------------------------------------------------------------------===//
2703// GraphWriter support for ScheduleDAGMI.
2704//===----------------------------------------------------------------------===//
2705
2706#ifndef NDEBUG
2707namespace llvm {
2708
2709template<> struct GraphTraits<
2710 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2711
2712template<>
2713struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2714
2715 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2716
2717 static std::string getGraphName(const ScheduleDAG *G) {
2718 return G->MF.getName();
2719 }
2720
2721 static bool renderGraphFromBottomUp() {
2722 return true;
2723 }
2724
2725 static bool isNodeHidden(const SUnit *Node) {
2726 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2727 }
2728
2729 static bool hasNodeAddressLabel(const SUnit *Node,
2730 const ScheduleDAG *Graph) {
2731 return false;
2732 }
2733
2734 /// If you want to override the dot attributes printed for a particular
2735 /// edge, override this method.
2736 static std::string getEdgeAttributes(const SUnit *Node,
2737 SUnitIterator EI,
2738 const ScheduleDAG *Graph) {
2739 if (EI.isArtificialDep())
2740 return "color=cyan,style=dashed";
2741 if (EI.isCtrlDep())
2742 return "color=blue,style=dashed";
2743 return "";
2744 }
2745
2746 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2747 std::string Str;
2748 raw_string_ostream SS(Str);
2749 SS << "SU(" << SU->NodeNum << ')';
2750 return SS.str();
2751 }
2752 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2753 return G->getGraphNodeLabel(SU);
2754 }
2755
2756 static std::string getNodeAttributes(const SUnit *N,
2757 const ScheduleDAG *Graph) {
2758 std::string Str("shape=Mrecord");
2759 const SchedDFSResult *DFS =
2760 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2761 if (DFS) {
2762 Str += ",style=filled,fillcolor=\"#";
2763 Str += DOT::getColorString(DFS->getSubtreeID(N));
2764 Str += '"';
2765 }
2766 return Str;
2767 }
2768};
2769} // namespace llvm
2770#endif // NDEBUG
2771
2772/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2773/// rendered using 'dot'.
2774///
2775void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2776#ifndef NDEBUG
2777 ViewGraph(this, Name, false, Title);
2778#else
2779 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2780 << "systems with Graphviz or gv!\n";
2781#endif // NDEBUG
2782}
2783
2784/// Out-of-line implementation with no arguments is handy for gdb.
2785void ScheduleDAGMI::viewGraph() {
2786 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
2787}