blob: ad3603e9c9e40d0ec36585aea83368c6d705f040 [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
Matthias Braun8c209aa2017-01-28 02:02:38 +0000507#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
508LLVM_DUMP_METHOD void 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}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000514#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000515
516//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000517// ScheduleDAGMI - Basic machine instruction scheduling. This is
518// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
519// virtual registers.
520// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000521
David Blaikie422b93d2014-04-21 20:32:32 +0000522// Provide a vtable anchor.
Andrew Trick44f750a2013-01-25 04:01:04 +0000523ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000524}
525
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000526bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
527 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
528}
529
Andrew Tricka7714a02012-11-12 19:40:10 +0000530bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000531 if (SuccSU != &ExitSU) {
532 // Do not use WillCreateCycle, it assumes SD scheduling.
533 // If Pred is reachable from Succ, then the edge creates a cycle.
534 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
535 return false;
536 Topo.AddPred(SuccSU, PredDep.getSUnit());
537 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000538 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
539 // Return true regardless of whether a new edge needed to be inserted.
540 return true;
541}
542
Andrew Trick02a80da2012-03-08 01:41:12 +0000543/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
544/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000545///
546/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000547void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000548 SUnit *SuccSU = SuccEdge->getSUnit();
549
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000550 if (SuccEdge->isWeak()) {
551 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000552 if (SuccEdge->isCluster())
553 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000554 return;
555 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000556#ifndef NDEBUG
557 if (SuccSU->NumPredsLeft == 0) {
558 dbgs() << "*** Scheduling failed! ***\n";
559 SuccSU->dump(this);
560 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000561 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000562 }
563#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000564 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
565 // CurrCycle may have advanced since then.
566 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
567 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
568
Andrew Trick02a80da2012-03-08 01:41:12 +0000569 --SuccSU->NumPredsLeft;
570 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000571 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000572}
573
574/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000575void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000576 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
577 I != E; ++I) {
578 releaseSucc(SU, &*I);
579 }
580}
581
Andrew Trick8823dec2012-03-14 04:00:41 +0000582/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
583/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000584///
585/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000586void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
587 SUnit *PredSU = PredEdge->getSUnit();
588
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000589 if (PredEdge->isWeak()) {
590 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000591 if (PredEdge->isCluster())
592 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000593 return;
594 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000595#ifndef NDEBUG
596 if (PredSU->NumSuccsLeft == 0) {
597 dbgs() << "*** Scheduling failed! ***\n";
598 PredSU->dump(this);
599 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000600 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000601 }
602#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000603 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
604 // CurrCycle may have advanced since then.
605 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
606 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
607
Andrew Trick8823dec2012-03-14 04:00:41 +0000608 --PredSU->NumSuccsLeft;
609 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
610 SchedImpl->releaseBottomNode(PredSU);
611}
612
613/// releasePredecessors - Call releasePred on each of SU's predecessors.
614void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
615 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
616 I != E; ++I) {
617 releasePred(SU, &*I);
618 }
619}
620
Andrew Trickd7f890e2013-12-28 21:56:47 +0000621/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
622/// crossing a scheduling boundary. [begin, end) includes all instructions in
623/// the region, including the boundary itself and single-instruction regions
624/// that don't get scheduled.
625void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
626 MachineBasicBlock::iterator begin,
627 MachineBasicBlock::iterator end,
628 unsigned regioninstrs)
629{
630 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
631
632 SchedImpl->initPolicy(begin, end, regioninstrs);
633}
634
Andrew Tricke833e1c2013-04-13 06:07:40 +0000635/// This is normally called from the main scheduler loop but may also be invoked
636/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000637void ScheduleDAGMI::moveInstruction(
638 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000639 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000640 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000641 ++RegionBegin;
642
643 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000644 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000645
646 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000647 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000648 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000649
650 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000651 if (RegionBegin == InsertPos)
652 RegionBegin = MI;
653}
654
Andrew Trickde670c02012-03-21 04:12:07 +0000655bool ScheduleDAGMI::checkSchedLimit() {
656#ifndef NDEBUG
657 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
658 CurrentTop = CurrentBottom;
659 return false;
660 }
661 ++NumInstrsScheduled;
662#endif
663 return true;
664}
665
Andrew Trickd7f890e2013-12-28 21:56:47 +0000666/// Per-region scheduling driver, called back from
667/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
668/// does not consider liveness or register pressure. It is useful for PostRA
669/// scheduling and potentially other custom schedulers.
670void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000671 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
672 DEBUG(SchedImpl->dumpPolicy());
673
Andrew Trickd7f890e2013-12-28 21:56:47 +0000674 // Build the DAG.
675 buildSchedGraph(AA);
676
677 Topo.InitDAGTopologicalSorting();
678
679 postprocessDAG();
680
681 SmallVector<SUnit*, 8> TopRoots, BotRoots;
682 findRootsAndBiasEdges(TopRoots, BotRoots);
683
684 // Initialize the strategy before modifying the DAG.
685 // This may initialize a DFSResult to be used for queue priority.
686 SchedImpl->initialize(this);
687
Matthias Braun69f1d122016-11-11 22:37:28 +0000688 DEBUG(
689 if (EntrySU.getInstr() != nullptr)
690 EntrySU.dumpAll(this);
691 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
692 SUnits[su].dumpAll(this);
693 if (ExitSU.getInstr() != nullptr)
694 ExitSU.dumpAll(this);
695 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000696 if (ViewMISchedDAGs) viewGraph();
697
698 // Initialize ready queues now that the DAG and priority data are finalized.
699 initQueues(TopRoots, BotRoots);
700
701 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000702 while (true) {
703 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
704 SUnit *SU = SchedImpl->pickNode(IsTopNode);
705 if (!SU) break;
706
Andrew Trickd7f890e2013-12-28 21:56:47 +0000707 assert(!SU->isScheduled && "Node already scheduled");
708 if (!checkSchedLimit())
709 break;
710
711 MachineInstr *MI = SU->getInstr();
712 if (IsTopNode) {
713 assert(SU->isTopReady() && "node still has unscheduled dependencies");
714 if (&*CurrentTop == MI)
715 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
716 else
717 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000718 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000719 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
720 MachineBasicBlock::iterator priorII =
721 priorNonDebug(CurrentBottom, CurrentTop);
722 if (&*priorII == MI)
723 CurrentBottom = priorII;
724 else {
725 if (&*CurrentTop == MI)
726 CurrentTop = nextIfDebug(++CurrentTop, priorII);
727 moveInstruction(MI, CurrentBottom);
728 CurrentBottom = MI;
729 }
730 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000731 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000732 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000733 // runs, it can then use the accurate ReadyCycle time to determine whether
734 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000735 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000736
737 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000738 }
739 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
740
741 placeDebugValues();
742
743 DEBUG({
744 unsigned BBNum = begin()->getParent()->getNumber();
745 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
746 dumpSchedule();
747 dbgs() << '\n';
748 });
749}
750
751/// Apply each ScheduleDAGMutation step in order.
752void ScheduleDAGMI::postprocessDAG() {
753 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
754 Mutations[i]->apply(this);
755 }
756}
757
758void ScheduleDAGMI::
759findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
760 SmallVectorImpl<SUnit*> &BotRoots) {
761 for (std::vector<SUnit>::iterator
762 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
763 SUnit *SU = &(*I);
764 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
765
766 // Order predecessors so DFSResult follows the critical path.
767 SU->biasCriticalPath();
768
769 // A SUnit is ready to top schedule if it has no predecessors.
770 if (!I->NumPredsLeft)
771 TopRoots.push_back(SU);
772 // A SUnit is ready to bottom schedule if it has no successors.
773 if (!I->NumSuccsLeft)
774 BotRoots.push_back(SU);
775 }
776 ExitSU.biasCriticalPath();
777}
778
779/// Identify DAG roots and setup scheduler queues.
780void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
781 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000782 NextClusterSucc = nullptr;
783 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000784
785 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
786 //
787 // Nodes with unreleased weak edges can still be roots.
788 // Release top roots in forward order.
789 for (SmallVectorImpl<SUnit*>::const_iterator
790 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
791 SchedImpl->releaseTopNode(*I);
792 }
793 // Release bottom roots in reverse order so the higher priority nodes appear
794 // first. This is more natural and slightly more efficient.
795 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
796 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
797 SchedImpl->releaseBottomNode(*I);
798 }
799
800 releaseSuccessors(&EntrySU);
801 releasePredecessors(&ExitSU);
802
803 SchedImpl->registerRoots();
804
805 // Advance past initial DebugValues.
806 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
807 CurrentBottom = RegionEnd;
808}
809
810/// Update scheduler queues after scheduling an instruction.
811void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
812 // Release dependent instructions for scheduling.
813 if (IsTopNode)
814 releaseSuccessors(SU);
815 else
816 releasePredecessors(SU);
817
818 SU->isScheduled = true;
819}
820
821/// Reinsert any remaining debug_values, just like the PostRA scheduler.
822void ScheduleDAGMI::placeDebugValues() {
823 // If first instruction was a DBG_VALUE then put it back.
824 if (FirstDbgValue) {
825 BB->splice(RegionBegin, BB, FirstDbgValue);
826 RegionBegin = FirstDbgValue;
827 }
828
829 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
830 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000831 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000832 MachineInstr *DbgValue = P.first;
833 MachineBasicBlock::iterator OrigPrevMI = P.second;
834 if (&*RegionBegin == DbgValue)
835 ++RegionBegin;
836 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000837 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000838 RegionEnd = DbgValue;
839 }
840 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000841 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000842}
843
844#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000845LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000846 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
847 if (SUnit *SU = getSUnit(&(*MI)))
848 SU->dump(this);
849 else
850 dbgs() << "Missing SUnit\n";
851 }
852}
853#endif
854
855//===----------------------------------------------------------------------===//
856// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
857// preservation.
858//===----------------------------------------------------------------------===//
859
860ScheduleDAGMILive::~ScheduleDAGMILive() {
861 delete DFSResult;
862}
863
Matthias Braun40639882016-11-11 22:37:31 +0000864void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
865 const MachineInstr &MI = *SU.getInstr();
866 for (const MachineOperand &MO : MI.operands()) {
867 if (!MO.isReg())
868 continue;
869 if (!MO.readsReg())
870 continue;
871 if (TrackLaneMasks && !MO.isUse())
872 continue;
873
874 unsigned Reg = MO.getReg();
875 if (!TargetRegisterInfo::isVirtualRegister(Reg))
876 continue;
877
878 // Ignore re-defs.
879 if (TrackLaneMasks) {
880 bool FoundDef = false;
881 for (const MachineOperand &MO2 : MI.operands()) {
882 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
883 FoundDef = true;
884 break;
885 }
886 }
887 if (FoundDef)
888 continue;
889 }
890
891 // Record this local VReg use.
892 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
893 for (; UI != VRegUses.end(); ++UI) {
894 if (UI->SU == &SU)
895 break;
896 }
897 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000898 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000899 }
900}
901
Andrew Trick88639922012-04-24 17:56:43 +0000902/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
903/// crossing a scheduling boundary. [begin, end) includes all instructions in
904/// the region, including the boundary itself and single-instruction regions
905/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000906void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000907 MachineBasicBlock::iterator begin,
908 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000909 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000910{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000911 // ScheduleDAGMI initializes SchedImpl's per-region policy.
912 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000913
914 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000915 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000916
Andrew Trickb248b4a2013-09-06 17:32:47 +0000917 SUPressureDiffs.clear();
918
Andrew Trick75e411c2013-09-06 17:32:34 +0000919 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000920 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
921
Matthias Braunf9acaca2016-05-31 22:38:06 +0000922 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
923 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000924}
925
926// Setup the register pressure trackers for the top scheduled top and bottom
927// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000928void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +0000929 VRegUses.clear();
930 VRegUses.setUniverse(MRI.getNumVirtRegs());
931 for (SUnit &SU : SUnits)
932 collectVRegUses(SU);
933
Matthias Braund4f64092016-01-20 00:23:32 +0000934 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
935 ShouldTrackLaneMasks, false);
936 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
937 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +0000938
939 // Close the RPTracker to finalize live ins.
940 RPTracker.closeRegion();
941
Andrew Trick9c17eab2013-07-30 19:59:12 +0000942 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000943
Andrew Trick4add42f2012-05-10 21:06:10 +0000944 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +0000945 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
946 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000947
948 // Close one end of the tracker so we can call
949 // getMaxUpward/DownwardPressureDelta before advancing across any
950 // instructions. This converts currently live regs into live ins/outs.
951 TopRPTracker.closeTop();
952 BotRPTracker.closeBottom();
953
Andrew Trick9c17eab2013-07-30 19:59:12 +0000954 BotRPTracker.initLiveThru(RPTracker);
955 if (!BotRPTracker.getLiveThru().empty()) {
956 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
957 DEBUG(dbgs() << "Live Thru: ";
958 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
959 };
960
Andrew Trick2bc74c22013-08-30 04:36:57 +0000961 // For each live out vreg reduce the pressure change associated with other
962 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +0000963 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +0000964
Andrew Trick4add42f2012-05-10 21:06:10 +0000965 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000966 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +0000967 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +0000968 BotRPTracker.recede(&LiveUses);
969 updatePressureDiffs(LiveUses);
970 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000971
Matthias Braune6edd482015-11-13 22:30:31 +0000972 DEBUG(
973 dbgs() << "Top Pressure:\n";
974 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
975 dbgs() << "Bottom Pressure:\n";
976 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
977 );
978
Andrew Trick4add42f2012-05-10 21:06:10 +0000979 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000980
981 // Cache the list of excess pressure sets in this region. This will also track
982 // the max pressure in the scheduled code for these sets.
983 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000984 const std::vector<unsigned> &RegionPressure =
985 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000986 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000987 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000988 if (RegionPressure[i] > Limit) {
989 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
990 << " Limit " << Limit
991 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000992 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000993 }
Andrew Trick22025772012-05-17 18:35:10 +0000994 }
995 DEBUG(dbgs() << "Excess PSets: ";
996 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
997 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000998 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000999 dbgs() << "\n");
1000}
1001
Andrew Trickd7f890e2013-12-28 21:56:47 +00001002void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001003updateScheduledPressure(const SUnit *SU,
1004 const std::vector<unsigned> &NewMaxPressure) {
1005 const PressureDiff &PDiff = getPressureDiff(SU);
1006 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1007 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
1008 I != E; ++I) {
1009 if (!I->isValid())
1010 break;
1011 unsigned ID = I->getPSet();
1012 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1013 ++CritIdx;
1014 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1015 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1016 && NewMaxPressure[ID] <= INT16_MAX)
1017 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1018 }
1019 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1020 if (NewMaxPressure[ID] >= Limit - 2) {
1021 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001022 << NewMaxPressure[ID]
1023 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1024 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001025 }
Andrew Trick22025772012-05-17 18:35:10 +00001026 }
Andrew Trick88639922012-04-24 17:56:43 +00001027}
1028
Andrew Trick2bc74c22013-08-30 04:36:57 +00001029/// Update the PressureDiff array for liveness after scheduling this
1030/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001031void ScheduleDAGMILive::updatePressureDiffs(
1032 ArrayRef<RegisterMaskPair> LiveUses) {
1033 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001034 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001035 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001036 if (!TRI->isVirtualRegister(Reg))
1037 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001038
Matthias Braund4f64092016-01-20 00:23:32 +00001039 if (ShouldTrackLaneMasks) {
1040 // If the register has just become live then other uses won't change
1041 // this fact anymore => decrement pressure.
1042 // If the register has just become dead then other uses make it come
1043 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001044 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001045
1046 for (const VReg2SUnit &V2SU
1047 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1048 SUnit &SU = *V2SU.SU;
1049 if (SU.isScheduled || &SU == &ExitSU)
1050 continue;
1051
1052 PressureDiff &PDiff = getPressureDiff(&SU);
1053 PDiff.addPressureChange(Reg, Decrement, &MRI);
1054 DEBUG(
1055 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1056 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1057 << ' ' << *SU.getInstr();
1058 dbgs() << " to ";
1059 PDiff.dump(*TRI);
1060 );
1061 }
1062 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001063 assert(P.LaneMask.any());
Matthias Braund4f64092016-01-20 00:23:32 +00001064 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1065 // This may be called before CurrentBottom has been initialized. However,
1066 // BotRPTracker must have a valid position. We want the value live into the
1067 // instruction or live out of the block, so ask for the previous
1068 // instruction's live-out.
1069 const LiveInterval &LI = LIS->getInterval(Reg);
1070 VNInfo *VNI;
1071 MachineBasicBlock::const_iterator I =
1072 nextIfDebug(BotRPTracker.getPos(), BB->end());
1073 if (I == BB->end())
1074 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1075 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001076 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001077 VNI = LRQ.valueIn();
1078 }
1079 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1080 assert(VNI && "No live value at use.");
1081 for (const VReg2SUnit &V2SU
1082 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1083 SUnit *SU = V2SU.SU;
1084 // If this use comes before the reaching def, it cannot be a last use,
1085 // so decrease its pressure change.
1086 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001087 LiveQueryResult LRQ =
1088 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001089 if (LRQ.valueIn() == VNI) {
1090 PressureDiff &PDiff = getPressureDiff(SU);
1091 PDiff.addPressureChange(Reg, true, &MRI);
1092 DEBUG(
1093 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1094 << *SU->getInstr();
1095 dbgs() << " to ";
1096 PDiff.dump(*TRI);
1097 );
1098 }
Matthias Braun9198c672015-11-06 20:59:02 +00001099 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001100 }
1101 }
1102 }
1103}
1104
Andrew Trick8823dec2012-03-14 04:00:41 +00001105/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001106/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1107/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001108///
1109/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001110/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001111/// implementing MachineSchedStrategy should be sufficient to implement a new
1112/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001113/// ScheduleDAGMILive then it will want to override this virtual method in order
1114/// to update any specialized state.
1115void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001116 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1117 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001118 buildDAGWithRegPressure();
1119
Andrew Tricka7714a02012-11-12 19:40:10 +00001120 Topo.InitDAGTopologicalSorting();
1121
Andrew Tricka2733e92012-09-14 17:22:42 +00001122 postprocessDAG();
1123
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001124 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1125 findRootsAndBiasEdges(TopRoots, BotRoots);
1126
1127 // Initialize the strategy before modifying the DAG.
1128 // This may initialize a DFSResult to be used for queue priority.
1129 SchedImpl->initialize(this);
1130
Matthias Braun9198c672015-11-06 20:59:02 +00001131 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001132 if (EntrySU.getInstr() != nullptr)
1133 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001134 for (const SUnit &SU : SUnits) {
1135 SU.dumpAll(this);
1136 if (ShouldTrackPressure) {
1137 dbgs() << " Pressure Diff : ";
1138 getPressureDiff(&SU).dump(*TRI);
1139 }
1140 dbgs() << '\n';
1141 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001142 if (ExitSU.getInstr() != nullptr)
1143 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001144 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001145 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001146
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001147 // Initialize ready queues now that the DAG and priority data are finalized.
1148 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001149
1150 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001151 while (true) {
1152 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1153 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1154 if (!SU) break;
1155
Andrew Trick984d98b2012-10-08 18:53:53 +00001156 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001157 if (!checkSchedLimit())
1158 break;
1159
1160 scheduleMI(SU, IsTopNode);
1161
Andrew Trickd7f890e2013-12-28 21:56:47 +00001162 if (DFSResult) {
1163 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1164 if (!ScheduledTrees.test(SubtreeID)) {
1165 ScheduledTrees.set(SubtreeID);
1166 DFSResult->scheduleTree(SubtreeID);
1167 SchedImpl->scheduleTree(SubtreeID);
1168 }
1169 }
1170
1171 // Notify the scheduling strategy after updating the DAG.
1172 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001173
1174 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001175 }
1176 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1177
1178 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001179
1180 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001181 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001182 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1183 dumpSchedule();
1184 dbgs() << '\n';
1185 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001186}
1187
1188/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001189void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001190 if (!ShouldTrackPressure) {
1191 RPTracker.reset();
1192 RegionCriticalPSets.clear();
1193 buildSchedGraph(AA);
1194 return;
1195 }
1196
Andrew Trick4add42f2012-05-10 21:06:10 +00001197 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001198 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001199 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001200
Andrew Trick4add42f2012-05-10 21:06:10 +00001201 // Account for liveness generate by the region boundary.
1202 if (LiveRegionEnd != RegionEnd)
1203 RPTracker.recede();
1204
1205 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001206 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001207
Andrew Trick4add42f2012-05-10 21:06:10 +00001208 // Initialize top/bottom trackers after computing region pressure.
1209 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001210}
Andrew Trick4add42f2012-05-10 21:06:10 +00001211
Andrew Trickd7f890e2013-12-28 21:56:47 +00001212void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001213 if (!DFSResult)
1214 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1215 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001216 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001217 DFSResult->resize(SUnits.size());
1218 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001219 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1220}
1221
Andrew Trick483f4192013-08-29 18:04:49 +00001222/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1223/// only provides the critical path for single block loops. To handle loops that
1224/// span blocks, we could use the vreg path latencies provided by
1225/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1226/// available for use in the scheduler.
1227///
1228/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001229/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001230/// the following instruction sequence where each instruction has unit latency
1231/// and defines an epomymous virtual register:
1232///
1233/// a->b(a,c)->c(b)->d(c)->exit
1234///
1235/// The cyclic critical path is a two cycles: b->c->b
1236/// The acyclic critical path is four cycles: a->b->c->d->exit
1237/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1238/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1239/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1240/// LiveInDepth = depth(b) = len(a->b) = 1
1241///
1242/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1243/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1244/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001245///
1246/// This could be relevant to PostRA scheduling, but is currently implemented
1247/// assuming LiveIntervals.
1248unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001249 // This only applies to single block loop.
1250 if (!BB->isSuccessor(BB))
1251 return 0;
1252
1253 unsigned MaxCyclicLatency = 0;
1254 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001255 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1256 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001257 if (!TRI->isVirtualRegister(Reg))
1258 continue;
1259 const LiveInterval &LI = LIS->getInterval(Reg);
1260 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1261 if (!DefVNI)
1262 continue;
1263
1264 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1265 const SUnit *DefSU = getSUnit(DefMI);
1266 if (!DefSU)
1267 continue;
1268
1269 unsigned LiveOutHeight = DefSU->getHeight();
1270 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1271 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001272 for (const VReg2SUnit &V2SU
1273 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1274 SUnit *SU = V2SU.SU;
1275 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001276 continue;
1277
1278 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001279 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001280 if (!LRQ.valueIn()->isPHIDef())
1281 continue;
1282
1283 // Assume that a path spanning two iterations is a cycle, which could
1284 // overestimate in strange cases. This allows cyclic latency to be
1285 // estimated as the minimum slack of the vreg's depth or height.
1286 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001287 if (LiveOutDepth > SU->getDepth())
1288 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001289
Matthias Braunb0c437b2015-10-29 03:57:17 +00001290 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001291 if (LiveInHeight > LiveOutHeight) {
1292 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1293 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001294 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001295 CyclicLatency = 0;
1296
1297 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001298 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001299 if (CyclicLatency > MaxCyclicLatency)
1300 MaxCyclicLatency = CyclicLatency;
1301 }
1302 }
1303 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1304 return MaxCyclicLatency;
1305}
1306
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001307/// Release ExitSU predecessors and setup scheduler queues. Re-position
1308/// the Top RP tracker in case the region beginning has changed.
1309void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1310 ArrayRef<SUnit*> BotRoots) {
1311 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1312 if (ShouldTrackPressure) {
1313 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1314 TopRPTracker.setPos(CurrentTop);
1315 }
1316}
1317
Andrew Trick7a8e1002012-09-11 00:39:15 +00001318/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001319void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001320 // Move the instruction to its new location in the instruction stream.
1321 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001322
Andrew Trick7a8e1002012-09-11 00:39:15 +00001323 if (IsTopNode) {
1324 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1325 if (&*CurrentTop == MI)
1326 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001327 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001328 moveInstruction(MI, CurrentTop);
1329 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001330 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001331
Andrew Trickb6e74712013-09-04 20:59:59 +00001332 if (ShouldTrackPressure) {
1333 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001334 RegisterOperands RegOpers;
1335 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1336 if (ShouldTrackLaneMasks) {
1337 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001338 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001339 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1340 } else {
1341 // Adjust for missing dead-def flags.
1342 RegOpers.detectDeadDefs(*MI, *LIS);
1343 }
1344
1345 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001346 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001347 DEBUG(
1348 dbgs() << "Top Pressure:\n";
1349 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1350 );
1351
Andrew Trickb248b4a2013-09-06 17:32:47 +00001352 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001353 }
Matthias Braunb550b762016-04-21 01:54:13 +00001354 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001355 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1356 MachineBasicBlock::iterator priorII =
1357 priorNonDebug(CurrentBottom, CurrentTop);
1358 if (&*priorII == MI)
1359 CurrentBottom = priorII;
1360 else {
1361 if (&*CurrentTop == MI) {
1362 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1363 TopRPTracker.setPos(CurrentTop);
1364 }
1365 moveInstruction(MI, CurrentBottom);
1366 CurrentBottom = MI;
1367 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001368 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001369 RegisterOperands RegOpers;
1370 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1371 if (ShouldTrackLaneMasks) {
1372 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001373 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001374 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1375 } else {
1376 // Adjust for missing dead-def flags.
1377 RegOpers.detectDeadDefs(*MI, *LIS);
1378 }
1379
1380 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001381 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001382 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001383 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001384 DEBUG(
1385 dbgs() << "Bottom Pressure:\n";
1386 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1387 );
1388
Andrew Trickb248b4a2013-09-06 17:32:47 +00001389 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001390 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001391 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001392 }
1393}
1394
Andrew Trick263280242012-11-12 19:52:20 +00001395//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001396// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001397//===----------------------------------------------------------------------===//
1398
Andrew Tricka7714a02012-11-12 19:40:10 +00001399namespace {
1400/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001401/// loads or between neighboring stores.
1402class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1403 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001404 SUnit *SU;
1405 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001406 int64_t Offset;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001407 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1408 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001409
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001410 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001411 return std::tie(BaseReg, Offset, SU->NodeNum) <
1412 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001413 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001414 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001415
1416 const TargetInstrInfo *TII;
1417 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001418 bool IsLoad;
1419
Andrew Tricka7714a02012-11-12 19:40:10 +00001420public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001421 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1422 const TargetRegisterInfo *tri, bool IsLoad)
1423 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001424
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001425 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001426
Andrew Tricka7714a02012-11-12 19:40:10 +00001427protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001428 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1429};
1430
1431class StoreClusterMutation : public BaseMemOpClusterMutation {
1432public:
1433 StoreClusterMutation(const TargetInstrInfo *tii,
1434 const TargetRegisterInfo *tri)
1435 : BaseMemOpClusterMutation(tii, tri, false) {}
1436};
1437
1438class LoadClusterMutation : public BaseMemOpClusterMutation {
1439public:
1440 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1441 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001442};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001443} // anonymous
Andrew Tricka7714a02012-11-12 19:40:10 +00001444
Tom Stellard68726a52016-08-19 19:59:18 +00001445namespace llvm {
1446
1447std::unique_ptr<ScheduleDAGMutation>
1448createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1449 const TargetRegisterInfo *TRI) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001450 return EnableMemOpCluster ? make_unique<LoadClusterMutation>(TII, TRI)
1451 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001452}
1453
1454std::unique_ptr<ScheduleDAGMutation>
1455createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1456 const TargetRegisterInfo *TRI) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001457 return EnableMemOpCluster ? make_unique<StoreClusterMutation>(TII, TRI)
1458 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001459}
1460
1461} // namespace llvm
1462
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001463void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1464 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1465 SmallVector<MemOpInfo, 32> MemOpRecords;
1466 for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1467 SUnit *SU = MemOps[Idx];
Andrew Tricka7714a02012-11-12 19:40:10 +00001468 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001469 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001470 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001471 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001472 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001473 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001474 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001475
1476 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001477 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001478 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1479 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001480 ClusterLength = 1;
1481 continue;
1482 }
1483
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001484 SUnit *SUa = MemOpRecords[Idx].SU;
1485 SUnit *SUb = MemOpRecords[Idx+1].SU;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001486 if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
1487 ClusterLength) &&
1488 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001489 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001490 << SUb->NodeNum << ")\n");
1491 // Copy successor edges from SUa to SUb. Interleaving computation
1492 // dependent on SUa can prevent load combining due to register reuse.
1493 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1494 // loads should have effectively the same inputs.
1495 for (SUnit::const_succ_iterator
1496 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1497 if (SI->getSUnit() == SUb)
1498 continue;
1499 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1500 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1501 }
1502 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001503 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001504 ClusterLength = 1;
1505 }
1506}
1507
1508/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001509void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1510
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001511 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1512
Andrew Tricka7714a02012-11-12 19:40:10 +00001513 // Map DAG NodeNum to store chain ID.
1514 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001515 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001516 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1517 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1518 SUnit *SU = &DAG->SUnits[Idx];
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001519 if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1520 (!IsLoad && !SU->getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001521 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001522
Andrew Tricka7714a02012-11-12 19:40:10 +00001523 unsigned ChainPredID = DAG->SUnits.size();
1524 for (SUnit::const_pred_iterator
1525 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1526 if (PI->isCtrl()) {
1527 ChainPredID = PI->getSUnit()->NodeNum;
1528 break;
1529 }
1530 }
1531 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001532 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001533 unsigned NumChains = StoreChainDependents.size();
1534 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1535 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1536 if (Result.second)
1537 StoreChainDependents.resize(NumChains + 1);
1538 StoreChainDependents[Result.first->second].push_back(SU);
1539 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001540
Andrew Tricka7714a02012-11-12 19:40:10 +00001541 // Iterate over the store chains.
1542 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001543 clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001544}
1545
Andrew Trick02a80da2012-03-08 01:41:12 +00001546//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001547// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1548//===----------------------------------------------------------------------===//
1549
1550namespace {
1551/// \brief Post-process the DAG to create cluster edges between instructions
1552/// that may be fused by the processor into a single operation.
1553class MacroFusion : public ScheduleDAGMutation {
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001554 const TargetInstrInfo &TII;
Andrew Trick263280242012-11-12 19:52:20 +00001555public:
Matthias Braun325cd2c2016-11-11 01:34:21 +00001556 MacroFusion(const TargetInstrInfo &TII)
1557 : TII(TII) {}
Andrew Trick263280242012-11-12 19:52:20 +00001558
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001559 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick263280242012-11-12 19:52:20 +00001560};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001561} // anonymous
Andrew Trick263280242012-11-12 19:52:20 +00001562
Tom Stellard68726a52016-08-19 19:59:18 +00001563namespace llvm {
1564
1565std::unique_ptr<ScheduleDAGMutation>
Matthias Braun325cd2c2016-11-11 01:34:21 +00001566createMacroFusionDAGMutation(const TargetInstrInfo *TII) {
Matthias Braun115efcd2016-11-28 20:11:54 +00001567 return EnableMacroFusion ? make_unique<MacroFusion>(*TII) : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001568}
1569
1570} // namespace llvm
1571
Andrew Trick263280242012-11-12 19:52:20 +00001572/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1573/// fused operations.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001574void MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) {
1575 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1576
Andrew Trick263280242012-11-12 19:52:20 +00001577 // For now, assume targets can only fuse with the branch.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001578 SUnit &ExitSU = DAG->ExitSU;
1579 MachineInstr *Branch = ExitSU.getInstr();
Andrew Trick263280242012-11-12 19:52:20 +00001580 if (!Branch)
1581 return;
1582
Matthias Braun325cd2c2016-11-11 01:34:21 +00001583 for (SDep &PredDep : ExitSU.Preds) {
1584 if (PredDep.isWeak())
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001585 continue;
Matthias Braun325cd2c2016-11-11 01:34:21 +00001586 SUnit &SU = *PredDep.getSUnit();
1587 MachineInstr &Pred = *SU.getInstr();
1588 if (!TII.shouldScheduleAdjacent(Pred, *Branch))
Andrew Trick263280242012-11-12 19:52:20 +00001589 continue;
1590
1591 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1592 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1593 // need to copy predecessor edges from ExitSU to SU, since top-down
1594 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1595 // of SU, we could create an artificial edge from the deepest root, but it
1596 // hasn't been needed yet.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001597 bool Success = DAG->addEdge(&ExitSU, SDep(&SU, SDep::Cluster));
Andrew Trick263280242012-11-12 19:52:20 +00001598 (void)Success;
1599 assert(Success && "No DAG nodes should be reachable from ExitSU");
1600
Matthias Braun325cd2c2016-11-11 01:34:21 +00001601 // Adjust latency of data deps between the nodes.
1602 for (SDep &PredDep : ExitSU.Preds) {
1603 if (PredDep.getSUnit() == &SU)
1604 PredDep.setLatency(0);
1605 }
1606 for (SDep &SuccDep : SU.Succs) {
1607 if (SuccDep.getSUnit() == &ExitSU)
1608 SuccDep.setLatency(0);
1609 }
1610
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001611 DEBUG(dbgs() << "Macro Fuse SU(" << SU.NodeNum << ")\n");
Andrew Trick263280242012-11-12 19:52:20 +00001612 break;
1613 }
1614}
1615
1616//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001617// CopyConstrain - DAG post-processing to encourage copy elimination.
1618//===----------------------------------------------------------------------===//
1619
1620namespace {
1621/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1622/// the one use that defines the copy's source vreg, most likely an induction
1623/// variable increment.
1624class CopyConstrain : public ScheduleDAGMutation {
1625 // Transient state.
1626 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001627 // RegionEndIdx is the slot index of the last non-debug instruction in the
1628 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001629 SlotIndex RegionEndIdx;
1630public:
1631 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1632
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001633 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001634
1635protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001636 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001637};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001638} // anonymous
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001639
Tom Stellard68726a52016-08-19 19:59:18 +00001640namespace llvm {
1641
1642std::unique_ptr<ScheduleDAGMutation>
1643createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1644 const TargetRegisterInfo *TRI) {
1645 return make_unique<CopyConstrain>(TII, TRI);
1646}
1647
1648} // namespace llvm
1649
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001650/// constrainLocalCopy handles two possibilities:
1651/// 1) Local src:
1652/// I0: = dst
1653/// I1: src = ...
1654/// I2: = dst
1655/// I3: dst = src (copy)
1656/// (create pred->succ edges I0->I1, I2->I1)
1657///
1658/// 2) Local copy:
1659/// I0: dst = src (copy)
1660/// I1: = dst
1661/// I2: src = ...
1662/// I3: = dst
1663/// (create pred->succ edges I1->I2, I3->I2)
1664///
1665/// Although the MachineScheduler is currently constrained to single blocks,
1666/// this algorithm should handle extended blocks. An EBB is a set of
1667/// contiguously numbered blocks such that the previous block in the EBB is
1668/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001669void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001670 LiveIntervals *LIS = DAG->getLIS();
1671 MachineInstr *Copy = CopySU->getInstr();
1672
1673 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001674 const MachineOperand &SrcOp = Copy->getOperand(1);
1675 unsigned SrcReg = SrcOp.getReg();
1676 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001677 return;
1678
Matthias Braun7511abd2016-04-04 21:23:46 +00001679 const MachineOperand &DstOp = Copy->getOperand(0);
1680 unsigned DstReg = DstOp.getReg();
1681 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001682 return;
1683
1684 // Check if either the dest or source is local. If it's live across a back
1685 // edge, it's not local. Note that if both vregs are live across the back
1686 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001687 // If both the copy's source and dest are local live intervals, then we
1688 // should treat the dest as the global for the purpose of adding
1689 // constraints. This adds edges from source's other uses to the copy.
1690 unsigned LocalReg = SrcReg;
1691 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001692 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1693 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001694 LocalReg = DstReg;
1695 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001696 LocalLI = &LIS->getInterval(LocalReg);
1697 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1698 return;
1699 }
1700 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1701
1702 // Find the global segment after the start of the local LI.
1703 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1704 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1705 // local live range. We could create edges from other global uses to the local
1706 // start, but the coalescer should have already eliminated these cases, so
1707 // don't bother dealing with it.
1708 if (GlobalSegment == GlobalLI->end())
1709 return;
1710
1711 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1712 // returned the next global segment. But if GlobalSegment overlaps with
1713 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1714 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1715 if (GlobalSegment->contains(LocalLI->beginIndex()))
1716 ++GlobalSegment;
1717
1718 if (GlobalSegment == GlobalLI->end())
1719 return;
1720
1721 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1722 if (GlobalSegment != GlobalLI->begin()) {
1723 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001724 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001725 GlobalSegment->start)) {
1726 return;
1727 }
Andrew Trickd9761772013-07-30 19:59:08 +00001728 // If the prior global segment may be defined by the same two-address
1729 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001730 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001731 LocalLI->beginIndex())) {
1732 return;
1733 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001734 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1735 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001736 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001737 "Disconnected LRG within the scheduling region.");
1738 }
1739 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1740 if (!GlobalDef)
1741 return;
1742
1743 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1744 if (!GlobalSU)
1745 return;
1746
1747 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1748 // constraining the uses of the last local def to precede GlobalDef.
1749 SmallVector<SUnit*,8> LocalUses;
1750 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1751 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1752 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1753 for (SUnit::const_succ_iterator
1754 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1755 I != E; ++I) {
1756 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1757 continue;
1758 if (I->getSUnit() == GlobalSU)
1759 continue;
1760 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1761 return;
1762 LocalUses.push_back(I->getSUnit());
1763 }
1764 // Open the top of the GlobalLI hole by constraining any earlier global uses
1765 // to precede the start of LocalLI.
1766 SmallVector<SUnit*,8> GlobalUses;
1767 MachineInstr *FirstLocalDef =
1768 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1769 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1770 for (SUnit::const_pred_iterator
1771 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1772 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1773 continue;
1774 if (I->getSUnit() == FirstLocalSU)
1775 continue;
1776 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1777 return;
1778 GlobalUses.push_back(I->getSUnit());
1779 }
1780 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1781 // Add the weak edges.
1782 for (SmallVectorImpl<SUnit*>::const_iterator
1783 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1784 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1785 << GlobalSU->NodeNum << ")\n");
1786 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1787 }
1788 for (SmallVectorImpl<SUnit*>::const_iterator
1789 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1790 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1791 << FirstLocalSU->NodeNum << ")\n");
1792 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1793 }
1794}
1795
1796/// \brief Callback from DAG postProcessing to create weak edges to encourage
1797/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001798void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1799 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001800 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1801
Andrew Trick2e875172013-04-24 23:19:56 +00001802 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1803 if (FirstPos == DAG->end())
1804 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001805 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001806 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001807 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001808
1809 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1810 SUnit *SU = &DAG->SUnits[Idx];
1811 if (!SU->getInstr()->isCopy())
1812 continue;
1813
Andrew Trickd7f890e2013-12-28 21:56:47 +00001814 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001815 }
1816}
1817
1818//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001819// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1820// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001821//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001822
Andrew Trick5a22df42013-12-05 17:56:02 +00001823static const unsigned InvalidCycle = ~0U;
1824
Andrew Trickfc127d12013-12-07 05:59:44 +00001825SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001826
Andrew Trickfc127d12013-12-07 05:59:44 +00001827void SchedBoundary::reset() {
1828 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1829 // Destroying and reconstructing it is very expensive though. So keep
1830 // invalid, placeholder HazardRecs.
1831 if (HazardRec && HazardRec->isEnabled()) {
1832 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001833 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001834 }
1835 Available.clear();
1836 Pending.clear();
1837 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001838 CurrCycle = 0;
1839 CurrMOps = 0;
1840 MinReadyCycle = UINT_MAX;
1841 ExpectedLatency = 0;
1842 DependentLatency = 0;
1843 RetiredMOps = 0;
1844 MaxExecutedResCount = 0;
1845 ZoneCritResIdx = 0;
1846 IsResourceLimited = false;
1847 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001848#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001849 // Track the maximum number of stall cycles that could arise either from the
1850 // latency of a DAG edge or the number of cycles that a processor resource is
1851 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001852 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001853#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001854 // Reserve a zero-count for invalid CritResIdx.
1855 ExecutedResCounts.resize(1);
1856 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1857}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001858
Andrew Trickfc127d12013-12-07 05:59:44 +00001859void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001860init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1861 reset();
1862 if (!SchedModel->hasInstrSchedModel())
1863 return;
1864 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1865 for (std::vector<SUnit>::iterator
1866 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1867 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001868 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1869 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001870 for (TargetSchedModel::ProcResIter
1871 PI = SchedModel->getWriteProcResBegin(SC),
1872 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1873 unsigned PIdx = PI->ProcResourceIdx;
1874 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1875 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1876 }
1877 }
1878}
1879
Andrew Trickfc127d12013-12-07 05:59:44 +00001880void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001881init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1882 reset();
1883 DAG = dag;
1884 SchedModel = smodel;
1885 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001886 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001887 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001888 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1889 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001890}
1891
Andrew Trick880e5732013-12-05 17:55:58 +00001892/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1893/// these "soft stalls" differently than the hard stall cycles based on CPU
1894/// resources and computed by checkHazard(). A fully in-order model
1895/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1896/// available for scheduling until they are ready. However, a weaker in-order
1897/// model may use this for heuristics. For example, if a processor has in-order
1898/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001899unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001900 if (!SU->isUnbuffered)
1901 return 0;
1902
1903 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1904 if (ReadyCycle > CurrCycle)
1905 return ReadyCycle - CurrCycle;
1906 return 0;
1907}
1908
Andrew Trick5a22df42013-12-05 17:56:02 +00001909/// Compute the next cycle at which the given processor resource can be
1910/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001911unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001912getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1913 unsigned NextUnreserved = ReservedCycles[PIdx];
1914 // If this resource has never been used, always return cycle zero.
1915 if (NextUnreserved == InvalidCycle)
1916 return 0;
1917 // For bottom-up scheduling add the cycles needed for the current operation.
1918 if (!isTop())
1919 NextUnreserved += Cycles;
1920 return NextUnreserved;
1921}
1922
Andrew Trick8c9e6722012-06-29 03:23:24 +00001923/// Does this SU have a hazard within the current instruction group.
1924///
1925/// The scheduler supports two modes of hazard recognition. The first is the
1926/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1927/// supports highly complicated in-order reservation tables
1928/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1929///
1930/// The second is a streamlined mechanism that checks for hazards based on
1931/// simple counters that the scheduler itself maintains. It explicitly checks
1932/// for instruction dispatch limitations, including the number of micro-ops that
1933/// can dispatch per cycle.
1934///
1935/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001936bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001937 if (HazardRec->isEnabled()
1938 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1939 return true;
1940 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001941 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001942 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001943 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1944 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001945 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001946 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001947 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1948 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1949 for (TargetSchedModel::ProcResIter
1950 PI = SchedModel->getWriteProcResBegin(SC),
1951 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick56327222014-06-27 04:57:05 +00001952 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1953 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001954#ifndef NDEBUG
Chad Rosieraba845e2014-07-02 16:46:08 +00001955 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001956#endif
Andrew Trick56327222014-06-27 04:57:05 +00001957 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1958 << SchedModel->getResourceName(PI->ProcResourceIdx)
1959 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001960 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001961 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001962 }
1963 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001964 return false;
1965}
1966
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001967// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001968unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001969findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001970 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001971 unsigned RemLatency = 0;
1972 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001973 I != E; ++I) {
1974 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001975 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001976 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001977 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001978 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001979 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001980 if (LateSU) {
1981 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1982 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001983 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001984 return RemLatency;
1985}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001986
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001987// Count resources in this zone and the remaining unscheduled
1988// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1989// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001990unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001991getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001992 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001993 if (!SchedModel->hasInstrSchedModel())
1994 return 0;
1995
1996 unsigned OtherCritCount = Rem->RemIssueCount
1997 + (RetiredMOps * SchedModel->getMicroOpFactor());
1998 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1999 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002000 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2001 PIdx != PEnd; ++PIdx) {
2002 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2003 if (OtherCount > OtherCritCount) {
2004 OtherCritCount = OtherCount;
2005 OtherCritIdx = PIdx;
2006 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002007 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002008 if (OtherCritIdx) {
2009 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
2010 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00002011 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002012 }
2013 return OtherCritCount;
2014}
2015
Andrew Trickfc127d12013-12-07 05:59:44 +00002016void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002017 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2018
2019#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002020 // ReadyCycle was been bumped up to the CurrCycle when this node was
2021 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2022 // scheduling, so may now be greater than ReadyCycle.
2023 if (ReadyCycle > CurrCycle)
2024 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002025#endif
2026
Andrew Trick61f1a272012-05-24 22:11:09 +00002027 if (ReadyCycle < MinReadyCycle)
2028 MinReadyCycle = ReadyCycle;
2029
2030 // Check for interlocks first. For the purpose of other heuristics, an
2031 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002032 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002033 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2034 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002035 Pending.push(SU);
2036 else
2037 Available.push(SU);
2038}
2039
2040/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002041void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002042 if (SchedModel->getMicroOpBufferSize() == 0) {
2043 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
2044 if (MinReadyCycle > NextCycle)
2045 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002046 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002047 // Update the current micro-ops, which will issue in the next cycle.
2048 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2049 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2050
2051 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002052 if ((NextCycle - CurrCycle) > DependentLatency)
2053 DependentLatency = 0;
2054 else
2055 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002056
2057 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002058 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002059 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002060 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002061 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002062 for (; CurrCycle != NextCycle; ++CurrCycle) {
2063 if (isTop())
2064 HazardRec->AdvanceCycle();
2065 else
2066 HazardRec->RecedeCycle();
2067 }
2068 }
2069 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002070 unsigned LFactor = SchedModel->getLatencyFactor();
2071 IsResourceLimited =
2072 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2073 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00002074
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002075 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2076}
2077
Andrew Trickfc127d12013-12-07 05:59:44 +00002078void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002079 ExecutedResCounts[PIdx] += Count;
2080 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2081 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002082}
2083
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002084/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002085///
2086/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2087/// during which this resource is consumed.
2088///
2089/// \return the next cycle at which the instruction may execute without
2090/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002091unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002092countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002093 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002094 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002095 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002096 << " +" << Cycles << "x" << Factor << "u\n");
2097
2098 // Update Executed resources counts.
2099 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002100 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2101 Rem->RemainingCounts[PIdx] -= Count;
2102
Andrew Trickb13ef172013-07-19 00:20:07 +00002103 // Check if this resource exceeds the current critical resource. If so, it
2104 // becomes the critical resource.
2105 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002106 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002107 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002108 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002109 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002110 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002111 // For reserved resources, record the highest cycle using the resource.
2112 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2113 if (NextAvailable > CurrCycle) {
2114 DEBUG(dbgs() << " Resource conflict: "
2115 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2116 << NextAvailable << "\n");
2117 }
2118 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002119}
2120
Andrew Trick45446062012-06-05 21:11:27 +00002121/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002122void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002123 // Update the reservation table.
2124 if (HazardRec->isEnabled()) {
2125 if (!isTop() && SU->isCall) {
2126 // Calls are scheduled with their preceding instructions. For bottom-up
2127 // scheduling, clear the pipeline state before emitting.
2128 HazardRec->Reset();
2129 }
2130 HazardRec->EmitInstruction(SU);
2131 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002132 // checkHazard should prevent scheduling multiple instructions per cycle that
2133 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002134 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2135 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002136 assert(
2137 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002138 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002139
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002140 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2141 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2142
Andrew Trick5a22df42013-12-05 17:56:02 +00002143 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002144 switch (SchedModel->getMicroOpBufferSize()) {
2145 case 0:
2146 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2147 break;
2148 case 1:
2149 if (ReadyCycle > NextCycle) {
2150 NextCycle = ReadyCycle;
2151 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2152 }
2153 break;
2154 default:
2155 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002156 // scheduled MOps to be "retired". We do loosely model in-order resource
2157 // latency. If this instruction uses an in-order resource, account for any
2158 // likely stall cycles.
2159 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2160 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002161 break;
2162 }
2163 RetiredMOps += IncMOps;
2164
2165 // Update resource counts and critical resource.
2166 if (SchedModel->hasInstrSchedModel()) {
2167 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2168 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2169 Rem->RemIssueCount -= DecRemIssue;
2170 if (ZoneCritResIdx) {
2171 // Scale scheduled micro-ops for comparing with the critical resource.
2172 unsigned ScaledMOps =
2173 RetiredMOps * SchedModel->getMicroOpFactor();
2174
2175 // If scaled micro-ops are now more than the previous critical resource by
2176 // a full cycle, then micro-ops issue becomes critical.
2177 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2178 >= (int)SchedModel->getLatencyFactor()) {
2179 ZoneCritResIdx = 0;
2180 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2181 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2182 }
2183 }
2184 for (TargetSchedModel::ProcResIter
2185 PI = SchedModel->getWriteProcResBegin(SC),
2186 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2187 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002188 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002189 if (RCycle > NextCycle)
2190 NextCycle = RCycle;
2191 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002192 if (SU->hasReservedResource) {
2193 // For reserved resources, record the highest cycle using the resource.
2194 // For top-down scheduling, this is the cycle in which we schedule this
2195 // instruction plus the number of cycles the operations reserves the
2196 // resource. For bottom-up is it simply the instruction's cycle.
2197 for (TargetSchedModel::ProcResIter
2198 PI = SchedModel->getWriteProcResBegin(SC),
2199 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2200 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002201 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002202 if (isTop()) {
2203 ReservedCycles[PIdx] =
2204 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2205 }
2206 else
2207 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002208 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002209 }
2210 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002211 }
2212 // Update ExpectedLatency and DependentLatency.
2213 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2214 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2215 if (SU->getDepth() > TopLatency) {
2216 TopLatency = SU->getDepth();
2217 DEBUG(dbgs() << " " << Available.getName()
2218 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2219 }
2220 if (SU->getHeight() > BotLatency) {
2221 BotLatency = SU->getHeight();
2222 DEBUG(dbgs() << " " << Available.getName()
2223 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2224 }
2225 // If we stall for any reason, bump the cycle.
2226 if (NextCycle > CurrCycle) {
2227 bumpCycle(NextCycle);
Matthias Braunb550b762016-04-21 01:54:13 +00002228 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002229 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002230 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002231 unsigned LFactor = SchedModel->getLatencyFactor();
2232 IsResourceLimited =
2233 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2234 > (int)LFactor;
2235 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002236 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2237 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2238 // one cycle. Since we commonly reach the max MOps here, opportunistically
2239 // bump the cycle to avoid uselessly checking everything in the readyQ.
2240 CurrMOps += IncMOps;
2241 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002242 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2243 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002244 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002245 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002246 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002247}
2248
Andrew Trick61f1a272012-05-24 22:11:09 +00002249/// Release pending ready nodes in to the available queue. This makes them
2250/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002251void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002252 // If the available queue is empty, it is safe to reset MinReadyCycle.
2253 if (Available.empty())
2254 MinReadyCycle = UINT_MAX;
2255
2256 // Check to see if any of the pending instructions are ready to issue. If
2257 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002258 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002259 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2260 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002261 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002262
2263 if (ReadyCycle < MinReadyCycle)
2264 MinReadyCycle = ReadyCycle;
2265
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002266 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002267 continue;
2268
Andrew Trick8c9e6722012-06-29 03:23:24 +00002269 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002270 continue;
2271
Matthias Braun6493bc22016-04-22 19:09:17 +00002272 if (Available.size() >= ReadyListLimit)
2273 break;
2274
Andrew Trick61f1a272012-05-24 22:11:09 +00002275 Available.push(SU);
2276 Pending.remove(Pending.begin()+i);
2277 --i; --e;
2278 }
2279 CheckPending = false;
2280}
2281
2282/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002283void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002284 if (Available.isInQueue(SU))
2285 Available.remove(Available.find(SU));
2286 else {
2287 assert(Pending.isInQueue(SU) && "bad ready count");
2288 Pending.remove(Pending.find(SU));
2289 }
2290}
2291
2292/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002293/// defer any nodes that now hit a hazard, and advance the cycle until at least
2294/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002295SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002296 if (CheckPending)
2297 releasePending();
2298
Andrew Tricke2ff5752013-06-15 04:49:49 +00002299 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002300 // Defer any ready instrs that now have a hazard.
2301 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2302 if (checkHazard(*I)) {
2303 Pending.push(*I);
2304 I = Available.remove(I);
2305 continue;
2306 }
2307 ++I;
2308 }
2309 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002310 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002311// FIXME: Re-enable assert once PR20057 is resolved.
2312// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2313// "permanent hazard");
2314 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002315 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002316 releasePending();
2317 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002318
2319 DEBUG(Pending.dump());
2320 DEBUG(Available.dump());
2321
Andrew Trick61f1a272012-05-24 22:11:09 +00002322 if (Available.size() == 1)
2323 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002324 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002325}
2326
Matthias Braun8c209aa2017-01-28 02:02:38 +00002327#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002328// This is useful information to dump after bumpNode.
2329// Note that the Queue contents are more useful before pickNodeFromQueue.
Matthias Braun8c209aa2017-01-28 02:02:38 +00002330LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002331 unsigned ResFactor;
2332 unsigned ResCount;
2333 if (ZoneCritResIdx) {
2334 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2335 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002336 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002337 ResFactor = SchedModel->getMicroOpFactor();
2338 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002339 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002340 unsigned LFactor = SchedModel->getLatencyFactor();
2341 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2342 << " Retired: " << RetiredMOps;
2343 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2344 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002345 << ResCount / ResFactor << " "
2346 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002347 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2348 << (IsResourceLimited ? " - Resource" : " - Latency")
2349 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002350}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002351#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002352
Andrew Trickfc127d12013-12-07 05:59:44 +00002353//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002354// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002355//===----------------------------------------------------------------------===//
2356
Andrew Trickd14d7c22013-12-28 21:56:57 +00002357void GenericSchedulerBase::SchedCandidate::
2358initResourceDelta(const ScheduleDAGMI *DAG,
2359 const TargetSchedModel *SchedModel) {
2360 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2361 return;
2362
2363 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2364 for (TargetSchedModel::ProcResIter
2365 PI = SchedModel->getWriteProcResBegin(SC),
2366 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2367 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2368 ResDelta.CritResources += PI->Cycles;
2369 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2370 ResDelta.DemandedResources += PI->Cycles;
2371 }
2372}
2373
2374/// Set the CandPolicy given a scheduling zone given the current resources and
2375/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002376void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002377 SchedBoundary &CurrZone,
2378 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002379 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002380 // inside and outside this zone. Potential stalls should be considered before
2381 // following this policy.
2382
2383 // Compute remaining latency. We need this both to determine whether the
2384 // overall schedule has become latency-limited and whether the instructions
2385 // outside this zone are resource or latency limited.
2386 //
2387 // The "dependent" latency is updated incrementally during scheduling as the
2388 // max height/depth of scheduled nodes minus the cycles since it was
2389 // scheduled:
2390 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2391 //
2392 // The "independent" latency is the max ready queue depth:
2393 // ILat = max N.depth for N in Available|Pending
2394 //
2395 // RemainingLatency is the greater of independent and dependent latency.
2396 unsigned RemLatency = CurrZone.getDependentLatency();
2397 RemLatency = std::max(RemLatency,
2398 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2399 RemLatency = std::max(RemLatency,
2400 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2401
2402 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002403 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002404 unsigned OtherCount =
2405 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2406
2407 bool OtherResLimited = false;
2408 if (SchedModel->hasInstrSchedModel()) {
2409 unsigned LFactor = SchedModel->getLatencyFactor();
2410 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2411 }
2412 // Schedule aggressively for latency in PostRA mode. We don't check for
2413 // acyclic latency during PostRA, and highly out-of-order processors will
2414 // skip PostRA scheduling.
2415 if (!OtherResLimited) {
2416 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2417 Policy.ReduceLatency |= true;
2418 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2419 << " RemainingLatency " << RemLatency << " + "
2420 << CurrZone.getCurrCycle() << "c > CritPath "
2421 << Rem.CriticalPath << "\n");
2422 }
2423 }
2424 // If the same resource is limiting inside and outside the zone, do nothing.
2425 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2426 return;
2427
2428 DEBUG(
2429 if (CurrZone.isResourceLimited()) {
2430 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2431 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2432 << "\n";
2433 }
2434 if (OtherResLimited)
2435 dbgs() << " RemainingLimit: "
2436 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2437 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2438 dbgs() << " Latency limited both directions.\n");
2439
2440 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2441 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2442
2443 if (OtherResLimited)
2444 Policy.DemandResIdx = OtherCritIdx;
2445}
2446
2447#ifndef NDEBUG
2448const char *GenericSchedulerBase::getReasonStr(
2449 GenericSchedulerBase::CandReason Reason) {
2450 switch (Reason) {
2451 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002452 case Only1: return "ONLY1 ";
2453 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002454 case RegExcess: return "REG-EXCESS";
2455 case RegCritical: return "REG-CRIT ";
2456 case Stall: return "STALL ";
2457 case Cluster: return "CLUSTER ";
2458 case Weak: return "WEAK ";
2459 case RegMax: return "REG-MAX ";
2460 case ResourceReduce: return "RES-REDUCE";
2461 case ResourceDemand: return "RES-DEMAND";
2462 case TopDepthReduce: return "TOP-DEPTH ";
2463 case TopPathReduce: return "TOP-PATH ";
2464 case BotHeightReduce:return "BOT-HEIGHT";
2465 case BotPathReduce: return "BOT-PATH ";
2466 case NextDefUse: return "DEF-USE ";
2467 case NodeOrder: return "ORDER ";
2468 };
2469 llvm_unreachable("Unknown reason!");
2470}
2471
2472void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2473 PressureChange P;
2474 unsigned ResIdx = 0;
2475 unsigned Latency = 0;
2476 switch (Cand.Reason) {
2477 default:
2478 break;
2479 case RegExcess:
2480 P = Cand.RPDelta.Excess;
2481 break;
2482 case RegCritical:
2483 P = Cand.RPDelta.CriticalMax;
2484 break;
2485 case RegMax:
2486 P = Cand.RPDelta.CurrentMax;
2487 break;
2488 case ResourceReduce:
2489 ResIdx = Cand.Policy.ReduceResIdx;
2490 break;
2491 case ResourceDemand:
2492 ResIdx = Cand.Policy.DemandResIdx;
2493 break;
2494 case TopDepthReduce:
2495 Latency = Cand.SU->getDepth();
2496 break;
2497 case TopPathReduce:
2498 Latency = Cand.SU->getHeight();
2499 break;
2500 case BotHeightReduce:
2501 Latency = Cand.SU->getHeight();
2502 break;
2503 case BotPathReduce:
2504 Latency = Cand.SU->getDepth();
2505 break;
2506 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002507 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002508 if (P.isValid())
2509 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2510 << ":" << P.getUnitInc() << " ";
2511 else
2512 dbgs() << " ";
2513 if (ResIdx)
2514 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2515 else
2516 dbgs() << " ";
2517 if (Latency)
2518 dbgs() << " " << Latency << " cycles ";
2519 else
2520 dbgs() << " ";
2521 dbgs() << '\n';
2522}
2523#endif
2524
2525/// Return true if this heuristic determines order.
2526static bool tryLess(int TryVal, int CandVal,
2527 GenericSchedulerBase::SchedCandidate &TryCand,
2528 GenericSchedulerBase::SchedCandidate &Cand,
2529 GenericSchedulerBase::CandReason Reason) {
2530 if (TryVal < CandVal) {
2531 TryCand.Reason = Reason;
2532 return true;
2533 }
2534 if (TryVal > CandVal) {
2535 if (Cand.Reason > Reason)
2536 Cand.Reason = Reason;
2537 return true;
2538 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002539 return false;
2540}
2541
2542static bool tryGreater(int TryVal, int CandVal,
2543 GenericSchedulerBase::SchedCandidate &TryCand,
2544 GenericSchedulerBase::SchedCandidate &Cand,
2545 GenericSchedulerBase::CandReason Reason) {
2546 if (TryVal > CandVal) {
2547 TryCand.Reason = Reason;
2548 return true;
2549 }
2550 if (TryVal < CandVal) {
2551 if (Cand.Reason > Reason)
2552 Cand.Reason = Reason;
2553 return true;
2554 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002555 return false;
2556}
2557
2558static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2559 GenericSchedulerBase::SchedCandidate &Cand,
2560 SchedBoundary &Zone) {
2561 if (Zone.isTop()) {
2562 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2563 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2564 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2565 return true;
2566 }
2567 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2568 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2569 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002570 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002571 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2572 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2573 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2574 return true;
2575 }
2576 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2577 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2578 return true;
2579 }
2580 return false;
2581}
2582
Matthias Braun49cb6e92016-05-27 22:14:26 +00002583static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2584 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2585 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2586}
2587
Matthias Braun6ad3d052016-06-25 00:23:00 +00002588static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2589 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002590}
2591
Andrew Trickfc127d12013-12-07 05:59:44 +00002592void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002593 assert(dag->hasVRegLiveness() &&
2594 "(PreRA)GenericScheduler needs vreg liveness");
2595 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002596 SchedModel = DAG->getSchedModel();
2597 TRI = DAG->TRI;
2598
2599 Rem.init(DAG, SchedModel);
2600 Top.init(DAG, SchedModel, &Rem);
2601 Bot.init(DAG, SchedModel, &Rem);
2602
2603 // Initialize resource counts.
2604
2605 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2606 // are disabled, then these HazardRecs will be disabled.
2607 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002608 if (!Top.HazardRec) {
2609 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002610 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002611 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002612 }
2613 if (!Bot.HazardRec) {
2614 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002615 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002616 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002617 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002618 TopCand.SU = nullptr;
2619 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002620}
2621
2622/// Initialize the per-region scheduling policy.
2623void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2624 MachineBasicBlock::iterator End,
2625 unsigned NumRegionInstrs) {
Eric Christopher99556d72014-10-14 06:56:25 +00002626 const MachineFunction &MF = *Begin->getParent()->getParent();
2627 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002628
2629 // Avoid setting up the register pressure tracker for small regions to save
2630 // compile time. As a rough heuristic, only track pressure when the number of
2631 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002632 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002633 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2634 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2635 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002636 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002637 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002638 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2639 }
2640 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002641
2642 // For generic targets, we default to bottom-up, because it's simpler and more
2643 // compile-time optimizations have been implemented in that direction.
2644 RegionPolicy.OnlyBottomUp = true;
2645
2646 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002647 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002648
2649 // After subtarget overrides, apply command line options.
2650 if (!EnableRegPressure)
2651 RegionPolicy.ShouldTrackPressure = false;
2652
2653 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2654 // e.g. -misched-bottomup=false allows scheduling in both directions.
2655 assert((!ForceTopDown || !ForceBottomUp) &&
2656 "-misched-topdown incompatible with -misched-bottomup");
2657 if (ForceBottomUp.getNumOccurrences() > 0) {
2658 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2659 if (RegionPolicy.OnlyBottomUp)
2660 RegionPolicy.OnlyTopDown = false;
2661 }
2662 if (ForceTopDown.getNumOccurrences() > 0) {
2663 RegionPolicy.OnlyTopDown = ForceTopDown;
2664 if (RegionPolicy.OnlyTopDown)
2665 RegionPolicy.OnlyBottomUp = false;
2666 }
2667}
2668
James Y Knighte72b0db2015-09-18 18:52:20 +00002669void GenericScheduler::dumpPolicy() {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002670 // Cannot completely remove virtual function even in release mode.
2671#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002672 dbgs() << "GenericScheduler RegionPolicy: "
2673 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2674 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2675 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2676 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002677#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002678}
2679
Andrew Trickfc127d12013-12-07 05:59:44 +00002680/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2681/// critical path by more cycles than it takes to drain the instruction buffer.
2682/// We estimate an upper bounds on in-flight instructions as:
2683///
2684/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2685/// InFlightIterations = AcyclicPath / CyclesPerIteration
2686/// InFlightResources = InFlightIterations * LoopResources
2687///
2688/// TODO: Check execution resources in addition to IssueCount.
2689void GenericScheduler::checkAcyclicLatency() {
2690 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2691 return;
2692
2693 // Scaled number of cycles per loop iteration.
2694 unsigned IterCount =
2695 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2696 Rem.RemIssueCount);
2697 // Scaled acyclic critical path.
2698 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2699 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2700 unsigned InFlightCount =
2701 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2702 unsigned BufferLimit =
2703 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2704
2705 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2706
2707 DEBUG(dbgs() << "IssueCycles="
2708 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2709 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2710 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2711 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2712 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2713 if (Rem.IsAcyclicLatencyLimited)
2714 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2715}
2716
2717void GenericScheduler::registerRoots() {
2718 Rem.CriticalPath = DAG->ExitSU.getDepth();
2719
2720 // Some roots may not feed into ExitSU. Check all of them in case.
2721 for (std::vector<SUnit*>::const_iterator
2722 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2723 if ((*I)->getDepth() > Rem.CriticalPath)
2724 Rem.CriticalPath = (*I)->getDepth();
2725 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002726 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2727 if (DumpCriticalPathLength) {
2728 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2729 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002730
2731 if (EnableCyclicPath) {
2732 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2733 checkAcyclicLatency();
2734 }
2735}
2736
Andrew Trick1a831342013-08-30 03:49:48 +00002737static bool tryPressure(const PressureChange &TryP,
2738 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002739 GenericSchedulerBase::SchedCandidate &TryCand,
2740 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002741 GenericSchedulerBase::CandReason Reason,
2742 const TargetRegisterInfo *TRI,
2743 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002744 // If one candidate decreases and the other increases, go with it.
2745 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002746 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2747 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002748 return true;
2749 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002750 // Do not compare the magnitude of pressure changes between top and bottom
2751 // boundary.
2752 if (Cand.AtTop != TryCand.AtTop)
2753 return false;
2754
2755 // If both candidates affect the same set in the same boundary, go with the
2756 // smallest increase.
2757 unsigned TryPSet = TryP.getPSetOrMax();
2758 unsigned CandPSet = CandP.getPSetOrMax();
2759 if (TryPSet == CandPSet) {
2760 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2761 Reason);
2762 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002763
2764 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2765 std::numeric_limits<int>::max();
2766
2767 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2768 std::numeric_limits<int>::max();
2769
Andrew Trick401b6952013-07-25 07:26:35 +00002770 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002771 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002772 std::swap(TryRank, CandRank);
2773 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2774}
2775
Andrew Tricka7714a02012-11-12 19:40:10 +00002776static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2777 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2778}
2779
Andrew Tricke833e1c2013-04-13 06:07:40 +00002780/// Minimize physical register live ranges. Regalloc wants them adjacent to
2781/// their physreg def/use.
2782///
2783/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2784/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2785/// with the operation that produces or consumes the physreg. We'll do this when
2786/// regalloc has support for parallel copies.
2787static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2788 const MachineInstr *MI = SU->getInstr();
2789 if (!MI->isCopy())
2790 return 0;
2791
2792 unsigned ScheduledOper = isTop ? 1 : 0;
2793 unsigned UnscheduledOper = isTop ? 0 : 1;
2794 // If we have already scheduled the physreg produce/consumer, immediately
2795 // schedule the copy.
2796 if (TargetRegisterInfo::isPhysicalRegister(
2797 MI->getOperand(ScheduledOper).getReg()))
2798 return 1;
2799 // If the physreg is at the boundary, defer it. Otherwise schedule it
2800 // immediately to free the dependent. We can hoist the copy later.
2801 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2802 if (TargetRegisterInfo::isPhysicalRegister(
2803 MI->getOperand(UnscheduledOper).getReg()))
2804 return AtBoundary ? -1 : 1;
2805 return 0;
2806}
2807
Matthias Braun4f573772016-04-22 19:10:15 +00002808void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2809 bool AtTop,
2810 const RegPressureTracker &RPTracker,
2811 RegPressureTracker &TempTracker) {
2812 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002813 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002814 if (DAG->isTrackingPressure()) {
2815 if (AtTop) {
2816 TempTracker.getMaxDownwardPressureDelta(
2817 Cand.SU->getInstr(),
2818 Cand.RPDelta,
2819 DAG->getRegionCriticalPSets(),
2820 DAG->getRegPressure().MaxSetPressure);
2821 } else {
2822 if (VerifyScheduling) {
2823 TempTracker.getMaxUpwardPressureDelta(
2824 Cand.SU->getInstr(),
2825 &DAG->getPressureDiff(Cand.SU),
2826 Cand.RPDelta,
2827 DAG->getRegionCriticalPSets(),
2828 DAG->getRegPressure().MaxSetPressure);
2829 } else {
2830 RPTracker.getUpwardPressureDelta(
2831 Cand.SU->getInstr(),
2832 DAG->getPressureDiff(Cand.SU),
2833 Cand.RPDelta,
2834 DAG->getRegionCriticalPSets(),
2835 DAG->getRegPressure().MaxSetPressure);
2836 }
2837 }
2838 }
2839 DEBUG(if (Cand.RPDelta.Excess.isValid())
2840 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2841 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2842 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2843}
2844
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002845/// Apply a set of heursitics to a new candidate. Heuristics are currently
2846/// hierarchical. This may be more efficient than a graduated cost model because
2847/// we don't need to evaluate all aspects of the model for each node in the
2848/// queue. But it's really done to make the heuristics easier to debug and
2849/// statistically analyze.
2850///
2851/// \param Cand provides the policy and current best candidate.
2852/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002853/// \param Zone describes the scheduled zone that we are extending, or nullptr
2854// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002855void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002856 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002857 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002858 // Initialize the candidate if needed.
2859 if (!Cand.isValid()) {
2860 TryCand.Reason = NodeOrder;
2861 return;
2862 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002863
Matthias Braun6ad3d052016-06-25 00:23:00 +00002864 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2865 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002866 TryCand, Cand, PhysRegCopy))
2867 return;
2868
Andrew Tricke02d5da2015-05-17 23:40:27 +00002869 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002870 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2871 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002872 TryCand, Cand, RegExcess, TRI,
2873 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002874 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002875
2876 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002877 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2878 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002879 TryCand, Cand, RegCritical, TRI,
2880 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002881 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002882
Matthias Braun6ad3d052016-06-25 00:23:00 +00002883 // We only compare a subset of features when comparing nodes between
2884 // Top and Bottom boundary. Some properties are simply incomparable, in many
2885 // other instances we should only override the other boundary if something
2886 // is a clear good pick on one boundary. Skip heuristics that are more
2887 // "tie-breaking" in nature.
2888 bool SameBoundary = Zone != nullptr;
2889 if (SameBoundary) {
2890 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002891 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2892 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002893 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2894 tryLatency(TryCand, Cand, *Zone))
2895 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002896
Matthias Braun6ad3d052016-06-25 00:23:00 +00002897 // Prioritize instructions that read unbuffered resources by stall cycles.
2898 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2899 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2900 return;
2901 }
Andrew Trick880e5732013-12-05 17:55:58 +00002902
Andrew Tricka7714a02012-11-12 19:40:10 +00002903 // Keep clustered nodes together to encourage downstream peephole
2904 // optimizations which may reduce resource requirements.
2905 //
2906 // This is a best effort to set things up for a post-RA pass. Optimizations
2907 // like generating loads of multiple registers should ideally be done within
2908 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002909 const SUnit *CandNextClusterSU =
2910 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2911 const SUnit *TryCandNextClusterSU =
2912 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2913 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2914 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002915 TryCand, Cand, Cluster))
2916 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002917
Matthias Braun6ad3d052016-06-25 00:23:00 +00002918 if (SameBoundary) {
2919 // Weak edges are for clustering and other constraints.
2920 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2921 getWeakLeft(Cand.SU, Cand.AtTop),
2922 TryCand, Cand, Weak))
2923 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002924 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002925
Andrew Trick71f08a32013-06-17 21:45:13 +00002926 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002927 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2928 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002929 TryCand, Cand, RegMax, TRI,
2930 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002931 return;
2932
Matthias Braun6ad3d052016-06-25 00:23:00 +00002933 if (SameBoundary) {
2934 // Avoid critical resource consumption and balance the schedule.
2935 TryCand.initResourceDelta(DAG, SchedModel);
2936 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2937 TryCand, Cand, ResourceReduce))
2938 return;
2939 if (tryGreater(TryCand.ResDelta.DemandedResources,
2940 Cand.ResDelta.DemandedResources,
2941 TryCand, Cand, ResourceDemand))
2942 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002943
Matthias Braun6ad3d052016-06-25 00:23:00 +00002944 // Avoid serializing long latency dependence chains.
2945 // For acyclic path limited loops, latency was already checked above.
2946 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2947 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2948 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002949
Matthias Braun6ad3d052016-06-25 00:23:00 +00002950 // Fall through to original instruction order.
2951 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2952 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2953 TryCand.Reason = NodeOrder;
2954 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002955 }
2956}
Andrew Trick419eae22012-05-10 21:06:19 +00002957
Andrew Trickc573cd92013-09-06 17:32:44 +00002958/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002959///
2960/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2961/// DAG building. To adjust for the current scheduling location we need to
2962/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002963void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002964 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002965 const RegPressureTracker &RPTracker,
2966 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002967 // getMaxPressureDelta temporarily modifies the tracker.
2968 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2969
Matthias Braund29d31e2016-06-23 21:27:38 +00002970 ReadyQueue &Q = Zone.Available;
Andrew Trickdd375dd2012-05-24 22:11:03 +00002971 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002972
Matthias Braun6ad3d052016-06-25 00:23:00 +00002973 SchedCandidate TryCand(ZonePolicy);
Matthias Braun4f573772016-04-22 19:10:15 +00002974 initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00002975 // Pass SchedBoundary only when comparing nodes from the same boundary.
2976 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
2977 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002978 if (TryCand.Reason != NoCand) {
2979 // Initialize resource delta if needed in case future heuristics query it.
2980 if (TryCand.ResDelta == SchedResourceDelta())
2981 TryCand.initResourceDelta(DAG, SchedModel);
2982 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002983 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002984 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002985 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002986}
2987
Andrew Trick22025772012-05-17 18:35:10 +00002988/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002989SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002990 // Schedule as far as possible in the direction of no choice. This is most
2991 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002992 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002993 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002994 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002995 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002996 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002997 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002998 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002999 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003000 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003001 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003002 // Set the bottom-up policy based on the state of the current bottom zone and
3003 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003004 CandPolicy BotPolicy;
3005 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003006 // Set the top-down policy based on the state of the current top zone and
3007 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003008 CandPolicy TopPolicy;
3009 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003010
Matthias Brauncc676c42016-06-25 02:03:36 +00003011 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00003012 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003013 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3014 BotCand.Policy != BotPolicy) {
3015 BotCand.reset(CandPolicy());
3016 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3017 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3018 } else {
3019 DEBUG(traceCandidate(BotCand));
3020#ifndef NDEBUG
3021 if (VerifyScheduling) {
3022 SchedCandidate TCand;
3023 TCand.reset(CandPolicy());
3024 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3025 assert(TCand.SU == BotCand.SU &&
3026 "Last pick result should correspond to re-picking right now");
3027 }
3028#endif
3029 }
Andrew Trick22025772012-05-17 18:35:10 +00003030
Andrew Trick22025772012-05-17 18:35:10 +00003031 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003032 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003033 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3034 TopCand.Policy != TopPolicy) {
3035 TopCand.reset(CandPolicy());
3036 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3037 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3038 } else {
3039 DEBUG(traceCandidate(TopCand));
3040#ifndef NDEBUG
3041 if (VerifyScheduling) {
3042 SchedCandidate TCand;
3043 TCand.reset(CandPolicy());
3044 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3045 assert(TCand.SU == TopCand.SU &&
3046 "Last pick result should correspond to re-picking right now");
3047 }
3048#endif
3049 }
3050
3051 // Pick best from BotCand and TopCand.
3052 assert(BotCand.isValid());
3053 assert(TopCand.isValid());
3054 SchedCandidate Cand = BotCand;
3055 TopCand.Reason = NoCand;
3056 tryCandidate(Cand, TopCand, nullptr);
3057 if (TopCand.Reason != NoCand) {
3058 Cand.setBest(TopCand);
3059 DEBUG(traceCandidate(Cand));
3060 }
Andrew Trick22025772012-05-17 18:35:10 +00003061
Matthias Braun6ad3d052016-06-25 00:23:00 +00003062 IsTopNode = Cand.AtTop;
3063 tracePick(Cand);
3064 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003065}
3066
3067/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003068SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003069 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003070 assert(Top.Available.empty() && Top.Pending.empty() &&
3071 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003072 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003073 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003074 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003075 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003076 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003077 SU = Top.pickOnlyChoice();
3078 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003079 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003080 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003081 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003082 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003083 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003084 SU = TopCand.SU;
3085 }
3086 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003087 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003088 SU = Bot.pickOnlyChoice();
3089 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003090 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003091 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003092 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003093 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003094 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003095 SU = BotCand.SU;
3096 }
3097 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003098 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003099 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003100 }
3101 } while (SU->isScheduled);
3102
Andrew Trick61f1a272012-05-24 22:11:09 +00003103 if (SU->isTopReady())
3104 Top.removeReady(SU);
3105 if (SU->isBottomReady())
3106 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003107
Andrew Trick1f0bb692013-04-13 06:07:49 +00003108 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003109 return SU;
3110}
3111
Andrew Trick665d3ec2013-09-19 23:10:59 +00003112void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003113
3114 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3115 if (!isTop)
3116 ++InsertPos;
3117 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3118
3119 // Find already scheduled copies with a single physreg dependence and move
3120 // them just above the scheduled instruction.
3121 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3122 I != E; ++I) {
3123 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3124 continue;
3125 SUnit *DepSU = I->getSUnit();
3126 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3127 continue;
3128 MachineInstr *Copy = DepSU->getInstr();
3129 if (!Copy->isCopy())
3130 continue;
3131 DEBUG(dbgs() << " Rescheduling physreg copy ";
3132 I->getSUnit()->dump(DAG));
3133 DAG->moveInstruction(Copy, InsertPos);
3134 }
3135}
3136
Andrew Trick61f1a272012-05-24 22:11:09 +00003137/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003138/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3139/// update it's state based on the current cycle before MachineSchedStrategy
3140/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003141///
3142/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3143/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003144void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003145 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003146 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003147 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003148 if (SU->hasPhysRegUses)
3149 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003150 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003151 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003152 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003153 if (SU->hasPhysRegDefs)
3154 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003155 }
3156}
3157
Andrew Trick8823dec2012-03-14 04:00:41 +00003158/// Create the standard converging machine scheduler. This will be used as the
3159/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003160ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003161 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003162 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003163 //
3164 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3165 // data and pass it to later mutations. Have a single mutation that gathers
3166 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003167 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003168 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003169}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003170
Matthias Braun115efcd2016-11-28 20:11:54 +00003171static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3172 return createGenericSchedLive(C);
3173}
3174
Andrew Tricke1c034f2012-01-17 06:55:03 +00003175static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003176GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003177 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003178
3179//===----------------------------------------------------------------------===//
3180// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3181//===----------------------------------------------------------------------===//
3182
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003183void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3184 DAG = Dag;
3185 SchedModel = DAG->getSchedModel();
3186 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003187
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003188 Rem.init(DAG, SchedModel);
3189 Top.init(DAG, SchedModel, &Rem);
3190 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003191
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003192 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3193 // or are disabled, then these HazardRecs will be disabled.
3194 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003195 if (!Top.HazardRec) {
3196 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003197 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003198 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003199 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003200}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003201
Andrew Trickd14d7c22013-12-28 21:56:57 +00003202
3203void PostGenericScheduler::registerRoots() {
3204 Rem.CriticalPath = DAG->ExitSU.getDepth();
3205
3206 // Some roots may not feed into ExitSU. Check all of them in case.
3207 for (SmallVectorImpl<SUnit*>::const_iterator
3208 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3209 if ((*I)->getDepth() > Rem.CriticalPath)
3210 Rem.CriticalPath = (*I)->getDepth();
3211 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003212 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3213 if (DumpCriticalPathLength) {
3214 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3215 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003216}
3217
3218/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3219///
3220/// \param Cand provides the policy and current best candidate.
3221/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3222void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3223 SchedCandidate &TryCand) {
3224
3225 // Initialize the candidate if needed.
3226 if (!Cand.isValid()) {
3227 TryCand.Reason = NodeOrder;
3228 return;
3229 }
3230
3231 // Prioritize instructions that read unbuffered resources by stall cycles.
3232 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3233 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3234 return;
3235
3236 // Avoid critical resource consumption and balance the schedule.
3237 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3238 TryCand, Cand, ResourceReduce))
3239 return;
3240 if (tryGreater(TryCand.ResDelta.DemandedResources,
3241 Cand.ResDelta.DemandedResources,
3242 TryCand, Cand, ResourceDemand))
3243 return;
3244
3245 // Avoid serializing long latency dependence chains.
3246 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3247 return;
3248 }
3249
3250 // Fall through to original instruction order.
3251 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3252 TryCand.Reason = NodeOrder;
3253}
3254
3255void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3256 ReadyQueue &Q = Top.Available;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003257 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3258 SchedCandidate TryCand(Cand.Policy);
3259 TryCand.SU = *I;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003260 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003261 TryCand.initResourceDelta(DAG, SchedModel);
3262 tryCandidate(Cand, TryCand);
3263 if (TryCand.Reason != NoCand) {
3264 Cand.setBest(TryCand);
3265 DEBUG(traceCandidate(Cand));
3266 }
3267 }
3268}
3269
3270/// Pick the next node to schedule.
3271SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3272 if (DAG->top() == DAG->bottom()) {
3273 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003274 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003275 }
3276 SUnit *SU;
3277 do {
3278 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003279 if (SU) {
3280 tracePick(Only1, true);
3281 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003282 CandPolicy NoPolicy;
3283 SchedCandidate TopCand(NoPolicy);
3284 // Set the top-down policy based on the state of the current top zone and
3285 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003286 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003287 pickNodeFromQueue(TopCand);
3288 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003289 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003290 SU = TopCand.SU;
3291 }
3292 } while (SU->isScheduled);
3293
3294 IsTopNode = true;
3295 Top.removeReady(SU);
3296
3297 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3298 return SU;
3299}
3300
3301/// Called after ScheduleDAGMI has scheduled an instruction and updated
3302/// scheduled/remaining flags in the DAG nodes.
3303void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3304 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3305 Top.bumpNode(SU);
3306}
3307
Matthias Braun115efcd2016-11-28 20:11:54 +00003308ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Jonas Paulsson28f29482016-11-09 09:59:27 +00003309 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C),
3310 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003311}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003312
3313//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003314// ILP Scheduler. Currently for experimental analysis of heuristics.
3315//===----------------------------------------------------------------------===//
3316
3317namespace {
3318/// \brief Order nodes by the ILP metric.
3319struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00003320 const SchedDFSResult *DFSResult;
3321 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00003322 bool MaximizeILP;
3323
Craig Topperc0196b12014-04-14 00:51:57 +00003324 ILPOrder(bool MaxILP)
3325 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003326
3327 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003328 ///
3329 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003330 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003331 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3332 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3333 if (SchedTreeA != SchedTreeB) {
3334 // Unscheduled trees have lower priority.
3335 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3336 return ScheduledTrees->test(SchedTreeB);
3337
3338 // Trees with shallower connections have have lower priority.
3339 if (DFSResult->getSubtreeLevel(SchedTreeA)
3340 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3341 return DFSResult->getSubtreeLevel(SchedTreeA)
3342 < DFSResult->getSubtreeLevel(SchedTreeB);
3343 }
3344 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003345 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003346 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003347 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003348 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003349 }
3350};
3351
3352/// \brief Schedule based on the ILP metric.
3353class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003354 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00003355 ILPOrder Cmp;
3356
3357 std::vector<SUnit*> ReadyQ;
3358public:
Craig Topperc0196b12014-04-14 00:51:57 +00003359 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003360
Craig Topper4584cd52014-03-07 09:26:03 +00003361 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003362 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3363 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003364 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003365 Cmp.DFSResult = DAG->getDFSResult();
3366 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003367 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003368 }
3369
Craig Topper4584cd52014-03-07 09:26:03 +00003370 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003371 // Restore the heap in ReadyQ with the updated DFS results.
3372 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003373 }
3374
3375 /// Implement MachineSchedStrategy interface.
3376 /// -----------------------------------------
3377
Andrew Trick48d392e2012-11-28 05:13:28 +00003378 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003379 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003380 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003381 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003382 SUnit *SU = ReadyQ.back();
3383 ReadyQ.pop_back();
3384 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003385 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003386 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3387 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3388 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003389 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3390 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003391 return SU;
3392 }
3393
Andrew Trick44f750a2013-01-25 04:01:04 +00003394 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003395 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003396 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3397 }
3398
Andrew Trick48d392e2012-11-28 05:13:28 +00003399 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3400 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003401 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003402 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003403 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003404
Craig Topper4584cd52014-03-07 09:26:03 +00003405 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003406
Craig Topper4584cd52014-03-07 09:26:03 +00003407 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003408 ReadyQ.push_back(SU);
3409 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3410 }
3411};
3412} // namespace
3413
3414static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003415 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003416}
3417static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003418 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003419}
3420static MachineSchedRegistry ILPMaxRegistry(
3421 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3422static MachineSchedRegistry ILPMinRegistry(
3423 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3424
3425//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003426// Machine Instruction Shuffler for Correctness Testing
3427//===----------------------------------------------------------------------===//
3428
Andrew Tricke77e84e2012-01-13 06:30:30 +00003429#ifndef NDEBUG
3430namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003431/// Apply a less-than relation on the node order, which corresponds to the
3432/// instruction order prior to scheduling. IsReverse implements greater-than.
3433template<bool IsReverse>
3434struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003435 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003436 if (IsReverse)
3437 return A->NodeNum > B->NodeNum;
3438 else
3439 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003440 }
3441};
3442
Andrew Tricke77e84e2012-01-13 06:30:30 +00003443/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003444class InstructionShuffler : public MachineSchedStrategy {
3445 bool IsAlternating;
3446 bool IsTopDown;
3447
3448 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3449 // gives nodes with a higher number higher priority causing the latest
3450 // instructions to be scheduled first.
3451 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3452 TopQ;
3453 // When scheduling bottom-up, use greater-than as the queue priority.
3454 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3455 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003456public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003457 InstructionShuffler(bool alternate, bool topdown)
3458 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003459
Craig Topper9d74a5a2014-04-29 07:58:41 +00003460 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003461 TopQ.clear();
3462 BottomQ.clear();
3463 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003464
Andrew Trick8823dec2012-03-14 04:00:41 +00003465 /// Implement MachineSchedStrategy interface.
3466 /// -----------------------------------------
3467
Craig Topper9d74a5a2014-04-29 07:58:41 +00003468 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003469 SUnit *SU;
3470 if (IsTopDown) {
3471 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003472 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003473 SU = TopQ.top();
3474 TopQ.pop();
3475 } while (SU->isScheduled);
3476 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003477 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003478 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003479 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003480 SU = BottomQ.top();
3481 BottomQ.pop();
3482 } while (SU->isScheduled);
3483 IsTopNode = false;
3484 }
3485 if (IsAlternating)
3486 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003487 return SU;
3488 }
3489
Craig Topper9d74a5a2014-04-29 07:58:41 +00003490 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003491
Craig Topper9d74a5a2014-04-29 07:58:41 +00003492 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003493 TopQ.push(SU);
3494 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003495 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003496 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003497 }
3498};
3499} // namespace
3500
Andrew Trick02a80da2012-03-08 01:41:12 +00003501static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003502 bool Alternate = !ForceTopDown && !ForceBottomUp;
3503 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003504 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003505 "-misched-topdown incompatible with -misched-bottomup");
David Blaikie422b93d2014-04-21 20:32:32 +00003506 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003507}
Andrew Trick8823dec2012-03-14 04:00:41 +00003508static MachineSchedRegistry ShufflerRegistry(
3509 "shuffle", "Shuffle machine instructions alternating directions",
3510 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003511#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003512
3513//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003514// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003515//===----------------------------------------------------------------------===//
3516
3517#ifndef NDEBUG
3518namespace llvm {
3519
3520template<> struct GraphTraits<
3521 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3522
3523template<>
3524struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3525
3526 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3527
3528 static std::string getGraphName(const ScheduleDAG *G) {
3529 return G->MF.getName();
3530 }
3531
3532 static bool renderGraphFromBottomUp() {
3533 return true;
3534 }
3535
3536 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003537 if (ViewMISchedCutoff == 0)
3538 return false;
3539 return (Node->Preds.size() > ViewMISchedCutoff
3540 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003541 }
3542
Andrew Trickea9fd952013-01-25 07:45:29 +00003543 /// If you want to override the dot attributes printed for a particular
3544 /// edge, override this method.
3545 static std::string getEdgeAttributes(const SUnit *Node,
3546 SUnitIterator EI,
3547 const ScheduleDAG *Graph) {
3548 if (EI.isArtificialDep())
3549 return "color=cyan,style=dashed";
3550 if (EI.isCtrlDep())
3551 return "color=blue,style=dashed";
3552 return "";
3553 }
3554
3555 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003556 std::string Str;
3557 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003558 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3559 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003560 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003561 SS << "SU:" << SU->NodeNum;
3562 if (DFS)
3563 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003564 return SS.str();
3565 }
3566 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3567 return G->getGraphNodeLabel(SU);
3568 }
3569
Andrew Trickd7f890e2013-12-28 21:56:47 +00003570 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003571 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003572 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3573 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003574 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003575 if (DFS) {
3576 Str += ",style=filled,fillcolor=\"#";
3577 Str += DOT::getColorString(DFS->getSubtreeID(N));
3578 Str += '"';
3579 }
3580 return Str;
3581 }
3582};
3583} // namespace llvm
3584#endif // NDEBUG
3585
3586/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3587/// rendered using 'dot'.
3588///
3589void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3590#ifndef NDEBUG
3591 ViewGraph(this, Name, false, Title);
3592#else
3593 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3594 << "systems with Graphviz or gv!\n";
3595#endif // NDEBUG
3596}
3597
3598/// Out-of-line implementation with no arguments is handy for gdb.
3599void ScheduleDAGMI::viewGraph() {
3600 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3601}