blob: 7787ba89adbf4bc185e554c322c5b3341c8fa1b0 [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-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
Andrew Trick02a80da2012-03-08 01:41:12 +000015#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/PriorityQueue.h"
17#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000019#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000026#include "llvm/CodeGen/TargetPassConfig.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000030#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000031#include "llvm/Support/raw_ostream.h"
Jakub Staszak80df8b82013-06-14 00:00:13 +000032#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000033
Andrew Tricke77e84e2012-01-13 06:30:30 +000034using namespace llvm;
35
Chandler Carruth1b9dde02014-04-22 02:02:50 +000036#define DEBUG_TYPE "misched"
37
Andrew Trick7a8e1002012-09-11 00:39:15 +000038namespace llvm {
39cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40 cl::desc("Force top-down list scheduling"));
41cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000043cl::opt<bool>
44DumpCriticalPathLength("misched-dcpl", cl::Hidden,
45 cl::desc("Print critical path length to stdout"));
Andrew Trick7a8e1002012-09-11 00:39:15 +000046}
Andrew Trick8823dec2012-03-14 04:00:41 +000047
Andrew Tricka5f19562012-03-07 00:18:25 +000048#ifndef NDEBUG
49static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
50 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000051
Matthias Braund78ee542015-09-17 21:09:59 +000052/// In some situations a few uninteresting nodes depend on nearly all other
53/// nodes in the graph, provide a cutoff to hide them.
54static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
55 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
56
Lang Hamesdd98c492012-03-19 18:38:38 +000057static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
58 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000059
60static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
61 cl::desc("Only schedule this function"));
62static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
63 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +000064#else
65static bool ViewMISchedDAGs = false;
66#endif // NDEBUG
67
Matthias Braun6493bc22016-04-22 19:09:17 +000068/// Avoid quadratic complexity in unusually large basic blocks by limiting the
69/// size of the ready lists.
70static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
71 cl::desc("Limit ready list to N instructions"), cl::init(256));
72
Andrew Trickb6e74712013-09-04 20:59:59 +000073static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
74 cl::desc("Enable register pressure scheduling."), cl::init(true));
75
Andrew Trickc01b0042013-08-23 17:48:43 +000076static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +000077 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +000078
Jun Bum Lim4c5bd582016-04-15 14:58:38 +000079static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
80 cl::desc("Enable memop clustering."),
81 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +000082
Andrew Trick263280242012-11-12 19:52:20 +000083// Experimental heuristics
84static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000085 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick263280242012-11-12 19:52:20 +000086
Andrew Trick48f2a722013-03-08 05:40:34 +000087static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
88 cl::desc("Verify machine instrs before and after machine scheduling"));
89
Andrew Trick44f750a2013-01-25 04:01:04 +000090// DAG subtrees must have at least this many nodes.
91static const unsigned MinSubtreeSize = 8;
92
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000093// Pin the vtables to this file.
94void MachineSchedStrategy::anchor() {}
95void ScheduleDAGMutation::anchor() {}
96
Andrew Trick63440872012-01-14 02:17:06 +000097//===----------------------------------------------------------------------===//
98// Machine Instruction Scheduling Pass and Registry
99//===----------------------------------------------------------------------===//
100
Andrew Trick4d4b5462012-04-24 20:36:19 +0000101MachineSchedContext::MachineSchedContext():
Craig Topperc0196b12014-04-14 00:51:57 +0000102 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000103 RegClassInfo = new RegisterClassInfo();
104}
105
106MachineSchedContext::~MachineSchedContext() {
107 delete RegClassInfo;
108}
109
Andrew Tricke77e84e2012-01-13 06:30:30 +0000110namespace {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000111/// Base class for a machine scheduler class that can run at any point.
112class MachineSchedulerBase : public MachineSchedContext,
113 public MachineFunctionPass {
114public:
115 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
116
Craig Topperc0196b12014-04-14 00:51:57 +0000117 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000118
119protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000120 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000121};
122
Andrew Tricke1c034f2012-01-17 06:55:03 +0000123/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000124class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000125public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000126 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000127
Craig Topper4584cd52014-03-07 09:26:03 +0000128 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000129
Craig Topper4584cd52014-03-07 09:26:03 +0000130 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000131
Andrew Tricke77e84e2012-01-13 06:30:30 +0000132 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000133
134protected:
135 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000136};
Andrew Trick17080b92013-12-28 21:56:51 +0000137
138/// PostMachineScheduler runs after shortly before code emission.
139class PostMachineScheduler : public MachineSchedulerBase {
140public:
141 PostMachineScheduler();
142
Craig Topper4584cd52014-03-07 09:26:03 +0000143 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000144
Craig Topper4584cd52014-03-07 09:26:03 +0000145 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000146
147 static char ID; // Class identification, replacement for typeinfo
148
149protected:
150 ScheduleDAGInstrs *createPostMachineScheduler();
151};
Andrew Tricke77e84e2012-01-13 06:30:30 +0000152} // namespace
153
Andrew Tricke1c034f2012-01-17 06:55:03 +0000154char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000155
Andrew Tricke1c034f2012-01-17 06:55:03 +0000156char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000157
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000158INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000159 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000160INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000161INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
162INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000163INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000164 "Machine Instruction Scheduler", false, false)
165
Andrew Tricke1c034f2012-01-17 06:55:03 +0000166MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000167: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000168 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000169}
170
Andrew Tricke1c034f2012-01-17 06:55:03 +0000171void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000172 AU.setPreservesCFG();
173 AU.addRequiredID(MachineDominatorsID);
174 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000175 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000176 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000177 AU.addRequired<SlotIndexes>();
178 AU.addPreserved<SlotIndexes>();
179 AU.addRequired<LiveIntervals>();
180 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000181 MachineFunctionPass::getAnalysisUsage(AU);
182}
183
Andrew Trick17080b92013-12-28 21:56:51 +0000184char PostMachineScheduler::ID = 0;
185
186char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
187
188INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000189 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000190
191PostMachineScheduler::PostMachineScheduler()
192: MachineSchedulerBase(ID) {
193 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
194}
195
196void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
197 AU.setPreservesCFG();
198 AU.addRequiredID(MachineDominatorsID);
199 AU.addRequired<MachineLoopInfo>();
200 AU.addRequired<TargetPassConfig>();
201 MachineFunctionPass::getAnalysisUsage(AU);
202}
203
Andrew Tricke77e84e2012-01-13 06:30:30 +0000204MachinePassRegistry MachineSchedRegistry::Registry;
205
Andrew Trick45300682012-03-09 00:52:20 +0000206/// A dummy default scheduler factory indicates whether the scheduler
207/// is overridden on the command line.
208static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000209 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000210}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000211
212/// MachineSchedOpt allows command line selection of the scheduler.
213static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
214 RegisterPassParser<MachineSchedRegistry> >
215MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000216 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000217 cl::desc("Machine instruction scheduler to use"));
218
Andrew Trick45300682012-03-09 00:52:20 +0000219static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000220DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000221 useDefaultMachineSched);
222
Eric Christopher5f141b02015-03-11 22:56:10 +0000223static cl::opt<bool> EnableMachineSched(
224 "enable-misched",
225 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
226 cl::Hidden);
227
Chad Rosier816a1ab2016-01-20 23:08:32 +0000228static cl::opt<bool> EnablePostRAMachineSched(
229 "enable-post-misched",
230 cl::desc("Enable the post-ra machine instruction scheduling pass."),
231 cl::init(true), cl::Hidden);
232
Andrew Trickcc45a282012-04-24 18:04:34 +0000233/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000234static MachineBasicBlock::const_iterator
235priorNonDebug(MachineBasicBlock::const_iterator I,
236 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000237 assert(I != Beg && "reached the top of the region, cannot decrement");
238 while (--I != Beg) {
239 if (!I->isDebugValue())
240 break;
241 }
242 return I;
243}
244
Andrew Trick2bc74c22013-08-30 04:36:57 +0000245/// Non-const version.
246static MachineBasicBlock::iterator
247priorNonDebug(MachineBasicBlock::iterator I,
248 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000249 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
250 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000251}
252
Andrew Trickcc45a282012-04-24 18:04:34 +0000253/// If this iterator is a debug value, increment until reaching the End or a
254/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000255static MachineBasicBlock::const_iterator
256nextIfDebug(MachineBasicBlock::const_iterator I,
257 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000258 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000259 if (!I->isDebugValue())
260 break;
261 }
262 return I;
263}
264
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000265/// Non-const version.
266static MachineBasicBlock::iterator
267nextIfDebug(MachineBasicBlock::iterator I,
268 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000269 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
270 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000271}
272
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000273/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000274ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
275 // Select the scheduler, or set the default.
276 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
277 if (Ctor != useDefaultMachineSched)
278 return Ctor(this);
279
280 // Get the default scheduler set by the target for this function.
281 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
282 if (Scheduler)
283 return Scheduler;
284
285 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000286 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000287}
288
Andrew Trick17080b92013-12-28 21:56:51 +0000289/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
290/// the caller. We don't have a command line option to override the postRA
291/// scheduler. The Target must configure it.
292ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
293 // Get the postRA scheduler set by the target for this function.
294 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
295 if (Scheduler)
296 return Scheduler;
297
298 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000299 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000300}
301
Andrew Trick72515be2012-03-14 04:00:38 +0000302/// Top-level MachineScheduler pass driver.
303///
304/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000305/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
306/// consistent with the DAG builder, which traverses the interior of the
307/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000308///
309/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000310/// simplifying the DAG builder's support for "special" target instructions.
311/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000312/// scheduling boundaries, for example to bundle the boudary instructions
313/// without reordering them. This creates complexity, because the target
314/// scheduler must update the RegionBegin and RegionEnd positions cached by
315/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
316/// design would be to split blocks at scheduling boundaries, but LLVM has a
317/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000318bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000319 if (skipFunction(*mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000320 return false;
321
Eric Christopher5f141b02015-03-11 22:56:10 +0000322 if (EnableMachineSched.getNumOccurrences()) {
323 if (!EnableMachineSched)
324 return false;
325 } else if (!mf.getSubtarget().enableMachineScheduler())
326 return false;
327
Matthias Braundc7580a2015-10-29 03:57:28 +0000328 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000329
Andrew Tricke77e84e2012-01-13 06:30:30 +0000330 // Initialize the context of the pass.
331 MF = &mf;
332 MLI = &getAnalysis<MachineLoopInfo>();
333 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000334 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000335 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000336
Lang Hamesad33d5a2012-01-27 22:36:19 +0000337 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000338
Andrew Trick48f2a722013-03-08 05:40:34 +0000339 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000340 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000341 MF->verify(this, "Before machine scheduling.");
342 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000343 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000344
Andrew Trick978674b2013-09-20 05:14:41 +0000345 // Instantiate the selected scheduler for this target, function, and
346 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000347 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000348 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000349
350 DEBUG(LIS->dump());
351 if (VerifyScheduling)
352 MF->verify(this, "After machine scheduling.");
353 return true;
354}
355
Andrew Trick17080b92013-12-28 21:56:51 +0000356bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000357 if (skipFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000358 return false;
359
Chad Rosier816a1ab2016-01-20 23:08:32 +0000360 if (EnablePostRAMachineSched.getNumOccurrences()) {
361 if (!EnablePostRAMachineSched)
362 return false;
363 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Andrew Trick8d2ee372014-06-04 07:06:27 +0000364 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
365 return false;
366 }
Andrew Trick17080b92013-12-28 21:56:51 +0000367 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
368
369 // Initialize the context of the pass.
370 MF = &mf;
371 PassConfig = &getAnalysis<TargetPassConfig>();
372
373 if (VerifyScheduling)
374 MF->verify(this, "Before post machine scheduling.");
375
376 // Instantiate the selected scheduler for this target, function, and
377 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000378 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000379 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000380
381 if (VerifyScheduling)
382 MF->verify(this, "After post machine scheduling.");
383 return true;
384}
385
Andrew Trickd14d7c22013-12-28 21:56:57 +0000386/// Return true of the given instruction should not be included in a scheduling
387/// region.
388///
389/// MachineScheduler does not currently support scheduling across calls. To
390/// handle calls, the DAG builder needs to be modified to create register
391/// anti/output dependencies on the registers clobbered by the call's regmask
392/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
393/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
394/// the boundary, but there would be no benefit to postRA scheduling across
395/// calls this late anyway.
396static bool isSchedBoundary(MachineBasicBlock::iterator MI,
397 MachineBasicBlock *MBB,
398 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000399 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000400 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000401}
402
Andrew Trickd7f890e2013-12-28 21:56:47 +0000403/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000404void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
405 bool FixKillFlags) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000406 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000407
408 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000409 //
410 // TODO: Visit blocks in global postorder or postorder within the bottom-up
411 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000412 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
413 MBB != MBBEnd; ++MBB) {
414
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000415 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000416
Andrew Trick33e05d72013-12-28 21:57:02 +0000417#ifndef NDEBUG
418 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
419 continue;
420 if (SchedOnlyBlock.getNumOccurrences()
421 && (int)SchedOnlyBlock != MBB->getNumber())
422 continue;
423#endif
424
Andrew Trick7e120f42012-01-14 02:17:09 +0000425 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000426 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000427 // boundary at the bottom of the region. The DAG does not include RegionEnd,
428 // but the region does (i.e. the next RegionEnd is above the previous
429 // RegionBegin). If the current block has no terminator then RegionEnd ==
430 // MBB->end() for the bottom region.
431 //
432 // The Scheduler may insert instructions during either schedule() or
433 // exitRegion(), even for empty regions. So the local iterators 'I' and
434 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000435 //
436 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
437 // as a single instruction.
Andrew Tricka21daf72012-03-09 03:46:39 +0000438 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000439 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000440
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000441 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000442 if (RegionEnd != MBB->end() ||
Matthias Braun93563e72015-11-03 01:53:29 +0000443 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000444 --RegionEnd;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000445 }
446
Andrew Trick7e120f42012-01-14 02:17:09 +0000447 // The next region starts above the previous region. Look backward in the
448 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000449 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000450 MachineBasicBlock::iterator I = RegionEnd;
Matthias Braun858d1df2016-05-20 19:46:13 +0000451 for (;I != MBB->begin(); --I) {
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000452 MachineInstr &MI = *std::prev(I);
453 if (isSchedBoundary(&MI, &*MBB, MF, TII))
Andrew Trick7e120f42012-01-14 02:17:09 +0000454 break;
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000455 if (!MI.isDebugValue())
Andrea Di Biagiod65fd9f2014-12-12 15:09:58 +0000456 ++NumRegionInstrs;
Andrew Trick7e120f42012-01-14 02:17:09 +0000457 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000458 // Notify the scheduler of the region, even if we may skip scheduling
459 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000460 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000461
462 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000463 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000464 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000465 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000466 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000467 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000468 }
Matthias Braun93563e72015-11-03 01:53:29 +0000469 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000470 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000471 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
472 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000473 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
474 else dbgs() << "End";
Matthias Braun858d1df2016-05-20 19:46:13 +0000475 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000476 if (DumpCriticalPathLength) {
477 errs() << MF->getName();
478 errs() << ":BB# " << MBB->getNumber();
479 errs() << " " << MBB->getName() << " \n";
480 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000481
Andrew Trick1c0ec452012-03-09 03:46:42 +0000482 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000483 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000484 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000485
486 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000487 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000488
489 // Scheduling has invalidated the current iterator 'I'. Ask the
490 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000491 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000492 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000493 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000494 // FIXME: Ideally, no further passes should rely on kill flags. However,
495 // thumb2 size reduction is currently an exception, so the PostMIScheduler
496 // needs to do this.
497 if (FixKillFlags)
498 Scheduler.fixupKills(&*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000499 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000500 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000501}
502
Andrew Trickd7f890e2013-12-28 21:56:47 +0000503void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000504 // unimplemented
505}
506
Alp Tokerd8d510a2014-07-01 21:19:13 +0000507LLVM_DUMP_METHOD
Andrew Trick7a8e1002012-09-11 00:39:15 +0000508void ReadyQueue::dump() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000509 dbgs() << "Queue " << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000510 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
511 dbgs() << Queue[i]->NodeNum << " ";
512 dbgs() << "\n";
513}
Andrew Trick8823dec2012-03-14 04:00:41 +0000514
515//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000516// ScheduleDAGMI - Basic machine instruction scheduling. This is
517// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
518// virtual registers.
519// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000520
David Blaikie422b93d2014-04-21 20:32:32 +0000521// Provide a vtable anchor.
Andrew Trick44f750a2013-01-25 04:01:04 +0000522ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000523}
524
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000525bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
526 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
527}
528
Andrew Tricka7714a02012-11-12 19:40:10 +0000529bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000530 if (SuccSU != &ExitSU) {
531 // Do not use WillCreateCycle, it assumes SD scheduling.
532 // If Pred is reachable from Succ, then the edge creates a cycle.
533 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
534 return false;
535 Topo.AddPred(SuccSU, PredDep.getSUnit());
536 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000537 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
538 // Return true regardless of whether a new edge needed to be inserted.
539 return true;
540}
541
Andrew Trick02a80da2012-03-08 01:41:12 +0000542/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
543/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000544///
545/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000546void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000547 SUnit *SuccSU = SuccEdge->getSUnit();
548
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000549 if (SuccEdge->isWeak()) {
550 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000551 if (SuccEdge->isCluster())
552 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000553 return;
554 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000555#ifndef NDEBUG
556 if (SuccSU->NumPredsLeft == 0) {
557 dbgs() << "*** Scheduling failed! ***\n";
558 SuccSU->dump(this);
559 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000560 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000561 }
562#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000563 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
564 // CurrCycle may have advanced since then.
565 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
566 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
567
Andrew Trick02a80da2012-03-08 01:41:12 +0000568 --SuccSU->NumPredsLeft;
569 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000570 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000571}
572
573/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000574void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000575 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
576 I != E; ++I) {
577 releaseSucc(SU, &*I);
578 }
579}
580
Andrew Trick8823dec2012-03-14 04:00:41 +0000581/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
582/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000583///
584/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000585void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
586 SUnit *PredSU = PredEdge->getSUnit();
587
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000588 if (PredEdge->isWeak()) {
589 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000590 if (PredEdge->isCluster())
591 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000592 return;
593 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000594#ifndef NDEBUG
595 if (PredSU->NumSuccsLeft == 0) {
596 dbgs() << "*** Scheduling failed! ***\n";
597 PredSU->dump(this);
598 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000599 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000600 }
601#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000602 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
603 // CurrCycle may have advanced since then.
604 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
605 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
606
Andrew Trick8823dec2012-03-14 04:00:41 +0000607 --PredSU->NumSuccsLeft;
608 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
609 SchedImpl->releaseBottomNode(PredSU);
610}
611
612/// releasePredecessors - Call releasePred on each of SU's predecessors.
613void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
614 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
615 I != E; ++I) {
616 releasePred(SU, &*I);
617 }
618}
619
Andrew Trickd7f890e2013-12-28 21:56:47 +0000620/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
621/// crossing a scheduling boundary. [begin, end) includes all instructions in
622/// the region, including the boundary itself and single-instruction regions
623/// that don't get scheduled.
624void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
625 MachineBasicBlock::iterator begin,
626 MachineBasicBlock::iterator end,
627 unsigned regioninstrs)
628{
629 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
630
631 SchedImpl->initPolicy(begin, end, regioninstrs);
632}
633
Andrew Tricke833e1c2013-04-13 06:07:40 +0000634/// This is normally called from the main scheduler loop but may also be invoked
635/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000636void ScheduleDAGMI::moveInstruction(
637 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000638 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000639 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000640 ++RegionBegin;
641
642 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000643 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000644
645 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000646 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000647 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000648
649 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000650 if (RegionBegin == InsertPos)
651 RegionBegin = MI;
652}
653
Andrew Trickde670c02012-03-21 04:12:07 +0000654bool ScheduleDAGMI::checkSchedLimit() {
655#ifndef NDEBUG
656 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
657 CurrentTop = CurrentBottom;
658 return false;
659 }
660 ++NumInstrsScheduled;
661#endif
662 return true;
663}
664
Andrew Trickd7f890e2013-12-28 21:56:47 +0000665/// Per-region scheduling driver, called back from
666/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
667/// does not consider liveness or register pressure. It is useful for PostRA
668/// scheduling and potentially other custom schedulers.
669void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000670 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
671 DEBUG(SchedImpl->dumpPolicy());
672
Andrew Trickd7f890e2013-12-28 21:56:47 +0000673 // Build the DAG.
674 buildSchedGraph(AA);
675
676 Topo.InitDAGTopologicalSorting();
677
678 postprocessDAG();
679
680 SmallVector<SUnit*, 8> TopRoots, BotRoots;
681 findRootsAndBiasEdges(TopRoots, BotRoots);
682
683 // Initialize the strategy before modifying the DAG.
684 // This may initialize a DFSResult to be used for queue priority.
685 SchedImpl->initialize(this);
686
Matthias Braun69f1d122016-11-11 22:37:28 +0000687 DEBUG(
688 if (EntrySU.getInstr() != nullptr)
689 EntrySU.dumpAll(this);
690 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
691 SUnits[su].dumpAll(this);
692 if (ExitSU.getInstr() != nullptr)
693 ExitSU.dumpAll(this);
694 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000695 if (ViewMISchedDAGs) viewGraph();
696
697 // Initialize ready queues now that the DAG and priority data are finalized.
698 initQueues(TopRoots, BotRoots);
699
700 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000701 while (true) {
702 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
703 SUnit *SU = SchedImpl->pickNode(IsTopNode);
704 if (!SU) break;
705
Andrew Trickd7f890e2013-12-28 21:56:47 +0000706 assert(!SU->isScheduled && "Node already scheduled");
707 if (!checkSchedLimit())
708 break;
709
710 MachineInstr *MI = SU->getInstr();
711 if (IsTopNode) {
712 assert(SU->isTopReady() && "node still has unscheduled dependencies");
713 if (&*CurrentTop == MI)
714 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
715 else
716 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000717 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000718 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
719 MachineBasicBlock::iterator priorII =
720 priorNonDebug(CurrentBottom, CurrentTop);
721 if (&*priorII == MI)
722 CurrentBottom = priorII;
723 else {
724 if (&*CurrentTop == MI)
725 CurrentTop = nextIfDebug(++CurrentTop, priorII);
726 moveInstruction(MI, CurrentBottom);
727 CurrentBottom = MI;
728 }
729 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000730 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000731 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000732 // runs, it can then use the accurate ReadyCycle time to determine whether
733 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000734 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000735
736 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000737 }
738 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
739
740 placeDebugValues();
741
742 DEBUG({
743 unsigned BBNum = begin()->getParent()->getNumber();
744 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
745 dumpSchedule();
746 dbgs() << '\n';
747 });
748}
749
750/// Apply each ScheduleDAGMutation step in order.
751void ScheduleDAGMI::postprocessDAG() {
752 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
753 Mutations[i]->apply(this);
754 }
755}
756
757void ScheduleDAGMI::
758findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
759 SmallVectorImpl<SUnit*> &BotRoots) {
760 for (std::vector<SUnit>::iterator
761 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
762 SUnit *SU = &(*I);
763 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
764
765 // Order predecessors so DFSResult follows the critical path.
766 SU->biasCriticalPath();
767
768 // A SUnit is ready to top schedule if it has no predecessors.
769 if (!I->NumPredsLeft)
770 TopRoots.push_back(SU);
771 // A SUnit is ready to bottom schedule if it has no successors.
772 if (!I->NumSuccsLeft)
773 BotRoots.push_back(SU);
774 }
775 ExitSU.biasCriticalPath();
776}
777
778/// Identify DAG roots and setup scheduler queues.
779void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
780 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000781 NextClusterSucc = nullptr;
782 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000783
784 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
785 //
786 // Nodes with unreleased weak edges can still be roots.
787 // Release top roots in forward order.
788 for (SmallVectorImpl<SUnit*>::const_iterator
789 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
790 SchedImpl->releaseTopNode(*I);
791 }
792 // Release bottom roots in reverse order so the higher priority nodes appear
793 // first. This is more natural and slightly more efficient.
794 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
795 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
796 SchedImpl->releaseBottomNode(*I);
797 }
798
799 releaseSuccessors(&EntrySU);
800 releasePredecessors(&ExitSU);
801
802 SchedImpl->registerRoots();
803
804 // Advance past initial DebugValues.
805 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
806 CurrentBottom = RegionEnd;
807}
808
809/// Update scheduler queues after scheduling an instruction.
810void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
811 // Release dependent instructions for scheduling.
812 if (IsTopNode)
813 releaseSuccessors(SU);
814 else
815 releasePredecessors(SU);
816
817 SU->isScheduled = true;
818}
819
820/// Reinsert any remaining debug_values, just like the PostRA scheduler.
821void ScheduleDAGMI::placeDebugValues() {
822 // If first instruction was a DBG_VALUE then put it back.
823 if (FirstDbgValue) {
824 BB->splice(RegionBegin, BB, FirstDbgValue);
825 RegionBegin = FirstDbgValue;
826 }
827
828 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
829 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000830 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000831 MachineInstr *DbgValue = P.first;
832 MachineBasicBlock::iterator OrigPrevMI = P.second;
833 if (&*RegionBegin == DbgValue)
834 ++RegionBegin;
835 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000836 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000837 RegionEnd = DbgValue;
838 }
839 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000840 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000841}
842
843#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
844void ScheduleDAGMI::dumpSchedule() const {
845 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
846 if (SUnit *SU = getSUnit(&(*MI)))
847 SU->dump(this);
848 else
849 dbgs() << "Missing SUnit\n";
850 }
851}
852#endif
853
854//===----------------------------------------------------------------------===//
855// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
856// preservation.
857//===----------------------------------------------------------------------===//
858
859ScheduleDAGMILive::~ScheduleDAGMILive() {
860 delete DFSResult;
861}
862
Matthias Braun40639882016-11-11 22:37:31 +0000863void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
864 const MachineInstr &MI = *SU.getInstr();
865 for (const MachineOperand &MO : MI.operands()) {
866 if (!MO.isReg())
867 continue;
868 if (!MO.readsReg())
869 continue;
870 if (TrackLaneMasks && !MO.isUse())
871 continue;
872
873 unsigned Reg = MO.getReg();
874 if (!TargetRegisterInfo::isVirtualRegister(Reg))
875 continue;
876
877 // Ignore re-defs.
878 if (TrackLaneMasks) {
879 bool FoundDef = false;
880 for (const MachineOperand &MO2 : MI.operands()) {
881 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
882 FoundDef = true;
883 break;
884 }
885 }
886 if (FoundDef)
887 continue;
888 }
889
890 // Record this local VReg use.
891 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
892 for (; UI != VRegUses.end(); ++UI) {
893 if (UI->SU == &SU)
894 break;
895 }
896 if (UI == VRegUses.end())
897 VRegUses.insert(VReg2SUnit(Reg, 0, &SU));
898 }
899}
900
Andrew Trick88639922012-04-24 17:56:43 +0000901/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
902/// crossing a scheduling boundary. [begin, end) includes all instructions in
903/// the region, including the boundary itself and single-instruction regions
904/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000905void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000906 MachineBasicBlock::iterator begin,
907 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000908 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000909{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000910 // ScheduleDAGMI initializes SchedImpl's per-region policy.
911 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000912
913 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000914 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000915
Andrew Trickb248b4a2013-09-06 17:32:47 +0000916 SUPressureDiffs.clear();
917
Andrew Trick75e411c2013-09-06 17:32:34 +0000918 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000919 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
920
Matthias Braunf9acaca2016-05-31 22:38:06 +0000921 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
922 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000923}
924
925// Setup the register pressure trackers for the top scheduled top and bottom
926// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000927void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +0000928 VRegUses.clear();
929 VRegUses.setUniverse(MRI.getNumVirtRegs());
930 for (SUnit &SU : SUnits)
931 collectVRegUses(SU);
932
Matthias Braund4f64092016-01-20 00:23:32 +0000933 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
934 ShouldTrackLaneMasks, false);
935 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
936 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +0000937
938 // Close the RPTracker to finalize live ins.
939 RPTracker.closeRegion();
940
Andrew Trick9c17eab2013-07-30 19:59:12 +0000941 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000942
Andrew Trick4add42f2012-05-10 21:06:10 +0000943 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +0000944 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
945 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000946
947 // Close one end of the tracker so we can call
948 // getMaxUpward/DownwardPressureDelta before advancing across any
949 // instructions. This converts currently live regs into live ins/outs.
950 TopRPTracker.closeTop();
951 BotRPTracker.closeBottom();
952
Andrew Trick9c17eab2013-07-30 19:59:12 +0000953 BotRPTracker.initLiveThru(RPTracker);
954 if (!BotRPTracker.getLiveThru().empty()) {
955 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
956 DEBUG(dbgs() << "Live Thru: ";
957 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
958 };
959
Andrew Trick2bc74c22013-08-30 04:36:57 +0000960 // For each live out vreg reduce the pressure change associated with other
961 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +0000962 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +0000963
Andrew Trick4add42f2012-05-10 21:06:10 +0000964 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000965 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +0000966 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +0000967 BotRPTracker.recede(&LiveUses);
968 updatePressureDiffs(LiveUses);
969 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000970
Matthias Braune6edd482015-11-13 22:30:31 +0000971 DEBUG(
972 dbgs() << "Top Pressure:\n";
973 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
974 dbgs() << "Bottom Pressure:\n";
975 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
976 );
977
Andrew Trick4add42f2012-05-10 21:06:10 +0000978 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000979
980 // Cache the list of excess pressure sets in this region. This will also track
981 // the max pressure in the scheduled code for these sets.
982 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000983 const std::vector<unsigned> &RegionPressure =
984 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000985 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000986 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000987 if (RegionPressure[i] > Limit) {
988 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
989 << " Limit " << Limit
990 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000991 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000992 }
Andrew Trick22025772012-05-17 18:35:10 +0000993 }
994 DEBUG(dbgs() << "Excess PSets: ";
995 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
996 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000997 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000998 dbgs() << "\n");
999}
1000
Andrew Trickd7f890e2013-12-28 21:56:47 +00001001void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001002updateScheduledPressure(const SUnit *SU,
1003 const std::vector<unsigned> &NewMaxPressure) {
1004 const PressureDiff &PDiff = getPressureDiff(SU);
1005 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1006 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
1007 I != E; ++I) {
1008 if (!I->isValid())
1009 break;
1010 unsigned ID = I->getPSet();
1011 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1012 ++CritIdx;
1013 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1014 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1015 && NewMaxPressure[ID] <= INT16_MAX)
1016 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1017 }
1018 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1019 if (NewMaxPressure[ID] >= Limit - 2) {
1020 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001021 << NewMaxPressure[ID]
1022 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1023 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001024 }
Andrew Trick22025772012-05-17 18:35:10 +00001025 }
Andrew Trick88639922012-04-24 17:56:43 +00001026}
1027
Andrew Trick2bc74c22013-08-30 04:36:57 +00001028/// Update the PressureDiff array for liveness after scheduling this
1029/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001030void ScheduleDAGMILive::updatePressureDiffs(
1031 ArrayRef<RegisterMaskPair> LiveUses) {
1032 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001033 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001034 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001035 if (!TRI->isVirtualRegister(Reg))
1036 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001037
Matthias Braund4f64092016-01-20 00:23:32 +00001038 if (ShouldTrackLaneMasks) {
1039 // If the register has just become live then other uses won't change
1040 // this fact anymore => decrement pressure.
1041 // If the register has just become dead then other uses make it come
1042 // back to life => increment pressure.
1043 bool Decrement = P.LaneMask != 0;
1044
1045 for (const VReg2SUnit &V2SU
1046 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1047 SUnit &SU = *V2SU.SU;
1048 if (SU.isScheduled || &SU == &ExitSU)
1049 continue;
1050
1051 PressureDiff &PDiff = getPressureDiff(&SU);
1052 PDiff.addPressureChange(Reg, Decrement, &MRI);
1053 DEBUG(
1054 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1055 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1056 << ' ' << *SU.getInstr();
1057 dbgs() << " to ";
1058 PDiff.dump(*TRI);
1059 );
1060 }
1061 } else {
1062 assert(P.LaneMask != 0);
1063 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1064 // This may be called before CurrentBottom has been initialized. However,
1065 // BotRPTracker must have a valid position. We want the value live into the
1066 // instruction or live out of the block, so ask for the previous
1067 // instruction's live-out.
1068 const LiveInterval &LI = LIS->getInterval(Reg);
1069 VNInfo *VNI;
1070 MachineBasicBlock::const_iterator I =
1071 nextIfDebug(BotRPTracker.getPos(), BB->end());
1072 if (I == BB->end())
1073 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1074 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001075 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001076 VNI = LRQ.valueIn();
1077 }
1078 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1079 assert(VNI && "No live value at use.");
1080 for (const VReg2SUnit &V2SU
1081 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1082 SUnit *SU = V2SU.SU;
1083 // If this use comes before the reaching def, it cannot be a last use,
1084 // so decrease its pressure change.
1085 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001086 LiveQueryResult LRQ =
1087 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001088 if (LRQ.valueIn() == VNI) {
1089 PressureDiff &PDiff = getPressureDiff(SU);
1090 PDiff.addPressureChange(Reg, true, &MRI);
1091 DEBUG(
1092 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1093 << *SU->getInstr();
1094 dbgs() << " to ";
1095 PDiff.dump(*TRI);
1096 );
1097 }
Matthias Braun9198c672015-11-06 20:59:02 +00001098 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001099 }
1100 }
1101 }
1102}
1103
Andrew Trick8823dec2012-03-14 04:00:41 +00001104/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001105/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1106/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001107///
1108/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001109/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001110/// implementing MachineSchedStrategy should be sufficient to implement a new
1111/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001112/// ScheduleDAGMILive then it will want to override this virtual method in order
1113/// to update any specialized state.
1114void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001115 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1116 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001117 buildDAGWithRegPressure();
1118
Andrew Tricka7714a02012-11-12 19:40:10 +00001119 Topo.InitDAGTopologicalSorting();
1120
Andrew Tricka2733e92012-09-14 17:22:42 +00001121 postprocessDAG();
1122
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001123 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1124 findRootsAndBiasEdges(TopRoots, BotRoots);
1125
1126 // Initialize the strategy before modifying the DAG.
1127 // This may initialize a DFSResult to be used for queue priority.
1128 SchedImpl->initialize(this);
1129
Matthias Braun9198c672015-11-06 20:59:02 +00001130 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001131 if (EntrySU.getInstr() != nullptr)
1132 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001133 for (const SUnit &SU : SUnits) {
1134 SU.dumpAll(this);
1135 if (ShouldTrackPressure) {
1136 dbgs() << " Pressure Diff : ";
1137 getPressureDiff(&SU).dump(*TRI);
1138 }
1139 dbgs() << '\n';
1140 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001141 if (ExitSU.getInstr() != nullptr)
1142 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001143 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001144 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001145
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001146 // Initialize ready queues now that the DAG and priority data are finalized.
1147 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001148
1149 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001150 while (true) {
1151 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1152 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1153 if (!SU) break;
1154
Andrew Trick984d98b2012-10-08 18:53:53 +00001155 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001156 if (!checkSchedLimit())
1157 break;
1158
1159 scheduleMI(SU, IsTopNode);
1160
Andrew Trickd7f890e2013-12-28 21:56:47 +00001161 if (DFSResult) {
1162 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1163 if (!ScheduledTrees.test(SubtreeID)) {
1164 ScheduledTrees.set(SubtreeID);
1165 DFSResult->scheduleTree(SubtreeID);
1166 SchedImpl->scheduleTree(SubtreeID);
1167 }
1168 }
1169
1170 // Notify the scheduling strategy after updating the DAG.
1171 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001172
1173 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001174 }
1175 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1176
1177 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001178
1179 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001180 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001181 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1182 dumpSchedule();
1183 dbgs() << '\n';
1184 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001185}
1186
1187/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001188void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001189 if (!ShouldTrackPressure) {
1190 RPTracker.reset();
1191 RegionCriticalPSets.clear();
1192 buildSchedGraph(AA);
1193 return;
1194 }
1195
Andrew Trick4add42f2012-05-10 21:06:10 +00001196 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001197 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001198 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001199
Andrew Trick4add42f2012-05-10 21:06:10 +00001200 // Account for liveness generate by the region boundary.
1201 if (LiveRegionEnd != RegionEnd)
1202 RPTracker.recede();
1203
1204 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001205 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001206
Andrew Trick4add42f2012-05-10 21:06:10 +00001207 // Initialize top/bottom trackers after computing region pressure.
1208 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001209}
Andrew Trick4add42f2012-05-10 21:06:10 +00001210
Andrew Trickd7f890e2013-12-28 21:56:47 +00001211void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001212 if (!DFSResult)
1213 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1214 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001215 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001216 DFSResult->resize(SUnits.size());
1217 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001218 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1219}
1220
Andrew Trick483f4192013-08-29 18:04:49 +00001221/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1222/// only provides the critical path for single block loops. To handle loops that
1223/// span blocks, we could use the vreg path latencies provided by
1224/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1225/// available for use in the scheduler.
1226///
1227/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001228/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001229/// the following instruction sequence where each instruction has unit latency
1230/// and defines an epomymous virtual register:
1231///
1232/// a->b(a,c)->c(b)->d(c)->exit
1233///
1234/// The cyclic critical path is a two cycles: b->c->b
1235/// The acyclic critical path is four cycles: a->b->c->d->exit
1236/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1237/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1238/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1239/// LiveInDepth = depth(b) = len(a->b) = 1
1240///
1241/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1242/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1243/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001244///
1245/// This could be relevant to PostRA scheduling, but is currently implemented
1246/// assuming LiveIntervals.
1247unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001248 // This only applies to single block loop.
1249 if (!BB->isSuccessor(BB))
1250 return 0;
1251
1252 unsigned MaxCyclicLatency = 0;
1253 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001254 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1255 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001256 if (!TRI->isVirtualRegister(Reg))
1257 continue;
1258 const LiveInterval &LI = LIS->getInterval(Reg);
1259 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1260 if (!DefVNI)
1261 continue;
1262
1263 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1264 const SUnit *DefSU = getSUnit(DefMI);
1265 if (!DefSU)
1266 continue;
1267
1268 unsigned LiveOutHeight = DefSU->getHeight();
1269 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1270 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001271 for (const VReg2SUnit &V2SU
1272 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1273 SUnit *SU = V2SU.SU;
1274 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001275 continue;
1276
1277 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001278 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001279 if (!LRQ.valueIn()->isPHIDef())
1280 continue;
1281
1282 // Assume that a path spanning two iterations is a cycle, which could
1283 // overestimate in strange cases. This allows cyclic latency to be
1284 // estimated as the minimum slack of the vreg's depth or height.
1285 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001286 if (LiveOutDepth > SU->getDepth())
1287 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001288
Matthias Braunb0c437b2015-10-29 03:57:17 +00001289 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001290 if (LiveInHeight > LiveOutHeight) {
1291 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1292 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001293 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001294 CyclicLatency = 0;
1295
1296 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001297 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001298 if (CyclicLatency > MaxCyclicLatency)
1299 MaxCyclicLatency = CyclicLatency;
1300 }
1301 }
1302 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1303 return MaxCyclicLatency;
1304}
1305
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001306/// Release ExitSU predecessors and setup scheduler queues. Re-position
1307/// the Top RP tracker in case the region beginning has changed.
1308void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1309 ArrayRef<SUnit*> BotRoots) {
1310 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1311 if (ShouldTrackPressure) {
1312 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1313 TopRPTracker.setPos(CurrentTop);
1314 }
1315}
1316
Andrew Trick7a8e1002012-09-11 00:39:15 +00001317/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001318void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001319 // Move the instruction to its new location in the instruction stream.
1320 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001321
Andrew Trick7a8e1002012-09-11 00:39:15 +00001322 if (IsTopNode) {
1323 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1324 if (&*CurrentTop == MI)
1325 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001326 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001327 moveInstruction(MI, CurrentTop);
1328 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001329 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001330
Andrew Trickb6e74712013-09-04 20:59:59 +00001331 if (ShouldTrackPressure) {
1332 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001333 RegisterOperands RegOpers;
1334 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1335 if (ShouldTrackLaneMasks) {
1336 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001337 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001338 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1339 } else {
1340 // Adjust for missing dead-def flags.
1341 RegOpers.detectDeadDefs(*MI, *LIS);
1342 }
1343
1344 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001345 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001346 DEBUG(
1347 dbgs() << "Top Pressure:\n";
1348 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1349 );
1350
Andrew Trickb248b4a2013-09-06 17:32:47 +00001351 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001352 }
Matthias Braunb550b762016-04-21 01:54:13 +00001353 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001354 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1355 MachineBasicBlock::iterator priorII =
1356 priorNonDebug(CurrentBottom, CurrentTop);
1357 if (&*priorII == MI)
1358 CurrentBottom = priorII;
1359 else {
1360 if (&*CurrentTop == MI) {
1361 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1362 TopRPTracker.setPos(CurrentTop);
1363 }
1364 moveInstruction(MI, CurrentBottom);
1365 CurrentBottom = MI;
1366 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001367 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001368 RegisterOperands RegOpers;
1369 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1370 if (ShouldTrackLaneMasks) {
1371 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001372 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001373 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1374 } else {
1375 // Adjust for missing dead-def flags.
1376 RegOpers.detectDeadDefs(*MI, *LIS);
1377 }
1378
1379 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001380 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001381 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001382 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001383 DEBUG(
1384 dbgs() << "Bottom Pressure:\n";
1385 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1386 );
1387
Andrew Trickb248b4a2013-09-06 17:32:47 +00001388 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001389 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001390 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001391 }
1392}
1393
Andrew Trick263280242012-11-12 19:52:20 +00001394//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001395// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001396//===----------------------------------------------------------------------===//
1397
Andrew Tricka7714a02012-11-12 19:40:10 +00001398namespace {
1399/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001400/// loads or between neighboring stores.
1401class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1402 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001403 SUnit *SU;
1404 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001405 int64_t Offset;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001406 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1407 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001408
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001409 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001410 return std::tie(BaseReg, Offset, SU->NodeNum) <
1411 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001412 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001413 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001414
1415 const TargetInstrInfo *TII;
1416 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001417 bool IsLoad;
1418
Andrew Tricka7714a02012-11-12 19:40:10 +00001419public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001420 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1421 const TargetRegisterInfo *tri, bool IsLoad)
1422 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001423
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001424 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001425
Andrew Tricka7714a02012-11-12 19:40:10 +00001426protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001427 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1428};
1429
1430class StoreClusterMutation : public BaseMemOpClusterMutation {
1431public:
1432 StoreClusterMutation(const TargetInstrInfo *tii,
1433 const TargetRegisterInfo *tri)
1434 : BaseMemOpClusterMutation(tii, tri, false) {}
1435};
1436
1437class LoadClusterMutation : public BaseMemOpClusterMutation {
1438public:
1439 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1440 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001441};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001442} // anonymous
Andrew Tricka7714a02012-11-12 19:40:10 +00001443
Tom Stellard68726a52016-08-19 19:59:18 +00001444namespace llvm {
1445
1446std::unique_ptr<ScheduleDAGMutation>
1447createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1448 const TargetRegisterInfo *TRI) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001449 return EnableMemOpCluster ? make_unique<LoadClusterMutation>(TII, TRI)
1450 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001451}
1452
1453std::unique_ptr<ScheduleDAGMutation>
1454createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1455 const TargetRegisterInfo *TRI) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001456 return EnableMemOpCluster ? make_unique<StoreClusterMutation>(TII, TRI)
1457 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001458}
1459
1460} // namespace llvm
1461
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001462void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1463 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1464 SmallVector<MemOpInfo, 32> MemOpRecords;
1465 for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1466 SUnit *SU = MemOps[Idx];
Andrew Tricka7714a02012-11-12 19:40:10 +00001467 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001468 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001469 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001470 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001471 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001472 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001473 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001474
1475 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001476 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001477 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1478 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001479 ClusterLength = 1;
1480 continue;
1481 }
1482
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001483 SUnit *SUa = MemOpRecords[Idx].SU;
1484 SUnit *SUb = MemOpRecords[Idx+1].SU;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001485 if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
1486 ClusterLength) &&
1487 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001488 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001489 << SUb->NodeNum << ")\n");
1490 // Copy successor edges from SUa to SUb. Interleaving computation
1491 // dependent on SUa can prevent load combining due to register reuse.
1492 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1493 // loads should have effectively the same inputs.
1494 for (SUnit::const_succ_iterator
1495 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1496 if (SI->getSUnit() == SUb)
1497 continue;
1498 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1499 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1500 }
1501 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001502 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001503 ClusterLength = 1;
1504 }
1505}
1506
1507/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001508void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1509
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001510 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1511
Andrew Tricka7714a02012-11-12 19:40:10 +00001512 // Map DAG NodeNum to store chain ID.
1513 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001514 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001515 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1516 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1517 SUnit *SU = &DAG->SUnits[Idx];
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001518 if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1519 (!IsLoad && !SU->getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001520 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001521
Andrew Tricka7714a02012-11-12 19:40:10 +00001522 unsigned ChainPredID = DAG->SUnits.size();
1523 for (SUnit::const_pred_iterator
1524 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1525 if (PI->isCtrl()) {
1526 ChainPredID = PI->getSUnit()->NodeNum;
1527 break;
1528 }
1529 }
1530 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001531 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001532 unsigned NumChains = StoreChainDependents.size();
1533 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1534 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1535 if (Result.second)
1536 StoreChainDependents.resize(NumChains + 1);
1537 StoreChainDependents[Result.first->second].push_back(SU);
1538 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001539
Andrew Tricka7714a02012-11-12 19:40:10 +00001540 // Iterate over the store chains.
1541 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001542 clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001543}
1544
Andrew Trick02a80da2012-03-08 01:41:12 +00001545//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001546// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1547//===----------------------------------------------------------------------===//
1548
1549namespace {
1550/// \brief Post-process the DAG to create cluster edges between instructions
1551/// that may be fused by the processor into a single operation.
1552class MacroFusion : public ScheduleDAGMutation {
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001553 const TargetInstrInfo &TII;
Andrew Trick263280242012-11-12 19:52:20 +00001554public:
Matthias Braun325cd2c2016-11-11 01:34:21 +00001555 MacroFusion(const TargetInstrInfo &TII)
1556 : TII(TII) {}
Andrew Trick263280242012-11-12 19:52:20 +00001557
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001558 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick263280242012-11-12 19:52:20 +00001559};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001560} // anonymous
Andrew Trick263280242012-11-12 19:52:20 +00001561
Tom Stellard68726a52016-08-19 19:59:18 +00001562namespace llvm {
1563
1564std::unique_ptr<ScheduleDAGMutation>
Matthias Braun325cd2c2016-11-11 01:34:21 +00001565createMacroFusionDAGMutation(const TargetInstrInfo *TII) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001566 return EnableMacroFusion ? make_unique<MacroFusion>(*TII) : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001567}
1568
1569} // namespace llvm
1570
Andrew Trick263280242012-11-12 19:52:20 +00001571/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1572/// fused operations.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001573void MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) {
1574 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1575
Andrew Trick263280242012-11-12 19:52:20 +00001576 // For now, assume targets can only fuse with the branch.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001577 SUnit &ExitSU = DAG->ExitSU;
1578 MachineInstr *Branch = ExitSU.getInstr();
Andrew Trick263280242012-11-12 19:52:20 +00001579 if (!Branch)
1580 return;
1581
Matthias Braun325cd2c2016-11-11 01:34:21 +00001582 for (SDep &PredDep : ExitSU.Preds) {
1583 if (PredDep.isWeak())
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001584 continue;
Matthias Braun325cd2c2016-11-11 01:34:21 +00001585 SUnit &SU = *PredDep.getSUnit();
1586 MachineInstr &Pred = *SU.getInstr();
1587 if (!TII.shouldScheduleAdjacent(Pred, *Branch))
Andrew Trick263280242012-11-12 19:52:20 +00001588 continue;
1589
1590 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1591 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1592 // need to copy predecessor edges from ExitSU to SU, since top-down
1593 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1594 // of SU, we could create an artificial edge from the deepest root, but it
1595 // hasn't been needed yet.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001596 bool Success = DAG->addEdge(&ExitSU, SDep(&SU, SDep::Cluster));
Andrew Trick263280242012-11-12 19:52:20 +00001597 (void)Success;
1598 assert(Success && "No DAG nodes should be reachable from ExitSU");
1599
Matthias Braun325cd2c2016-11-11 01:34:21 +00001600 // Adjust latency of data deps between the nodes.
1601 for (SDep &PredDep : ExitSU.Preds) {
1602 if (PredDep.getSUnit() == &SU)
1603 PredDep.setLatency(0);
1604 }
1605 for (SDep &SuccDep : SU.Succs) {
1606 if (SuccDep.getSUnit() == &ExitSU)
1607 SuccDep.setLatency(0);
1608 }
1609
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001610 DEBUG(dbgs() << "Macro Fuse SU(" << SU.NodeNum << ")\n");
Andrew Trick263280242012-11-12 19:52:20 +00001611 break;
1612 }
1613}
1614
1615//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001616// CopyConstrain - DAG post-processing to encourage copy elimination.
1617//===----------------------------------------------------------------------===//
1618
1619namespace {
1620/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1621/// the one use that defines the copy's source vreg, most likely an induction
1622/// variable increment.
1623class CopyConstrain : public ScheduleDAGMutation {
1624 // Transient state.
1625 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001626 // RegionEndIdx is the slot index of the last non-debug instruction in the
1627 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001628 SlotIndex RegionEndIdx;
1629public:
1630 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1631
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001632 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001633
1634protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001635 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001636};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001637} // anonymous
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001638
Tom Stellard68726a52016-08-19 19:59:18 +00001639namespace llvm {
1640
1641std::unique_ptr<ScheduleDAGMutation>
1642createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1643 const TargetRegisterInfo *TRI) {
1644 return make_unique<CopyConstrain>(TII, TRI);
1645}
1646
1647} // namespace llvm
1648
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001649/// constrainLocalCopy handles two possibilities:
1650/// 1) Local src:
1651/// I0: = dst
1652/// I1: src = ...
1653/// I2: = dst
1654/// I3: dst = src (copy)
1655/// (create pred->succ edges I0->I1, I2->I1)
1656///
1657/// 2) Local copy:
1658/// I0: dst = src (copy)
1659/// I1: = dst
1660/// I2: src = ...
1661/// I3: = dst
1662/// (create pred->succ edges I1->I2, I3->I2)
1663///
1664/// Although the MachineScheduler is currently constrained to single blocks,
1665/// this algorithm should handle extended blocks. An EBB is a set of
1666/// contiguously numbered blocks such that the previous block in the EBB is
1667/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001668void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001669 LiveIntervals *LIS = DAG->getLIS();
1670 MachineInstr *Copy = CopySU->getInstr();
1671
1672 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001673 const MachineOperand &SrcOp = Copy->getOperand(1);
1674 unsigned SrcReg = SrcOp.getReg();
1675 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001676 return;
1677
Matthias Braun7511abd2016-04-04 21:23:46 +00001678 const MachineOperand &DstOp = Copy->getOperand(0);
1679 unsigned DstReg = DstOp.getReg();
1680 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001681 return;
1682
1683 // Check if either the dest or source is local. If it's live across a back
1684 // edge, it's not local. Note that if both vregs are live across the back
1685 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001686 // If both the copy's source and dest are local live intervals, then we
1687 // should treat the dest as the global for the purpose of adding
1688 // constraints. This adds edges from source's other uses to the copy.
1689 unsigned LocalReg = SrcReg;
1690 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001691 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1692 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001693 LocalReg = DstReg;
1694 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001695 LocalLI = &LIS->getInterval(LocalReg);
1696 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1697 return;
1698 }
1699 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1700
1701 // Find the global segment after the start of the local LI.
1702 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1703 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1704 // local live range. We could create edges from other global uses to the local
1705 // start, but the coalescer should have already eliminated these cases, so
1706 // don't bother dealing with it.
1707 if (GlobalSegment == GlobalLI->end())
1708 return;
1709
1710 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1711 // returned the next global segment. But if GlobalSegment overlaps with
1712 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1713 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1714 if (GlobalSegment->contains(LocalLI->beginIndex()))
1715 ++GlobalSegment;
1716
1717 if (GlobalSegment == GlobalLI->end())
1718 return;
1719
1720 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1721 if (GlobalSegment != GlobalLI->begin()) {
1722 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001723 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001724 GlobalSegment->start)) {
1725 return;
1726 }
Andrew Trickd9761772013-07-30 19:59:08 +00001727 // If the prior global segment may be defined by the same two-address
1728 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001729 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001730 LocalLI->beginIndex())) {
1731 return;
1732 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001733 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1734 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001735 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001736 "Disconnected LRG within the scheduling region.");
1737 }
1738 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1739 if (!GlobalDef)
1740 return;
1741
1742 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1743 if (!GlobalSU)
1744 return;
1745
1746 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1747 // constraining the uses of the last local def to precede GlobalDef.
1748 SmallVector<SUnit*,8> LocalUses;
1749 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1750 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1751 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1752 for (SUnit::const_succ_iterator
1753 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1754 I != E; ++I) {
1755 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1756 continue;
1757 if (I->getSUnit() == GlobalSU)
1758 continue;
1759 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1760 return;
1761 LocalUses.push_back(I->getSUnit());
1762 }
1763 // Open the top of the GlobalLI hole by constraining any earlier global uses
1764 // to precede the start of LocalLI.
1765 SmallVector<SUnit*,8> GlobalUses;
1766 MachineInstr *FirstLocalDef =
1767 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1768 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1769 for (SUnit::const_pred_iterator
1770 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1771 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1772 continue;
1773 if (I->getSUnit() == FirstLocalSU)
1774 continue;
1775 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1776 return;
1777 GlobalUses.push_back(I->getSUnit());
1778 }
1779 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1780 // Add the weak edges.
1781 for (SmallVectorImpl<SUnit*>::const_iterator
1782 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1783 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1784 << GlobalSU->NodeNum << ")\n");
1785 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1786 }
1787 for (SmallVectorImpl<SUnit*>::const_iterator
1788 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1789 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1790 << FirstLocalSU->NodeNum << ")\n");
1791 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1792 }
1793}
1794
1795/// \brief Callback from DAG postProcessing to create weak edges to encourage
1796/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001797void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1798 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001799 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1800
Andrew Trick2e875172013-04-24 23:19:56 +00001801 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1802 if (FirstPos == DAG->end())
1803 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001804 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001805 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001806 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001807
1808 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1809 SUnit *SU = &DAG->SUnits[Idx];
1810 if (!SU->getInstr()->isCopy())
1811 continue;
1812
Andrew Trickd7f890e2013-12-28 21:56:47 +00001813 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001814 }
1815}
1816
1817//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001818// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1819// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001820//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001821
Andrew Trick5a22df42013-12-05 17:56:02 +00001822static const unsigned InvalidCycle = ~0U;
1823
Andrew Trickfc127d12013-12-07 05:59:44 +00001824SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001825
Andrew Trickfc127d12013-12-07 05:59:44 +00001826void SchedBoundary::reset() {
1827 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1828 // Destroying and reconstructing it is very expensive though. So keep
1829 // invalid, placeholder HazardRecs.
1830 if (HazardRec && HazardRec->isEnabled()) {
1831 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001832 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001833 }
1834 Available.clear();
1835 Pending.clear();
1836 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001837 CurrCycle = 0;
1838 CurrMOps = 0;
1839 MinReadyCycle = UINT_MAX;
1840 ExpectedLatency = 0;
1841 DependentLatency = 0;
1842 RetiredMOps = 0;
1843 MaxExecutedResCount = 0;
1844 ZoneCritResIdx = 0;
1845 IsResourceLimited = false;
1846 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001847#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001848 // Track the maximum number of stall cycles that could arise either from the
1849 // latency of a DAG edge or the number of cycles that a processor resource is
1850 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001851 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001852#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001853 // Reserve a zero-count for invalid CritResIdx.
1854 ExecutedResCounts.resize(1);
1855 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1856}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001857
Andrew Trickfc127d12013-12-07 05:59:44 +00001858void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001859init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1860 reset();
1861 if (!SchedModel->hasInstrSchedModel())
1862 return;
1863 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1864 for (std::vector<SUnit>::iterator
1865 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1866 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001867 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1868 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001869 for (TargetSchedModel::ProcResIter
1870 PI = SchedModel->getWriteProcResBegin(SC),
1871 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1872 unsigned PIdx = PI->ProcResourceIdx;
1873 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1874 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1875 }
1876 }
1877}
1878
Andrew Trickfc127d12013-12-07 05:59:44 +00001879void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001880init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1881 reset();
1882 DAG = dag;
1883 SchedModel = smodel;
1884 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001885 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001886 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001887 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1888 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001889}
1890
Andrew Trick880e5732013-12-05 17:55:58 +00001891/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1892/// these "soft stalls" differently than the hard stall cycles based on CPU
1893/// resources and computed by checkHazard(). A fully in-order model
1894/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1895/// available for scheduling until they are ready. However, a weaker in-order
1896/// model may use this for heuristics. For example, if a processor has in-order
1897/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001898unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001899 if (!SU->isUnbuffered)
1900 return 0;
1901
1902 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1903 if (ReadyCycle > CurrCycle)
1904 return ReadyCycle - CurrCycle;
1905 return 0;
1906}
1907
Andrew Trick5a22df42013-12-05 17:56:02 +00001908/// Compute the next cycle at which the given processor resource can be
1909/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001910unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001911getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1912 unsigned NextUnreserved = ReservedCycles[PIdx];
1913 // If this resource has never been used, always return cycle zero.
1914 if (NextUnreserved == InvalidCycle)
1915 return 0;
1916 // For bottom-up scheduling add the cycles needed for the current operation.
1917 if (!isTop())
1918 NextUnreserved += Cycles;
1919 return NextUnreserved;
1920}
1921
Andrew Trick8c9e6722012-06-29 03:23:24 +00001922/// Does this SU have a hazard within the current instruction group.
1923///
1924/// The scheduler supports two modes of hazard recognition. The first is the
1925/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1926/// supports highly complicated in-order reservation tables
1927/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1928///
1929/// The second is a streamlined mechanism that checks for hazards based on
1930/// simple counters that the scheduler itself maintains. It explicitly checks
1931/// for instruction dispatch limitations, including the number of micro-ops that
1932/// can dispatch per cycle.
1933///
1934/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001935bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001936 if (HazardRec->isEnabled()
1937 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1938 return true;
1939 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001940 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001941 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001942 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1943 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001944 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001945 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001946 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1947 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1948 for (TargetSchedModel::ProcResIter
1949 PI = SchedModel->getWriteProcResBegin(SC),
1950 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick56327222014-06-27 04:57:05 +00001951 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1952 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001953#ifndef NDEBUG
Chad Rosieraba845e2014-07-02 16:46:08 +00001954 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001955#endif
Andrew Trick56327222014-06-27 04:57:05 +00001956 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1957 << SchedModel->getResourceName(PI->ProcResourceIdx)
1958 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001959 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001960 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001961 }
1962 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001963 return false;
1964}
1965
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001966// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001967unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001968findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001969 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001970 unsigned RemLatency = 0;
1971 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001972 I != E; ++I) {
1973 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001974 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001975 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001976 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001977 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001978 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001979 if (LateSU) {
1980 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1981 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001982 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001983 return RemLatency;
1984}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001985
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001986// Count resources in this zone and the remaining unscheduled
1987// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1988// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001989unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001990getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001991 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001992 if (!SchedModel->hasInstrSchedModel())
1993 return 0;
1994
1995 unsigned OtherCritCount = Rem->RemIssueCount
1996 + (RetiredMOps * SchedModel->getMicroOpFactor());
1997 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1998 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001999 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2000 PIdx != PEnd; ++PIdx) {
2001 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2002 if (OtherCount > OtherCritCount) {
2003 OtherCritCount = OtherCount;
2004 OtherCritIdx = PIdx;
2005 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002006 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002007 if (OtherCritIdx) {
2008 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
2009 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00002010 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002011 }
2012 return OtherCritCount;
2013}
2014
Andrew Trickfc127d12013-12-07 05:59:44 +00002015void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002016 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2017
2018#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002019 // ReadyCycle was been bumped up to the CurrCycle when this node was
2020 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2021 // scheduling, so may now be greater than ReadyCycle.
2022 if (ReadyCycle > CurrCycle)
2023 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002024#endif
2025
Andrew Trick61f1a272012-05-24 22:11:09 +00002026 if (ReadyCycle < MinReadyCycle)
2027 MinReadyCycle = ReadyCycle;
2028
2029 // Check for interlocks first. For the purpose of other heuristics, an
2030 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002031 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002032 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2033 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002034 Pending.push(SU);
2035 else
2036 Available.push(SU);
2037}
2038
2039/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002040void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002041 if (SchedModel->getMicroOpBufferSize() == 0) {
2042 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
2043 if (MinReadyCycle > NextCycle)
2044 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002045 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002046 // Update the current micro-ops, which will issue in the next cycle.
2047 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2048 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2049
2050 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002051 if ((NextCycle - CurrCycle) > DependentLatency)
2052 DependentLatency = 0;
2053 else
2054 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002055
2056 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002057 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002058 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002059 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002060 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002061 for (; CurrCycle != NextCycle; ++CurrCycle) {
2062 if (isTop())
2063 HazardRec->AdvanceCycle();
2064 else
2065 HazardRec->RecedeCycle();
2066 }
2067 }
2068 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002069 unsigned LFactor = SchedModel->getLatencyFactor();
2070 IsResourceLimited =
2071 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2072 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00002073
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002074 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2075}
2076
Andrew Trickfc127d12013-12-07 05:59:44 +00002077void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002078 ExecutedResCounts[PIdx] += Count;
2079 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2080 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002081}
2082
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002083/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002084///
2085/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2086/// during which this resource is consumed.
2087///
2088/// \return the next cycle at which the instruction may execute without
2089/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002090unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002091countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002092 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002093 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002094 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002095 << " +" << Cycles << "x" << Factor << "u\n");
2096
2097 // Update Executed resources counts.
2098 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002099 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2100 Rem->RemainingCounts[PIdx] -= Count;
2101
Andrew Trickb13ef172013-07-19 00:20:07 +00002102 // Check if this resource exceeds the current critical resource. If so, it
2103 // becomes the critical resource.
2104 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002105 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002106 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002107 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002108 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002109 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002110 // For reserved resources, record the highest cycle using the resource.
2111 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2112 if (NextAvailable > CurrCycle) {
2113 DEBUG(dbgs() << " Resource conflict: "
2114 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2115 << NextAvailable << "\n");
2116 }
2117 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002118}
2119
Andrew Trick45446062012-06-05 21:11:27 +00002120/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002121void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002122 // Update the reservation table.
2123 if (HazardRec->isEnabled()) {
2124 if (!isTop() && SU->isCall) {
2125 // Calls are scheduled with their preceding instructions. For bottom-up
2126 // scheduling, clear the pipeline state before emitting.
2127 HazardRec->Reset();
2128 }
2129 HazardRec->EmitInstruction(SU);
2130 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002131 // checkHazard should prevent scheduling multiple instructions per cycle that
2132 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002133 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2134 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002135 assert(
2136 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002137 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002138
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002139 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2140 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2141
Andrew Trick5a22df42013-12-05 17:56:02 +00002142 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002143 switch (SchedModel->getMicroOpBufferSize()) {
2144 case 0:
2145 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2146 break;
2147 case 1:
2148 if (ReadyCycle > NextCycle) {
2149 NextCycle = ReadyCycle;
2150 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2151 }
2152 break;
2153 default:
2154 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002155 // scheduled MOps to be "retired". We do loosely model in-order resource
2156 // latency. If this instruction uses an in-order resource, account for any
2157 // likely stall cycles.
2158 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2159 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002160 break;
2161 }
2162 RetiredMOps += IncMOps;
2163
2164 // Update resource counts and critical resource.
2165 if (SchedModel->hasInstrSchedModel()) {
2166 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2167 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2168 Rem->RemIssueCount -= DecRemIssue;
2169 if (ZoneCritResIdx) {
2170 // Scale scheduled micro-ops for comparing with the critical resource.
2171 unsigned ScaledMOps =
2172 RetiredMOps * SchedModel->getMicroOpFactor();
2173
2174 // If scaled micro-ops are now more than the previous critical resource by
2175 // a full cycle, then micro-ops issue becomes critical.
2176 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2177 >= (int)SchedModel->getLatencyFactor()) {
2178 ZoneCritResIdx = 0;
2179 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2180 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2181 }
2182 }
2183 for (TargetSchedModel::ProcResIter
2184 PI = SchedModel->getWriteProcResBegin(SC),
2185 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2186 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002187 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002188 if (RCycle > NextCycle)
2189 NextCycle = RCycle;
2190 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002191 if (SU->hasReservedResource) {
2192 // For reserved resources, record the highest cycle using the resource.
2193 // For top-down scheduling, this is the cycle in which we schedule this
2194 // instruction plus the number of cycles the operations reserves the
2195 // resource. For bottom-up is it simply the instruction's cycle.
2196 for (TargetSchedModel::ProcResIter
2197 PI = SchedModel->getWriteProcResBegin(SC),
2198 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2199 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002200 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002201 if (isTop()) {
2202 ReservedCycles[PIdx] =
2203 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2204 }
2205 else
2206 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002207 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002208 }
2209 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002210 }
2211 // Update ExpectedLatency and DependentLatency.
2212 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2213 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2214 if (SU->getDepth() > TopLatency) {
2215 TopLatency = SU->getDepth();
2216 DEBUG(dbgs() << " " << Available.getName()
2217 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2218 }
2219 if (SU->getHeight() > BotLatency) {
2220 BotLatency = SU->getHeight();
2221 DEBUG(dbgs() << " " << Available.getName()
2222 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2223 }
2224 // If we stall for any reason, bump the cycle.
2225 if (NextCycle > CurrCycle) {
2226 bumpCycle(NextCycle);
Matthias Braunb550b762016-04-21 01:54:13 +00002227 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002228 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002229 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002230 unsigned LFactor = SchedModel->getLatencyFactor();
2231 IsResourceLimited =
2232 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2233 > (int)LFactor;
2234 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002235 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2236 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2237 // one cycle. Since we commonly reach the max MOps here, opportunistically
2238 // bump the cycle to avoid uselessly checking everything in the readyQ.
2239 CurrMOps += IncMOps;
2240 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002241 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2242 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002243 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002244 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002245 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002246}
2247
Andrew Trick61f1a272012-05-24 22:11:09 +00002248/// Release pending ready nodes in to the available queue. This makes them
2249/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002250void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002251 // If the available queue is empty, it is safe to reset MinReadyCycle.
2252 if (Available.empty())
2253 MinReadyCycle = UINT_MAX;
2254
2255 // Check to see if any of the pending instructions are ready to issue. If
2256 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002257 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002258 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2259 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002260 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002261
2262 if (ReadyCycle < MinReadyCycle)
2263 MinReadyCycle = ReadyCycle;
2264
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002265 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002266 continue;
2267
Andrew Trick8c9e6722012-06-29 03:23:24 +00002268 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002269 continue;
2270
Matthias Braun6493bc22016-04-22 19:09:17 +00002271 if (Available.size() >= ReadyListLimit)
2272 break;
2273
Andrew Trick61f1a272012-05-24 22:11:09 +00002274 Available.push(SU);
2275 Pending.remove(Pending.begin()+i);
2276 --i; --e;
2277 }
2278 CheckPending = false;
2279}
2280
2281/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002282void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002283 if (Available.isInQueue(SU))
2284 Available.remove(Available.find(SU));
2285 else {
2286 assert(Pending.isInQueue(SU) && "bad ready count");
2287 Pending.remove(Pending.find(SU));
2288 }
2289}
2290
2291/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002292/// defer any nodes that now hit a hazard, and advance the cycle until at least
2293/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002294SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002295 if (CheckPending)
2296 releasePending();
2297
Andrew Tricke2ff5752013-06-15 04:49:49 +00002298 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002299 // Defer any ready instrs that now have a hazard.
2300 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2301 if (checkHazard(*I)) {
2302 Pending.push(*I);
2303 I = Available.remove(I);
2304 continue;
2305 }
2306 ++I;
2307 }
2308 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002309 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002310// FIXME: Re-enable assert once PR20057 is resolved.
2311// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2312// "permanent hazard");
2313 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002314 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002315 releasePending();
2316 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002317
2318 DEBUG(Pending.dump());
2319 DEBUG(Available.dump());
2320
Andrew Trick61f1a272012-05-24 22:11:09 +00002321 if (Available.size() == 1)
2322 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002323 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002324}
2325
Andrew Trick8e8415f2013-06-15 05:46:47 +00002326#ifndef NDEBUG
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002327// This is useful information to dump after bumpNode.
2328// Note that the Queue contents are more useful before pickNodeFromQueue.
Andrew Trickfc127d12013-12-07 05:59:44 +00002329void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002330 unsigned ResFactor;
2331 unsigned ResCount;
2332 if (ZoneCritResIdx) {
2333 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2334 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002335 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002336 ResFactor = SchedModel->getMicroOpFactor();
2337 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002338 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002339 unsigned LFactor = SchedModel->getLatencyFactor();
2340 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2341 << " Retired: " << RetiredMOps;
2342 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2343 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002344 << ResCount / ResFactor << " "
2345 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002346 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2347 << (IsResourceLimited ? " - Resource" : " - Latency")
2348 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002349}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002350#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002351
Andrew Trickfc127d12013-12-07 05:59:44 +00002352//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002353// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002354//===----------------------------------------------------------------------===//
2355
Andrew Trickd14d7c22013-12-28 21:56:57 +00002356void GenericSchedulerBase::SchedCandidate::
2357initResourceDelta(const ScheduleDAGMI *DAG,
2358 const TargetSchedModel *SchedModel) {
2359 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2360 return;
2361
2362 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2363 for (TargetSchedModel::ProcResIter
2364 PI = SchedModel->getWriteProcResBegin(SC),
2365 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2366 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2367 ResDelta.CritResources += PI->Cycles;
2368 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2369 ResDelta.DemandedResources += PI->Cycles;
2370 }
2371}
2372
2373/// Set the CandPolicy given a scheduling zone given the current resources and
2374/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002375void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002376 SchedBoundary &CurrZone,
2377 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002378 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002379 // inside and outside this zone. Potential stalls should be considered before
2380 // following this policy.
2381
2382 // Compute remaining latency. We need this both to determine whether the
2383 // overall schedule has become latency-limited and whether the instructions
2384 // outside this zone are resource or latency limited.
2385 //
2386 // The "dependent" latency is updated incrementally during scheduling as the
2387 // max height/depth of scheduled nodes minus the cycles since it was
2388 // scheduled:
2389 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2390 //
2391 // The "independent" latency is the max ready queue depth:
2392 // ILat = max N.depth for N in Available|Pending
2393 //
2394 // RemainingLatency is the greater of independent and dependent latency.
2395 unsigned RemLatency = CurrZone.getDependentLatency();
2396 RemLatency = std::max(RemLatency,
2397 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2398 RemLatency = std::max(RemLatency,
2399 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2400
2401 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002402 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002403 unsigned OtherCount =
2404 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2405
2406 bool OtherResLimited = false;
2407 if (SchedModel->hasInstrSchedModel()) {
2408 unsigned LFactor = SchedModel->getLatencyFactor();
2409 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2410 }
2411 // Schedule aggressively for latency in PostRA mode. We don't check for
2412 // acyclic latency during PostRA, and highly out-of-order processors will
2413 // skip PostRA scheduling.
2414 if (!OtherResLimited) {
2415 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2416 Policy.ReduceLatency |= true;
2417 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2418 << " RemainingLatency " << RemLatency << " + "
2419 << CurrZone.getCurrCycle() << "c > CritPath "
2420 << Rem.CriticalPath << "\n");
2421 }
2422 }
2423 // If the same resource is limiting inside and outside the zone, do nothing.
2424 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2425 return;
2426
2427 DEBUG(
2428 if (CurrZone.isResourceLimited()) {
2429 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2430 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2431 << "\n";
2432 }
2433 if (OtherResLimited)
2434 dbgs() << " RemainingLimit: "
2435 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2436 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2437 dbgs() << " Latency limited both directions.\n");
2438
2439 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2440 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2441
2442 if (OtherResLimited)
2443 Policy.DemandResIdx = OtherCritIdx;
2444}
2445
2446#ifndef NDEBUG
2447const char *GenericSchedulerBase::getReasonStr(
2448 GenericSchedulerBase::CandReason Reason) {
2449 switch (Reason) {
2450 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002451 case Only1: return "ONLY1 ";
2452 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002453 case RegExcess: return "REG-EXCESS";
2454 case RegCritical: return "REG-CRIT ";
2455 case Stall: return "STALL ";
2456 case Cluster: return "CLUSTER ";
2457 case Weak: return "WEAK ";
2458 case RegMax: return "REG-MAX ";
2459 case ResourceReduce: return "RES-REDUCE";
2460 case ResourceDemand: return "RES-DEMAND";
2461 case TopDepthReduce: return "TOP-DEPTH ";
2462 case TopPathReduce: return "TOP-PATH ";
2463 case BotHeightReduce:return "BOT-HEIGHT";
2464 case BotPathReduce: return "BOT-PATH ";
2465 case NextDefUse: return "DEF-USE ";
2466 case NodeOrder: return "ORDER ";
2467 };
2468 llvm_unreachable("Unknown reason!");
2469}
2470
2471void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2472 PressureChange P;
2473 unsigned ResIdx = 0;
2474 unsigned Latency = 0;
2475 switch (Cand.Reason) {
2476 default:
2477 break;
2478 case RegExcess:
2479 P = Cand.RPDelta.Excess;
2480 break;
2481 case RegCritical:
2482 P = Cand.RPDelta.CriticalMax;
2483 break;
2484 case RegMax:
2485 P = Cand.RPDelta.CurrentMax;
2486 break;
2487 case ResourceReduce:
2488 ResIdx = Cand.Policy.ReduceResIdx;
2489 break;
2490 case ResourceDemand:
2491 ResIdx = Cand.Policy.DemandResIdx;
2492 break;
2493 case TopDepthReduce:
2494 Latency = Cand.SU->getDepth();
2495 break;
2496 case TopPathReduce:
2497 Latency = Cand.SU->getHeight();
2498 break;
2499 case BotHeightReduce:
2500 Latency = Cand.SU->getHeight();
2501 break;
2502 case BotPathReduce:
2503 Latency = Cand.SU->getDepth();
2504 break;
2505 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002506 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002507 if (P.isValid())
2508 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2509 << ":" << P.getUnitInc() << " ";
2510 else
2511 dbgs() << " ";
2512 if (ResIdx)
2513 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2514 else
2515 dbgs() << " ";
2516 if (Latency)
2517 dbgs() << " " << Latency << " cycles ";
2518 else
2519 dbgs() << " ";
2520 dbgs() << '\n';
2521}
2522#endif
2523
2524/// Return true if this heuristic determines order.
2525static bool tryLess(int TryVal, int CandVal,
2526 GenericSchedulerBase::SchedCandidate &TryCand,
2527 GenericSchedulerBase::SchedCandidate &Cand,
2528 GenericSchedulerBase::CandReason Reason) {
2529 if (TryVal < CandVal) {
2530 TryCand.Reason = Reason;
2531 return true;
2532 }
2533 if (TryVal > CandVal) {
2534 if (Cand.Reason > Reason)
2535 Cand.Reason = Reason;
2536 return true;
2537 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002538 return false;
2539}
2540
2541static bool tryGreater(int TryVal, int CandVal,
2542 GenericSchedulerBase::SchedCandidate &TryCand,
2543 GenericSchedulerBase::SchedCandidate &Cand,
2544 GenericSchedulerBase::CandReason Reason) {
2545 if (TryVal > CandVal) {
2546 TryCand.Reason = Reason;
2547 return true;
2548 }
2549 if (TryVal < CandVal) {
2550 if (Cand.Reason > Reason)
2551 Cand.Reason = Reason;
2552 return true;
2553 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002554 return false;
2555}
2556
2557static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2558 GenericSchedulerBase::SchedCandidate &Cand,
2559 SchedBoundary &Zone) {
2560 if (Zone.isTop()) {
2561 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2562 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2563 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2564 return true;
2565 }
2566 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2567 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2568 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002569 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002570 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2571 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2572 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2573 return true;
2574 }
2575 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2576 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2577 return true;
2578 }
2579 return false;
2580}
2581
Matthias Braun49cb6e92016-05-27 22:14:26 +00002582static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2583 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2584 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2585}
2586
Matthias Braun6ad3d052016-06-25 00:23:00 +00002587static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2588 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002589}
2590
Andrew Trickfc127d12013-12-07 05:59:44 +00002591void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002592 assert(dag->hasVRegLiveness() &&
2593 "(PreRA)GenericScheduler needs vreg liveness");
2594 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002595 SchedModel = DAG->getSchedModel();
2596 TRI = DAG->TRI;
2597
2598 Rem.init(DAG, SchedModel);
2599 Top.init(DAG, SchedModel, &Rem);
2600 Bot.init(DAG, SchedModel, &Rem);
2601
2602 // Initialize resource counts.
2603
2604 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2605 // are disabled, then these HazardRecs will be disabled.
2606 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002607 if (!Top.HazardRec) {
2608 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002609 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002610 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002611 }
2612 if (!Bot.HazardRec) {
2613 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002614 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002615 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002616 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002617 TopCand.SU = nullptr;
2618 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002619}
2620
2621/// Initialize the per-region scheduling policy.
2622void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2623 MachineBasicBlock::iterator End,
2624 unsigned NumRegionInstrs) {
Eric Christopher99556d72014-10-14 06:56:25 +00002625 const MachineFunction &MF = *Begin->getParent()->getParent();
2626 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002627
2628 // Avoid setting up the register pressure tracker for small regions to save
2629 // compile time. As a rough heuristic, only track pressure when the number of
2630 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002631 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002632 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2633 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2634 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002635 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002636 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002637 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2638 }
2639 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002640
2641 // For generic targets, we default to bottom-up, because it's simpler and more
2642 // compile-time optimizations have been implemented in that direction.
2643 RegionPolicy.OnlyBottomUp = true;
2644
2645 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002646 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002647
2648 // After subtarget overrides, apply command line options.
2649 if (!EnableRegPressure)
2650 RegionPolicy.ShouldTrackPressure = false;
2651
2652 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2653 // e.g. -misched-bottomup=false allows scheduling in both directions.
2654 assert((!ForceTopDown || !ForceBottomUp) &&
2655 "-misched-topdown incompatible with -misched-bottomup");
2656 if (ForceBottomUp.getNumOccurrences() > 0) {
2657 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2658 if (RegionPolicy.OnlyBottomUp)
2659 RegionPolicy.OnlyTopDown = false;
2660 }
2661 if (ForceTopDown.getNumOccurrences() > 0) {
2662 RegionPolicy.OnlyTopDown = ForceTopDown;
2663 if (RegionPolicy.OnlyTopDown)
2664 RegionPolicy.OnlyBottomUp = false;
2665 }
2666}
2667
James Y Knighte72b0db2015-09-18 18:52:20 +00002668void GenericScheduler::dumpPolicy() {
2669 dbgs() << "GenericScheduler RegionPolicy: "
2670 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2671 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2672 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2673 << "\n";
2674}
2675
Andrew Trickfc127d12013-12-07 05:59:44 +00002676/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2677/// critical path by more cycles than it takes to drain the instruction buffer.
2678/// We estimate an upper bounds on in-flight instructions as:
2679///
2680/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2681/// InFlightIterations = AcyclicPath / CyclesPerIteration
2682/// InFlightResources = InFlightIterations * LoopResources
2683///
2684/// TODO: Check execution resources in addition to IssueCount.
2685void GenericScheduler::checkAcyclicLatency() {
2686 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2687 return;
2688
2689 // Scaled number of cycles per loop iteration.
2690 unsigned IterCount =
2691 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2692 Rem.RemIssueCount);
2693 // Scaled acyclic critical path.
2694 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2695 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2696 unsigned InFlightCount =
2697 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2698 unsigned BufferLimit =
2699 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2700
2701 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2702
2703 DEBUG(dbgs() << "IssueCycles="
2704 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2705 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2706 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2707 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2708 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2709 if (Rem.IsAcyclicLatencyLimited)
2710 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2711}
2712
2713void GenericScheduler::registerRoots() {
2714 Rem.CriticalPath = DAG->ExitSU.getDepth();
2715
2716 // Some roots may not feed into ExitSU. Check all of them in case.
2717 for (std::vector<SUnit*>::const_iterator
2718 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2719 if ((*I)->getDepth() > Rem.CriticalPath)
2720 Rem.CriticalPath = (*I)->getDepth();
2721 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002722 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2723 if (DumpCriticalPathLength) {
2724 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2725 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002726
2727 if (EnableCyclicPath) {
2728 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2729 checkAcyclicLatency();
2730 }
2731}
2732
Andrew Trick1a831342013-08-30 03:49:48 +00002733static bool tryPressure(const PressureChange &TryP,
2734 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002735 GenericSchedulerBase::SchedCandidate &TryCand,
2736 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002737 GenericSchedulerBase::CandReason Reason,
2738 const TargetRegisterInfo *TRI,
2739 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002740 // If one candidate decreases and the other increases, go with it.
2741 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002742 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2743 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002744 return true;
2745 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002746 // Do not compare the magnitude of pressure changes between top and bottom
2747 // boundary.
2748 if (Cand.AtTop != TryCand.AtTop)
2749 return false;
2750
2751 // If both candidates affect the same set in the same boundary, go with the
2752 // smallest increase.
2753 unsigned TryPSet = TryP.getPSetOrMax();
2754 unsigned CandPSet = CandP.getPSetOrMax();
2755 if (TryPSet == CandPSet) {
2756 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2757 Reason);
2758 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002759
2760 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2761 std::numeric_limits<int>::max();
2762
2763 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2764 std::numeric_limits<int>::max();
2765
Andrew Trick401b6952013-07-25 07:26:35 +00002766 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002767 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002768 std::swap(TryRank, CandRank);
2769 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2770}
2771
Andrew Tricka7714a02012-11-12 19:40:10 +00002772static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2773 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2774}
2775
Andrew Tricke833e1c2013-04-13 06:07:40 +00002776/// Minimize physical register live ranges. Regalloc wants them adjacent to
2777/// their physreg def/use.
2778///
2779/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2780/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2781/// with the operation that produces or consumes the physreg. We'll do this when
2782/// regalloc has support for parallel copies.
2783static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2784 const MachineInstr *MI = SU->getInstr();
2785 if (!MI->isCopy())
2786 return 0;
2787
2788 unsigned ScheduledOper = isTop ? 1 : 0;
2789 unsigned UnscheduledOper = isTop ? 0 : 1;
2790 // If we have already scheduled the physreg produce/consumer, immediately
2791 // schedule the copy.
2792 if (TargetRegisterInfo::isPhysicalRegister(
2793 MI->getOperand(ScheduledOper).getReg()))
2794 return 1;
2795 // If the physreg is at the boundary, defer it. Otherwise schedule it
2796 // immediately to free the dependent. We can hoist the copy later.
2797 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2798 if (TargetRegisterInfo::isPhysicalRegister(
2799 MI->getOperand(UnscheduledOper).getReg()))
2800 return AtBoundary ? -1 : 1;
2801 return 0;
2802}
2803
Matthias Braun4f573772016-04-22 19:10:15 +00002804void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2805 bool AtTop,
2806 const RegPressureTracker &RPTracker,
2807 RegPressureTracker &TempTracker) {
2808 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002809 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002810 if (DAG->isTrackingPressure()) {
2811 if (AtTop) {
2812 TempTracker.getMaxDownwardPressureDelta(
2813 Cand.SU->getInstr(),
2814 Cand.RPDelta,
2815 DAG->getRegionCriticalPSets(),
2816 DAG->getRegPressure().MaxSetPressure);
2817 } else {
2818 if (VerifyScheduling) {
2819 TempTracker.getMaxUpwardPressureDelta(
2820 Cand.SU->getInstr(),
2821 &DAG->getPressureDiff(Cand.SU),
2822 Cand.RPDelta,
2823 DAG->getRegionCriticalPSets(),
2824 DAG->getRegPressure().MaxSetPressure);
2825 } else {
2826 RPTracker.getUpwardPressureDelta(
2827 Cand.SU->getInstr(),
2828 DAG->getPressureDiff(Cand.SU),
2829 Cand.RPDelta,
2830 DAG->getRegionCriticalPSets(),
2831 DAG->getRegPressure().MaxSetPressure);
2832 }
2833 }
2834 }
2835 DEBUG(if (Cand.RPDelta.Excess.isValid())
2836 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2837 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2838 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2839}
2840
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002841/// Apply a set of heursitics to a new candidate. Heuristics are currently
2842/// hierarchical. This may be more efficient than a graduated cost model because
2843/// we don't need to evaluate all aspects of the model for each node in the
2844/// queue. But it's really done to make the heuristics easier to debug and
2845/// statistically analyze.
2846///
2847/// \param Cand provides the policy and current best candidate.
2848/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002849/// \param Zone describes the scheduled zone that we are extending, or nullptr
2850// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002851void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002852 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002853 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002854 // Initialize the candidate if needed.
2855 if (!Cand.isValid()) {
2856 TryCand.Reason = NodeOrder;
2857 return;
2858 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002859
Matthias Braun6ad3d052016-06-25 00:23:00 +00002860 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2861 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002862 TryCand, Cand, PhysRegCopy))
2863 return;
2864
Andrew Tricke02d5da2015-05-17 23:40:27 +00002865 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002866 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2867 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002868 TryCand, Cand, RegExcess, TRI,
2869 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002870 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002871
2872 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002873 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2874 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002875 TryCand, Cand, RegCritical, TRI,
2876 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002877 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002878
Matthias Braun6ad3d052016-06-25 00:23:00 +00002879 // We only compare a subset of features when comparing nodes between
2880 // Top and Bottom boundary. Some properties are simply incomparable, in many
2881 // other instances we should only override the other boundary if something
2882 // is a clear good pick on one boundary. Skip heuristics that are more
2883 // "tie-breaking" in nature.
2884 bool SameBoundary = Zone != nullptr;
2885 if (SameBoundary) {
2886 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002887 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2888 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002889 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2890 tryLatency(TryCand, Cand, *Zone))
2891 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002892
Matthias Braun6ad3d052016-06-25 00:23:00 +00002893 // Prioritize instructions that read unbuffered resources by stall cycles.
2894 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2895 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2896 return;
2897 }
Andrew Trick880e5732013-12-05 17:55:58 +00002898
Andrew Tricka7714a02012-11-12 19:40:10 +00002899 // Keep clustered nodes together to encourage downstream peephole
2900 // optimizations which may reduce resource requirements.
2901 //
2902 // This is a best effort to set things up for a post-RA pass. Optimizations
2903 // like generating loads of multiple registers should ideally be done within
2904 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002905 const SUnit *CandNextClusterSU =
2906 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2907 const SUnit *TryCandNextClusterSU =
2908 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2909 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2910 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002911 TryCand, Cand, Cluster))
2912 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002913
Matthias Braun6ad3d052016-06-25 00:23:00 +00002914 if (SameBoundary) {
2915 // Weak edges are for clustering and other constraints.
2916 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2917 getWeakLeft(Cand.SU, Cand.AtTop),
2918 TryCand, Cand, Weak))
2919 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002920 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002921
Andrew Trick71f08a32013-06-17 21:45:13 +00002922 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002923 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2924 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002925 TryCand, Cand, RegMax, TRI,
2926 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002927 return;
2928
Matthias Braun6ad3d052016-06-25 00:23:00 +00002929 if (SameBoundary) {
2930 // Avoid critical resource consumption and balance the schedule.
2931 TryCand.initResourceDelta(DAG, SchedModel);
2932 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2933 TryCand, Cand, ResourceReduce))
2934 return;
2935 if (tryGreater(TryCand.ResDelta.DemandedResources,
2936 Cand.ResDelta.DemandedResources,
2937 TryCand, Cand, ResourceDemand))
2938 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002939
Matthias Braun6ad3d052016-06-25 00:23:00 +00002940 // Avoid serializing long latency dependence chains.
2941 // For acyclic path limited loops, latency was already checked above.
2942 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2943 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2944 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002945
Matthias Braun6ad3d052016-06-25 00:23:00 +00002946 // Fall through to original instruction order.
2947 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2948 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2949 TryCand.Reason = NodeOrder;
2950 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002951 }
2952}
Andrew Trick419eae22012-05-10 21:06:19 +00002953
Andrew Trickc573cd92013-09-06 17:32:44 +00002954/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002955///
2956/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2957/// DAG building. To adjust for the current scheduling location we need to
2958/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002959void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002960 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002961 const RegPressureTracker &RPTracker,
2962 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002963 // getMaxPressureDelta temporarily modifies the tracker.
2964 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2965
Matthias Braund29d31e2016-06-23 21:27:38 +00002966 ReadyQueue &Q = Zone.Available;
Andrew Trickdd375dd2012-05-24 22:11:03 +00002967 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002968
Matthias Braun6ad3d052016-06-25 00:23:00 +00002969 SchedCandidate TryCand(ZonePolicy);
Matthias Braun4f573772016-04-22 19:10:15 +00002970 initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00002971 // Pass SchedBoundary only when comparing nodes from the same boundary.
2972 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
2973 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002974 if (TryCand.Reason != NoCand) {
2975 // Initialize resource delta if needed in case future heuristics query it.
2976 if (TryCand.ResDelta == SchedResourceDelta())
2977 TryCand.initResourceDelta(DAG, SchedModel);
2978 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002979 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002980 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002981 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002982}
2983
Andrew Trick22025772012-05-17 18:35:10 +00002984/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002985SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002986 // Schedule as far as possible in the direction of no choice. This is most
2987 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002988 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002989 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002990 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002991 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002992 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002993 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002994 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002995 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002996 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002997 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002998 // Set the bottom-up policy based on the state of the current bottom zone and
2999 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003000 CandPolicy BotPolicy;
3001 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003002 // Set the top-down policy based on the state of the current top zone and
3003 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003004 CandPolicy TopPolicy;
3005 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003006
Matthias Brauncc676c42016-06-25 02:03:36 +00003007 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00003008 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003009 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3010 BotCand.Policy != BotPolicy) {
3011 BotCand.reset(CandPolicy());
3012 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3013 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3014 } else {
3015 DEBUG(traceCandidate(BotCand));
3016#ifndef NDEBUG
3017 if (VerifyScheduling) {
3018 SchedCandidate TCand;
3019 TCand.reset(CandPolicy());
3020 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3021 assert(TCand.SU == BotCand.SU &&
3022 "Last pick result should correspond to re-picking right now");
3023 }
3024#endif
3025 }
Andrew Trick22025772012-05-17 18:35:10 +00003026
Andrew Trick22025772012-05-17 18:35:10 +00003027 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003028 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003029 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3030 TopCand.Policy != TopPolicy) {
3031 TopCand.reset(CandPolicy());
3032 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3033 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3034 } else {
3035 DEBUG(traceCandidate(TopCand));
3036#ifndef NDEBUG
3037 if (VerifyScheduling) {
3038 SchedCandidate TCand;
3039 TCand.reset(CandPolicy());
3040 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3041 assert(TCand.SU == TopCand.SU &&
3042 "Last pick result should correspond to re-picking right now");
3043 }
3044#endif
3045 }
3046
3047 // Pick best from BotCand and TopCand.
3048 assert(BotCand.isValid());
3049 assert(TopCand.isValid());
3050 SchedCandidate Cand = BotCand;
3051 TopCand.Reason = NoCand;
3052 tryCandidate(Cand, TopCand, nullptr);
3053 if (TopCand.Reason != NoCand) {
3054 Cand.setBest(TopCand);
3055 DEBUG(traceCandidate(Cand));
3056 }
Andrew Trick22025772012-05-17 18:35:10 +00003057
Matthias Braun6ad3d052016-06-25 00:23:00 +00003058 IsTopNode = Cand.AtTop;
3059 tracePick(Cand);
3060 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003061}
3062
3063/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003064SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003065 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003066 assert(Top.Available.empty() && Top.Pending.empty() &&
3067 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003068 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003069 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003070 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003071 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003072 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003073 SU = Top.pickOnlyChoice();
3074 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003075 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003076 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003077 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003078 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003079 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003080 SU = TopCand.SU;
3081 }
3082 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003083 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003084 SU = Bot.pickOnlyChoice();
3085 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003086 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003087 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003088 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003089 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003090 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003091 SU = BotCand.SU;
3092 }
3093 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003094 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003095 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003096 }
3097 } while (SU->isScheduled);
3098
Andrew Trick61f1a272012-05-24 22:11:09 +00003099 if (SU->isTopReady())
3100 Top.removeReady(SU);
3101 if (SU->isBottomReady())
3102 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003103
Andrew Trick1f0bb692013-04-13 06:07:49 +00003104 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003105 return SU;
3106}
3107
Andrew Trick665d3ec2013-09-19 23:10:59 +00003108void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003109
3110 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3111 if (!isTop)
3112 ++InsertPos;
3113 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3114
3115 // Find already scheduled copies with a single physreg dependence and move
3116 // them just above the scheduled instruction.
3117 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3118 I != E; ++I) {
3119 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3120 continue;
3121 SUnit *DepSU = I->getSUnit();
3122 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3123 continue;
3124 MachineInstr *Copy = DepSU->getInstr();
3125 if (!Copy->isCopy())
3126 continue;
3127 DEBUG(dbgs() << " Rescheduling physreg copy ";
3128 I->getSUnit()->dump(DAG));
3129 DAG->moveInstruction(Copy, InsertPos);
3130 }
3131}
3132
Andrew Trick61f1a272012-05-24 22:11:09 +00003133/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003134/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3135/// update it's state based on the current cycle before MachineSchedStrategy
3136/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003137///
3138/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3139/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003140void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003141 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003142 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003143 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003144 if (SU->hasPhysRegUses)
3145 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003146 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003147 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003148 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003149 if (SU->hasPhysRegDefs)
3150 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003151 }
3152}
3153
Andrew Trick8823dec2012-03-14 04:00:41 +00003154/// Create the standard converging machine scheduler. This will be used as the
3155/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003156ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003157 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003158 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003159 //
3160 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3161 // data and pass it to later mutations. Have a single mutation that gathers
3162 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003163 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003164 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003165}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003166
Matthias Braun115efcd2016-11-28 20:11:54 +00003167static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3168 return createGenericSchedLive(C);
3169}
3170
Andrew Tricke1c034f2012-01-17 06:55:03 +00003171static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003172GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003173 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003174
3175//===----------------------------------------------------------------------===//
3176// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3177//===----------------------------------------------------------------------===//
3178
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003179void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3180 DAG = Dag;
3181 SchedModel = DAG->getSchedModel();
3182 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003183
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003184 Rem.init(DAG, SchedModel);
3185 Top.init(DAG, SchedModel, &Rem);
3186 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003187
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003188 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3189 // or are disabled, then these HazardRecs will be disabled.
3190 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003191 if (!Top.HazardRec) {
3192 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003193 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003194 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003195 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003196}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003197
Andrew Trickd14d7c22013-12-28 21:56:57 +00003198
3199void PostGenericScheduler::registerRoots() {
3200 Rem.CriticalPath = DAG->ExitSU.getDepth();
3201
3202 // Some roots may not feed into ExitSU. Check all of them in case.
3203 for (SmallVectorImpl<SUnit*>::const_iterator
3204 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3205 if ((*I)->getDepth() > Rem.CriticalPath)
3206 Rem.CriticalPath = (*I)->getDepth();
3207 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003208 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3209 if (DumpCriticalPathLength) {
3210 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3211 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003212}
3213
3214/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3215///
3216/// \param Cand provides the policy and current best candidate.
3217/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3218void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3219 SchedCandidate &TryCand) {
3220
3221 // Initialize the candidate if needed.
3222 if (!Cand.isValid()) {
3223 TryCand.Reason = NodeOrder;
3224 return;
3225 }
3226
3227 // Prioritize instructions that read unbuffered resources by stall cycles.
3228 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3229 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3230 return;
3231
3232 // Avoid critical resource consumption and balance the schedule.
3233 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3234 TryCand, Cand, ResourceReduce))
3235 return;
3236 if (tryGreater(TryCand.ResDelta.DemandedResources,
3237 Cand.ResDelta.DemandedResources,
3238 TryCand, Cand, ResourceDemand))
3239 return;
3240
3241 // Avoid serializing long latency dependence chains.
3242 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3243 return;
3244 }
3245
3246 // Fall through to original instruction order.
3247 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3248 TryCand.Reason = NodeOrder;
3249}
3250
3251void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3252 ReadyQueue &Q = Top.Available;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003253 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3254 SchedCandidate TryCand(Cand.Policy);
3255 TryCand.SU = *I;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003256 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003257 TryCand.initResourceDelta(DAG, SchedModel);
3258 tryCandidate(Cand, TryCand);
3259 if (TryCand.Reason != NoCand) {
3260 Cand.setBest(TryCand);
3261 DEBUG(traceCandidate(Cand));
3262 }
3263 }
3264}
3265
3266/// Pick the next node to schedule.
3267SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3268 if (DAG->top() == DAG->bottom()) {
3269 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003270 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003271 }
3272 SUnit *SU;
3273 do {
3274 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003275 if (SU) {
3276 tracePick(Only1, true);
3277 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003278 CandPolicy NoPolicy;
3279 SchedCandidate TopCand(NoPolicy);
3280 // Set the top-down policy based on the state of the current top zone and
3281 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003282 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003283 pickNodeFromQueue(TopCand);
3284 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003285 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003286 SU = TopCand.SU;
3287 }
3288 } while (SU->isScheduled);
3289
3290 IsTopNode = true;
3291 Top.removeReady(SU);
3292
3293 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3294 return SU;
3295}
3296
3297/// Called after ScheduleDAGMI has scheduled an instruction and updated
3298/// scheduled/remaining flags in the DAG nodes.
3299void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3300 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3301 Top.bumpNode(SU);
3302}
3303
Matthias Braun115efcd2016-11-28 20:11:54 +00003304ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Jonas Paulsson28f29482016-11-09 09:59:27 +00003305 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C),
3306 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003307}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003308
3309//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003310// ILP Scheduler. Currently for experimental analysis of heuristics.
3311//===----------------------------------------------------------------------===//
3312
3313namespace {
3314/// \brief Order nodes by the ILP metric.
3315struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00003316 const SchedDFSResult *DFSResult;
3317 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00003318 bool MaximizeILP;
3319
Craig Topperc0196b12014-04-14 00:51:57 +00003320 ILPOrder(bool MaxILP)
3321 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003322
3323 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003324 ///
3325 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003326 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003327 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3328 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3329 if (SchedTreeA != SchedTreeB) {
3330 // Unscheduled trees have lower priority.
3331 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3332 return ScheduledTrees->test(SchedTreeB);
3333
3334 // Trees with shallower connections have have lower priority.
3335 if (DFSResult->getSubtreeLevel(SchedTreeA)
3336 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3337 return DFSResult->getSubtreeLevel(SchedTreeA)
3338 < DFSResult->getSubtreeLevel(SchedTreeB);
3339 }
3340 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003341 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003342 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003343 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003344 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003345 }
3346};
3347
3348/// \brief Schedule based on the ILP metric.
3349class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003350 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00003351 ILPOrder Cmp;
3352
3353 std::vector<SUnit*> ReadyQ;
3354public:
Craig Topperc0196b12014-04-14 00:51:57 +00003355 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003356
Craig Topper4584cd52014-03-07 09:26:03 +00003357 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003358 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3359 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003360 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003361 Cmp.DFSResult = DAG->getDFSResult();
3362 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003363 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003364 }
3365
Craig Topper4584cd52014-03-07 09:26:03 +00003366 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003367 // Restore the heap in ReadyQ with the updated DFS results.
3368 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003369 }
3370
3371 /// Implement MachineSchedStrategy interface.
3372 /// -----------------------------------------
3373
Andrew Trick48d392e2012-11-28 05:13:28 +00003374 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003375 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003376 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003377 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003378 SUnit *SU = ReadyQ.back();
3379 ReadyQ.pop_back();
3380 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003381 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003382 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3383 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3384 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003385 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3386 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003387 return SU;
3388 }
3389
Andrew Trick44f750a2013-01-25 04:01:04 +00003390 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003391 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003392 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3393 }
3394
Andrew Trick48d392e2012-11-28 05:13:28 +00003395 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3396 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003397 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003398 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003399 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003400
Craig Topper4584cd52014-03-07 09:26:03 +00003401 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003402
Craig Topper4584cd52014-03-07 09:26:03 +00003403 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003404 ReadyQ.push_back(SU);
3405 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3406 }
3407};
3408} // namespace
3409
3410static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003411 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003412}
3413static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003414 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003415}
3416static MachineSchedRegistry ILPMaxRegistry(
3417 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3418static MachineSchedRegistry ILPMinRegistry(
3419 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3420
3421//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003422// Machine Instruction Shuffler for Correctness Testing
3423//===----------------------------------------------------------------------===//
3424
Andrew Tricke77e84e2012-01-13 06:30:30 +00003425#ifndef NDEBUG
3426namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003427/// Apply a less-than relation on the node order, which corresponds to the
3428/// instruction order prior to scheduling. IsReverse implements greater-than.
3429template<bool IsReverse>
3430struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003431 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003432 if (IsReverse)
3433 return A->NodeNum > B->NodeNum;
3434 else
3435 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003436 }
3437};
3438
Andrew Tricke77e84e2012-01-13 06:30:30 +00003439/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003440class InstructionShuffler : public MachineSchedStrategy {
3441 bool IsAlternating;
3442 bool IsTopDown;
3443
3444 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3445 // gives nodes with a higher number higher priority causing the latest
3446 // instructions to be scheduled first.
3447 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3448 TopQ;
3449 // When scheduling bottom-up, use greater-than as the queue priority.
3450 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3451 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003452public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003453 InstructionShuffler(bool alternate, bool topdown)
3454 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003455
Craig Topper9d74a5a2014-04-29 07:58:41 +00003456 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003457 TopQ.clear();
3458 BottomQ.clear();
3459 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003460
Andrew Trick8823dec2012-03-14 04:00:41 +00003461 /// Implement MachineSchedStrategy interface.
3462 /// -----------------------------------------
3463
Craig Topper9d74a5a2014-04-29 07:58:41 +00003464 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003465 SUnit *SU;
3466 if (IsTopDown) {
3467 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003468 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003469 SU = TopQ.top();
3470 TopQ.pop();
3471 } while (SU->isScheduled);
3472 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003473 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003474 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003475 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003476 SU = BottomQ.top();
3477 BottomQ.pop();
3478 } while (SU->isScheduled);
3479 IsTopNode = false;
3480 }
3481 if (IsAlternating)
3482 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003483 return SU;
3484 }
3485
Craig Topper9d74a5a2014-04-29 07:58:41 +00003486 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003487
Craig Topper9d74a5a2014-04-29 07:58:41 +00003488 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003489 TopQ.push(SU);
3490 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003491 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003492 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003493 }
3494};
3495} // namespace
3496
Andrew Trick02a80da2012-03-08 01:41:12 +00003497static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003498 bool Alternate = !ForceTopDown && !ForceBottomUp;
3499 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003500 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003501 "-misched-topdown incompatible with -misched-bottomup");
David Blaikie422b93d2014-04-21 20:32:32 +00003502 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003503}
Andrew Trick8823dec2012-03-14 04:00:41 +00003504static MachineSchedRegistry ShufflerRegistry(
3505 "shuffle", "Shuffle machine instructions alternating directions",
3506 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003507#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003508
3509//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003510// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003511//===----------------------------------------------------------------------===//
3512
3513#ifndef NDEBUG
3514namespace llvm {
3515
3516template<> struct GraphTraits<
3517 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3518
3519template<>
3520struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3521
3522 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3523
3524 static std::string getGraphName(const ScheduleDAG *G) {
3525 return G->MF.getName();
3526 }
3527
3528 static bool renderGraphFromBottomUp() {
3529 return true;
3530 }
3531
3532 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003533 if (ViewMISchedCutoff == 0)
3534 return false;
3535 return (Node->Preds.size() > ViewMISchedCutoff
3536 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003537 }
3538
Andrew Trickea9fd952013-01-25 07:45:29 +00003539 /// If you want to override the dot attributes printed for a particular
3540 /// edge, override this method.
3541 static std::string getEdgeAttributes(const SUnit *Node,
3542 SUnitIterator EI,
3543 const ScheduleDAG *Graph) {
3544 if (EI.isArtificialDep())
3545 return "color=cyan,style=dashed";
3546 if (EI.isCtrlDep())
3547 return "color=blue,style=dashed";
3548 return "";
3549 }
3550
3551 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003552 std::string Str;
3553 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003554 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3555 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003556 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003557 SS << "SU:" << SU->NodeNum;
3558 if (DFS)
3559 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003560 return SS.str();
3561 }
3562 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3563 return G->getGraphNodeLabel(SU);
3564 }
3565
Andrew Trickd7f890e2013-12-28 21:56:47 +00003566 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003567 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003568 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3569 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003570 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003571 if (DFS) {
3572 Str += ",style=filled,fillcolor=\"#";
3573 Str += DOT::getColorString(DFS->getSubtreeID(N));
3574 Str += '"';
3575 }
3576 return Str;
3577 }
3578};
3579} // namespace llvm
3580#endif // NDEBUG
3581
3582/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3583/// rendered using 'dot'.
3584///
3585void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3586#ifndef NDEBUG
3587 ViewGraph(this, Name, false, Title);
3588#else
3589 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3590 << "systems with Graphviz or gv!\n";
3591#endif // NDEBUG
3592}
3593
3594/// Out-of-line implementation with no arguments is handy for gdb.
3595void ScheduleDAGMI::viewGraph() {
3596 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3597}