blob: d60f17ad07f128e0eb8d101c8cf13156c1b8e585 [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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000025#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000035#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000036#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000038#include "llvm/CodeGen/ScheduleDAG.h"
39#include "llvm/CodeGen/ScheduleDAGInstrs.h"
40#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000041#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000042#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000043#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000044#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000045#include "llvm/CodeGen/TargetLowering.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000046#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000047#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000048#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000049#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000050#include "llvm/Config/llvm-config.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000051#include "llvm/MC/LaneBitmask.h"
52#include "llvm/Pass.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000053#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000054#include "llvm/Support/Compiler.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000055#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000057#include "llvm/Support/GraphWriter.h"
David Blaikie13e77db2018-03-23 23:58:25 +000058#include "llvm/Support/MachineValueType.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000059#include "llvm/Support/raw_ostream.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000060#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <iterator>
64#include <limits>
65#include <memory>
66#include <string>
67#include <tuple>
68#include <utility>
69#include <vector>
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000070
Andrew Tricke77e84e2012-01-13 06:30:30 +000071using namespace llvm;
72
Matthias Braun1527baa2017-05-25 21:26:32 +000073#define DEBUG_TYPE "machine-scheduler"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000074
Andrew Trick7a8e1002012-09-11 00:39:15 +000075namespace llvm {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000076
Andrew Trick7a8e1002012-09-11 00:39:15 +000077cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
78 cl::desc("Force top-down list scheduling"));
79cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
80 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000081cl::opt<bool>
82DumpCriticalPathLength("misched-dcpl", cl::Hidden,
83 cl::desc("Print critical path length to stdout"));
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000084
85} // end namespace llvm
Andrew Trick8823dec2012-03-14 04:00:41 +000086
Andrew Tricka5f19562012-03-07 00:18:25 +000087#ifndef NDEBUG
88static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
89 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000090
Matthias Braund78ee542015-09-17 21:09:59 +000091/// In some situations a few uninteresting nodes depend on nearly all other
92/// nodes in the graph, provide a cutoff to hide them.
93static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
94 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
95
Lang Hamesdd98c492012-03-19 18:38:38 +000096static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
97 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000098
99static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
100 cl::desc("Only schedule this function"));
101static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000102 cl::desc("Only schedule this MBB#"));
Matthias Braun3136e422018-09-19 20:50:49 +0000103static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
104 cl::desc("Print schedule DAGs"));
Andrew Tricka5f19562012-03-07 00:18:25 +0000105#else
Matthias Braun3136e422018-09-19 20:50:49 +0000106static const bool ViewMISchedDAGs = false;
107static const bool PrintDAGs = false;
Andrew Tricka5f19562012-03-07 00:18:25 +0000108#endif // NDEBUG
109
Matthias Braun6493bc22016-04-22 19:09:17 +0000110/// Avoid quadratic complexity in unusually large basic blocks by limiting the
111/// size of the ready lists.
112static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
113 cl::desc("Limit ready list to N instructions"), cl::init(256));
114
Andrew Trickb6e74712013-09-04 20:59:59 +0000115static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
116 cl::desc("Enable register pressure scheduling."), cl::init(true));
117
Andrew Trickc01b0042013-08-23 17:48:43 +0000118static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +0000119 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +0000120
Jun Bum Lim4c5bd582016-04-15 14:58:38 +0000121static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
122 cl::desc("Enable memop clustering."),
123 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +0000124
Andrew Trick48f2a722013-03-08 05:40:34 +0000125static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
126 cl::desc("Verify machine instrs before and after machine scheduling"));
127
Andrew Trick44f750a2013-01-25 04:01:04 +0000128// DAG subtrees must have at least this many nodes.
129static const unsigned MinSubtreeSize = 8;
130
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000131// Pin the vtables to this file.
132void MachineSchedStrategy::anchor() {}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000133
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000134void ScheduleDAGMutation::anchor() {}
135
Andrew Trick63440872012-01-14 02:17:06 +0000136//===----------------------------------------------------------------------===//
137// Machine Instruction Scheduling Pass and Registry
138//===----------------------------------------------------------------------===//
139
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000140MachineSchedContext::MachineSchedContext() {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000141 RegClassInfo = new RegisterClassInfo();
142}
143
144MachineSchedContext::~MachineSchedContext() {
145 delete RegClassInfo;
146}
147
Andrew Tricke77e84e2012-01-13 06:30:30 +0000148namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000149
Andrew Trickd7f890e2013-12-28 21:56:47 +0000150/// Base class for a machine scheduler class that can run at any point.
151class MachineSchedulerBase : public MachineSchedContext,
152 public MachineFunctionPass {
153public:
154 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
155
Craig Topperc0196b12014-04-14 00:51:57 +0000156 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000157
158protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000159 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000160};
161
Andrew Tricke1c034f2012-01-17 06:55:03 +0000162/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000163class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000164public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000165 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000166
Craig Topper4584cd52014-03-07 09:26:03 +0000167 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000168
Craig Topper4584cd52014-03-07 09:26:03 +0000169 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000170
Andrew Tricke77e84e2012-01-13 06:30:30 +0000171 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000172
173protected:
174 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000175};
Andrew Trick17080b92013-12-28 21:56:51 +0000176
177/// PostMachineScheduler runs after shortly before code emission.
178class PostMachineScheduler : public MachineSchedulerBase {
179public:
180 PostMachineScheduler();
181
Craig Topper4584cd52014-03-07 09:26:03 +0000182 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000183
Craig Topper4584cd52014-03-07 09:26:03 +0000184 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000185
186 static char ID; // Class identification, replacement for typeinfo
187
188protected:
189 ScheduleDAGInstrs *createPostMachineScheduler();
190};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000191
192} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +0000193
Andrew Tricke1c034f2012-01-17 06:55:03 +0000194char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000195
Andrew Tricke1c034f2012-01-17 06:55:03 +0000196char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000197
Matthias Braun1527baa2017-05-25 21:26:32 +0000198INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000199 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000200INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Davide Italiano6a1209e2017-03-24 20:52:56 +0000201INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000202INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
203INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000204INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000205 "Machine Instruction Scheduler", false, false)
206
Eugene Zelenko32a40562017-09-11 23:00:48 +0000207MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000208 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000209}
210
Andrew Tricke1c034f2012-01-17 06:55:03 +0000211void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000212 AU.setPreservesCFG();
213 AU.addRequiredID(MachineDominatorsID);
214 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000215 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000216 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000217 AU.addRequired<SlotIndexes>();
218 AU.addPreserved<SlotIndexes>();
219 AU.addRequired<LiveIntervals>();
220 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000221 MachineFunctionPass::getAnalysisUsage(AU);
222}
223
Andrew Trick17080b92013-12-28 21:56:51 +0000224char PostMachineScheduler::ID = 0;
225
226char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
227
228INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000229 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000230
Eugene Zelenko32a40562017-09-11 23:00:48 +0000231PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
Andrew Trick17080b92013-12-28 21:56:51 +0000232 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
233}
234
235void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
236 AU.setPreservesCFG();
237 AU.addRequiredID(MachineDominatorsID);
238 AU.addRequired<MachineLoopInfo>();
239 AU.addRequired<TargetPassConfig>();
240 MachineFunctionPass::getAnalysisUsage(AU);
241}
242
Andrew Tricke77e84e2012-01-13 06:30:30 +0000243MachinePassRegistry MachineSchedRegistry::Registry;
244
Andrew Trick45300682012-03-09 00:52:20 +0000245/// A dummy default scheduler factory indicates whether the scheduler
246/// is overridden on the command line.
247static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000248 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000249}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000250
251/// MachineSchedOpt allows command line selection of the scheduler.
252static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000253 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000254MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000255 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000256 cl::desc("Machine instruction scheduler to use"));
257
Andrew Trick45300682012-03-09 00:52:20 +0000258static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000259DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000260 useDefaultMachineSched);
261
Eric Christopher5f141b02015-03-11 22:56:10 +0000262static cl::opt<bool> EnableMachineSched(
263 "enable-misched",
264 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
265 cl::Hidden);
266
Chad Rosier816a1ab2016-01-20 23:08:32 +0000267static cl::opt<bool> EnablePostRAMachineSched(
268 "enable-post-misched",
269 cl::desc("Enable the post-ra machine instruction scheduling pass."),
270 cl::init(true), cl::Hidden);
271
Andrew Trickcc45a282012-04-24 18:04:34 +0000272/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000273static MachineBasicBlock::const_iterator
274priorNonDebug(MachineBasicBlock::const_iterator I,
275 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000276 assert(I != Beg && "reached the top of the region, cannot decrement");
277 while (--I != Beg) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000278 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000279 break;
280 }
281 return I;
282}
283
Andrew Trick2bc74c22013-08-30 04:36:57 +0000284/// Non-const version.
285static MachineBasicBlock::iterator
286priorNonDebug(MachineBasicBlock::iterator I,
287 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000288 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
289 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000290}
291
Andrew Trickcc45a282012-04-24 18:04:34 +0000292/// If this iterator is a debug value, increment until reaching the End or a
293/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000294static MachineBasicBlock::const_iterator
295nextIfDebug(MachineBasicBlock::const_iterator I,
296 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000297 for(; I != End; ++I) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000298 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000299 break;
300 }
301 return I;
302}
303
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000304/// Non-const version.
305static MachineBasicBlock::iterator
306nextIfDebug(MachineBasicBlock::iterator I,
307 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000308 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
309 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000310}
311
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000312/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000313ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
314 // Select the scheduler, or set the default.
315 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
316 if (Ctor != useDefaultMachineSched)
317 return Ctor(this);
318
319 // Get the default scheduler set by the target for this function.
320 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
321 if (Scheduler)
322 return Scheduler;
323
324 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000325 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000326}
327
Andrew Trick17080b92013-12-28 21:56:51 +0000328/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
329/// the caller. We don't have a command line option to override the postRA
330/// scheduler. The Target must configure it.
331ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
332 // Get the postRA scheduler set by the target for this function.
333 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
334 if (Scheduler)
335 return Scheduler;
336
337 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000338 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000339}
340
Andrew Trick72515be2012-03-14 04:00:38 +0000341/// Top-level MachineScheduler pass driver.
342///
343/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000344/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
345/// consistent with the DAG builder, which traverses the interior of the
346/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000347///
348/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000349/// simplifying the DAG builder's support for "special" target instructions.
350/// At the same time the design allows target schedulers to operate across
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000351/// scheduling boundaries, for example to bundle the boundary instructions
Andrew Trick72515be2012-03-14 04:00:38 +0000352/// without reordering them. This creates complexity, because the target
353/// scheduler must update the RegionBegin and RegionEnd positions cached by
354/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
355/// design would be to split blocks at scheduling boundaries, but LLVM has a
356/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000357bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000358 if (skipFunction(mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000359 return false;
360
Eric Christopher5f141b02015-03-11 22:56:10 +0000361 if (EnableMachineSched.getNumOccurrences()) {
362 if (!EnableMachineSched)
363 return false;
364 } else if (!mf.getSubtarget().enableMachineScheduler())
365 return false;
366
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000367 LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000368
Andrew Tricke77e84e2012-01-13 06:30:30 +0000369 // Initialize the context of the pass.
370 MF = &mf;
371 MLI = &getAnalysis<MachineLoopInfo>();
372 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000373 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000374 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000375
Lang Hamesad33d5a2012-01-27 22:36:19 +0000376 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000377
Andrew Trick48f2a722013-03-08 05:40:34 +0000378 if (VerifyScheduling) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000379 LLVM_DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000380 MF->verify(this, "Before machine scheduling.");
381 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000382 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000383
Andrew Trick978674b2013-09-20 05:14:41 +0000384 // Instantiate the selected scheduler for this target, function, and
385 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000386 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000387 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000388
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000389 LLVM_DEBUG(LIS->dump());
Andrew Trickd7f890e2013-12-28 21:56:47 +0000390 if (VerifyScheduling)
391 MF->verify(this, "After machine scheduling.");
392 return true;
393}
394
Andrew Trick17080b92013-12-28 21:56:51 +0000395bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000396 if (skipFunction(mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000397 return false;
398
Chad Rosier816a1ab2016-01-20 23:08:32 +0000399 if (EnablePostRAMachineSched.getNumOccurrences()) {
400 if (!EnablePostRAMachineSched)
401 return false;
402 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000403 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
Andrew Trick8d2ee372014-06-04 07:06:27 +0000404 return false;
405 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000406 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
Andrew Trick17080b92013-12-28 21:56:51 +0000407
408 // Initialize the context of the pass.
409 MF = &mf;
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000410 MLI = &getAnalysis<MachineLoopInfo>();
Andrew Trick17080b92013-12-28 21:56:51 +0000411 PassConfig = &getAnalysis<TargetPassConfig>();
412
413 if (VerifyScheduling)
414 MF->verify(this, "Before post machine scheduling.");
415
416 // Instantiate the selected scheduler for this target, function, and
417 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000418 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000419 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000420
421 if (VerifyScheduling)
422 MF->verify(this, "After post machine scheduling.");
423 return true;
424}
425
Andrew Trickd14d7c22013-12-28 21:56:57 +0000426/// Return true of the given instruction should not be included in a scheduling
427/// region.
428///
429/// MachineScheduler does not currently support scheduling across calls. To
430/// handle calls, the DAG builder needs to be modified to create register
431/// anti/output dependencies on the registers clobbered by the call's regmask
432/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
433/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
434/// the boundary, but there would be no benefit to postRA scheduling across
435/// calls this late anyway.
436static bool isSchedBoundary(MachineBasicBlock::iterator MI,
437 MachineBasicBlock *MBB,
438 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000439 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000440 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000441}
442
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000443/// A region of an MBB for scheduling.
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000444namespace {
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000445struct SchedRegion {
446 /// RegionBegin is the first instruction in the scheduling region, and
447 /// RegionEnd is either MBB->end() or the scheduling boundary after the
448 /// last instruction in the scheduling region. These iterators cannot refer
449 /// to instructions outside of the identified scheduling region because
450 /// those may be reordered before scheduling this region.
451 MachineBasicBlock::iterator RegionBegin;
452 MachineBasicBlock::iterator RegionEnd;
453 unsigned NumRegionInstrs;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000454
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000455 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
456 unsigned N) :
457 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
458};
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000459} // end anonymous namespace
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000460
Eugene Zelenko32a40562017-09-11 23:00:48 +0000461using MBBRegionsVector = SmallVector<SchedRegion, 16>;
462
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000463static void
464getSchedRegions(MachineBasicBlock *MBB,
465 MBBRegionsVector &Regions,
466 bool RegionsTopDown) {
467 MachineFunction *MF = MBB->getParent();
468 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
469
470 MachineBasicBlock::iterator I = nullptr;
471 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
472 RegionEnd != MBB->begin(); RegionEnd = I) {
473
474 // Avoid decrementing RegionEnd for blocks with no terminator.
475 if (RegionEnd != MBB->end() ||
476 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
477 --RegionEnd;
478 }
479
480 // The next region starts above the previous region. Look backward in the
481 // instruction stream until we find the nearest boundary.
482 unsigned NumRegionInstrs = 0;
483 I = RegionEnd;
484 for (;I != MBB->begin(); --I) {
485 MachineInstr &MI = *std::prev(I);
486 if (isSchedBoundary(&MI, &*MBB, MF, TII))
487 break;
Shiva Chen801bf7e2018-05-09 02:42:00 +0000488 if (!MI.isDebugInstr())
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000489 // MBB::size() uses instr_iterator to count. Here we need a bundle to
490 // count as a single instruction.
491 ++NumRegionInstrs;
492 }
493
494 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
495 }
496
497 if (RegionsTopDown)
498 std::reverse(Regions.begin(), Regions.end());
499}
500
Andrew Trickd7f890e2013-12-28 21:56:47 +0000501/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000502void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
503 bool FixKillFlags) {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000504 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000505 //
506 // TODO: Visit blocks in global postorder or postorder within the bottom-up
507 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000508 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
509 MBB != MBBEnd; ++MBB) {
510
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000511 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000512
Andrew Trick33e05d72013-12-28 21:57:02 +0000513#ifndef NDEBUG
514 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
515 continue;
516 if (SchedOnlyBlock.getNumOccurrences()
517 && (int)SchedOnlyBlock != MBB->getNumber())
518 continue;
519#endif
520
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000521 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
522 // points to the scheduling boundary at the bottom of the region. The DAG
523 // does not include RegionEnd, but the region does (i.e. the next
524 // RegionEnd is above the previous RegionBegin). If the current block has
525 // no terminator then RegionEnd == MBB->end() for the bottom region.
526 //
527 // All the regions of MBB are first found and stored in MBBRegions, which
528 // will be processed (MBB) top-down if initialized with true.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000529 //
530 // The Scheduler may insert instructions during either schedule() or
531 // exitRegion(), even for empty regions. So the local iterators 'I' and
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000532 // 'RegionEnd' are invalid across these calls. Instructions must not be
533 // added to other regions than the current one without updating MBBRegions.
Andrew Trick88639922012-04-24 17:56:43 +0000534
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000535 MBBRegionsVector MBBRegions;
536 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
537 for (MBBRegionsVector::iterator R = MBBRegions.begin();
538 R != MBBRegions.end(); ++R) {
539 MachineBasicBlock::iterator I = R->RegionBegin;
540 MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
541 unsigned NumRegionInstrs = R->NumRegionInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000542
Andrew Trick60cf03e2012-03-07 05:21:52 +0000543 // Notify the scheduler of the region, even if we may skip scheduling
544 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000545 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000546
547 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000548 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000549 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000550 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000551 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000552 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000553 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
555 LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
556 << " " << MBB->getName() << "\n From: " << *I
557 << " To: ";
558 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
559 else dbgs() << "End";
560 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000561 if (DumpCriticalPathLength) {
562 errs() << MF->getName();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000563 errs() << ":%bb. " << MBB->getNumber();
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000564 errs() << " " << MBB->getName() << " \n";
565 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000566
Andrew Trick1c0ec452012-03-09 03:46:42 +0000567 // Schedule a region: possibly reorder instructions.
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000568 // This invalidates the original region iterators.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000569 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000570
571 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000572 Scheduler.exitRegion();
Andrew Trick7e120f42012-01-14 02:17:09 +0000573 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000574 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000575 // FIXME: Ideally, no further passes should rely on kill flags. However,
576 // thumb2 size reduction is currently an exception, so the PostMIScheduler
577 // needs to do this.
578 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000579 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000580 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000581 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000582}
583
Andrew Trickd7f890e2013-12-28 21:56:47 +0000584void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000585 // unimplemented
586}
587
Aaron Ballman615eb472017-10-15 14:32:27 +0000588#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000589LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000590 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000591 for (const SUnit *SU : Queue)
592 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000593 dbgs() << "\n";
594}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000595#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000596
597//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000598// ScheduleDAGMI - Basic machine instruction scheduling. This is
599// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
600// virtual registers.
601// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000602
David Blaikie422b93d2014-04-21 20:32:32 +0000603// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000604ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000605
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000606bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
607 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
608}
609
Andrew Tricka7714a02012-11-12 19:40:10 +0000610bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000611 if (SuccSU != &ExitSU) {
612 // Do not use WillCreateCycle, it assumes SD scheduling.
613 // If Pred is reachable from Succ, then the edge creates a cycle.
614 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
615 return false;
616 Topo.AddPred(SuccSU, PredDep.getSUnit());
617 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000618 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
619 // Return true regardless of whether a new edge needed to be inserted.
620 return true;
621}
622
Andrew Trick02a80da2012-03-08 01:41:12 +0000623/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
624/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000625///
626/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000627void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000628 SUnit *SuccSU = SuccEdge->getSUnit();
629
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000630 if (SuccEdge->isWeak()) {
631 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000632 if (SuccEdge->isCluster())
633 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000634 return;
635 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000636#ifndef NDEBUG
637 if (SuccSU->NumPredsLeft == 0) {
638 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braun726e12c2018-09-19 00:23:35 +0000639 dumpNode(*SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000640 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000641 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000642 }
643#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000644 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
645 // CurrCycle may have advanced since then.
646 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
647 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
648
Andrew Trick02a80da2012-03-08 01:41:12 +0000649 --SuccSU->NumPredsLeft;
650 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000651 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000652}
653
654/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000655void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000656 for (SDep &Succ : SU->Succs)
657 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000658}
659
Andrew Trick8823dec2012-03-14 04:00:41 +0000660/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
661/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000662///
663/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000664void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
665 SUnit *PredSU = PredEdge->getSUnit();
666
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000667 if (PredEdge->isWeak()) {
668 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000669 if (PredEdge->isCluster())
670 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000671 return;
672 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000673#ifndef NDEBUG
674 if (PredSU->NumSuccsLeft == 0) {
675 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braun726e12c2018-09-19 00:23:35 +0000676 dumpNode(*PredSU);
Andrew Trick8823dec2012-03-14 04:00:41 +0000677 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000678 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000679 }
680#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000681 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
682 // CurrCycle may have advanced since then.
683 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
684 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
685
Andrew Trick8823dec2012-03-14 04:00:41 +0000686 --PredSU->NumSuccsLeft;
687 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
688 SchedImpl->releaseBottomNode(PredSU);
689}
690
691/// releasePredecessors - Call releasePred on each of SU's predecessors.
692void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000693 for (SDep &Pred : SU->Preds)
694 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000695}
696
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000697void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
698 ScheduleDAGInstrs::startBlock(bb);
699 SchedImpl->enterMBB(bb);
700}
701
702void ScheduleDAGMI::finishBlock() {
703 SchedImpl->leaveMBB();
704 ScheduleDAGInstrs::finishBlock();
705}
706
Andrew Trickd7f890e2013-12-28 21:56:47 +0000707/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
708/// crossing a scheduling boundary. [begin, end) includes all instructions in
709/// the region, including the boundary itself and single-instruction regions
710/// that don't get scheduled.
711void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
712 MachineBasicBlock::iterator begin,
713 MachineBasicBlock::iterator end,
714 unsigned regioninstrs)
715{
716 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
717
718 SchedImpl->initPolicy(begin, end, regioninstrs);
719}
720
Andrew Tricke833e1c2013-04-13 06:07:40 +0000721/// This is normally called from the main scheduler loop but may also be invoked
722/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000723void ScheduleDAGMI::moveInstruction(
724 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000725 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000726 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000727 ++RegionBegin;
728
729 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000730 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000731
732 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000733 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000734 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000735
736 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000737 if (RegionBegin == InsertPos)
738 RegionBegin = MI;
739}
740
Andrew Trickde670c02012-03-21 04:12:07 +0000741bool ScheduleDAGMI::checkSchedLimit() {
742#ifndef NDEBUG
743 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
744 CurrentTop = CurrentBottom;
745 return false;
746 }
747 ++NumInstrsScheduled;
748#endif
749 return true;
750}
751
Andrew Trickd7f890e2013-12-28 21:56:47 +0000752/// Per-region scheduling driver, called back from
753/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
754/// does not consider liveness or register pressure. It is useful for PostRA
755/// scheduling and potentially other custom schedulers.
756void ScheduleDAGMI::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000757 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
758 LLVM_DEBUG(SchedImpl->dumpPolicy());
James Y Knighte72b0db2015-09-18 18:52:20 +0000759
Andrew Trickd7f890e2013-12-28 21:56:47 +0000760 // Build the DAG.
761 buildSchedGraph(AA);
762
763 Topo.InitDAGTopologicalSorting();
764
765 postprocessDAG();
766
767 SmallVector<SUnit*, 8> TopRoots, BotRoots;
768 findRootsAndBiasEdges(TopRoots, BotRoots);
769
Matthias Braun726e12c2018-09-19 00:23:35 +0000770 LLVM_DEBUG(dump());
Matthias Braun3136e422018-09-19 20:50:49 +0000771 if (PrintDAGs) dump();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000772 if (ViewMISchedDAGs) viewGraph();
773
Jonas Paulssonbc32f7d2018-03-05 16:31:49 +0000774 // Initialize the strategy before modifying the DAG.
775 // This may initialize a DFSResult to be used for queue priority.
776 SchedImpl->initialize(this);
777
Andrew Trickd7f890e2013-12-28 21:56:47 +0000778 // Initialize ready queues now that the DAG and priority data are finalized.
779 initQueues(TopRoots, BotRoots);
780
781 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000782 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000783 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +0000784 SUnit *SU = SchedImpl->pickNode(IsTopNode);
785 if (!SU) break;
786
Andrew Trickd7f890e2013-12-28 21:56:47 +0000787 assert(!SU->isScheduled && "Node already scheduled");
788 if (!checkSchedLimit())
789 break;
790
791 MachineInstr *MI = SU->getInstr();
792 if (IsTopNode) {
793 assert(SU->isTopReady() && "node still has unscheduled dependencies");
794 if (&*CurrentTop == MI)
795 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
796 else
797 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000798 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000799 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
800 MachineBasicBlock::iterator priorII =
801 priorNonDebug(CurrentBottom, CurrentTop);
802 if (&*priorII == MI)
803 CurrentBottom = priorII;
804 else {
805 if (&*CurrentTop == MI)
806 CurrentTop = nextIfDebug(++CurrentTop, priorII);
807 moveInstruction(MI, CurrentBottom);
808 CurrentBottom = MI;
809 }
810 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000811 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000812 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000813 // runs, it can then use the accurate ReadyCycle time to determine whether
814 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000815 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000816
817 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000818 }
819 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
820
821 placeDebugValues();
822
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000823 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000824 dbgs() << "*** Final schedule for "
825 << printMBBReference(*begin()->getParent()) << " ***\n";
826 dumpSchedule();
827 dbgs() << '\n';
828 });
Andrew Trickd7f890e2013-12-28 21:56:47 +0000829}
830
831/// Apply each ScheduleDAGMutation step in order.
832void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000833 for (auto &m : Mutations)
834 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000835}
836
837void ScheduleDAGMI::
838findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
839 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000840 for (SUnit &SU : SUnits) {
841 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000842
843 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000844 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000845
846 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000847 if (!SU.NumPredsLeft)
848 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000849 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000850 if (!SU.NumSuccsLeft)
851 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000852 }
853 ExitSU.biasCriticalPath();
854}
855
856/// Identify DAG roots and setup scheduler queues.
857void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
858 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000859 NextClusterSucc = nullptr;
860 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000861
862 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
863 //
864 // Nodes with unreleased weak edges can still be roots.
865 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000866 for (SUnit *SU : TopRoots)
867 SchedImpl->releaseTopNode(SU);
868
Andrew Trickd7f890e2013-12-28 21:56:47 +0000869 // Release bottom roots in reverse order so the higher priority nodes appear
870 // first. This is more natural and slightly more efficient.
871 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
872 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
873 SchedImpl->releaseBottomNode(*I);
874 }
875
876 releaseSuccessors(&EntrySU);
877 releasePredecessors(&ExitSU);
878
879 SchedImpl->registerRoots();
880
881 // Advance past initial DebugValues.
882 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
883 CurrentBottom = RegionEnd;
884}
885
886/// Update scheduler queues after scheduling an instruction.
887void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
888 // Release dependent instructions for scheduling.
889 if (IsTopNode)
890 releaseSuccessors(SU);
891 else
892 releasePredecessors(SU);
893
894 SU->isScheduled = true;
895}
896
897/// Reinsert any remaining debug_values, just like the PostRA scheduler.
898void ScheduleDAGMI::placeDebugValues() {
899 // If first instruction was a DBG_VALUE then put it back.
900 if (FirstDbgValue) {
901 BB->splice(RegionBegin, BB, FirstDbgValue);
902 RegionBegin = FirstDbgValue;
903 }
904
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000905 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000906 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000907 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000908 MachineInstr *DbgValue = P.first;
909 MachineBasicBlock::iterator OrigPrevMI = P.second;
910 if (&*RegionBegin == DbgValue)
911 ++RegionBegin;
912 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000913 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000914 RegionEnd = DbgValue;
915 }
916 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000917 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000918}
919
Aaron Ballman615eb472017-10-15 14:32:27 +0000920#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000921LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000922 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
923 if (SUnit *SU = getSUnit(&(*MI)))
Matthias Braun726e12c2018-09-19 00:23:35 +0000924 dumpNode(*SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000925 else
926 dbgs() << "Missing SUnit\n";
927 }
928}
929#endif
930
931//===----------------------------------------------------------------------===//
932// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
933// preservation.
934//===----------------------------------------------------------------------===//
935
936ScheduleDAGMILive::~ScheduleDAGMILive() {
937 delete DFSResult;
938}
939
Matthias Braun40639882016-11-11 22:37:31 +0000940void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
941 const MachineInstr &MI = *SU.getInstr();
942 for (const MachineOperand &MO : MI.operands()) {
943 if (!MO.isReg())
944 continue;
945 if (!MO.readsReg())
946 continue;
947 if (TrackLaneMasks && !MO.isUse())
948 continue;
949
950 unsigned Reg = MO.getReg();
951 if (!TargetRegisterInfo::isVirtualRegister(Reg))
952 continue;
953
954 // Ignore re-defs.
955 if (TrackLaneMasks) {
956 bool FoundDef = false;
957 for (const MachineOperand &MO2 : MI.operands()) {
958 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
959 FoundDef = true;
960 break;
961 }
962 }
963 if (FoundDef)
964 continue;
965 }
966
967 // Record this local VReg use.
968 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
969 for (; UI != VRegUses.end(); ++UI) {
970 if (UI->SU == &SU)
971 break;
972 }
973 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000974 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000975 }
976}
977
Andrew Trick88639922012-04-24 17:56:43 +0000978/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
979/// crossing a scheduling boundary. [begin, end) includes all instructions in
980/// the region, including the boundary itself and single-instruction regions
981/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000982void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000983 MachineBasicBlock::iterator begin,
984 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000985 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000986{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000987 // ScheduleDAGMI initializes SchedImpl's per-region policy.
988 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000989
990 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000991 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000992
Andrew Trickb248b4a2013-09-06 17:32:47 +0000993 SUPressureDiffs.clear();
994
Andrew Trick75e411c2013-09-06 17:32:34 +0000995 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000996 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
997
Matthias Braunf9acaca2016-05-31 22:38:06 +0000998 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
999 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +00001000}
1001
1002// Setup the register pressure trackers for the top scheduled top and bottom
1003// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001004void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +00001005 VRegUses.clear();
1006 VRegUses.setUniverse(MRI.getNumVirtRegs());
1007 for (SUnit &SU : SUnits)
1008 collectVRegUses(SU);
1009
Matthias Braund4f64092016-01-20 00:23:32 +00001010 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1011 ShouldTrackLaneMasks, false);
1012 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1013 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +00001014
1015 // Close the RPTracker to finalize live ins.
1016 RPTracker.closeRegion();
1017
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001018 LLVM_DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +00001019
Andrew Trick4add42f2012-05-10 21:06:10 +00001020 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +00001021 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1022 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +00001023
1024 // Close one end of the tracker so we can call
1025 // getMaxUpward/DownwardPressureDelta before advancing across any
1026 // instructions. This converts currently live regs into live ins/outs.
1027 TopRPTracker.closeTop();
1028 BotRPTracker.closeBottom();
1029
Andrew Trick9c17eab2013-07-30 19:59:12 +00001030 BotRPTracker.initLiveThru(RPTracker);
1031 if (!BotRPTracker.getLiveThru().empty()) {
1032 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001033 LLVM_DEBUG(dbgs() << "Live Thru: ";
1034 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
Andrew Trick9c17eab2013-07-30 19:59:12 +00001035 };
1036
Andrew Trick2bc74c22013-08-30 04:36:57 +00001037 // For each live out vreg reduce the pressure change associated with other
1038 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +00001039 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +00001040
Andrew Trick4add42f2012-05-10 21:06:10 +00001041 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001042 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001043 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001044 BotRPTracker.recede(&LiveUses);
1045 updatePressureDiffs(LiveUses);
1046 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001047
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001048 LLVM_DEBUG(dbgs() << "Top Pressure:\n";
1049 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1050 dbgs() << "Bottom Pressure:\n";
1051 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braune6edd482015-11-13 22:30:31 +00001052
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001053 assert((BotRPTracker.getPos() == RegionEnd ||
Shiva Chen801bf7e2018-05-09 02:42:00 +00001054 (RegionEnd->isDebugInstr() &&
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001055 BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
1056 "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001057
1058 // Cache the list of excess pressure sets in this region. This will also track
1059 // the max pressure in the scheduled code for these sets.
1060 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001061 const std::vector<unsigned> &RegionPressure =
1062 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001063 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001064 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001065 if (RegionPressure[i] > Limit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001066 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1067 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001068 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001069 }
Andrew Trick22025772012-05-17 18:35:10 +00001070 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001071 LLVM_DEBUG(dbgs() << "Excess PSets: ";
1072 for (const PressureChange &RCPS
1073 : RegionCriticalPSets) dbgs()
1074 << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1075 dbgs() << "\n");
Andrew Trick22025772012-05-17 18:35:10 +00001076}
1077
Andrew Trickd7f890e2013-12-28 21:56:47 +00001078void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001079updateScheduledPressure(const SUnit *SU,
1080 const std::vector<unsigned> &NewMaxPressure) {
1081 const PressureDiff &PDiff = getPressureDiff(SU);
1082 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001083 for (const PressureChange &PC : PDiff) {
1084 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001085 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001086 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001087 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1088 ++CritIdx;
1089 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1090 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001091 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001092 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1093 }
1094 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1095 if (NewMaxPressure[ID] >= Limit - 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001096 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
1097 << NewMaxPressure[ID]
1098 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1099 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1100 << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001101 }
Andrew Trick22025772012-05-17 18:35:10 +00001102 }
Andrew Trick88639922012-04-24 17:56:43 +00001103}
1104
Andrew Trick2bc74c22013-08-30 04:36:57 +00001105/// Update the PressureDiff array for liveness after scheduling this
1106/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001107void ScheduleDAGMILive::updatePressureDiffs(
1108 ArrayRef<RegisterMaskPair> LiveUses) {
1109 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001110 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001111 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001112 if (!TRI->isVirtualRegister(Reg))
1113 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001114
Matthias Braund4f64092016-01-20 00:23:32 +00001115 if (ShouldTrackLaneMasks) {
1116 // If the register has just become live then other uses won't change
1117 // this fact anymore => decrement pressure.
1118 // If the register has just become dead then other uses make it come
1119 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001120 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001121
1122 for (const VReg2SUnit &V2SU
1123 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1124 SUnit &SU = *V2SU.SU;
1125 if (SU.isScheduled || &SU == &ExitSU)
1126 continue;
1127
1128 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001129 PDiff.addPressureChange(Reg, Decrement, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001130 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1131 << printReg(Reg, TRI) << ':'
1132 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1133 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001134 }
1135 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001136 assert(P.LaneMask.any());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001137 LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
Matthias Braund4f64092016-01-20 00:23:32 +00001138 // This may be called before CurrentBottom has been initialized. However,
1139 // BotRPTracker must have a valid position. We want the value live into the
1140 // instruction or live out of the block, so ask for the previous
1141 // instruction's live-out.
1142 const LiveInterval &LI = LIS->getInterval(Reg);
1143 VNInfo *VNI;
1144 MachineBasicBlock::const_iterator I =
1145 nextIfDebug(BotRPTracker.getPos(), BB->end());
1146 if (I == BB->end())
1147 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1148 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001149 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001150 VNI = LRQ.valueIn();
1151 }
1152 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1153 assert(VNI && "No live value at use.");
1154 for (const VReg2SUnit &V2SU
1155 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1156 SUnit *SU = V2SU.SU;
1157 // If this use comes before the reaching def, it cannot be a last use,
1158 // so decrease its pressure change.
1159 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001160 LiveQueryResult LRQ =
1161 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001162 if (LRQ.valueIn() == VNI) {
1163 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001164 PDiff.addPressureChange(Reg, true, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001165 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1166 << *SU->getInstr();
1167 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001168 }
Matthias Braun9198c672015-11-06 20:59:02 +00001169 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001170 }
1171 }
1172 }
1173}
1174
Matthias Braun726e12c2018-09-19 00:23:35 +00001175void ScheduleDAGMILive::dump() const {
1176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1177 if (EntrySU.getInstr() != nullptr)
1178 dumpNodeAll(EntrySU);
1179 for (const SUnit &SU : SUnits) {
1180 dumpNodeAll(SU);
1181 if (ShouldTrackPressure) {
1182 dbgs() << " Pressure Diff : ";
1183 getPressureDiff(&SU).dump(*TRI);
1184 }
1185 dbgs() << " Single Issue : ";
1186 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1187 SchedModel.mustEndGroup(SU.getInstr()))
1188 dbgs() << "true;";
1189 else
1190 dbgs() << "false;";
1191 dbgs() << '\n';
1192 }
1193 if (ExitSU.getInstr() != nullptr)
1194 dumpNodeAll(ExitSU);
1195#endif
1196}
1197
Andrew Trick8823dec2012-03-14 04:00:41 +00001198/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001199/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1200/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001201///
1202/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001203/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001204/// implementing MachineSchedStrategy should be sufficient to implement a new
1205/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001206/// ScheduleDAGMILive then it will want to override this virtual method in order
1207/// to update any specialized state.
1208void ScheduleDAGMILive::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001209 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1210 LLVM_DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001211 buildDAGWithRegPressure();
1212
Andrew Tricka7714a02012-11-12 19:40:10 +00001213 Topo.InitDAGTopologicalSorting();
1214
Andrew Tricka2733e92012-09-14 17:22:42 +00001215 postprocessDAG();
1216
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001217 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1218 findRootsAndBiasEdges(TopRoots, BotRoots);
1219
1220 // Initialize the strategy before modifying the DAG.
1221 // This may initialize a DFSResult to be used for queue priority.
1222 SchedImpl->initialize(this);
1223
Matthias Braun726e12c2018-09-19 00:23:35 +00001224 LLVM_DEBUG(dump());
Matthias Braun3136e422018-09-19 20:50:49 +00001225 if (PrintDAGs) dump();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001226 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001227
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001228 // Initialize ready queues now that the DAG and priority data are finalized.
1229 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001230
1231 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001232 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001233 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +00001234 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1235 if (!SU) break;
1236
Andrew Trick984d98b2012-10-08 18:53:53 +00001237 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001238 if (!checkSchedLimit())
1239 break;
1240
1241 scheduleMI(SU, IsTopNode);
1242
Andrew Trickd7f890e2013-12-28 21:56:47 +00001243 if (DFSResult) {
1244 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1245 if (!ScheduledTrees.test(SubtreeID)) {
1246 ScheduledTrees.set(SubtreeID);
1247 DFSResult->scheduleTree(SubtreeID);
1248 SchedImpl->scheduleTree(SubtreeID);
1249 }
1250 }
1251
1252 // Notify the scheduling strategy after updating the DAG.
1253 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001254
1255 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001256 }
1257 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1258
1259 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001260
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001261 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001262 dbgs() << "*** Final schedule for "
1263 << printMBBReference(*begin()->getParent()) << " ***\n";
1264 dumpSchedule();
1265 dbgs() << '\n';
1266 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001267}
1268
1269/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001270void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001271 if (!ShouldTrackPressure) {
1272 RPTracker.reset();
1273 RegionCriticalPSets.clear();
1274 buildSchedGraph(AA);
1275 return;
1276 }
1277
Andrew Trick4add42f2012-05-10 21:06:10 +00001278 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001279 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001280 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001281
Andrew Trick4add42f2012-05-10 21:06:10 +00001282 // Account for liveness generate by the region boundary.
1283 if (LiveRegionEnd != RegionEnd)
1284 RPTracker.recede();
1285
1286 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001287 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001288
Andrew Trick4add42f2012-05-10 21:06:10 +00001289 // Initialize top/bottom trackers after computing region pressure.
1290 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001291}
Andrew Trick4add42f2012-05-10 21:06:10 +00001292
Andrew Trickd7f890e2013-12-28 21:56:47 +00001293void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001294 if (!DFSResult)
1295 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1296 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001297 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001298 DFSResult->resize(SUnits.size());
1299 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001300 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1301}
1302
Andrew Trick483f4192013-08-29 18:04:49 +00001303/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1304/// only provides the critical path for single block loops. To handle loops that
1305/// span blocks, we could use the vreg path latencies provided by
1306/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1307/// available for use in the scheduler.
1308///
1309/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001310/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001311/// the following instruction sequence where each instruction has unit latency
1312/// and defines an epomymous virtual register:
1313///
1314/// a->b(a,c)->c(b)->d(c)->exit
1315///
1316/// The cyclic critical path is a two cycles: b->c->b
1317/// The acyclic critical path is four cycles: a->b->c->d->exit
1318/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1319/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1320/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1321/// LiveInDepth = depth(b) = len(a->b) = 1
1322///
1323/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1324/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1325/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001326///
1327/// This could be relevant to PostRA scheduling, but is currently implemented
1328/// assuming LiveIntervals.
1329unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001330 // This only applies to single block loop.
1331 if (!BB->isSuccessor(BB))
1332 return 0;
1333
1334 unsigned MaxCyclicLatency = 0;
1335 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001336 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1337 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001338 if (!TRI->isVirtualRegister(Reg))
1339 continue;
1340 const LiveInterval &LI = LIS->getInterval(Reg);
1341 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1342 if (!DefVNI)
1343 continue;
1344
1345 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1346 const SUnit *DefSU = getSUnit(DefMI);
1347 if (!DefSU)
1348 continue;
1349
1350 unsigned LiveOutHeight = DefSU->getHeight();
1351 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1352 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001353 for (const VReg2SUnit &V2SU
1354 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1355 SUnit *SU = V2SU.SU;
1356 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001357 continue;
1358
1359 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001360 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001361 if (!LRQ.valueIn()->isPHIDef())
1362 continue;
1363
1364 // Assume that a path spanning two iterations is a cycle, which could
1365 // overestimate in strange cases. This allows cyclic latency to be
1366 // estimated as the minimum slack of the vreg's depth or height.
1367 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001368 if (LiveOutDepth > SU->getDepth())
1369 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001370
Matthias Braunb0c437b2015-10-29 03:57:17 +00001371 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001372 if (LiveInHeight > LiveOutHeight) {
1373 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1374 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001375 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001376 CyclicLatency = 0;
1377
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001378 LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1379 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001380 if (CyclicLatency > MaxCyclicLatency)
1381 MaxCyclicLatency = CyclicLatency;
1382 }
1383 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001384 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001385 return MaxCyclicLatency;
1386}
1387
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001388/// Release ExitSU predecessors and setup scheduler queues. Re-position
1389/// the Top RP tracker in case the region beginning has changed.
1390void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1391 ArrayRef<SUnit*> BotRoots) {
1392 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1393 if (ShouldTrackPressure) {
1394 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1395 TopRPTracker.setPos(CurrentTop);
1396 }
1397}
1398
Andrew Trick7a8e1002012-09-11 00:39:15 +00001399/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001400void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001401 // Move the instruction to its new location in the instruction stream.
1402 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001403
Andrew Trick7a8e1002012-09-11 00:39:15 +00001404 if (IsTopNode) {
1405 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1406 if (&*CurrentTop == MI)
1407 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001408 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001409 moveInstruction(MI, CurrentTop);
1410 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001411 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001412
Andrew Trickb6e74712013-09-04 20:59:59 +00001413 if (ShouldTrackPressure) {
1414 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001415 RegisterOperands RegOpers;
1416 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1417 if (ShouldTrackLaneMasks) {
1418 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001419 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001420 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1421 } else {
1422 // Adjust for missing dead-def flags.
1423 RegOpers.detectDeadDefs(*MI, *LIS);
1424 }
1425
1426 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001427 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001428 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
1429 TopRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001430
Andrew Trickb248b4a2013-09-06 17:32:47 +00001431 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001432 }
Matthias Braunb550b762016-04-21 01:54:13 +00001433 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001434 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1435 MachineBasicBlock::iterator priorII =
1436 priorNonDebug(CurrentBottom, CurrentTop);
1437 if (&*priorII == MI)
1438 CurrentBottom = priorII;
1439 else {
1440 if (&*CurrentTop == MI) {
1441 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1442 TopRPTracker.setPos(CurrentTop);
1443 }
1444 moveInstruction(MI, CurrentBottom);
1445 CurrentBottom = MI;
Yaxun Liu8b7454a2018-01-23 16:04:53 +00001446 BotRPTracker.setPos(CurrentBottom);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001447 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001448 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001449 RegisterOperands RegOpers;
1450 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1451 if (ShouldTrackLaneMasks) {
1452 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001453 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001454 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1455 } else {
1456 // Adjust for missing dead-def flags.
1457 RegOpers.detectDeadDefs(*MI, *LIS);
1458 }
1459
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001460 if (BotRPTracker.getPos() != CurrentBottom)
1461 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001462 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001463 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001464 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001465 LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
1466 BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001467
Andrew Trickb248b4a2013-09-06 17:32:47 +00001468 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001469 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001470 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001471 }
1472}
1473
Andrew Trick263280242012-11-12 19:52:20 +00001474//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001475// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001476//===----------------------------------------------------------------------===//
1477
Andrew Tricka7714a02012-11-12 19:40:10 +00001478namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001479
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001480/// Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001481/// loads or between neighboring stores.
1482class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1483 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001484 SUnit *SU;
1485 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001486 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001487
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001488 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1489 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001490
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001491 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001492 return std::tie(BaseReg, Offset, SU->NodeNum) <
1493 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001494 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001495 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001496
1497 const TargetInstrInfo *TII;
1498 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001499 bool IsLoad;
1500
Andrew Tricka7714a02012-11-12 19:40:10 +00001501public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001502 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1503 const TargetRegisterInfo *tri, bool IsLoad)
1504 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001505
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001506 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001507
Andrew Tricka7714a02012-11-12 19:40:10 +00001508protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001509 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1510};
1511
1512class StoreClusterMutation : public BaseMemOpClusterMutation {
1513public:
1514 StoreClusterMutation(const TargetInstrInfo *tii,
1515 const TargetRegisterInfo *tri)
1516 : BaseMemOpClusterMutation(tii, tri, false) {}
1517};
1518
1519class LoadClusterMutation : public BaseMemOpClusterMutation {
1520public:
1521 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1522 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001523};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001524
1525} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001526
Tom Stellard68726a52016-08-19 19:59:18 +00001527namespace llvm {
1528
1529std::unique_ptr<ScheduleDAGMutation>
1530createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1531 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001532 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001533 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001534}
1535
1536std::unique_ptr<ScheduleDAGMutation>
1537createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1538 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001539 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001540 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001541}
1542
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001543} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001544
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001545void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1546 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1547 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001548 for (SUnit *SU : MemOps) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001549 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001550 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001551 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001552 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001553 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001554 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001555 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001556
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +00001557 llvm::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001558 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001559 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001560 SUnit *SUa = MemOpRecords[Idx].SU;
1561 SUnit *SUb = MemOpRecords[Idx+1].SU;
Stanislav Mekhanoshin7fe9a5d2017-09-13 22:20:47 +00001562 if (TII->shouldClusterMemOps(*SUa->getInstr(), MemOpRecords[Idx].BaseReg,
1563 *SUb->getInstr(), MemOpRecords[Idx+1].BaseReg,
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001564 ClusterLength) &&
1565 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001566 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1567 << SUb->NodeNum << ")\n");
Andrew Tricka7714a02012-11-12 19:40:10 +00001568 // Copy successor edges from SUa to SUb. Interleaving computation
1569 // dependent on SUa can prevent load combining due to register reuse.
1570 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1571 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001572 for (const SDep &Succ : SUa->Succs) {
1573 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001574 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001575 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum
1576 << ")\n");
Javed Absare3a0cc22017-06-21 09:10:10 +00001577 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001578 }
1579 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001580 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001581 ClusterLength = 1;
1582 }
1583}
1584
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001585/// Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001586void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001587 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1588
Andrew Tricka7714a02012-11-12 19:40:10 +00001589 // Map DAG NodeNum to store chain ID.
1590 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001591 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001592 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001593 for (SUnit &SU : DAG->SUnits) {
1594 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1595 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001596 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001597
Andrew Tricka7714a02012-11-12 19:40:10 +00001598 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001599 for (const SDep &Pred : SU.Preds) {
1600 if (Pred.isCtrl()) {
1601 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001602 break;
1603 }
1604 }
1605 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001606 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001607 unsigned NumChains = StoreChainDependents.size();
1608 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1609 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1610 if (Result.second)
1611 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001612 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001613 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001614
Andrew Tricka7714a02012-11-12 19:40:10 +00001615 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001616 for (auto &SCD : StoreChainDependents)
1617 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001618}
1619
Andrew Trick02a80da2012-03-08 01:41:12 +00001620//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001621// CopyConstrain - DAG post-processing to encourage copy elimination.
1622//===----------------------------------------------------------------------===//
1623
1624namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001625
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001626/// Post-process the DAG to create weak edges from all uses of a copy to
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001627/// the one use that defines the copy's source vreg, most likely an induction
1628/// variable increment.
1629class CopyConstrain : public ScheduleDAGMutation {
1630 // Transient state.
1631 SlotIndex RegionBeginIdx;
Eugene Zelenko32a40562017-09-11 23:00:48 +00001632
Andrew Trick2e875172013-04-24 23:19:56 +00001633 // RegionEndIdx is the slot index of the last non-debug instruction in the
1634 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001635 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001636
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001637public:
1638 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1639
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001640 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001641
1642protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001643 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001644};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001645
1646} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001647
Tom Stellard68726a52016-08-19 19:59:18 +00001648namespace llvm {
1649
1650std::unique_ptr<ScheduleDAGMutation>
1651createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001652 const TargetRegisterInfo *TRI) {
1653 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001654}
1655
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001656} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001657
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001658/// constrainLocalCopy handles two possibilities:
1659/// 1) Local src:
1660/// I0: = dst
1661/// I1: src = ...
1662/// I2: = dst
1663/// I3: dst = src (copy)
1664/// (create pred->succ edges I0->I1, I2->I1)
1665///
1666/// 2) Local copy:
1667/// I0: dst = src (copy)
1668/// I1: = dst
1669/// I2: src = ...
1670/// I3: = dst
1671/// (create pred->succ edges I1->I2, I3->I2)
1672///
1673/// Although the MachineScheduler is currently constrained to single blocks,
1674/// this algorithm should handle extended blocks. An EBB is a set of
1675/// contiguously numbered blocks such that the previous block in the EBB is
1676/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001677void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001678 LiveIntervals *LIS = DAG->getLIS();
1679 MachineInstr *Copy = CopySU->getInstr();
1680
1681 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001682 const MachineOperand &SrcOp = Copy->getOperand(1);
1683 unsigned SrcReg = SrcOp.getReg();
1684 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001685 return;
1686
Matthias Braun7511abd2016-04-04 21:23:46 +00001687 const MachineOperand &DstOp = Copy->getOperand(0);
1688 unsigned DstReg = DstOp.getReg();
1689 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001690 return;
1691
1692 // Check if either the dest or source is local. If it's live across a back
1693 // edge, it's not local. Note that if both vregs are live across the back
1694 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001695 // If both the copy's source and dest are local live intervals, then we
1696 // should treat the dest as the global for the purpose of adding
1697 // constraints. This adds edges from source's other uses to the copy.
1698 unsigned LocalReg = SrcReg;
1699 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001700 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1701 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001702 LocalReg = DstReg;
1703 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001704 LocalLI = &LIS->getInterval(LocalReg);
1705 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1706 return;
1707 }
1708 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1709
1710 // Find the global segment after the start of the local LI.
1711 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1712 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1713 // local live range. We could create edges from other global uses to the local
1714 // start, but the coalescer should have already eliminated these cases, so
1715 // don't bother dealing with it.
1716 if (GlobalSegment == GlobalLI->end())
1717 return;
1718
1719 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1720 // returned the next global segment. But if GlobalSegment overlaps with
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001721 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001722 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1723 if (GlobalSegment->contains(LocalLI->beginIndex()))
1724 ++GlobalSegment;
1725
1726 if (GlobalSegment == GlobalLI->end())
1727 return;
1728
1729 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1730 if (GlobalSegment != GlobalLI->begin()) {
1731 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001732 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001733 GlobalSegment->start)) {
1734 return;
1735 }
Andrew Trickd9761772013-07-30 19:59:08 +00001736 // If the prior global segment may be defined by the same two-address
1737 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001738 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001739 LocalLI->beginIndex())) {
1740 return;
1741 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001742 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1743 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001744 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001745 "Disconnected LRG within the scheduling region.");
1746 }
1747 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1748 if (!GlobalDef)
1749 return;
1750
1751 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1752 if (!GlobalSU)
1753 return;
1754
1755 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1756 // constraining the uses of the last local def to precede GlobalDef.
1757 SmallVector<SUnit*,8> LocalUses;
1758 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1759 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1760 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001761 for (const SDep &Succ : LastLocalSU->Succs) {
1762 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001763 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001764 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001765 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001766 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001767 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001768 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001769 }
1770 // Open the top of the GlobalLI hole by constraining any earlier global uses
1771 // to precede the start of LocalLI.
1772 SmallVector<SUnit*,8> GlobalUses;
1773 MachineInstr *FirstLocalDef =
1774 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1775 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001776 for (const SDep &Pred : GlobalSU->Preds) {
1777 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001778 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001779 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001780 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001781 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001782 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001783 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001784 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001786 // Add the weak edges.
1787 for (SmallVectorImpl<SUnit*>::const_iterator
1788 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001789 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1790 << GlobalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001791 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1792 }
1793 for (SmallVectorImpl<SUnit*>::const_iterator
1794 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001795 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1796 << FirstLocalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001797 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1798 }
1799}
1800
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001801/// Callback from DAG postProcessing to create weak edges to encourage
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001802/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001803void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1804 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001805 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1806
Andrew Trick2e875172013-04-24 23:19:56 +00001807 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1808 if (FirstPos == DAG->end())
1809 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001810 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001811 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001812 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001813
Javed Absare3a0cc22017-06-21 09:10:10 +00001814 for (SUnit &SU : DAG->SUnits) {
1815 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001816 continue;
1817
Javed Absare3a0cc22017-06-21 09:10:10 +00001818 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001819 }
1820}
1821
1822//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001823// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1824// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001825//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001826
Andrew Trick5a22df42013-12-05 17:56:02 +00001827static const unsigned InvalidCycle = ~0U;
1828
Andrew Trickfc127d12013-12-07 05:59:44 +00001829SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001830
Jonas Paulsson238c14b2017-10-25 08:23:33 +00001831/// Given a Count of resource usage and a Latency value, return true if a
1832/// SchedBoundary becomes resource limited.
1833static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1834 unsigned Latency) {
1835 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1836}
1837
Andrew Trickfc127d12013-12-07 05:59:44 +00001838void SchedBoundary::reset() {
1839 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1840 // Destroying and reconstructing it is very expensive though. So keep
1841 // invalid, placeholder HazardRecs.
1842 if (HazardRec && HazardRec->isEnabled()) {
1843 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001844 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001845 }
1846 Available.clear();
1847 Pending.clear();
1848 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001849 CurrCycle = 0;
1850 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001851 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001852 ExpectedLatency = 0;
1853 DependentLatency = 0;
1854 RetiredMOps = 0;
1855 MaxExecutedResCount = 0;
1856 ZoneCritResIdx = 0;
1857 IsResourceLimited = false;
1858 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001859#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001860 // Track the maximum number of stall cycles that could arise either from the
1861 // latency of a DAG edge or the number of cycles that a processor resource is
1862 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001863 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001864#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001865 // Reserve a zero-count for invalid CritResIdx.
1866 ExecutedResCounts.resize(1);
1867 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1868}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001869
Andrew Trickfc127d12013-12-07 05:59:44 +00001870void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001871init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1872 reset();
1873 if (!SchedModel->hasInstrSchedModel())
1874 return;
1875 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001876 for (SUnit &SU : DAG->SUnits) {
1877 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1878 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001879 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001880 for (TargetSchedModel::ProcResIter
1881 PI = SchedModel->getWriteProcResBegin(SC),
1882 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1883 unsigned PIdx = PI->ProcResourceIdx;
1884 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1885 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1886 }
1887 }
1888}
1889
Andrew Trickfc127d12013-12-07 05:59:44 +00001890void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001891init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1892 reset();
1893 DAG = dag;
1894 SchedModel = smodel;
1895 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001896 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001897 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001898 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1899 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001900}
1901
Andrew Trick880e5732013-12-05 17:55:58 +00001902/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1903/// these "soft stalls" differently than the hard stall cycles based on CPU
1904/// resources and computed by checkHazard(). A fully in-order model
1905/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1906/// available for scheduling until they are ready. However, a weaker in-order
1907/// model may use this for heuristics. For example, if a processor has in-order
1908/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001909unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001910 if (!SU->isUnbuffered)
1911 return 0;
1912
1913 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1914 if (ReadyCycle > CurrCycle)
1915 return ReadyCycle - CurrCycle;
1916 return 0;
1917}
1918
Andrew Trick5a22df42013-12-05 17:56:02 +00001919/// Compute the next cycle at which the given processor resource can be
1920/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001921unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001922getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1923 unsigned NextUnreserved = ReservedCycles[PIdx];
1924 // If this resource has never been used, always return cycle zero.
1925 if (NextUnreserved == InvalidCycle)
1926 return 0;
1927 // For bottom-up scheduling add the cycles needed for the current operation.
1928 if (!isTop())
1929 NextUnreserved += Cycles;
1930 return NextUnreserved;
1931}
1932
Andrew Trick8c9e6722012-06-29 03:23:24 +00001933/// Does this SU have a hazard within the current instruction group.
1934///
1935/// The scheduler supports two modes of hazard recognition. The first is the
1936/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1937/// supports highly complicated in-order reservation tables
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001938/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
Andrew Trick8c9e6722012-06-29 03:23:24 +00001939///
1940/// The second is a streamlined mechanism that checks for hazards based on
1941/// simple counters that the scheduler itself maintains. It explicitly checks
1942/// for instruction dispatch limitations, including the number of micro-ops that
1943/// can dispatch per cycle.
1944///
1945/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001946bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001947 if (HazardRec->isEnabled()
1948 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1949 return true;
1950 }
Javed Absar3d594372017-03-27 20:46:37 +00001951
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001952 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001953 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001954 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1955 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001956 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001957 }
Javed Absar3d594372017-03-27 20:46:37 +00001958
1959 if (CurrMOps > 0 &&
1960 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1961 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001962 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1963 << (isTop() ? "begin" : "end") << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00001964 return true;
1965 }
1966
Andrew Trick5a22df42013-12-05 17:56:02 +00001967 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1968 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absare485b142017-10-03 09:35:04 +00001969 for (const MCWriteProcResEntry &PE :
1970 make_range(SchedModel->getWriteProcResBegin(SC),
1971 SchedModel->getWriteProcResEnd(SC))) {
1972 unsigned ResIdx = PE.ProcResourceIdx;
1973 unsigned Cycles = PE.Cycles;
1974 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
Andrew Trick56327222014-06-27 04:57:05 +00001975 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001976#ifndef NDEBUG
Javed Absare485b142017-10-03 09:35:04 +00001977 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001978#endif
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001979 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1980 << SchedModel->getResourceName(ResIdx) << "="
1981 << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001982 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001983 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001984 }
1985 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001986 return false;
1987}
1988
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001989// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001990unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001991findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001992 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001993 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00001994 for (SUnit *SU : ReadySUs) {
1995 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001996 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001997 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00001998 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001999 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002000 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002001 if (LateSU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002002 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2003 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002004 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002005 return RemLatency;
2006}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002007
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002008// Count resources in this zone and the remaining unscheduled
2009// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2010// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00002011unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002012getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00002013 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002014 if (!SchedModel->hasInstrSchedModel())
2015 return 0;
2016
2017 unsigned OtherCritCount = Rem->RemIssueCount
2018 + (RetiredMOps * SchedModel->getMicroOpFactor());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002019 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2020 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002021 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2022 PIdx != PEnd; ++PIdx) {
2023 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2024 if (OtherCount > OtherCritCount) {
2025 OtherCritCount = OtherCount;
2026 OtherCritIdx = PIdx;
2027 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002028 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002029 if (OtherCritIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002030 LLVM_DEBUG(
2031 dbgs() << " " << Available.getName() << " + Remain CritRes: "
2032 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2033 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002034 }
2035 return OtherCritCount;
2036}
2037
Andrew Trickfc127d12013-12-07 05:59:44 +00002038void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002039 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2040
2041#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002042 // ReadyCycle was been bumped up to the CurrCycle when this node was
2043 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2044 // scheduling, so may now be greater than ReadyCycle.
2045 if (ReadyCycle > CurrCycle)
2046 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002047#endif
2048
Andrew Trick61f1a272012-05-24 22:11:09 +00002049 if (ReadyCycle < MinReadyCycle)
2050 MinReadyCycle = ReadyCycle;
2051
2052 // Check for interlocks first. For the purpose of other heuristics, an
2053 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002054 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002055 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2056 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002057 Pending.push(SU);
2058 else
2059 Available.push(SU);
2060}
2061
2062/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002063void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002064 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002065 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2066 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002067 if (MinReadyCycle > NextCycle)
2068 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002069 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002070 // Update the current micro-ops, which will issue in the next cycle.
2071 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2072 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2073
2074 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002075 if ((NextCycle - CurrCycle) > DependentLatency)
2076 DependentLatency = 0;
2077 else
2078 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002079
2080 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002081 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002082 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002083 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002084 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002085 for (; CurrCycle != NextCycle; ++CurrCycle) {
2086 if (isTop())
2087 HazardRec->AdvanceCycle();
2088 else
2089 HazardRec->RecedeCycle();
2090 }
2091 }
2092 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002093 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002094 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2095 getScheduledLatency());
Andrew Trick61f1a272012-05-24 22:11:09 +00002096
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002097 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
2098 << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002099}
2100
Andrew Trickfc127d12013-12-07 05:59:44 +00002101void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002102 ExecutedResCounts[PIdx] += Count;
2103 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2104 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002105}
2106
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002107/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002108///
2109/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2110/// during which this resource is consumed.
2111///
2112/// \return the next cycle at which the instruction may execute without
2113/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002114unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002115countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002116 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002117 unsigned Count = Factor * Cycles;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002118 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
2119 << Cycles << "x" << Factor << "u\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002120
2121 // Update Executed resources counts.
2122 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002123 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2124 Rem->RemainingCounts[PIdx] -= Count;
2125
Andrew Trickb13ef172013-07-19 00:20:07 +00002126 // Check if this resource exceeds the current critical resource. If so, it
2127 // becomes the critical resource.
2128 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002129 ZoneCritResIdx = PIdx;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002130 LLVM_DEBUG(dbgs() << " *** Critical resource "
2131 << SchedModel->getResourceName(PIdx) << ": "
2132 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2133 << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002134 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002135 // For reserved resources, record the highest cycle using the resource.
2136 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2137 if (NextAvailable > CurrCycle) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002138 LLVM_DEBUG(dbgs() << " Resource conflict: "
2139 << SchedModel->getProcResource(PIdx)->Name
2140 << " reserved until @" << NextAvailable << "\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00002141 }
2142 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002143}
2144
Andrew Trick45446062012-06-05 21:11:27 +00002145/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002146void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002147 // Update the reservation table.
2148 if (HazardRec->isEnabled()) {
2149 if (!isTop() && SU->isCall) {
2150 // Calls are scheduled with their preceding instructions. For bottom-up
2151 // scheduling, clear the pipeline state before emitting.
2152 HazardRec->Reset();
2153 }
2154 HazardRec->EmitInstruction(SU);
2155 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002156 // checkHazard should prevent scheduling multiple instructions per cycle that
2157 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002158 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2159 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002160 assert(
2161 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002162 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002163
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002164 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002165 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002166
Andrew Trick5a22df42013-12-05 17:56:02 +00002167 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002168 switch (SchedModel->getMicroOpBufferSize()) {
2169 case 0:
2170 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2171 break;
2172 case 1:
2173 if (ReadyCycle > NextCycle) {
2174 NextCycle = ReadyCycle;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002175 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002176 }
2177 break;
2178 default:
2179 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002180 // scheduled MOps to be "retired". We do loosely model in-order resource
2181 // latency. If this instruction uses an in-order resource, account for any
2182 // likely stall cycles.
2183 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2184 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002185 break;
2186 }
2187 RetiredMOps += IncMOps;
2188
2189 // Update resource counts and critical resource.
2190 if (SchedModel->hasInstrSchedModel()) {
2191 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2192 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2193 Rem->RemIssueCount -= DecRemIssue;
2194 if (ZoneCritResIdx) {
2195 // Scale scheduled micro-ops for comparing with the critical resource.
2196 unsigned ScaledMOps =
2197 RetiredMOps * SchedModel->getMicroOpFactor();
2198
2199 // If scaled micro-ops are now more than the previous critical resource by
2200 // a full cycle, then micro-ops issue becomes critical.
2201 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2202 >= (int)SchedModel->getLatencyFactor()) {
2203 ZoneCritResIdx = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002204 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2205 << ScaledMOps / SchedModel->getLatencyFactor()
2206 << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002207 }
2208 }
2209 for (TargetSchedModel::ProcResIter
2210 PI = SchedModel->getWriteProcResBegin(SC),
2211 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2212 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002213 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002214 if (RCycle > NextCycle)
2215 NextCycle = RCycle;
2216 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002217 if (SU->hasReservedResource) {
2218 // For reserved resources, record the highest cycle using the resource.
2219 // For top-down scheduling, this is the cycle in which we schedule this
2220 // instruction plus the number of cycles the operations reserves the
2221 // resource. For bottom-up is it simply the instruction's cycle.
2222 for (TargetSchedModel::ProcResIter
2223 PI = SchedModel->getWriteProcResBegin(SC),
2224 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2225 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002226 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002227 if (isTop()) {
2228 ReservedCycles[PIdx] =
2229 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2230 }
2231 else
2232 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002233 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002234 }
2235 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002236 }
2237 // Update ExpectedLatency and DependentLatency.
2238 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2239 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2240 if (SU->getDepth() > TopLatency) {
2241 TopLatency = SU->getDepth();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002242 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU("
2243 << SU->NodeNum << ") " << TopLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002244 }
2245 if (SU->getHeight() > BotLatency) {
2246 BotLatency = SU->getHeight();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002247 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU("
2248 << SU->NodeNum << ") " << BotLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002249 }
2250 // If we stall for any reason, bump the cycle.
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002251 if (NextCycle > CurrCycle)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002252 bumpCycle(NextCycle);
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002253 else
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002254 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002255 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002256 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002257 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2258 getScheduledLatency());
2259
Andrew Trick5a22df42013-12-05 17:56:02 +00002260 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2261 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2262 // one cycle. Since we commonly reach the max MOps here, opportunistically
2263 // bump the cycle to avoid uselessly checking everything in the readyQ.
2264 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002265
2266 // Bump the cycle count for issue group constraints.
2267 // This must be done after NextCycle has been adjust for all other stalls.
2268 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2269 // currCycle to X.
2270 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2271 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002272 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
2273 << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00002274 bumpCycle(++NextCycle);
2275 }
2276
Andrew Trick5a22df42013-12-05 17:56:02 +00002277 while (CurrMOps >= SchedModel->getIssueWidth()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002278 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
2279 << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002280 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002281 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002282 LLVM_DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002283}
2284
Andrew Trick61f1a272012-05-24 22:11:09 +00002285/// Release pending ready nodes in to the available queue. This makes them
2286/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002287void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002288 // If the available queue is empty, it is safe to reset MinReadyCycle.
2289 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002290 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002291
2292 // Check to see if any of the pending instructions are ready to issue. If
2293 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002294 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002295 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2296 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002297 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002298
2299 if (ReadyCycle < MinReadyCycle)
2300 MinReadyCycle = ReadyCycle;
2301
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002302 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002303 continue;
2304
Andrew Trick8c9e6722012-06-29 03:23:24 +00002305 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002306 continue;
2307
Matthias Braun6493bc22016-04-22 19:09:17 +00002308 if (Available.size() >= ReadyListLimit)
2309 break;
2310
Andrew Trick61f1a272012-05-24 22:11:09 +00002311 Available.push(SU);
2312 Pending.remove(Pending.begin()+i);
2313 --i; --e;
2314 }
2315 CheckPending = false;
2316}
2317
2318/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002319void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002320 if (Available.isInQueue(SU))
2321 Available.remove(Available.find(SU));
2322 else {
2323 assert(Pending.isInQueue(SU) && "bad ready count");
2324 Pending.remove(Pending.find(SU));
2325 }
2326}
2327
2328/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002329/// defer any nodes that now hit a hazard, and advance the cycle until at least
2330/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002331SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002332 if (CheckPending)
2333 releasePending();
2334
Andrew Tricke2ff5752013-06-15 04:49:49 +00002335 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002336 // Defer any ready instrs that now have a hazard.
2337 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2338 if (checkHazard(*I)) {
2339 Pending.push(*I);
2340 I = Available.remove(I);
2341 continue;
2342 }
2343 ++I;
2344 }
2345 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002346 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002347// FIXME: Re-enable assert once PR20057 is resolved.
2348// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2349// "permanent hazard");
2350 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002351 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002352 releasePending();
2353 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002354
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002355 LLVM_DEBUG(Pending.dump());
2356 LLVM_DEBUG(Available.dump());
Matthias Braund29d31e2016-06-23 21:27:38 +00002357
Andrew Trick61f1a272012-05-24 22:11:09 +00002358 if (Available.size() == 1)
2359 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002360 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002361}
2362
Aaron Ballman615eb472017-10-15 14:32:27 +00002363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002364// This is useful information to dump after bumpNode.
2365// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002366LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002367 unsigned ResFactor;
2368 unsigned ResCount;
2369 if (ZoneCritResIdx) {
2370 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2371 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002372 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002373 ResFactor = SchedModel->getMicroOpFactor();
Javed Absar1a77bcc2017-09-27 10:31:58 +00002374 ResCount = RetiredMOps * ResFactor;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002375 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002376 unsigned LFactor = SchedModel->getLatencyFactor();
2377 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2378 << " Retired: " << RetiredMOps;
2379 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2380 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002381 << ResCount / ResFactor << " "
2382 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002383 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2384 << (IsResourceLimited ? " - Resource" : " - Latency")
2385 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002386}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002387#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002388
Andrew Trickfc127d12013-12-07 05:59:44 +00002389//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002390// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002391//===----------------------------------------------------------------------===//
2392
Andrew Trickd14d7c22013-12-28 21:56:57 +00002393void GenericSchedulerBase::SchedCandidate::
2394initResourceDelta(const ScheduleDAGMI *DAG,
2395 const TargetSchedModel *SchedModel) {
2396 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2397 return;
2398
2399 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2400 for (TargetSchedModel::ProcResIter
2401 PI = SchedModel->getWriteProcResBegin(SC),
2402 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2403 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2404 ResDelta.CritResources += PI->Cycles;
2405 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2406 ResDelta.DemandedResources += PI->Cycles;
2407 }
2408}
2409
Tom Stellardecd6aa52018-08-21 21:48:43 +00002410/// Compute remaining latency. We need this both to determine whether the
2411/// overall schedule has become latency-limited and whether the instructions
2412/// outside this zone are resource or latency limited.
2413///
2414/// The "dependent" latency is updated incrementally during scheduling as the
2415/// max height/depth of scheduled nodes minus the cycles since it was
2416/// scheduled:
2417/// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2418///
2419/// The "independent" latency is the max ready queue depth:
2420/// ILat = max N.depth for N in Available|Pending
2421///
2422/// RemainingLatency is the greater of independent and dependent latency.
2423///
2424/// These computations are expensive, especially in DAGs with many edges, so
2425/// only do them if necessary.
2426static unsigned computeRemLatency(SchedBoundary &CurrZone) {
2427 unsigned RemLatency = CurrZone.getDependentLatency();
2428 RemLatency = std::max(RemLatency,
2429 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2430 RemLatency = std::max(RemLatency,
2431 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2432 return RemLatency;
2433}
2434
2435/// Returns true if the current cycle plus remaning latency is greater than
2436/// the cirtical path in the scheduling region.
2437bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
2438 SchedBoundary &CurrZone,
2439 bool ComputeRemLatency,
2440 unsigned &RemLatency) const {
2441 // The current cycle is already greater than the critical path, so we are
2442 // already latnecy limited and don't need to compute the remaining latency.
2443 if (CurrZone.getCurrCycle() > Rem.CriticalPath)
2444 return true;
2445
2446 // If we haven't scheduled anything yet, then we aren't latency limited.
2447 if (CurrZone.getCurrCycle() == 0)
2448 return false;
2449
2450 if (ComputeRemLatency)
2451 RemLatency = computeRemLatency(CurrZone);
2452
2453 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
2454}
2455
Andrew Trickd14d7c22013-12-28 21:56:57 +00002456/// Set the CandPolicy given a scheduling zone given the current resources and
2457/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002458void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002459 SchedBoundary &CurrZone,
2460 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002461 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002462 // inside and outside this zone. Potential stalls should be considered before
2463 // following this policy.
2464
Andrew Trickd14d7c22013-12-28 21:56:57 +00002465 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002466 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002467 unsigned OtherCount =
2468 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2469
2470 bool OtherResLimited = false;
Tom Stellardecd6aa52018-08-21 21:48:43 +00002471 unsigned RemLatency = 0;
2472 bool RemLatencyComputed = false;
2473 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
2474 RemLatency = computeRemLatency(CurrZone);
2475 RemLatencyComputed = true;
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002476 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2477 OtherCount, RemLatency);
Tom Stellardecd6aa52018-08-21 21:48:43 +00002478 }
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002479
Andrew Trickd14d7c22013-12-28 21:56:57 +00002480 // Schedule aggressively for latency in PostRA mode. We don't check for
2481 // acyclic latency during PostRA, and highly out-of-order processors will
2482 // skip PostRA scheduling.
Tom Stellardecd6aa52018-08-21 21:48:43 +00002483 if (!OtherResLimited &&
2484 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2485 RemLatency))) {
2486 Policy.ReduceLatency |= true;
2487 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
2488 << " RemainingLatency " << RemLatency << " + "
2489 << CurrZone.getCurrCycle() << "c > CritPath "
2490 << Rem.CriticalPath << "\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002491 }
2492 // If the same resource is limiting inside and outside the zone, do nothing.
2493 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2494 return;
2495
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002496 LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
2497 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2498 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
2499 } if (OtherResLimited) dbgs()
2500 << " RemainingLimit: "
2501 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2502 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
2503 << " Latency limited both directions.\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002504
2505 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2506 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2507
2508 if (OtherResLimited)
2509 Policy.DemandResIdx = OtherCritIdx;
2510}
2511
2512#ifndef NDEBUG
2513const char *GenericSchedulerBase::getReasonStr(
2514 GenericSchedulerBase::CandReason Reason) {
2515 switch (Reason) {
2516 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002517 case Only1: return "ONLY1 ";
2518 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002519 case RegExcess: return "REG-EXCESS";
2520 case RegCritical: return "REG-CRIT ";
2521 case Stall: return "STALL ";
2522 case Cluster: return "CLUSTER ";
2523 case Weak: return "WEAK ";
2524 case RegMax: return "REG-MAX ";
2525 case ResourceReduce: return "RES-REDUCE";
2526 case ResourceDemand: return "RES-DEMAND";
2527 case TopDepthReduce: return "TOP-DEPTH ";
2528 case TopPathReduce: return "TOP-PATH ";
2529 case BotHeightReduce:return "BOT-HEIGHT";
2530 case BotPathReduce: return "BOT-PATH ";
2531 case NextDefUse: return "DEF-USE ";
2532 case NodeOrder: return "ORDER ";
2533 };
2534 llvm_unreachable("Unknown reason!");
2535}
2536
2537void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2538 PressureChange P;
2539 unsigned ResIdx = 0;
2540 unsigned Latency = 0;
2541 switch (Cand.Reason) {
2542 default:
2543 break;
2544 case RegExcess:
2545 P = Cand.RPDelta.Excess;
2546 break;
2547 case RegCritical:
2548 P = Cand.RPDelta.CriticalMax;
2549 break;
2550 case RegMax:
2551 P = Cand.RPDelta.CurrentMax;
2552 break;
2553 case ResourceReduce:
2554 ResIdx = Cand.Policy.ReduceResIdx;
2555 break;
2556 case ResourceDemand:
2557 ResIdx = Cand.Policy.DemandResIdx;
2558 break;
2559 case TopDepthReduce:
2560 Latency = Cand.SU->getDepth();
2561 break;
2562 case TopPathReduce:
2563 Latency = Cand.SU->getHeight();
2564 break;
2565 case BotHeightReduce:
2566 Latency = Cand.SU->getHeight();
2567 break;
2568 case BotPathReduce:
2569 Latency = Cand.SU->getDepth();
2570 break;
2571 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002572 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002573 if (P.isValid())
2574 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2575 << ":" << P.getUnitInc() << " ";
2576 else
2577 dbgs() << " ";
2578 if (ResIdx)
2579 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2580 else
2581 dbgs() << " ";
2582 if (Latency)
2583 dbgs() << " " << Latency << " cycles ";
2584 else
2585 dbgs() << " ";
2586 dbgs() << '\n';
2587}
2588#endif
2589
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002590namespace llvm {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002591/// Return true if this heuristic determines order.
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002592bool tryLess(int TryVal, int CandVal,
2593 GenericSchedulerBase::SchedCandidate &TryCand,
2594 GenericSchedulerBase::SchedCandidate &Cand,
2595 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002596 if (TryVal < CandVal) {
2597 TryCand.Reason = Reason;
2598 return true;
2599 }
2600 if (TryVal > CandVal) {
2601 if (Cand.Reason > Reason)
2602 Cand.Reason = Reason;
2603 return true;
2604 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002605 return false;
2606}
2607
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002608bool tryGreater(int TryVal, int CandVal,
2609 GenericSchedulerBase::SchedCandidate &TryCand,
2610 GenericSchedulerBase::SchedCandidate &Cand,
2611 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002612 if (TryVal > CandVal) {
2613 TryCand.Reason = Reason;
2614 return true;
2615 }
2616 if (TryVal < CandVal) {
2617 if (Cand.Reason > Reason)
2618 Cand.Reason = Reason;
2619 return true;
2620 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002621 return false;
2622}
2623
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002624bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2625 GenericSchedulerBase::SchedCandidate &Cand,
2626 SchedBoundary &Zone) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002627 if (Zone.isTop()) {
2628 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2629 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2630 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2631 return true;
2632 }
2633 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2634 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2635 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002636 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002637 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2638 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2639 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2640 return true;
2641 }
2642 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2643 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2644 return true;
2645 }
2646 return false;
2647}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002648} // end namespace llvm
Andrew Trickd14d7c22013-12-28 21:56:57 +00002649
Matthias Braun49cb6e92016-05-27 22:14:26 +00002650static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002651 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2652 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
Matthias Braun49cb6e92016-05-27 22:14:26 +00002653}
2654
Matthias Braun6ad3d052016-06-25 00:23:00 +00002655static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2656 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002657}
2658
Andrew Trickfc127d12013-12-07 05:59:44 +00002659void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002660 assert(dag->hasVRegLiveness() &&
2661 "(PreRA)GenericScheduler needs vreg liveness");
2662 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002663 SchedModel = DAG->getSchedModel();
2664 TRI = DAG->TRI;
2665
2666 Rem.init(DAG, SchedModel);
2667 Top.init(DAG, SchedModel, &Rem);
2668 Bot.init(DAG, SchedModel, &Rem);
2669
2670 // Initialize resource counts.
2671
2672 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2673 // are disabled, then these HazardRecs will be disabled.
2674 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002675 if (!Top.HazardRec) {
2676 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002677 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002678 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002679 }
2680 if (!Bot.HazardRec) {
2681 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002682 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002683 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002684 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002685 TopCand.SU = nullptr;
2686 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002687}
2688
2689/// Initialize the per-region scheduling policy.
2690void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2691 MachineBasicBlock::iterator End,
2692 unsigned NumRegionInstrs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002693 const MachineFunction &MF = *Begin->getMF();
Eric Christopher99556d72014-10-14 06:56:25 +00002694 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002695
2696 // Avoid setting up the register pressure tracker for small regions to save
2697 // compile time. As a rough heuristic, only track pressure when the number of
2698 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002699 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002700 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2701 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2702 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002703 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002704 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002705 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2706 }
2707 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002708
2709 // For generic targets, we default to bottom-up, because it's simpler and more
2710 // compile-time optimizations have been implemented in that direction.
2711 RegionPolicy.OnlyBottomUp = true;
2712
2713 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002714 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002715
2716 // After subtarget overrides, apply command line options.
2717 if (!EnableRegPressure)
2718 RegionPolicy.ShouldTrackPressure = false;
2719
2720 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2721 // e.g. -misched-bottomup=false allows scheduling in both directions.
2722 assert((!ForceTopDown || !ForceBottomUp) &&
2723 "-misched-topdown incompatible with -misched-bottomup");
2724 if (ForceBottomUp.getNumOccurrences() > 0) {
2725 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2726 if (RegionPolicy.OnlyBottomUp)
2727 RegionPolicy.OnlyTopDown = false;
2728 }
2729 if (ForceTopDown.getNumOccurrences() > 0) {
2730 RegionPolicy.OnlyTopDown = ForceTopDown;
2731 if (RegionPolicy.OnlyTopDown)
2732 RegionPolicy.OnlyBottomUp = false;
2733 }
2734}
2735
Sam Clegg705f7982017-06-21 22:19:17 +00002736void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002737 // Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002739 dbgs() << "GenericScheduler RegionPolicy: "
2740 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2741 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2742 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2743 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002744#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002745}
2746
Andrew Trickfc127d12013-12-07 05:59:44 +00002747/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2748/// critical path by more cycles than it takes to drain the instruction buffer.
2749/// We estimate an upper bounds on in-flight instructions as:
2750///
2751/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2752/// InFlightIterations = AcyclicPath / CyclesPerIteration
2753/// InFlightResources = InFlightIterations * LoopResources
2754///
2755/// TODO: Check execution resources in addition to IssueCount.
2756void GenericScheduler::checkAcyclicLatency() {
2757 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2758 return;
2759
2760 // Scaled number of cycles per loop iteration.
2761 unsigned IterCount =
2762 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2763 Rem.RemIssueCount);
2764 // Scaled acyclic critical path.
2765 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2766 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2767 unsigned InFlightCount =
2768 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2769 unsigned BufferLimit =
2770 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2771
2772 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2773
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002774 LLVM_DEBUG(
2775 dbgs() << "IssueCycles="
2776 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2777 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2778 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2779 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2780 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2781 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
Andrew Trickfc127d12013-12-07 05:59:44 +00002782}
2783
2784void GenericScheduler::registerRoots() {
2785 Rem.CriticalPath = DAG->ExitSU.getDepth();
2786
2787 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002788 for (const SUnit *SU : Bot.Available) {
2789 if (SU->getDepth() > Rem.CriticalPath)
2790 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002791 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002792 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002793 if (DumpCriticalPathLength) {
2794 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2795 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002796
Matthias Braun99551052017-04-12 18:09:05 +00002797 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002798 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2799 checkAcyclicLatency();
2800 }
2801}
2802
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002803namespace llvm {
2804bool tryPressure(const PressureChange &TryP,
2805 const PressureChange &CandP,
2806 GenericSchedulerBase::SchedCandidate &TryCand,
2807 GenericSchedulerBase::SchedCandidate &Cand,
2808 GenericSchedulerBase::CandReason Reason,
2809 const TargetRegisterInfo *TRI,
2810 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002811 // If one candidate decreases and the other increases, go with it.
2812 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002813 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2814 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002815 return true;
2816 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002817 // Do not compare the magnitude of pressure changes between top and bottom
2818 // boundary.
2819 if (Cand.AtTop != TryCand.AtTop)
2820 return false;
2821
2822 // If both candidates affect the same set in the same boundary, go with the
2823 // smallest increase.
2824 unsigned TryPSet = TryP.getPSetOrMax();
2825 unsigned CandPSet = CandP.getPSetOrMax();
2826 if (TryPSet == CandPSet) {
2827 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2828 Reason);
2829 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002830
2831 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2832 std::numeric_limits<int>::max();
2833
2834 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2835 std::numeric_limits<int>::max();
2836
Andrew Trick401b6952013-07-25 07:26:35 +00002837 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002838 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002839 std::swap(TryRank, CandRank);
2840 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2841}
2842
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002843unsigned getWeakLeft(const SUnit *SU, bool isTop) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002844 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2845}
2846
Andrew Tricke833e1c2013-04-13 06:07:40 +00002847/// Minimize physical register live ranges. Regalloc wants them adjacent to
2848/// their physreg def/use.
2849///
2850/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2851/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2852/// with the operation that produces or consumes the physreg. We'll do this when
2853/// regalloc has support for parallel copies.
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002854int biasPhysRegCopy(const SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002855 const MachineInstr *MI = SU->getInstr();
2856 if (!MI->isCopy())
2857 return 0;
2858
2859 unsigned ScheduledOper = isTop ? 1 : 0;
2860 unsigned UnscheduledOper = isTop ? 0 : 1;
2861 // If we have already scheduled the physreg produce/consumer, immediately
2862 // schedule the copy.
2863 if (TargetRegisterInfo::isPhysicalRegister(
2864 MI->getOperand(ScheduledOper).getReg()))
2865 return 1;
2866 // If the physreg is at the boundary, defer it. Otherwise schedule it
2867 // immediately to free the dependent. We can hoist the copy later.
2868 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2869 if (TargetRegisterInfo::isPhysicalRegister(
2870 MI->getOperand(UnscheduledOper).getReg()))
2871 return AtBoundary ? -1 : 1;
2872 return 0;
2873}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002874} // end namespace llvm
Andrew Tricke833e1c2013-04-13 06:07:40 +00002875
Matthias Braun4f573772016-04-22 19:10:15 +00002876void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2877 bool AtTop,
2878 const RegPressureTracker &RPTracker,
2879 RegPressureTracker &TempTracker) {
2880 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002881 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002882 if (DAG->isTrackingPressure()) {
2883 if (AtTop) {
2884 TempTracker.getMaxDownwardPressureDelta(
2885 Cand.SU->getInstr(),
2886 Cand.RPDelta,
2887 DAG->getRegionCriticalPSets(),
2888 DAG->getRegPressure().MaxSetPressure);
2889 } else {
2890 if (VerifyScheduling) {
2891 TempTracker.getMaxUpwardPressureDelta(
2892 Cand.SU->getInstr(),
2893 &DAG->getPressureDiff(Cand.SU),
2894 Cand.RPDelta,
2895 DAG->getRegionCriticalPSets(),
2896 DAG->getRegPressure().MaxSetPressure);
2897 } else {
2898 RPTracker.getUpwardPressureDelta(
2899 Cand.SU->getInstr(),
2900 DAG->getPressureDiff(Cand.SU),
2901 Cand.RPDelta,
2902 DAG->getRegionCriticalPSets(),
2903 DAG->getRegPressure().MaxSetPressure);
2904 }
2905 }
2906 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002907 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
2908 << " Try SU(" << Cand.SU->NodeNum << ") "
2909 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
2910 << Cand.RPDelta.Excess.getUnitInc() << "\n");
Matthias Braun4f573772016-04-22 19:10:15 +00002911}
2912
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002913/// Apply a set of heuristics to a new candidate. Heuristics are currently
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002914/// hierarchical. This may be more efficient than a graduated cost model because
2915/// we don't need to evaluate all aspects of the model for each node in the
2916/// queue. But it's really done to make the heuristics easier to debug and
2917/// statistically analyze.
2918///
2919/// \param Cand provides the policy and current best candidate.
2920/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002921/// \param Zone describes the scheduled zone that we are extending, or nullptr
2922// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002923void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002924 SchedCandidate &TryCand,
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002925 SchedBoundary *Zone) const {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002926 // Initialize the candidate if needed.
2927 if (!Cand.isValid()) {
2928 TryCand.Reason = NodeOrder;
2929 return;
2930 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002931
Matthias Braun6ad3d052016-06-25 00:23:00 +00002932 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2933 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002934 TryCand, Cand, PhysRegCopy))
2935 return;
2936
Andrew Tricke02d5da2015-05-17 23:40:27 +00002937 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002938 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2939 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002940 TryCand, Cand, RegExcess, TRI,
2941 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002942 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002943
2944 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002945 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2946 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002947 TryCand, Cand, RegCritical, TRI,
2948 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002949 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002950
Matthias Braun6ad3d052016-06-25 00:23:00 +00002951 // We only compare a subset of features when comparing nodes between
2952 // Top and Bottom boundary. Some properties are simply incomparable, in many
2953 // other instances we should only override the other boundary if something
2954 // is a clear good pick on one boundary. Skip heuristics that are more
2955 // "tie-breaking" in nature.
2956 bool SameBoundary = Zone != nullptr;
2957 if (SameBoundary) {
2958 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002959 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2960 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002961 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2962 tryLatency(TryCand, Cand, *Zone))
2963 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002964
Matthias Braun6ad3d052016-06-25 00:23:00 +00002965 // Prioritize instructions that read unbuffered resources by stall cycles.
2966 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2967 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2968 return;
2969 }
Andrew Trick880e5732013-12-05 17:55:58 +00002970
Andrew Tricka7714a02012-11-12 19:40:10 +00002971 // Keep clustered nodes together to encourage downstream peephole
2972 // optimizations which may reduce resource requirements.
2973 //
2974 // This is a best effort to set things up for a post-RA pass. Optimizations
2975 // like generating loads of multiple registers should ideally be done within
2976 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002977 const SUnit *CandNextClusterSU =
2978 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2979 const SUnit *TryCandNextClusterSU =
2980 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2981 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2982 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002983 TryCand, Cand, Cluster))
2984 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002985
Matthias Braun6ad3d052016-06-25 00:23:00 +00002986 if (SameBoundary) {
2987 // Weak edges are for clustering and other constraints.
2988 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2989 getWeakLeft(Cand.SU, Cand.AtTop),
2990 TryCand, Cand, Weak))
2991 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002992 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002993
Andrew Trick71f08a32013-06-17 21:45:13 +00002994 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002995 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2996 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002997 TryCand, Cand, RegMax, TRI,
2998 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002999 return;
3000
Matthias Braun6ad3d052016-06-25 00:23:00 +00003001 if (SameBoundary) {
3002 // Avoid critical resource consumption and balance the schedule.
3003 TryCand.initResourceDelta(DAG, SchedModel);
3004 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3005 TryCand, Cand, ResourceReduce))
3006 return;
3007 if (tryGreater(TryCand.ResDelta.DemandedResources,
3008 Cand.ResDelta.DemandedResources,
3009 TryCand, Cand, ResourceDemand))
3010 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003011
Matthias Braun6ad3d052016-06-25 00:23:00 +00003012 // Avoid serializing long latency dependence chains.
3013 // For acyclic path limited loops, latency was already checked above.
3014 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
3015 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
3016 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003017
Matthias Braun6ad3d052016-06-25 00:23:00 +00003018 // Fall through to original instruction order.
3019 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
3020 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
3021 TryCand.Reason = NodeOrder;
3022 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003023 }
3024}
Andrew Trick419eae22012-05-10 21:06:19 +00003025
Andrew Trickc573cd92013-09-06 17:32:44 +00003026/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00003027///
3028/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
3029/// DAG building. To adjust for the current scheduling location we need to
3030/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003031void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00003032 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00003033 const RegPressureTracker &RPTracker,
3034 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003035 // getMaxPressureDelta temporarily modifies the tracker.
3036 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3037
Matthias Braund29d31e2016-06-23 21:27:38 +00003038 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003039 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003040
Matthias Braun6ad3d052016-06-25 00:23:00 +00003041 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003042 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003043 // Pass SchedBoundary only when comparing nodes from the same boundary.
3044 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3045 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003046 if (TryCand.Reason != NoCand) {
3047 // Initialize resource delta if needed in case future heuristics query it.
3048 if (TryCand.ResDelta == SchedResourceDelta())
3049 TryCand.initResourceDelta(DAG, SchedModel);
3050 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003051 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00003052 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003053 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003054}
3055
Andrew Trick22025772012-05-17 18:35:10 +00003056/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003057SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00003058 // Schedule as far as possible in the direction of no choice. This is most
3059 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00003060 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003061 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003062 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003063 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003064 }
Andrew Trick61f1a272012-05-24 22:11:09 +00003065 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003066 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003067 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003068 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003069 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003070 // Set the bottom-up policy based on the state of the current bottom zone and
3071 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003072 CandPolicy BotPolicy;
3073 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003074 // Set the top-down policy based on the state of the current top zone and
3075 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003076 CandPolicy TopPolicy;
3077 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003078
Matthias Brauncc676c42016-06-25 02:03:36 +00003079 // See if BotCand is still valid (because we previously scheduled from Top).
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003080 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003081 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3082 BotCand.Policy != BotPolicy) {
3083 BotCand.reset(CandPolicy());
3084 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3085 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3086 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003087 LLVM_DEBUG(traceCandidate(BotCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003088#ifndef NDEBUG
3089 if (VerifyScheduling) {
3090 SchedCandidate TCand;
3091 TCand.reset(CandPolicy());
3092 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3093 assert(TCand.SU == BotCand.SU &&
3094 "Last pick result should correspond to re-picking right now");
3095 }
3096#endif
3097 }
Andrew Trick22025772012-05-17 18:35:10 +00003098
Andrew Trick22025772012-05-17 18:35:10 +00003099 // Check if the top Q has a better candidate.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003100 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003101 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3102 TopCand.Policy != TopPolicy) {
3103 TopCand.reset(CandPolicy());
3104 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3105 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3106 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003107 LLVM_DEBUG(traceCandidate(TopCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003108#ifndef NDEBUG
3109 if (VerifyScheduling) {
3110 SchedCandidate TCand;
3111 TCand.reset(CandPolicy());
3112 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3113 assert(TCand.SU == TopCand.SU &&
3114 "Last pick result should correspond to re-picking right now");
3115 }
3116#endif
3117 }
3118
3119 // Pick best from BotCand and TopCand.
3120 assert(BotCand.isValid());
3121 assert(TopCand.isValid());
3122 SchedCandidate Cand = BotCand;
3123 TopCand.Reason = NoCand;
3124 tryCandidate(Cand, TopCand, nullptr);
3125 if (TopCand.Reason != NoCand) {
3126 Cand.setBest(TopCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003127 LLVM_DEBUG(traceCandidate(Cand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003128 }
Andrew Trick22025772012-05-17 18:35:10 +00003129
Matthias Braun6ad3d052016-06-25 00:23:00 +00003130 IsTopNode = Cand.AtTop;
3131 tracePick(Cand);
3132 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003133}
3134
3135/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003136SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003137 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003138 assert(Top.Available.empty() && Top.Pending.empty() &&
3139 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003140 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003141 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003142 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003143 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003144 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003145 SU = Top.pickOnlyChoice();
3146 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003147 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003148 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003149 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003150 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003151 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003152 SU = TopCand.SU;
3153 }
3154 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003155 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003156 SU = Bot.pickOnlyChoice();
3157 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003158 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003159 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003160 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003161 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003162 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003163 SU = BotCand.SU;
3164 }
3165 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003166 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003167 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003168 }
3169 } while (SU->isScheduled);
3170
Andrew Trick61f1a272012-05-24 22:11:09 +00003171 if (SU->isTopReady())
3172 Top.removeReady(SU);
3173 if (SU->isBottomReady())
3174 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003175
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003176 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3177 << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003178 return SU;
3179}
3180
Andrew Trick665d3ec2013-09-19 23:10:59 +00003181void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003182 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3183 if (!isTop)
3184 ++InsertPos;
3185 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3186
3187 // Find already scheduled copies with a single physreg dependence and move
3188 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003189 for (SDep &Dep : Deps) {
3190 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003191 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003192 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003193 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3194 continue;
3195 MachineInstr *Copy = DepSU->getInstr();
3196 if (!Copy->isCopy())
3197 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003198 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
Matthias Braun726e12c2018-09-19 00:23:35 +00003199 DAG->dumpNode(*Dep.getSUnit()));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003200 DAG->moveInstruction(Copy, InsertPos);
3201 }
3202}
3203
Andrew Trick61f1a272012-05-24 22:11:09 +00003204/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003205/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3206/// update it's state based on the current cycle before MachineSchedStrategy
3207/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003208///
3209/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3210/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003211void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003212 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003213 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003214 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003215 if (SU->hasPhysRegUses)
3216 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003217 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003218 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003219 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003220 if (SU->hasPhysRegDefs)
3221 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003222 }
3223}
3224
Andrew Trick8823dec2012-03-14 04:00:41 +00003225/// Create the standard converging machine scheduler. This will be used as the
3226/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003227ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003228 ScheduleDAGMILive *DAG =
3229 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003230 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003231 //
3232 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3233 // data and pass it to later mutations. Have a single mutation that gathers
3234 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003235 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003236 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003237}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003238
Matthias Braun115efcd2016-11-28 20:11:54 +00003239static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3240 return createGenericSchedLive(C);
3241}
3242
Andrew Tricke1c034f2012-01-17 06:55:03 +00003243static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003244GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003245 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003246
3247//===----------------------------------------------------------------------===//
3248// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3249//===----------------------------------------------------------------------===//
3250
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003251void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3252 DAG = Dag;
3253 SchedModel = DAG->getSchedModel();
3254 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003255
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003256 Rem.init(DAG, SchedModel);
3257 Top.init(DAG, SchedModel, &Rem);
3258 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003259
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003260 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3261 // or are disabled, then these HazardRecs will be disabled.
3262 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003263 if (!Top.HazardRec) {
3264 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003265 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003266 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003267 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003268}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003269
Andrew Trickd14d7c22013-12-28 21:56:57 +00003270void PostGenericScheduler::registerRoots() {
3271 Rem.CriticalPath = DAG->ExitSU.getDepth();
3272
3273 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003274 for (const SUnit *SU : BotRoots) {
3275 if (SU->getDepth() > Rem.CriticalPath)
3276 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003277 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003278 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003279 if (DumpCriticalPathLength) {
3280 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3281 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003282}
3283
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003284/// Apply a set of heuristics to a new candidate for PostRA scheduling.
Andrew Trickd14d7c22013-12-28 21:56:57 +00003285///
3286/// \param Cand provides the policy and current best candidate.
3287/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3288void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3289 SchedCandidate &TryCand) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003290 // Initialize the candidate if needed.
3291 if (!Cand.isValid()) {
3292 TryCand.Reason = NodeOrder;
3293 return;
3294 }
3295
3296 // Prioritize instructions that read unbuffered resources by stall cycles.
3297 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3298 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3299 return;
3300
Florian Hahnabb42182017-05-23 09:33:34 +00003301 // Keep clustered nodes together.
3302 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3303 Cand.SU == DAG->getNextClusterSucc(),
3304 TryCand, Cand, Cluster))
3305 return;
3306
Andrew Trickd14d7c22013-12-28 21:56:57 +00003307 // Avoid critical resource consumption and balance the schedule.
3308 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3309 TryCand, Cand, ResourceReduce))
3310 return;
3311 if (tryGreater(TryCand.ResDelta.DemandedResources,
3312 Cand.ResDelta.DemandedResources,
3313 TryCand, Cand, ResourceDemand))
3314 return;
3315
3316 // Avoid serializing long latency dependence chains.
3317 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3318 return;
3319 }
3320
3321 // Fall through to original instruction order.
3322 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3323 TryCand.Reason = NodeOrder;
3324}
3325
3326void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3327 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003328 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003329 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003330 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003331 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003332 TryCand.initResourceDelta(DAG, SchedModel);
3333 tryCandidate(Cand, TryCand);
3334 if (TryCand.Reason != NoCand) {
3335 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003336 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trickd14d7c22013-12-28 21:56:57 +00003337 }
3338 }
3339}
3340
3341/// Pick the next node to schedule.
3342SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3343 if (DAG->top() == DAG->bottom()) {
3344 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003345 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003346 }
3347 SUnit *SU;
3348 do {
3349 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003350 if (SU) {
3351 tracePick(Only1, true);
3352 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003353 CandPolicy NoPolicy;
3354 SchedCandidate TopCand(NoPolicy);
3355 // Set the top-down policy based on the state of the current top zone and
3356 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003357 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003358 pickNodeFromQueue(TopCand);
3359 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003360 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003361 SU = TopCand.SU;
3362 }
3363 } while (SU->isScheduled);
3364
3365 IsTopNode = true;
3366 Top.removeReady(SU);
3367
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003368 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3369 << *SU->getInstr());
Andrew Trickd14d7c22013-12-28 21:56:57 +00003370 return SU;
3371}
3372
3373/// Called after ScheduleDAGMI has scheduled an instruction and updated
3374/// scheduled/remaining flags in the DAG nodes.
3375void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3376 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3377 Top.bumpNode(SU);
3378}
3379
Matthias Braun115efcd2016-11-28 20:11:54 +00003380ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003381 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003382 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003383}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003384
3385//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003386// ILP Scheduler. Currently for experimental analysis of heuristics.
3387//===----------------------------------------------------------------------===//
3388
3389namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003390
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003391/// Order nodes by the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003392struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003393 const SchedDFSResult *DFSResult = nullptr;
3394 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003395 bool MaximizeILP;
3396
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003397 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003398
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003399 /// Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003400 ///
3401 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003402 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003403 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3404 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3405 if (SchedTreeA != SchedTreeB) {
3406 // Unscheduled trees have lower priority.
3407 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3408 return ScheduledTrees->test(SchedTreeB);
3409
3410 // Trees with shallower connections have have lower priority.
3411 if (DFSResult->getSubtreeLevel(SchedTreeA)
3412 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3413 return DFSResult->getSubtreeLevel(SchedTreeA)
3414 < DFSResult->getSubtreeLevel(SchedTreeB);
3415 }
3416 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003417 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003418 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003419 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003420 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003421 }
3422};
3423
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003424/// Schedule based on the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003425class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003426 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003427 ILPOrder Cmp;
3428
3429 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003430
Andrew Trick90f711d2012-10-15 18:02:27 +00003431public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003432 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003433
Craig Topper4584cd52014-03-07 09:26:03 +00003434 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003435 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3436 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003437 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003438 Cmp.DFSResult = DAG->getDFSResult();
3439 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003440 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003441 }
3442
Craig Topper4584cd52014-03-07 09:26:03 +00003443 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003444 // Restore the heap in ReadyQ with the updated DFS results.
3445 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003446 }
3447
3448 /// Implement MachineSchedStrategy interface.
3449 /// -----------------------------------------
3450
Andrew Trick48d392e2012-11-28 05:13:28 +00003451 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003452 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003453 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003454 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003455 SUnit *SU = ReadyQ.back();
3456 ReadyQ.pop_back();
3457 IsTopNode = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003458 LLVM_DEBUG(dbgs() << "Pick node "
3459 << "SU(" << SU->NodeNum << ") "
3460 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3461 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
3462 << " @"
3463 << DAG->getDFSResult()->getSubtreeLevel(
3464 DAG->getDFSResult()->getSubtreeID(SU))
3465 << '\n'
3466 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003467 return SU;
3468 }
3469
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003470 /// Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003471 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003472 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3473 }
3474
Andrew Trick48d392e2012-11-28 05:13:28 +00003475 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3476 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003477 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003478 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003479 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003480
Craig Topper4584cd52014-03-07 09:26:03 +00003481 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003482
Craig Topper4584cd52014-03-07 09:26:03 +00003483 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003484 ReadyQ.push_back(SU);
3485 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3486 }
3487};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003488
3489} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003490
3491static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003492 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003493}
3494static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003495 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003496}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003497
Andrew Trick90f711d2012-10-15 18:02:27 +00003498static MachineSchedRegistry ILPMaxRegistry(
3499 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3500static MachineSchedRegistry ILPMinRegistry(
3501 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3502
3503//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003504// Machine Instruction Shuffler for Correctness Testing
3505//===----------------------------------------------------------------------===//
3506
Andrew Tricke77e84e2012-01-13 06:30:30 +00003507#ifndef NDEBUG
3508namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003509
Andrew Trick8823dec2012-03-14 04:00:41 +00003510/// Apply a less-than relation on the node order, which corresponds to the
3511/// instruction order prior to scheduling. IsReverse implements greater-than.
3512template<bool IsReverse>
3513struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003514 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003515 if (IsReverse)
3516 return A->NodeNum > B->NodeNum;
3517 else
3518 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003519 }
3520};
3521
Andrew Tricke77e84e2012-01-13 06:30:30 +00003522/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003523class InstructionShuffler : public MachineSchedStrategy {
3524 bool IsAlternating;
3525 bool IsTopDown;
3526
3527 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3528 // gives nodes with a higher number higher priority causing the latest
3529 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003530 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003531 TopQ;
Eugene Zelenko32a40562017-09-11 23:00:48 +00003532
Andrew Trick8823dec2012-03-14 04:00:41 +00003533 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003534 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003535 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003536
Andrew Tricke77e84e2012-01-13 06:30:30 +00003537public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003538 InstructionShuffler(bool alternate, bool topdown)
3539 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003540
Craig Topper9d74a5a2014-04-29 07:58:41 +00003541 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003542 TopQ.clear();
3543 BottomQ.clear();
3544 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003545
Andrew Trick8823dec2012-03-14 04:00:41 +00003546 /// Implement MachineSchedStrategy interface.
3547 /// -----------------------------------------
3548
Craig Topper9d74a5a2014-04-29 07:58:41 +00003549 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003550 SUnit *SU;
3551 if (IsTopDown) {
3552 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003553 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003554 SU = TopQ.top();
3555 TopQ.pop();
3556 } while (SU->isScheduled);
3557 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003558 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003559 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003560 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003561 SU = BottomQ.top();
3562 BottomQ.pop();
3563 } while (SU->isScheduled);
3564 IsTopNode = false;
3565 }
3566 if (IsAlternating)
3567 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003568 return SU;
3569 }
3570
Craig Topper9d74a5a2014-04-29 07:58:41 +00003571 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003572
Craig Topper9d74a5a2014-04-29 07:58:41 +00003573 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003574 TopQ.push(SU);
3575 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003576 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003577 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003578 }
3579};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003580
3581} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003582
Andrew Trick02a80da2012-03-08 01:41:12 +00003583static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003584 bool Alternate = !ForceTopDown && !ForceBottomUp;
3585 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003586 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003587 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003588 return new ScheduleDAGMILive(
3589 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003590}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003591
Andrew Trick8823dec2012-03-14 04:00:41 +00003592static MachineSchedRegistry ShufflerRegistry(
3593 "shuffle", "Shuffle machine instructions alternating directions",
3594 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003595#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003596
3597//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003598// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003599//===----------------------------------------------------------------------===//
3600
3601#ifndef NDEBUG
3602namespace llvm {
3603
3604template<> struct GraphTraits<
3605 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3606
3607template<>
3608struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003609 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003610
3611 static std::string getGraphName(const ScheduleDAG *G) {
3612 return G->MF.getName();
3613 }
3614
3615 static bool renderGraphFromBottomUp() {
3616 return true;
3617 }
3618
3619 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003620 if (ViewMISchedCutoff == 0)
3621 return false;
3622 return (Node->Preds.size() > ViewMISchedCutoff
3623 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003624 }
3625
Andrew Trickea9fd952013-01-25 07:45:29 +00003626 /// If you want to override the dot attributes printed for a particular
3627 /// edge, override this method.
3628 static std::string getEdgeAttributes(const SUnit *Node,
3629 SUnitIterator EI,
3630 const ScheduleDAG *Graph) {
3631 if (EI.isArtificialDep())
3632 return "color=cyan,style=dashed";
3633 if (EI.isCtrlDep())
3634 return "color=blue,style=dashed";
3635 return "";
3636 }
3637
3638 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003639 std::string Str;
3640 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003641 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3642 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003643 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003644 SS << "SU:" << SU->NodeNum;
3645 if (DFS)
3646 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003647 return SS.str();
3648 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00003649
Andrew Trickea9fd952013-01-25 07:45:29 +00003650 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3651 return G->getGraphNodeLabel(SU);
3652 }
3653
Andrew Trickd7f890e2013-12-28 21:56:47 +00003654 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003655 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003656 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3657 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003658 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003659 if (DFS) {
3660 Str += ",style=filled,fillcolor=\"#";
3661 Str += DOT::getColorString(DFS->getSubtreeID(N));
3662 Str += '"';
3663 }
3664 return Str;
3665 }
3666};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003667
3668} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003669#endif // NDEBUG
3670
3671/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3672/// rendered using 'dot'.
Andrew Trickea9fd952013-01-25 07:45:29 +00003673void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3674#ifndef NDEBUG
3675 ViewGraph(this, Name, false, Title);
3676#else
3677 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3678 << "systems with Graphviz or gv!\n";
3679#endif // NDEBUG
3680}
3681
3682/// Out-of-line implementation with no arguments is handy for gdb.
3683void ScheduleDAGMI::viewGraph() {
3684 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3685}