blob: 0e7974133e4889e17305341db1398d6a27c135d3 [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-01-13 06:30:30 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Tricke77e84e2012-01-13 06:30:30 +00006//
7//===----------------------------------------------------------------------===//
8//
9// MachineScheduler schedules machine instructions after phi elimination. It
10// preserves LiveIntervals so it can be invoked before register allocation.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000023#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000024#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000026#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000031#include "llvm/CodeGen/MachineOperand.h"
32#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000034#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000035#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000036#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000037#include "llvm/CodeGen/ScheduleDAG.h"
38#include "llvm/CodeGen/ScheduleDAGInstrs.h"
39#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000040#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000041#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000042#include "llvm/CodeGen/SlotIndexes.h"
Francis Visoiu Mistrih0b8dd442018-11-29 20:03:19 +000043#include "llvm/CodeGen/TargetFrameLowering.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
Serge Guelton86f8b702018-11-09 17:19:45 +0000243MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
244 MachineSchedRegistry::Registry;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000245
Andrew Trick45300682012-03-09 00:52:20 +0000246/// A dummy default scheduler factory indicates whether the scheduler
247/// is overridden on the command line.
248static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000249 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000250}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000251
252/// MachineSchedOpt allows command line selection of the scheduler.
253static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000254 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000255MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000256 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000257 cl::desc("Machine instruction scheduler to use"));
258
Andrew Trick45300682012-03-09 00:52:20 +0000259static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000260DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000261 useDefaultMachineSched);
262
Eric Christopher5f141b02015-03-11 22:56:10 +0000263static cl::opt<bool> EnableMachineSched(
264 "enable-misched",
265 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
266 cl::Hidden);
267
Chad Rosier816a1ab2016-01-20 23:08:32 +0000268static cl::opt<bool> EnablePostRAMachineSched(
269 "enable-post-misched",
270 cl::desc("Enable the post-ra machine instruction scheduling pass."),
271 cl::init(true), cl::Hidden);
272
Andrew Trickcc45a282012-04-24 18:04:34 +0000273/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000274static MachineBasicBlock::const_iterator
275priorNonDebug(MachineBasicBlock::const_iterator I,
276 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000277 assert(I != Beg && "reached the top of the region, cannot decrement");
278 while (--I != Beg) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000279 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000280 break;
281 }
282 return I;
283}
284
Andrew Trick2bc74c22013-08-30 04:36:57 +0000285/// Non-const version.
286static MachineBasicBlock::iterator
287priorNonDebug(MachineBasicBlock::iterator I,
288 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000289 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
290 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000291}
292
Andrew Trickcc45a282012-04-24 18:04:34 +0000293/// If this iterator is a debug value, increment until reaching the End or a
294/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000295static MachineBasicBlock::const_iterator
296nextIfDebug(MachineBasicBlock::const_iterator I,
297 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000298 for(; I != End; ++I) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000299 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000300 break;
301 }
302 return I;
303}
304
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000305/// Non-const version.
306static MachineBasicBlock::iterator
307nextIfDebug(MachineBasicBlock::iterator I,
308 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000309 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
310 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000311}
312
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000313/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000314ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
315 // Select the scheduler, or set the default.
316 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
317 if (Ctor != useDefaultMachineSched)
318 return Ctor(this);
319
320 // Get the default scheduler set by the target for this function.
321 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
322 if (Scheduler)
323 return Scheduler;
324
325 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000326 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000327}
328
Andrew Trick17080b92013-12-28 21:56:51 +0000329/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
330/// the caller. We don't have a command line option to override the postRA
331/// scheduler. The Target must configure it.
332ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
333 // Get the postRA scheduler set by the target for this function.
334 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
335 if (Scheduler)
336 return Scheduler;
337
338 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000339 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000340}
341
Andrew Trick72515be2012-03-14 04:00:38 +0000342/// Top-level MachineScheduler pass driver.
343///
344/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000345/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
346/// consistent with the DAG builder, which traverses the interior of the
347/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000348///
349/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000350/// simplifying the DAG builder's support for "special" target instructions.
351/// At the same time the design allows target schedulers to operate across
Hiroshi Inouec73b6d62018-06-20 05:29:26 +0000352/// scheduling boundaries, for example to bundle the boundary instructions
Andrew Trick72515be2012-03-14 04:00:38 +0000353/// without reordering them. This creates complexity, because the target
354/// scheduler must update the RegionBegin and RegionEnd positions cached by
355/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
356/// design would be to split blocks at scheduling boundaries, but LLVM has a
357/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000358bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000359 if (skipFunction(mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000360 return false;
361
Eric Christopher5f141b02015-03-11 22:56:10 +0000362 if (EnableMachineSched.getNumOccurrences()) {
363 if (!EnableMachineSched)
364 return false;
365 } else if (!mf.getSubtarget().enableMachineScheduler())
366 return false;
367
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000369
Andrew Tricke77e84e2012-01-13 06:30:30 +0000370 // Initialize the context of the pass.
371 MF = &mf;
372 MLI = &getAnalysis<MachineLoopInfo>();
373 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000374 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000375 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000376
Lang Hamesad33d5a2012-01-27 22:36:19 +0000377 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000378
Andrew Trick48f2a722013-03-08 05:40:34 +0000379 if (VerifyScheduling) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000380 LLVM_DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000381 MF->verify(this, "Before machine scheduling.");
382 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000383 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000384
Andrew Trick978674b2013-09-20 05:14:41 +0000385 // Instantiate the selected scheduler for this target, function, and
386 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000387 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000388 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000389
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000390 LLVM_DEBUG(LIS->dump());
Andrew Trickd7f890e2013-12-28 21:56:47 +0000391 if (VerifyScheduling)
392 MF->verify(this, "After machine scheduling.");
393 return true;
394}
395
Andrew Trick17080b92013-12-28 21:56:51 +0000396bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000397 if (skipFunction(mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000398 return false;
399
Chad Rosier816a1ab2016-01-20 23:08:32 +0000400 if (EnablePostRAMachineSched.getNumOccurrences()) {
401 if (!EnablePostRAMachineSched)
402 return false;
403 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000404 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
Andrew Trick8d2ee372014-06-04 07:06:27 +0000405 return false;
406 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
Andrew Trick17080b92013-12-28 21:56:51 +0000408
409 // Initialize the context of the pass.
410 MF = &mf;
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000411 MLI = &getAnalysis<MachineLoopInfo>();
Andrew Trick17080b92013-12-28 21:56:51 +0000412 PassConfig = &getAnalysis<TargetPassConfig>();
413
414 if (VerifyScheduling)
415 MF->verify(this, "Before post machine scheduling.");
416
417 // Instantiate the selected scheduler for this target, function, and
418 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000419 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000420 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000421
422 if (VerifyScheduling)
423 MF->verify(this, "After post machine scheduling.");
424 return true;
425}
426
Andrew Trickd14d7c22013-12-28 21:56:57 +0000427/// Return true of the given instruction should not be included in a scheduling
428/// region.
429///
430/// MachineScheduler does not currently support scheduling across calls. To
431/// handle calls, the DAG builder needs to be modified to create register
432/// anti/output dependencies on the registers clobbered by the call's regmask
433/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
434/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
435/// the boundary, but there would be no benefit to postRA scheduling across
436/// calls this late anyway.
437static bool isSchedBoundary(MachineBasicBlock::iterator MI,
438 MachineBasicBlock *MBB,
439 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000440 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000441 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000442}
443
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000444/// A region of an MBB for scheduling.
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000445namespace {
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000446struct SchedRegion {
447 /// RegionBegin is the first instruction in the scheduling region, and
448 /// RegionEnd is either MBB->end() or the scheduling boundary after the
449 /// last instruction in the scheduling region. These iterators cannot refer
450 /// to instructions outside of the identified scheduling region because
451 /// those may be reordered before scheduling this region.
452 MachineBasicBlock::iterator RegionBegin;
453 MachineBasicBlock::iterator RegionEnd;
454 unsigned NumRegionInstrs;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000455
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000456 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
457 unsigned N) :
458 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
459};
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000460} // end anonymous namespace
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000461
Eugene Zelenko32a40562017-09-11 23:00:48 +0000462using MBBRegionsVector = SmallVector<SchedRegion, 16>;
463
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000464static void
465getSchedRegions(MachineBasicBlock *MBB,
466 MBBRegionsVector &Regions,
467 bool RegionsTopDown) {
468 MachineFunction *MF = MBB->getParent();
469 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
470
471 MachineBasicBlock::iterator I = nullptr;
472 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
473 RegionEnd != MBB->begin(); RegionEnd = I) {
474
475 // Avoid decrementing RegionEnd for blocks with no terminator.
476 if (RegionEnd != MBB->end() ||
477 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
478 --RegionEnd;
479 }
480
481 // The next region starts above the previous region. Look backward in the
482 // instruction stream until we find the nearest boundary.
483 unsigned NumRegionInstrs = 0;
484 I = RegionEnd;
485 for (;I != MBB->begin(); --I) {
486 MachineInstr &MI = *std::prev(I);
487 if (isSchedBoundary(&MI, &*MBB, MF, TII))
488 break;
Matt Arsenaultb27e49742019-03-25 17:15:44 +0000489 if (!MI.isDebugInstr()) {
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000490 // MBB::size() uses instr_iterator to count. Here we need a bundle to
491 // count as a single instruction.
492 ++NumRegionInstrs;
Matt Arsenaultb27e49742019-03-25 17:15:44 +0000493 }
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000494 }
495
Matt Arsenaultb27e49742019-03-25 17:15:44 +0000496 // It's possible we found a scheduling region that only has debug
497 // instructions. Don't bother scheduling these.
498 if (NumRegionInstrs != 0)
499 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000500 }
501
502 if (RegionsTopDown)
503 std::reverse(Regions.begin(), Regions.end());
504}
505
Andrew Trickd7f890e2013-12-28 21:56:47 +0000506/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000507void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
508 bool FixKillFlags) {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000509 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000510 //
511 // TODO: Visit blocks in global postorder or postorder within the bottom-up
512 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000513 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
514 MBB != MBBEnd; ++MBB) {
515
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000516 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000517
Andrew Trick33e05d72013-12-28 21:57:02 +0000518#ifndef NDEBUG
519 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
520 continue;
521 if (SchedOnlyBlock.getNumOccurrences()
522 && (int)SchedOnlyBlock != MBB->getNumber())
523 continue;
524#endif
525
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000526 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
527 // points to the scheduling boundary at the bottom of the region. The DAG
528 // does not include RegionEnd, but the region does (i.e. the next
529 // RegionEnd is above the previous RegionBegin). If the current block has
530 // no terminator then RegionEnd == MBB->end() for the bottom region.
531 //
532 // All the regions of MBB are first found and stored in MBBRegions, which
533 // will be processed (MBB) top-down if initialized with true.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000534 //
535 // The Scheduler may insert instructions during either schedule() or
536 // exitRegion(), even for empty regions. So the local iterators 'I' and
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000537 // 'RegionEnd' are invalid across these calls. Instructions must not be
538 // added to other regions than the current one without updating MBBRegions.
Andrew Trick88639922012-04-24 17:56:43 +0000539
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000540 MBBRegionsVector MBBRegions;
541 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
542 for (MBBRegionsVector::iterator R = MBBRegions.begin();
543 R != MBBRegions.end(); ++R) {
544 MachineBasicBlock::iterator I = R->RegionBegin;
545 MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
546 unsigned NumRegionInstrs = R->NumRegionInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000547
Andrew Trick60cf03e2012-03-07 05:21:52 +0000548 // Notify the scheduler of the region, even if we may skip scheduling
549 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000550 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000551
552 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000553 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000554 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000555 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000556 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000557 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000558 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000559 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
560 LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
561 << " " << MBB->getName() << "\n From: " << *I
562 << " To: ";
563 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
564 else dbgs() << "End";
565 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000566 if (DumpCriticalPathLength) {
567 errs() << MF->getName();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000568 errs() << ":%bb. " << MBB->getNumber();
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000569 errs() << " " << MBB->getName() << " \n";
570 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000571
Andrew Trick1c0ec452012-03-09 03:46:42 +0000572 // Schedule a region: possibly reorder instructions.
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000573 // This invalidates the original region iterators.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000574 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000575
576 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000577 Scheduler.exitRegion();
Andrew Trick7e120f42012-01-14 02:17:09 +0000578 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000579 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000580 // FIXME: Ideally, no further passes should rely on kill flags. However,
581 // thumb2 size reduction is currently an exception, so the PostMIScheduler
582 // needs to do this.
583 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000584 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000585 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000586 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000587}
588
Andrew Trickd7f890e2013-12-28 21:56:47 +0000589void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000590 // unimplemented
591}
592
Aaron Ballman615eb472017-10-15 14:32:27 +0000593#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000594LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000595 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000596 for (const SUnit *SU : Queue)
597 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000598 dbgs() << "\n";
599}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000600#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000601
602//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000603// ScheduleDAGMI - Basic machine instruction scheduling. This is
604// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
605// virtual registers.
606// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000607
David Blaikie422b93d2014-04-21 20:32:32 +0000608// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000609ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000610
Andrew Trick02a80da2012-03-08 01:41:12 +0000611/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
612/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000613///
614/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000615void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000616 SUnit *SuccSU = SuccEdge->getSUnit();
617
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000618 if (SuccEdge->isWeak()) {
619 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000620 if (SuccEdge->isCluster())
621 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000622 return;
623 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000624#ifndef NDEBUG
625 if (SuccSU->NumPredsLeft == 0) {
626 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braun726e12c2018-09-19 00:23:35 +0000627 dumpNode(*SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000628 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000629 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000630 }
631#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000632 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
633 // CurrCycle may have advanced since then.
634 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
635 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
636
Andrew Trick02a80da2012-03-08 01:41:12 +0000637 --SuccSU->NumPredsLeft;
638 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000639 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000640}
641
642/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000643void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000644 for (SDep &Succ : SU->Succs)
645 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000646}
647
Andrew Trick8823dec2012-03-14 04:00:41 +0000648/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
649/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000650///
651/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000652void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
653 SUnit *PredSU = PredEdge->getSUnit();
654
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000655 if (PredEdge->isWeak()) {
656 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000657 if (PredEdge->isCluster())
658 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000659 return;
660 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000661#ifndef NDEBUG
662 if (PredSU->NumSuccsLeft == 0) {
663 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braun726e12c2018-09-19 00:23:35 +0000664 dumpNode(*PredSU);
Andrew Trick8823dec2012-03-14 04:00:41 +0000665 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000666 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000667 }
668#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000669 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
670 // CurrCycle may have advanced since then.
671 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
672 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
673
Andrew Trick8823dec2012-03-14 04:00:41 +0000674 --PredSU->NumSuccsLeft;
675 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
676 SchedImpl->releaseBottomNode(PredSU);
677}
678
679/// releasePredecessors - Call releasePred on each of SU's predecessors.
680void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000681 for (SDep &Pred : SU->Preds)
682 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000683}
684
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000685void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
686 ScheduleDAGInstrs::startBlock(bb);
687 SchedImpl->enterMBB(bb);
688}
689
690void ScheduleDAGMI::finishBlock() {
691 SchedImpl->leaveMBB();
692 ScheduleDAGInstrs::finishBlock();
693}
694
Andrew Trickd7f890e2013-12-28 21:56:47 +0000695/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
696/// crossing a scheduling boundary. [begin, end) includes all instructions in
697/// the region, including the boundary itself and single-instruction regions
698/// that don't get scheduled.
699void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
700 MachineBasicBlock::iterator begin,
701 MachineBasicBlock::iterator end,
702 unsigned regioninstrs)
703{
704 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
705
706 SchedImpl->initPolicy(begin, end, regioninstrs);
707}
708
Andrew Tricke833e1c2013-04-13 06:07:40 +0000709/// This is normally called from the main scheduler loop but may also be invoked
710/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000711void ScheduleDAGMI::moveInstruction(
712 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000713 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000714 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000715 ++RegionBegin;
716
717 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000718 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000719
720 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000721 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000722 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000723
724 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000725 if (RegionBegin == InsertPos)
726 RegionBegin = MI;
727}
728
Andrew Trickde670c02012-03-21 04:12:07 +0000729bool ScheduleDAGMI::checkSchedLimit() {
730#ifndef NDEBUG
731 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
732 CurrentTop = CurrentBottom;
733 return false;
734 }
735 ++NumInstrsScheduled;
736#endif
737 return true;
738}
739
Andrew Trickd7f890e2013-12-28 21:56:47 +0000740/// Per-region scheduling driver, called back from
741/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
742/// does not consider liveness or register pressure. It is useful for PostRA
743/// scheduling and potentially other custom schedulers.
744void ScheduleDAGMI::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000745 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
746 LLVM_DEBUG(SchedImpl->dumpPolicy());
James Y Knighte72b0db2015-09-18 18:52:20 +0000747
Andrew Trickd7f890e2013-12-28 21:56:47 +0000748 // Build the DAG.
749 buildSchedGraph(AA);
750
Andrew Trickd7f890e2013-12-28 21:56:47 +0000751 postprocessDAG();
752
753 SmallVector<SUnit*, 8> TopRoots, BotRoots;
754 findRootsAndBiasEdges(TopRoots, BotRoots);
755
Matthias Braun726e12c2018-09-19 00:23:35 +0000756 LLVM_DEBUG(dump());
Matthias Braun3136e422018-09-19 20:50:49 +0000757 if (PrintDAGs) dump();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000758 if (ViewMISchedDAGs) viewGraph();
759
Jonas Paulssonbc32f7d2018-03-05 16:31:49 +0000760 // Initialize the strategy before modifying the DAG.
761 // This may initialize a DFSResult to be used for queue priority.
762 SchedImpl->initialize(this);
763
Andrew Trickd7f890e2013-12-28 21:56:47 +0000764 // Initialize ready queues now that the DAG and priority data are finalized.
765 initQueues(TopRoots, BotRoots);
766
767 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000768 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000769 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +0000770 SUnit *SU = SchedImpl->pickNode(IsTopNode);
771 if (!SU) break;
772
Andrew Trickd7f890e2013-12-28 21:56:47 +0000773 assert(!SU->isScheduled && "Node already scheduled");
774 if (!checkSchedLimit())
775 break;
776
777 MachineInstr *MI = SU->getInstr();
778 if (IsTopNode) {
779 assert(SU->isTopReady() && "node still has unscheduled dependencies");
780 if (&*CurrentTop == MI)
781 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
782 else
783 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000784 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000785 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
786 MachineBasicBlock::iterator priorII =
787 priorNonDebug(CurrentBottom, CurrentTop);
788 if (&*priorII == MI)
789 CurrentBottom = priorII;
790 else {
791 if (&*CurrentTop == MI)
792 CurrentTop = nextIfDebug(++CurrentTop, priorII);
793 moveInstruction(MI, CurrentBottom);
794 CurrentBottom = MI;
795 }
796 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000797 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000798 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000799 // runs, it can then use the accurate ReadyCycle time to determine whether
800 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000801 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000802
803 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000804 }
805 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
806
807 placeDebugValues();
808
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000809 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000810 dbgs() << "*** Final schedule for "
811 << printMBBReference(*begin()->getParent()) << " ***\n";
812 dumpSchedule();
813 dbgs() << '\n';
814 });
Andrew Trickd7f890e2013-12-28 21:56:47 +0000815}
816
817/// Apply each ScheduleDAGMutation step in order.
818void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000819 for (auto &m : Mutations)
820 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000821}
822
823void ScheduleDAGMI::
824findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
825 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000826 for (SUnit &SU : SUnits) {
827 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000828
829 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000830 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000831
832 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000833 if (!SU.NumPredsLeft)
834 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000835 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000836 if (!SU.NumSuccsLeft)
837 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000838 }
839 ExitSU.biasCriticalPath();
840}
841
842/// Identify DAG roots and setup scheduler queues.
843void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
844 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000845 NextClusterSucc = nullptr;
846 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000847
848 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
849 //
850 // Nodes with unreleased weak edges can still be roots.
851 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000852 for (SUnit *SU : TopRoots)
853 SchedImpl->releaseTopNode(SU);
854
Andrew Trickd7f890e2013-12-28 21:56:47 +0000855 // Release bottom roots in reverse order so the higher priority nodes appear
856 // first. This is more natural and slightly more efficient.
857 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
858 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
859 SchedImpl->releaseBottomNode(*I);
860 }
861
862 releaseSuccessors(&EntrySU);
863 releasePredecessors(&ExitSU);
864
865 SchedImpl->registerRoots();
866
867 // Advance past initial DebugValues.
868 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
869 CurrentBottom = RegionEnd;
870}
871
872/// Update scheduler queues after scheduling an instruction.
873void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
874 // Release dependent instructions for scheduling.
875 if (IsTopNode)
876 releaseSuccessors(SU);
877 else
878 releasePredecessors(SU);
879
880 SU->isScheduled = true;
881}
882
883/// Reinsert any remaining debug_values, just like the PostRA scheduler.
884void ScheduleDAGMI::placeDebugValues() {
885 // If first instruction was a DBG_VALUE then put it back.
886 if (FirstDbgValue) {
887 BB->splice(RegionBegin, BB, FirstDbgValue);
888 RegionBegin = FirstDbgValue;
889 }
890
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000891 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000892 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000893 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000894 MachineInstr *DbgValue = P.first;
895 MachineBasicBlock::iterator OrigPrevMI = P.second;
896 if (&*RegionBegin == DbgValue)
897 ++RegionBegin;
898 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000899 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000900 RegionEnd = DbgValue;
901 }
902 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000903 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000904}
905
Aaron Ballman615eb472017-10-15 14:32:27 +0000906#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000907LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000908 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
909 if (SUnit *SU = getSUnit(&(*MI)))
Matthias Braun726e12c2018-09-19 00:23:35 +0000910 dumpNode(*SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000911 else
912 dbgs() << "Missing SUnit\n";
913 }
914}
915#endif
916
917//===----------------------------------------------------------------------===//
918// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
919// preservation.
920//===----------------------------------------------------------------------===//
921
922ScheduleDAGMILive::~ScheduleDAGMILive() {
923 delete DFSResult;
924}
925
Matthias Braun40639882016-11-11 22:37:31 +0000926void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
927 const MachineInstr &MI = *SU.getInstr();
928 for (const MachineOperand &MO : MI.operands()) {
929 if (!MO.isReg())
930 continue;
931 if (!MO.readsReg())
932 continue;
933 if (TrackLaneMasks && !MO.isUse())
934 continue;
935
936 unsigned Reg = MO.getReg();
937 if (!TargetRegisterInfo::isVirtualRegister(Reg))
938 continue;
939
940 // Ignore re-defs.
941 if (TrackLaneMasks) {
942 bool FoundDef = false;
943 for (const MachineOperand &MO2 : MI.operands()) {
944 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
945 FoundDef = true;
946 break;
947 }
948 }
949 if (FoundDef)
950 continue;
951 }
952
953 // Record this local VReg use.
954 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
955 for (; UI != VRegUses.end(); ++UI) {
956 if (UI->SU == &SU)
957 break;
958 }
959 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000960 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000961 }
962}
963
Andrew Trick88639922012-04-24 17:56:43 +0000964/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
965/// crossing a scheduling boundary. [begin, end) includes all instructions in
966/// the region, including the boundary itself and single-instruction regions
967/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000968void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000969 MachineBasicBlock::iterator begin,
970 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000971 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000972{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000973 // ScheduleDAGMI initializes SchedImpl's per-region policy.
974 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000975
976 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000977 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000978
Andrew Trickb248b4a2013-09-06 17:32:47 +0000979 SUPressureDiffs.clear();
980
Andrew Trick75e411c2013-09-06 17:32:34 +0000981 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000982 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
983
Matthias Braunf9acaca2016-05-31 22:38:06 +0000984 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
985 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000986}
987
988// Setup the register pressure trackers for the top scheduled top and bottom
989// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000990void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +0000991 VRegUses.clear();
992 VRegUses.setUniverse(MRI.getNumVirtRegs());
993 for (SUnit &SU : SUnits)
994 collectVRegUses(SU);
995
Matthias Braund4f64092016-01-20 00:23:32 +0000996 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
997 ShouldTrackLaneMasks, false);
998 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
999 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +00001000
1001 // Close the RPTracker to finalize live ins.
1002 RPTracker.closeRegion();
1003
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001004 LLVM_DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +00001005
Andrew Trick4add42f2012-05-10 21:06:10 +00001006 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +00001007 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1008 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +00001009
1010 // Close one end of the tracker so we can call
1011 // getMaxUpward/DownwardPressureDelta before advancing across any
1012 // instructions. This converts currently live regs into live ins/outs.
1013 TopRPTracker.closeTop();
1014 BotRPTracker.closeBottom();
1015
Andrew Trick9c17eab2013-07-30 19:59:12 +00001016 BotRPTracker.initLiveThru(RPTracker);
1017 if (!BotRPTracker.getLiveThru().empty()) {
1018 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001019 LLVM_DEBUG(dbgs() << "Live Thru: ";
1020 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
Andrew Trick9c17eab2013-07-30 19:59:12 +00001021 };
1022
Andrew Trick2bc74c22013-08-30 04:36:57 +00001023 // For each live out vreg reduce the pressure change associated with other
1024 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +00001025 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +00001026
Andrew Trick4add42f2012-05-10 21:06:10 +00001027 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001028 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001029 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001030 BotRPTracker.recede(&LiveUses);
1031 updatePressureDiffs(LiveUses);
1032 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001033
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001034 LLVM_DEBUG(dbgs() << "Top Pressure:\n";
1035 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1036 dbgs() << "Bottom Pressure:\n";
1037 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braune6edd482015-11-13 22:30:31 +00001038
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001039 assert((BotRPTracker.getPos() == RegionEnd ||
Shiva Chen801bf7e2018-05-09 02:42:00 +00001040 (RegionEnd->isDebugInstr() &&
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001041 BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
1042 "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001043
1044 // Cache the list of excess pressure sets in this region. This will also track
1045 // the max pressure in the scheduled code for these sets.
1046 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001047 const std::vector<unsigned> &RegionPressure =
1048 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001049 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001050 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001051 if (RegionPressure[i] > Limit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001052 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1053 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001054 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001055 }
Andrew Trick22025772012-05-17 18:35:10 +00001056 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001057 LLVM_DEBUG(dbgs() << "Excess PSets: ";
1058 for (const PressureChange &RCPS
1059 : RegionCriticalPSets) dbgs()
1060 << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1061 dbgs() << "\n");
Andrew Trick22025772012-05-17 18:35:10 +00001062}
1063
Andrew Trickd7f890e2013-12-28 21:56:47 +00001064void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001065updateScheduledPressure(const SUnit *SU,
1066 const std::vector<unsigned> &NewMaxPressure) {
1067 const PressureDiff &PDiff = getPressureDiff(SU);
1068 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001069 for (const PressureChange &PC : PDiff) {
1070 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001071 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001072 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001073 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1074 ++CritIdx;
1075 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1076 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001077 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001078 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1079 }
1080 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1081 if (NewMaxPressure[ID] >= Limit - 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001082 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
1083 << NewMaxPressure[ID]
1084 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1085 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1086 << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001087 }
Andrew Trick22025772012-05-17 18:35:10 +00001088 }
Andrew Trick88639922012-04-24 17:56:43 +00001089}
1090
Andrew Trick2bc74c22013-08-30 04:36:57 +00001091/// Update the PressureDiff array for liveness after scheduling this
1092/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001093void ScheduleDAGMILive::updatePressureDiffs(
1094 ArrayRef<RegisterMaskPair> LiveUses) {
1095 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001096 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001097 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001098 if (!TRI->isVirtualRegister(Reg))
1099 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001100
Matthias Braund4f64092016-01-20 00:23:32 +00001101 if (ShouldTrackLaneMasks) {
1102 // If the register has just become live then other uses won't change
1103 // this fact anymore => decrement pressure.
1104 // If the register has just become dead then other uses make it come
1105 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001106 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001107
1108 for (const VReg2SUnit &V2SU
1109 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1110 SUnit &SU = *V2SU.SU;
1111 if (SU.isScheduled || &SU == &ExitSU)
1112 continue;
1113
1114 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001115 PDiff.addPressureChange(Reg, Decrement, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001116 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1117 << printReg(Reg, TRI) << ':'
1118 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1119 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001120 }
1121 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001122 assert(P.LaneMask.any());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001123 LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
Matthias Braund4f64092016-01-20 00:23:32 +00001124 // This may be called before CurrentBottom has been initialized. However,
1125 // BotRPTracker must have a valid position. We want the value live into the
1126 // instruction or live out of the block, so ask for the previous
1127 // instruction's live-out.
1128 const LiveInterval &LI = LIS->getInterval(Reg);
1129 VNInfo *VNI;
1130 MachineBasicBlock::const_iterator I =
1131 nextIfDebug(BotRPTracker.getPos(), BB->end());
1132 if (I == BB->end())
1133 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1134 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001135 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001136 VNI = LRQ.valueIn();
1137 }
1138 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1139 assert(VNI && "No live value at use.");
1140 for (const VReg2SUnit &V2SU
1141 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1142 SUnit *SU = V2SU.SU;
1143 // If this use comes before the reaching def, it cannot be a last use,
1144 // so decrease its pressure change.
1145 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001146 LiveQueryResult LRQ =
1147 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001148 if (LRQ.valueIn() == VNI) {
1149 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001150 PDiff.addPressureChange(Reg, true, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001151 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1152 << *SU->getInstr();
1153 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001154 }
Matthias Braun9198c672015-11-06 20:59:02 +00001155 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001156 }
1157 }
1158 }
1159}
1160
Matthias Braun726e12c2018-09-19 00:23:35 +00001161void ScheduleDAGMILive::dump() const {
1162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1163 if (EntrySU.getInstr() != nullptr)
1164 dumpNodeAll(EntrySU);
1165 for (const SUnit &SU : SUnits) {
1166 dumpNodeAll(SU);
1167 if (ShouldTrackPressure) {
1168 dbgs() << " Pressure Diff : ";
1169 getPressureDiff(&SU).dump(*TRI);
1170 }
1171 dbgs() << " Single Issue : ";
1172 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1173 SchedModel.mustEndGroup(SU.getInstr()))
1174 dbgs() << "true;";
1175 else
1176 dbgs() << "false;";
1177 dbgs() << '\n';
1178 }
1179 if (ExitSU.getInstr() != nullptr)
1180 dumpNodeAll(ExitSU);
1181#endif
1182}
1183
Andrew Trick8823dec2012-03-14 04:00:41 +00001184/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001185/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1186/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001187///
1188/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001189/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001190/// implementing MachineSchedStrategy should be sufficient to implement a new
1191/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001192/// ScheduleDAGMILive then it will want to override this virtual method in order
1193/// to update any specialized state.
1194void ScheduleDAGMILive::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001195 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1196 LLVM_DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001197 buildDAGWithRegPressure();
1198
Andrew Tricka2733e92012-09-14 17:22:42 +00001199 postprocessDAG();
1200
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001201 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1202 findRootsAndBiasEdges(TopRoots, BotRoots);
1203
1204 // Initialize the strategy before modifying the DAG.
1205 // This may initialize a DFSResult to be used for queue priority.
1206 SchedImpl->initialize(this);
1207
Matthias Braun726e12c2018-09-19 00:23:35 +00001208 LLVM_DEBUG(dump());
Matthias Braun3136e422018-09-19 20:50:49 +00001209 if (PrintDAGs) dump();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001210 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001211
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001212 // Initialize ready queues now that the DAG and priority data are finalized.
1213 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001214
1215 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001216 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001217 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +00001218 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1219 if (!SU) break;
1220
Andrew Trick984d98b2012-10-08 18:53:53 +00001221 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001222 if (!checkSchedLimit())
1223 break;
1224
1225 scheduleMI(SU, IsTopNode);
1226
Andrew Trickd7f890e2013-12-28 21:56:47 +00001227 if (DFSResult) {
1228 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1229 if (!ScheduledTrees.test(SubtreeID)) {
1230 ScheduledTrees.set(SubtreeID);
1231 DFSResult->scheduleTree(SubtreeID);
1232 SchedImpl->scheduleTree(SubtreeID);
1233 }
1234 }
1235
1236 // Notify the scheduling strategy after updating the DAG.
1237 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001238
1239 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001240 }
1241 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1242
1243 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001244
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001245 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001246 dbgs() << "*** Final schedule for "
1247 << printMBBReference(*begin()->getParent()) << " ***\n";
1248 dumpSchedule();
1249 dbgs() << '\n';
1250 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001251}
1252
1253/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001254void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001255 if (!ShouldTrackPressure) {
1256 RPTracker.reset();
1257 RegionCriticalPSets.clear();
1258 buildSchedGraph(AA);
1259 return;
1260 }
1261
Andrew Trick4add42f2012-05-10 21:06:10 +00001262 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001263 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001264 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001265
Andrew Trick4add42f2012-05-10 21:06:10 +00001266 // Account for liveness generate by the region boundary.
1267 if (LiveRegionEnd != RegionEnd)
1268 RPTracker.recede();
1269
1270 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001271 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001272
Andrew Trick4add42f2012-05-10 21:06:10 +00001273 // Initialize top/bottom trackers after computing region pressure.
1274 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001275}
Andrew Trick4add42f2012-05-10 21:06:10 +00001276
Andrew Trickd7f890e2013-12-28 21:56:47 +00001277void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001278 if (!DFSResult)
1279 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1280 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001281 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001282 DFSResult->resize(SUnits.size());
1283 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001284 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1285}
1286
Andrew Trick483f4192013-08-29 18:04:49 +00001287/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1288/// only provides the critical path for single block loops. To handle loops that
1289/// span blocks, we could use the vreg path latencies provided by
1290/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1291/// available for use in the scheduler.
1292///
1293/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001294/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001295/// the following instruction sequence where each instruction has unit latency
1296/// and defines an epomymous virtual register:
1297///
1298/// a->b(a,c)->c(b)->d(c)->exit
1299///
1300/// The cyclic critical path is a two cycles: b->c->b
1301/// The acyclic critical path is four cycles: a->b->c->d->exit
1302/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1303/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1304/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1305/// LiveInDepth = depth(b) = len(a->b) = 1
1306///
1307/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1308/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1309/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001310///
1311/// This could be relevant to PostRA scheduling, but is currently implemented
1312/// assuming LiveIntervals.
1313unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001314 // This only applies to single block loop.
1315 if (!BB->isSuccessor(BB))
1316 return 0;
1317
1318 unsigned MaxCyclicLatency = 0;
1319 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001320 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1321 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001322 if (!TRI->isVirtualRegister(Reg))
1323 continue;
1324 const LiveInterval &LI = LIS->getInterval(Reg);
1325 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1326 if (!DefVNI)
1327 continue;
1328
1329 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1330 const SUnit *DefSU = getSUnit(DefMI);
1331 if (!DefSU)
1332 continue;
1333
1334 unsigned LiveOutHeight = DefSU->getHeight();
1335 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1336 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001337 for (const VReg2SUnit &V2SU
1338 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1339 SUnit *SU = V2SU.SU;
1340 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001341 continue;
1342
1343 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001344 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001345 if (!LRQ.valueIn()->isPHIDef())
1346 continue;
1347
1348 // Assume that a path spanning two iterations is a cycle, which could
1349 // overestimate in strange cases. This allows cyclic latency to be
1350 // estimated as the minimum slack of the vreg's depth or height.
1351 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001352 if (LiveOutDepth > SU->getDepth())
1353 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001354
Matthias Braunb0c437b2015-10-29 03:57:17 +00001355 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001356 if (LiveInHeight > LiveOutHeight) {
1357 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1358 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001359 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001360 CyclicLatency = 0;
1361
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001362 LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1363 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001364 if (CyclicLatency > MaxCyclicLatency)
1365 MaxCyclicLatency = CyclicLatency;
1366 }
1367 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001368 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001369 return MaxCyclicLatency;
1370}
1371
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001372/// Release ExitSU predecessors and setup scheduler queues. Re-position
1373/// the Top RP tracker in case the region beginning has changed.
1374void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1375 ArrayRef<SUnit*> BotRoots) {
1376 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1377 if (ShouldTrackPressure) {
1378 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1379 TopRPTracker.setPos(CurrentTop);
1380 }
1381}
1382
Andrew Trick7a8e1002012-09-11 00:39:15 +00001383/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001384void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001385 // Move the instruction to its new location in the instruction stream.
1386 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001387
Andrew Trick7a8e1002012-09-11 00:39:15 +00001388 if (IsTopNode) {
1389 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1390 if (&*CurrentTop == MI)
1391 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001392 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001393 moveInstruction(MI, CurrentTop);
1394 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001395 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001396
Andrew Trickb6e74712013-09-04 20:59:59 +00001397 if (ShouldTrackPressure) {
1398 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001399 RegisterOperands RegOpers;
1400 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1401 if (ShouldTrackLaneMasks) {
1402 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001403 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001404 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1405 } else {
1406 // Adjust for missing dead-def flags.
1407 RegOpers.detectDeadDefs(*MI, *LIS);
1408 }
1409
1410 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001411 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001412 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
1413 TopRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001414
Andrew Trickb248b4a2013-09-06 17:32:47 +00001415 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001416 }
Matthias Braunb550b762016-04-21 01:54:13 +00001417 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001418 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1419 MachineBasicBlock::iterator priorII =
1420 priorNonDebug(CurrentBottom, CurrentTop);
1421 if (&*priorII == MI)
1422 CurrentBottom = priorII;
1423 else {
1424 if (&*CurrentTop == MI) {
1425 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1426 TopRPTracker.setPos(CurrentTop);
1427 }
1428 moveInstruction(MI, CurrentBottom);
1429 CurrentBottom = MI;
Yaxun Liu8b7454a2018-01-23 16:04:53 +00001430 BotRPTracker.setPos(CurrentBottom);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001431 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001432 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001433 RegisterOperands RegOpers;
1434 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1435 if (ShouldTrackLaneMasks) {
1436 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001437 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001438 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1439 } else {
1440 // Adjust for missing dead-def flags.
1441 RegOpers.detectDeadDefs(*MI, *LIS);
1442 }
1443
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001444 if (BotRPTracker.getPos() != CurrentBottom)
1445 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001446 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001447 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001448 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001449 LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
1450 BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001451
Andrew Trickb248b4a2013-09-06 17:32:47 +00001452 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001453 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001454 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001455 }
1456}
1457
Andrew Trick263280242012-11-12 19:52:20 +00001458//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001459// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001460//===----------------------------------------------------------------------===//
1461
Andrew Tricka7714a02012-11-12 19:40:10 +00001462namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001463
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001464/// Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001465/// loads or between neighboring stores.
1466class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1467 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001468 SUnit *SU;
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00001469 const MachineOperand *BaseOp;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001470 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001471
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00001472 MemOpInfo(SUnit *su, const MachineOperand *Op, int64_t ofs)
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00001473 : SU(su), BaseOp(Op), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001474
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00001475 bool operator<(const MemOpInfo &RHS) const {
Francis Visoiu Mistrih879087c2018-11-28 12:00:28 +00001476 if (BaseOp->getType() != RHS.BaseOp->getType())
1477 return BaseOp->getType() < RHS.BaseOp->getType();
1478
1479 if (BaseOp->isReg())
1480 return std::make_tuple(BaseOp->getReg(), Offset, SU->NodeNum) <
1481 std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
1482 RHS.SU->NodeNum);
Francis Visoiu Mistrih0b8dd442018-11-29 20:03:19 +00001483 if (BaseOp->isFI()) {
1484 const MachineFunction &MF =
1485 *BaseOp->getParent()->getParent()->getParent();
1486 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1487 bool StackGrowsDown = TFI.getStackGrowthDirection() ==
1488 TargetFrameLowering::StackGrowsDown;
1489 // Can't use tuple comparison here since we might need to use a
1490 // different order when the stack grows down.
1491 if (BaseOp->getIndex() != RHS.BaseOp->getIndex())
1492 return StackGrowsDown ? BaseOp->getIndex() > RHS.BaseOp->getIndex()
1493 : BaseOp->getIndex() < RHS.BaseOp->getIndex();
1494
1495 if (Offset != RHS.Offset)
1496 return StackGrowsDown ? Offset > RHS.Offset : Offset < RHS.Offset;
1497
1498 return SU->NodeNum < RHS.SU->NodeNum;
1499 }
Francis Visoiu Mistrih879087c2018-11-28 12:00:28 +00001500
1501 llvm_unreachable("MemOpClusterMutation only supports register or frame "
1502 "index bases.");
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001503 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001504 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001505
1506 const TargetInstrInfo *TII;
1507 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001508 bool IsLoad;
1509
Andrew Tricka7714a02012-11-12 19:40:10 +00001510public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001511 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1512 const TargetRegisterInfo *tri, bool IsLoad)
1513 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001514
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001515 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001516
Andrew Tricka7714a02012-11-12 19:40:10 +00001517protected:
Clement Courbetb70355f2019-03-29 08:33:05 +00001518 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG);
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001519};
1520
1521class StoreClusterMutation : public BaseMemOpClusterMutation {
1522public:
1523 StoreClusterMutation(const TargetInstrInfo *tii,
1524 const TargetRegisterInfo *tri)
1525 : BaseMemOpClusterMutation(tii, tri, false) {}
1526};
1527
1528class LoadClusterMutation : public BaseMemOpClusterMutation {
1529public:
1530 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1531 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001532};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001533
1534} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001535
Tom Stellard68726a52016-08-19 19:59:18 +00001536namespace llvm {
1537
1538std::unique_ptr<ScheduleDAGMutation>
1539createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1540 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001541 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001542 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001543}
1544
1545std::unique_ptr<ScheduleDAGMutation>
1546createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1547 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001548 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001549 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001550}
1551
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001552} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001553
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001554void BaseMemOpClusterMutation::clusterNeighboringMemOps(
Clement Courbetb70355f2019-03-29 08:33:05 +00001555 ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001556 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001557 for (SUnit *SU : MemOps) {
Bjorn Pettersson238c9d6302019-04-19 09:08:38 +00001558 const MachineOperand *BaseOp;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001559 int64_t Offset;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00001560 if (TII->getMemOperandWithOffset(*SU->getInstr(), BaseOp, Offset, TRI))
1561 MemOpRecords.push_back(MemOpInfo(SU, BaseOp, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001562 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001563 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001564 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001565
Fangrui Song0cac7262018-09-27 02:13:45 +00001566 llvm::sort(MemOpRecords);
Andrew Tricka7714a02012-11-12 19:40:10 +00001567 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001568 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001569 SUnit *SUa = MemOpRecords[Idx].SU;
1570 SUnit *SUb = MemOpRecords[Idx+1].SU;
Francis Visoiu Mistrihd7eebd62018-11-28 12:00:20 +00001571 if (TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
1572 *MemOpRecords[Idx + 1].BaseOp,
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001573 ClusterLength) &&
1574 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001575 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1576 << SUb->NodeNum << ")\n");
Andrew Tricka7714a02012-11-12 19:40:10 +00001577 // Copy successor edges from SUa to SUb. Interleaving computation
1578 // dependent on SUa can prevent load combining due to register reuse.
1579 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1580 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001581 for (const SDep &Succ : SUa->Succs) {
1582 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001583 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001584 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum
1585 << ")\n");
Javed Absare3a0cc22017-06-21 09:10:10 +00001586 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001587 }
1588 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001589 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001590 ClusterLength = 1;
1591 }
1592}
1593
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001594/// Callback from DAG postProcessing to create cluster edges for loads.
Clement Courbetb70355f2019-03-29 08:33:05 +00001595void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001596 // Map DAG NodeNum to store chain ID.
1597 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001598 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001599 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001600 for (SUnit &SU : DAG->SUnits) {
1601 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1602 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001603 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001604
Andrew Tricka7714a02012-11-12 19:40:10 +00001605 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001606 for (const SDep &Pred : SU.Preds) {
1607 if (Pred.isCtrl()) {
1608 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001609 break;
1610 }
1611 }
1612 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001613 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001614 unsigned NumChains = StoreChainDependents.size();
1615 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1616 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1617 if (Result.second)
1618 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001619 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001620 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001621
Andrew Tricka7714a02012-11-12 19:40:10 +00001622 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001623 for (auto &SCD : StoreChainDependents)
1624 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001625}
1626
Andrew Trick02a80da2012-03-08 01:41:12 +00001627//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001628// CopyConstrain - DAG post-processing to encourage copy elimination.
1629//===----------------------------------------------------------------------===//
1630
1631namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001632
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001633/// Post-process the DAG to create weak edges from all uses of a copy to
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001634/// the one use that defines the copy's source vreg, most likely an induction
1635/// variable increment.
1636class CopyConstrain : public ScheduleDAGMutation {
1637 // Transient state.
1638 SlotIndex RegionBeginIdx;
Eugene Zelenko32a40562017-09-11 23:00:48 +00001639
Andrew Trick2e875172013-04-24 23:19:56 +00001640 // RegionEndIdx is the slot index of the last non-debug instruction in the
1641 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001642 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001643
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001644public:
1645 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1646
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001647 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001648
1649protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001650 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001651};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001652
1653} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001654
Tom Stellard68726a52016-08-19 19:59:18 +00001655namespace llvm {
1656
1657std::unique_ptr<ScheduleDAGMutation>
1658createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001659 const TargetRegisterInfo *TRI) {
1660 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001661}
1662
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001663} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001664
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001665/// constrainLocalCopy handles two possibilities:
1666/// 1) Local src:
1667/// I0: = dst
1668/// I1: src = ...
1669/// I2: = dst
1670/// I3: dst = src (copy)
1671/// (create pred->succ edges I0->I1, I2->I1)
1672///
1673/// 2) Local copy:
1674/// I0: dst = src (copy)
1675/// I1: = dst
1676/// I2: src = ...
1677/// I3: = dst
1678/// (create pred->succ edges I1->I2, I3->I2)
1679///
1680/// Although the MachineScheduler is currently constrained to single blocks,
1681/// this algorithm should handle extended blocks. An EBB is a set of
1682/// contiguously numbered blocks such that the previous block in the EBB is
1683/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001684void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001685 LiveIntervals *LIS = DAG->getLIS();
1686 MachineInstr *Copy = CopySU->getInstr();
1687
1688 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001689 const MachineOperand &SrcOp = Copy->getOperand(1);
1690 unsigned SrcReg = SrcOp.getReg();
1691 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001692 return;
1693
Matthias Braun7511abd2016-04-04 21:23:46 +00001694 const MachineOperand &DstOp = Copy->getOperand(0);
1695 unsigned DstReg = DstOp.getReg();
1696 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001697 return;
1698
1699 // Check if either the dest or source is local. If it's live across a back
1700 // edge, it's not local. Note that if both vregs are live across the back
1701 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001702 // If both the copy's source and dest are local live intervals, then we
1703 // should treat the dest as the global for the purpose of adding
1704 // constraints. This adds edges from source's other uses to the copy.
1705 unsigned LocalReg = SrcReg;
1706 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001707 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1708 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001709 LocalReg = DstReg;
1710 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001711 LocalLI = &LIS->getInterval(LocalReg);
1712 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1713 return;
1714 }
1715 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1716
1717 // Find the global segment after the start of the local LI.
1718 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1719 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1720 // local live range. We could create edges from other global uses to the local
1721 // start, but the coalescer should have already eliminated these cases, so
1722 // don't bother dealing with it.
1723 if (GlobalSegment == GlobalLI->end())
1724 return;
1725
1726 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1727 // returned the next global segment. But if GlobalSegment overlaps with
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001728 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001729 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1730 if (GlobalSegment->contains(LocalLI->beginIndex()))
1731 ++GlobalSegment;
1732
1733 if (GlobalSegment == GlobalLI->end())
1734 return;
1735
1736 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1737 if (GlobalSegment != GlobalLI->begin()) {
1738 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001739 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001740 GlobalSegment->start)) {
1741 return;
1742 }
Andrew Trickd9761772013-07-30 19:59:08 +00001743 // If the prior global segment may be defined by the same two-address
1744 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001745 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001746 LocalLI->beginIndex())) {
1747 return;
1748 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001749 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1750 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001751 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001752 "Disconnected LRG within the scheduling region.");
1753 }
1754 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1755 if (!GlobalDef)
1756 return;
1757
1758 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1759 if (!GlobalSU)
1760 return;
1761
1762 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1763 // constraining the uses of the last local def to precede GlobalDef.
1764 SmallVector<SUnit*,8> LocalUses;
1765 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1766 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1767 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001768 for (const SDep &Succ : LastLocalSU->Succs) {
1769 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001770 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001771 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001772 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001773 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001774 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001775 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001776 }
1777 // Open the top of the GlobalLI hole by constraining any earlier global uses
1778 // to precede the start of LocalLI.
1779 SmallVector<SUnit*,8> GlobalUses;
1780 MachineInstr *FirstLocalDef =
1781 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1782 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001783 for (const SDep &Pred : GlobalSU->Preds) {
1784 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001785 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001786 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001787 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001788 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001789 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001790 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001791 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001792 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001793 // Add the weak edges.
1794 for (SmallVectorImpl<SUnit*>::const_iterator
1795 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001796 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1797 << GlobalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001798 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1799 }
1800 for (SmallVectorImpl<SUnit*>::const_iterator
1801 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001802 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1803 << FirstLocalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001804 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1805 }
1806}
1807
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001808/// Callback from DAG postProcessing to create weak edges to encourage
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001809/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001810void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1811 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001812 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1813
Andrew Trick2e875172013-04-24 23:19:56 +00001814 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1815 if (FirstPos == DAG->end())
1816 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001817 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001818 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001819 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001820
Javed Absare3a0cc22017-06-21 09:10:10 +00001821 for (SUnit &SU : DAG->SUnits) {
1822 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001823 continue;
1824
Javed Absare3a0cc22017-06-21 09:10:10 +00001825 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001826 }
1827}
1828
1829//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001830// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1831// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001832//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001833
Andrew Trick5a22df42013-12-05 17:56:02 +00001834static const unsigned InvalidCycle = ~0U;
1835
Andrew Trickfc127d12013-12-07 05:59:44 +00001836SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001837
Jonas Paulsson238c14b2017-10-25 08:23:33 +00001838/// Given a Count of resource usage and a Latency value, return true if a
1839/// SchedBoundary becomes resource limited.
1840static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1841 unsigned Latency) {
1842 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1843}
1844
Andrew Trickfc127d12013-12-07 05:59:44 +00001845void SchedBoundary::reset() {
1846 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1847 // Destroying and reconstructing it is very expensive though. So keep
1848 // invalid, placeholder HazardRecs.
1849 if (HazardRec && HazardRec->isEnabled()) {
1850 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001851 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001852 }
1853 Available.clear();
1854 Pending.clear();
1855 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001856 CurrCycle = 0;
1857 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001858 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001859 ExpectedLatency = 0;
1860 DependentLatency = 0;
1861 RetiredMOps = 0;
1862 MaxExecutedResCount = 0;
1863 ZoneCritResIdx = 0;
1864 IsResourceLimited = false;
1865 ReservedCycles.clear();
Momchil Velikovc396f092019-05-10 16:54:32 +00001866 ReservedCyclesIndex.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001867#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001868 // Track the maximum number of stall cycles that could arise either from the
1869 // latency of a DAG edge or the number of cycles that a processor resource is
1870 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001871 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001872#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001873 // Reserve a zero-count for invalid CritResIdx.
1874 ExecutedResCounts.resize(1);
1875 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1876}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001877
Andrew Trickfc127d12013-12-07 05:59:44 +00001878void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001879init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1880 reset();
1881 if (!SchedModel->hasInstrSchedModel())
1882 return;
1883 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001884 for (SUnit &SU : DAG->SUnits) {
1885 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1886 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001887 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001888 for (TargetSchedModel::ProcResIter
1889 PI = SchedModel->getWriteProcResBegin(SC),
1890 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1891 unsigned PIdx = PI->ProcResourceIdx;
1892 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1893 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1894 }
1895 }
1896}
1897
Andrew Trickfc127d12013-12-07 05:59:44 +00001898void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001899init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1900 reset();
1901 DAG = dag;
1902 SchedModel = smodel;
1903 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001904 if (SchedModel->hasInstrSchedModel()) {
Momchil Velikovc396f092019-05-10 16:54:32 +00001905 unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
1906 ReservedCyclesIndex.resize(ResourceCount);
1907 ExecutedResCounts.resize(ResourceCount);
1908 unsigned NumUnits = 0;
1909
1910 for (unsigned i = 0; i < ResourceCount; ++i) {
1911 ReservedCyclesIndex[i] = NumUnits;
1912 NumUnits += SchedModel->getProcResource(i)->NumUnits;
1913 }
1914
1915 ReservedCycles.resize(NumUnits, InvalidCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00001916 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001917}
1918
Andrew Trick880e5732013-12-05 17:55:58 +00001919/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1920/// these "soft stalls" differently than the hard stall cycles based on CPU
1921/// resources and computed by checkHazard(). A fully in-order model
1922/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1923/// available for scheduling until they are ready. However, a weaker in-order
1924/// model may use this for heuristics. For example, if a processor has in-order
1925/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001926unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001927 if (!SU->isUnbuffered)
1928 return 0;
1929
1930 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1931 if (ReadyCycle > CurrCycle)
1932 return ReadyCycle - CurrCycle;
1933 return 0;
1934}
1935
Momchil Velikovc396f092019-05-10 16:54:32 +00001936/// Compute the next cycle at which the given processor resource unit
1937/// can be scheduled.
1938unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx,
1939 unsigned Cycles) {
1940 unsigned NextUnreserved = ReservedCycles[InstanceIdx];
Andrew Trick5a22df42013-12-05 17:56:02 +00001941 // If this resource has never been used, always return cycle zero.
1942 if (NextUnreserved == InvalidCycle)
1943 return 0;
1944 // For bottom-up scheduling add the cycles needed for the current operation.
1945 if (!isTop())
1946 NextUnreserved += Cycles;
1947 return NextUnreserved;
1948}
1949
Momchil Velikovc396f092019-05-10 16:54:32 +00001950/// Compute the next cycle at which the given processor resource can be
1951/// scheduled. Returns the next cycle and the index of the processor resource
1952/// instance in the reserved cycles vector.
1953std::pair<unsigned, unsigned>
1954SchedBoundary::getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1955 unsigned MinNextUnreserved = InvalidCycle;
1956 unsigned InstanceIdx = 0;
1957 unsigned StartIndex = ReservedCyclesIndex[PIdx];
1958 unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
1959 assert(NumberOfInstances > 0 &&
1960 "Cannot have zero instances of a ProcResource");
1961
1962 for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End;
1963 ++I) {
1964 unsigned NextUnreserved = getNextResourceCycleByInstance(I, Cycles);
1965 if (MinNextUnreserved > NextUnreserved) {
1966 InstanceIdx = I;
1967 MinNextUnreserved = NextUnreserved;
1968 }
1969 }
1970 return std::make_pair(MinNextUnreserved, InstanceIdx);
1971}
1972
Andrew Trick8c9e6722012-06-29 03:23:24 +00001973/// Does this SU have a hazard within the current instruction group.
1974///
1975/// The scheduler supports two modes of hazard recognition. The first is the
1976/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1977/// supports highly complicated in-order reservation tables
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001978/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
Andrew Trick8c9e6722012-06-29 03:23:24 +00001979///
1980/// The second is a streamlined mechanism that checks for hazards based on
1981/// simple counters that the scheduler itself maintains. It explicitly checks
1982/// for instruction dispatch limitations, including the number of micro-ops that
1983/// can dispatch per cycle.
1984///
1985/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001986bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001987 if (HazardRec->isEnabled()
1988 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1989 return true;
1990 }
Javed Absar3d594372017-03-27 20:46:37 +00001991
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001992 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001993 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001994 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1995 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001996 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001997 }
Javed Absar3d594372017-03-27 20:46:37 +00001998
1999 if (CurrMOps > 0 &&
2000 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
2001 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002002 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
2003 << (isTop() ? "begin" : "end") << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00002004 return true;
2005 }
2006
Andrew Trick5a22df42013-12-05 17:56:02 +00002007 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
2008 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absare485b142017-10-03 09:35:04 +00002009 for (const MCWriteProcResEntry &PE :
2010 make_range(SchedModel->getWriteProcResBegin(SC),
2011 SchedModel->getWriteProcResEnd(SC))) {
2012 unsigned ResIdx = PE.ProcResourceIdx;
2013 unsigned Cycles = PE.Cycles;
Momchil Velikovc396f092019-05-10 16:54:32 +00002014 unsigned NRCycle, InstanceIdx;
2015 std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles);
Andrew Trick56327222014-06-27 04:57:05 +00002016 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00002017#ifndef NDEBUG
Javed Absare485b142017-10-03 09:35:04 +00002018 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00002019#endif
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002020 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
Momchil Velikovc396f092019-05-10 16:54:32 +00002021 << SchedModel->getResourceName(ResIdx)
2022 << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx] << ']'
2023 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00002024 return true;
Andrew Trick56327222014-06-27 04:57:05 +00002025 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002026 }
2027 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00002028 return false;
2029}
2030
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002031// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00002032unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002033findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00002034 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002035 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00002036 for (SUnit *SU : ReadySUs) {
2037 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002038 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002039 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00002040 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002041 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002042 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002043 if (LateSU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002044 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2045 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002046 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002047 return RemLatency;
2048}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002049
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002050// Count resources in this zone and the remaining unscheduled
2051// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2052// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00002053unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002054getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00002055 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002056 if (!SchedModel->hasInstrSchedModel())
2057 return 0;
2058
2059 unsigned OtherCritCount = Rem->RemIssueCount
2060 + (RetiredMOps * SchedModel->getMicroOpFactor());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002061 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2062 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002063 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2064 PIdx != PEnd; ++PIdx) {
2065 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2066 if (OtherCount > OtherCritCount) {
2067 OtherCritCount = OtherCount;
2068 OtherCritIdx = PIdx;
2069 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002070 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002071 if (OtherCritIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002072 LLVM_DEBUG(
2073 dbgs() << " " << Available.getName() << " + Remain CritRes: "
2074 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2075 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002076 }
2077 return OtherCritCount;
2078}
2079
Andrew Trickfc127d12013-12-07 05:59:44 +00002080void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002081 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2082
2083#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002084 // ReadyCycle was been bumped up to the CurrCycle when this node was
2085 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2086 // scheduling, so may now be greater than ReadyCycle.
2087 if (ReadyCycle > CurrCycle)
2088 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002089#endif
2090
Andrew Trick61f1a272012-05-24 22:11:09 +00002091 if (ReadyCycle < MinReadyCycle)
2092 MinReadyCycle = ReadyCycle;
2093
2094 // Check for interlocks first. For the purpose of other heuristics, an
2095 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002096 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002097 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2098 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002099 Pending.push(SU);
2100 else
2101 Available.push(SU);
2102}
2103
2104/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002105void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002106 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002107 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2108 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002109 if (MinReadyCycle > NextCycle)
2110 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002111 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002112 // Update the current micro-ops, which will issue in the next cycle.
2113 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2114 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2115
2116 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002117 if ((NextCycle - CurrCycle) > DependentLatency)
2118 DependentLatency = 0;
2119 else
2120 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002121
2122 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002123 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002124 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002125 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002126 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002127 for (; CurrCycle != NextCycle; ++CurrCycle) {
2128 if (isTop())
2129 HazardRec->AdvanceCycle();
2130 else
2131 HazardRec->RecedeCycle();
2132 }
2133 }
2134 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002135 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002136 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2137 getScheduledLatency());
Andrew Trick61f1a272012-05-24 22:11:09 +00002138
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002139 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
2140 << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002141}
2142
Andrew Trickfc127d12013-12-07 05:59:44 +00002143void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002144 ExecutedResCounts[PIdx] += Count;
2145 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2146 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002147}
2148
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002149/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002150///
2151/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2152/// during which this resource is consumed.
2153///
2154/// \return the next cycle at which the instruction may execute without
2155/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002156unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002157countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002158 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002159 unsigned Count = Factor * Cycles;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002160 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
2161 << Cycles << "x" << Factor << "u\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002162
2163 // Update Executed resources counts.
2164 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002165 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2166 Rem->RemainingCounts[PIdx] -= Count;
2167
Andrew Trickb13ef172013-07-19 00:20:07 +00002168 // Check if this resource exceeds the current critical resource. If so, it
2169 // becomes the critical resource.
2170 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002171 ZoneCritResIdx = PIdx;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002172 LLVM_DEBUG(dbgs() << " *** Critical resource "
2173 << SchedModel->getResourceName(PIdx) << ": "
2174 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2175 << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002176 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002177 // For reserved resources, record the highest cycle using the resource.
Momchil Velikovc396f092019-05-10 16:54:32 +00002178 unsigned NextAvailable, InstanceIdx;
2179 std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles);
Andrew Trick5a22df42013-12-05 17:56:02 +00002180 if (NextAvailable > CurrCycle) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002181 LLVM_DEBUG(dbgs() << " Resource conflict: "
Momchil Velikovc396f092019-05-10 16:54:32 +00002182 << SchedModel->getResourceName(PIdx)
2183 << '[' << InstanceIdx - ReservedCyclesIndex[PIdx] << ']'
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002184 << " reserved until @" << NextAvailable << "\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00002185 }
2186 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002187}
2188
Andrew Trick45446062012-06-05 21:11:27 +00002189/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002190void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002191 // Update the reservation table.
2192 if (HazardRec->isEnabled()) {
2193 if (!isTop() && SU->isCall) {
2194 // Calls are scheduled with their preceding instructions. For bottom-up
2195 // scheduling, clear the pipeline state before emitting.
2196 HazardRec->Reset();
2197 }
2198 HazardRec->EmitInstruction(SU);
James Molloy9ad4cb32019-04-19 09:00:55 +00002199 // Scheduling an instruction may have made pending instructions available.
2200 CheckPending = true;
Andrew Trick45446062012-06-05 21:11:27 +00002201 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002202 // checkHazard should prevent scheduling multiple instructions per cycle that
2203 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002204 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2205 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002206 assert(
2207 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002208 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002209
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002210 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002211 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002212
Andrew Trick5a22df42013-12-05 17:56:02 +00002213 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002214 switch (SchedModel->getMicroOpBufferSize()) {
2215 case 0:
2216 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2217 break;
2218 case 1:
2219 if (ReadyCycle > NextCycle) {
2220 NextCycle = ReadyCycle;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002221 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002222 }
2223 break;
2224 default:
2225 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002226 // scheduled MOps to be "retired". We do loosely model in-order resource
2227 // latency. If this instruction uses an in-order resource, account for any
2228 // likely stall cycles.
2229 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2230 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002231 break;
2232 }
2233 RetiredMOps += IncMOps;
2234
2235 // Update resource counts and critical resource.
2236 if (SchedModel->hasInstrSchedModel()) {
2237 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2238 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2239 Rem->RemIssueCount -= DecRemIssue;
2240 if (ZoneCritResIdx) {
2241 // Scale scheduled micro-ops for comparing with the critical resource.
2242 unsigned ScaledMOps =
2243 RetiredMOps * SchedModel->getMicroOpFactor();
2244
2245 // If scaled micro-ops are now more than the previous critical resource by
2246 // a full cycle, then micro-ops issue becomes critical.
2247 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2248 >= (int)SchedModel->getLatencyFactor()) {
2249 ZoneCritResIdx = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002250 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2251 << ScaledMOps / SchedModel->getLatencyFactor()
2252 << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002253 }
2254 }
2255 for (TargetSchedModel::ProcResIter
2256 PI = SchedModel->getWriteProcResBegin(SC),
2257 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2258 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002259 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002260 if (RCycle > NextCycle)
2261 NextCycle = RCycle;
2262 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002263 if (SU->hasReservedResource) {
2264 // For reserved resources, record the highest cycle using the resource.
2265 // For top-down scheduling, this is the cycle in which we schedule this
2266 // instruction plus the number of cycles the operations reserves the
2267 // resource. For bottom-up is it simply the instruction's cycle.
2268 for (TargetSchedModel::ProcResIter
2269 PI = SchedModel->getWriteProcResBegin(SC),
2270 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2271 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002272 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Momchil Velikovc396f092019-05-10 16:54:32 +00002273 unsigned ReservedUntil, InstanceIdx;
2274 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0);
Chad Rosieraba845e2014-07-02 16:46:08 +00002275 if (isTop()) {
Momchil Velikovc396f092019-05-10 16:54:32 +00002276 ReservedCycles[InstanceIdx] =
2277 std::max(ReservedUntil, NextCycle + PI->Cycles);
2278 } else
2279 ReservedCycles[InstanceIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002280 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002281 }
2282 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002283 }
2284 // Update ExpectedLatency and DependentLatency.
2285 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2286 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2287 if (SU->getDepth() > TopLatency) {
2288 TopLatency = SU->getDepth();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002289 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU("
2290 << SU->NodeNum << ") " << TopLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002291 }
2292 if (SU->getHeight() > BotLatency) {
2293 BotLatency = SU->getHeight();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002294 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU("
2295 << SU->NodeNum << ") " << BotLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002296 }
2297 // If we stall for any reason, bump the cycle.
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002298 if (NextCycle > CurrCycle)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002299 bumpCycle(NextCycle);
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002300 else
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002301 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002302 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002303 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002304 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2305 getScheduledLatency());
2306
Andrew Trick5a22df42013-12-05 17:56:02 +00002307 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2308 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2309 // one cycle. Since we commonly reach the max MOps here, opportunistically
2310 // bump the cycle to avoid uselessly checking everything in the readyQ.
2311 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002312
2313 // Bump the cycle count for issue group constraints.
2314 // This must be done after NextCycle has been adjust for all other stalls.
2315 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2316 // currCycle to X.
2317 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2318 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002319 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
2320 << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00002321 bumpCycle(++NextCycle);
2322 }
2323
Andrew Trick5a22df42013-12-05 17:56:02 +00002324 while (CurrMOps >= SchedModel->getIssueWidth()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002325 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
2326 << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002327 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002328 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002329 LLVM_DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002330}
2331
Andrew Trick61f1a272012-05-24 22:11:09 +00002332/// Release pending ready nodes in to the available queue. This makes them
2333/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002334void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002335 // If the available queue is empty, it is safe to reset MinReadyCycle.
2336 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002337 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002338
2339 // Check to see if any of the pending instructions are ready to issue. If
2340 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002341 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002342 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2343 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002344 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002345
2346 if (ReadyCycle < MinReadyCycle)
2347 MinReadyCycle = ReadyCycle;
2348
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002349 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002350 continue;
2351
Andrew Trick8c9e6722012-06-29 03:23:24 +00002352 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002353 continue;
2354
Matthias Braun6493bc22016-04-22 19:09:17 +00002355 if (Available.size() >= ReadyListLimit)
2356 break;
2357
Andrew Trick61f1a272012-05-24 22:11:09 +00002358 Available.push(SU);
2359 Pending.remove(Pending.begin()+i);
2360 --i; --e;
2361 }
2362 CheckPending = false;
2363}
2364
2365/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002366void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002367 if (Available.isInQueue(SU))
2368 Available.remove(Available.find(SU));
2369 else {
2370 assert(Pending.isInQueue(SU) && "bad ready count");
2371 Pending.remove(Pending.find(SU));
2372 }
2373}
2374
2375/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002376/// defer any nodes that now hit a hazard, and advance the cycle until at least
2377/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002378SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002379 if (CheckPending)
2380 releasePending();
2381
Andrew Tricke2ff5752013-06-15 04:49:49 +00002382 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002383 // Defer any ready instrs that now have a hazard.
2384 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2385 if (checkHazard(*I)) {
2386 Pending.push(*I);
2387 I = Available.remove(I);
2388 continue;
2389 }
2390 ++I;
2391 }
2392 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002393 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002394// FIXME: Re-enable assert once PR20057 is resolved.
2395// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2396// "permanent hazard");
2397 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002398 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002399 releasePending();
2400 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002401
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002402 LLVM_DEBUG(Pending.dump());
2403 LLVM_DEBUG(Available.dump());
Matthias Braund29d31e2016-06-23 21:27:38 +00002404
Andrew Trick61f1a272012-05-24 22:11:09 +00002405 if (Available.size() == 1)
2406 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002407 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002408}
2409
Aaron Ballman615eb472017-10-15 14:32:27 +00002410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002411// This is useful information to dump after bumpNode.
2412// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002413LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002414 unsigned ResFactor;
2415 unsigned ResCount;
2416 if (ZoneCritResIdx) {
2417 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2418 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002419 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002420 ResFactor = SchedModel->getMicroOpFactor();
Javed Absar1a77bcc2017-09-27 10:31:58 +00002421 ResCount = RetiredMOps * ResFactor;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002422 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002423 unsigned LFactor = SchedModel->getLatencyFactor();
2424 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2425 << " Retired: " << RetiredMOps;
2426 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2427 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002428 << ResCount / ResFactor << " "
2429 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002430 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2431 << (IsResourceLimited ? " - Resource" : " - Latency")
2432 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002433}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002434#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002435
Andrew Trickfc127d12013-12-07 05:59:44 +00002436//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002437// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002438//===----------------------------------------------------------------------===//
2439
Andrew Trickd14d7c22013-12-28 21:56:57 +00002440void GenericSchedulerBase::SchedCandidate::
2441initResourceDelta(const ScheduleDAGMI *DAG,
2442 const TargetSchedModel *SchedModel) {
2443 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2444 return;
2445
2446 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2447 for (TargetSchedModel::ProcResIter
2448 PI = SchedModel->getWriteProcResBegin(SC),
2449 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2450 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2451 ResDelta.CritResources += PI->Cycles;
2452 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2453 ResDelta.DemandedResources += PI->Cycles;
2454 }
2455}
2456
Tom Stellardecd6aa52018-08-21 21:48:43 +00002457/// Compute remaining latency. We need this both to determine whether the
2458/// overall schedule has become latency-limited and whether the instructions
2459/// outside this zone are resource or latency limited.
2460///
2461/// The "dependent" latency is updated incrementally during scheduling as the
2462/// max height/depth of scheduled nodes minus the cycles since it was
2463/// scheduled:
2464/// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2465///
2466/// The "independent" latency is the max ready queue depth:
2467/// ILat = max N.depth for N in Available|Pending
2468///
2469/// RemainingLatency is the greater of independent and dependent latency.
2470///
2471/// These computations are expensive, especially in DAGs with many edges, so
2472/// only do them if necessary.
2473static unsigned computeRemLatency(SchedBoundary &CurrZone) {
2474 unsigned RemLatency = CurrZone.getDependentLatency();
2475 RemLatency = std::max(RemLatency,
2476 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2477 RemLatency = std::max(RemLatency,
2478 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2479 return RemLatency;
2480}
2481
2482/// Returns true if the current cycle plus remaning latency is greater than
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002483/// the critical path in the scheduling region.
Tom Stellardecd6aa52018-08-21 21:48:43 +00002484bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
2485 SchedBoundary &CurrZone,
2486 bool ComputeRemLatency,
2487 unsigned &RemLatency) const {
2488 // The current cycle is already greater than the critical path, so we are
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +00002489 // already latency limited and don't need to compute the remaining latency.
Tom Stellardecd6aa52018-08-21 21:48:43 +00002490 if (CurrZone.getCurrCycle() > Rem.CriticalPath)
2491 return true;
2492
2493 // If we haven't scheduled anything yet, then we aren't latency limited.
2494 if (CurrZone.getCurrCycle() == 0)
2495 return false;
2496
2497 if (ComputeRemLatency)
2498 RemLatency = computeRemLatency(CurrZone);
2499
2500 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
2501}
2502
Andrew Trickd14d7c22013-12-28 21:56:57 +00002503/// Set the CandPolicy given a scheduling zone given the current resources and
2504/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002505void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002506 SchedBoundary &CurrZone,
2507 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002508 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002509 // inside and outside this zone. Potential stalls should be considered before
2510 // following this policy.
2511
Andrew Trickd14d7c22013-12-28 21:56:57 +00002512 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002513 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002514 unsigned OtherCount =
2515 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2516
2517 bool OtherResLimited = false;
Tom Stellardecd6aa52018-08-21 21:48:43 +00002518 unsigned RemLatency = 0;
2519 bool RemLatencyComputed = false;
2520 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
2521 RemLatency = computeRemLatency(CurrZone);
2522 RemLatencyComputed = true;
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002523 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2524 OtherCount, RemLatency);
Tom Stellardecd6aa52018-08-21 21:48:43 +00002525 }
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002526
Andrew Trickd14d7c22013-12-28 21:56:57 +00002527 // Schedule aggressively for latency in PostRA mode. We don't check for
2528 // acyclic latency during PostRA, and highly out-of-order processors will
2529 // skip PostRA scheduling.
Tom Stellardecd6aa52018-08-21 21:48:43 +00002530 if (!OtherResLimited &&
2531 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2532 RemLatency))) {
2533 Policy.ReduceLatency |= true;
2534 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
2535 << " RemainingLatency " << RemLatency << " + "
2536 << CurrZone.getCurrCycle() << "c > CritPath "
2537 << Rem.CriticalPath << "\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002538 }
2539 // If the same resource is limiting inside and outside the zone, do nothing.
2540 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2541 return;
2542
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002543 LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
2544 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2545 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
2546 } if (OtherResLimited) dbgs()
2547 << " RemainingLimit: "
2548 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2549 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
2550 << " Latency limited both directions.\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002551
2552 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2553 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2554
2555 if (OtherResLimited)
2556 Policy.DemandResIdx = OtherCritIdx;
2557}
2558
2559#ifndef NDEBUG
2560const char *GenericSchedulerBase::getReasonStr(
2561 GenericSchedulerBase::CandReason Reason) {
2562 switch (Reason) {
2563 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002564 case Only1: return "ONLY1 ";
Nirav Dave1241dcb2018-11-14 21:11:53 +00002565 case PhysReg: return "PHYS-REG ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002566 case RegExcess: return "REG-EXCESS";
2567 case RegCritical: return "REG-CRIT ";
2568 case Stall: return "STALL ";
2569 case Cluster: return "CLUSTER ";
2570 case Weak: return "WEAK ";
2571 case RegMax: return "REG-MAX ";
2572 case ResourceReduce: return "RES-REDUCE";
2573 case ResourceDemand: return "RES-DEMAND";
2574 case TopDepthReduce: return "TOP-DEPTH ";
2575 case TopPathReduce: return "TOP-PATH ";
2576 case BotHeightReduce:return "BOT-HEIGHT";
2577 case BotPathReduce: return "BOT-PATH ";
2578 case NextDefUse: return "DEF-USE ";
2579 case NodeOrder: return "ORDER ";
2580 };
2581 llvm_unreachable("Unknown reason!");
2582}
2583
2584void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2585 PressureChange P;
2586 unsigned ResIdx = 0;
2587 unsigned Latency = 0;
2588 switch (Cand.Reason) {
2589 default:
2590 break;
2591 case RegExcess:
2592 P = Cand.RPDelta.Excess;
2593 break;
2594 case RegCritical:
2595 P = Cand.RPDelta.CriticalMax;
2596 break;
2597 case RegMax:
2598 P = Cand.RPDelta.CurrentMax;
2599 break;
2600 case ResourceReduce:
2601 ResIdx = Cand.Policy.ReduceResIdx;
2602 break;
2603 case ResourceDemand:
2604 ResIdx = Cand.Policy.DemandResIdx;
2605 break;
2606 case TopDepthReduce:
2607 Latency = Cand.SU->getDepth();
2608 break;
2609 case TopPathReduce:
2610 Latency = Cand.SU->getHeight();
2611 break;
2612 case BotHeightReduce:
2613 Latency = Cand.SU->getHeight();
2614 break;
2615 case BotPathReduce:
2616 Latency = Cand.SU->getDepth();
2617 break;
2618 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002619 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002620 if (P.isValid())
2621 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2622 << ":" << P.getUnitInc() << " ";
2623 else
2624 dbgs() << " ";
2625 if (ResIdx)
2626 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2627 else
2628 dbgs() << " ";
2629 if (Latency)
2630 dbgs() << " " << Latency << " cycles ";
2631 else
2632 dbgs() << " ";
2633 dbgs() << '\n';
2634}
2635#endif
2636
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002637namespace llvm {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002638/// Return true if this heuristic determines order.
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002639bool tryLess(int TryVal, int CandVal,
2640 GenericSchedulerBase::SchedCandidate &TryCand,
2641 GenericSchedulerBase::SchedCandidate &Cand,
2642 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002643 if (TryVal < CandVal) {
2644 TryCand.Reason = Reason;
2645 return true;
2646 }
2647 if (TryVal > CandVal) {
2648 if (Cand.Reason > Reason)
2649 Cand.Reason = Reason;
2650 return true;
2651 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002652 return false;
2653}
2654
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002655bool tryGreater(int TryVal, int CandVal,
2656 GenericSchedulerBase::SchedCandidate &TryCand,
2657 GenericSchedulerBase::SchedCandidate &Cand,
2658 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002659 if (TryVal > CandVal) {
2660 TryCand.Reason = Reason;
2661 return true;
2662 }
2663 if (TryVal < CandVal) {
2664 if (Cand.Reason > Reason)
2665 Cand.Reason = Reason;
2666 return true;
2667 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002668 return false;
2669}
2670
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002671bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2672 GenericSchedulerBase::SchedCandidate &Cand,
2673 SchedBoundary &Zone) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002674 if (Zone.isTop()) {
2675 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2676 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2677 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2678 return true;
2679 }
2680 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2681 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2682 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002683 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002684 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2685 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2686 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2687 return true;
2688 }
2689 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2690 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2691 return true;
2692 }
2693 return false;
2694}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002695} // end namespace llvm
Andrew Trickd14d7c22013-12-28 21:56:57 +00002696
Matthias Braun49cb6e92016-05-27 22:14:26 +00002697static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002698 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2699 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
Matthias Braun49cb6e92016-05-27 22:14:26 +00002700}
2701
Matthias Braun6ad3d052016-06-25 00:23:00 +00002702static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2703 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002704}
2705
Andrew Trickfc127d12013-12-07 05:59:44 +00002706void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002707 assert(dag->hasVRegLiveness() &&
2708 "(PreRA)GenericScheduler needs vreg liveness");
2709 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002710 SchedModel = DAG->getSchedModel();
2711 TRI = DAG->TRI;
2712
2713 Rem.init(DAG, SchedModel);
2714 Top.init(DAG, SchedModel, &Rem);
2715 Bot.init(DAG, SchedModel, &Rem);
2716
2717 // Initialize resource counts.
2718
2719 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2720 // are disabled, then these HazardRecs will be disabled.
2721 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002722 if (!Top.HazardRec) {
2723 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002724 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002725 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002726 }
2727 if (!Bot.HazardRec) {
2728 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002729 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002730 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002731 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002732 TopCand.SU = nullptr;
2733 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002734}
2735
2736/// Initialize the per-region scheduling policy.
2737void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2738 MachineBasicBlock::iterator End,
2739 unsigned NumRegionInstrs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002740 const MachineFunction &MF = *Begin->getMF();
Eric Christopher99556d72014-10-14 06:56:25 +00002741 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002742
2743 // Avoid setting up the register pressure tracker for small regions to save
2744 // compile time. As a rough heuristic, only track pressure when the number of
2745 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002746 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002747 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2748 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2749 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002750 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002751 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002752 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2753 }
2754 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002755
2756 // For generic targets, we default to bottom-up, because it's simpler and more
2757 // compile-time optimizations have been implemented in that direction.
2758 RegionPolicy.OnlyBottomUp = true;
2759
2760 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002761 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002762
2763 // After subtarget overrides, apply command line options.
2764 if (!EnableRegPressure)
2765 RegionPolicy.ShouldTrackPressure = false;
2766
2767 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2768 // e.g. -misched-bottomup=false allows scheduling in both directions.
2769 assert((!ForceTopDown || !ForceBottomUp) &&
2770 "-misched-topdown incompatible with -misched-bottomup");
2771 if (ForceBottomUp.getNumOccurrences() > 0) {
2772 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2773 if (RegionPolicy.OnlyBottomUp)
2774 RegionPolicy.OnlyTopDown = false;
2775 }
2776 if (ForceTopDown.getNumOccurrences() > 0) {
2777 RegionPolicy.OnlyTopDown = ForceTopDown;
2778 if (RegionPolicy.OnlyTopDown)
2779 RegionPolicy.OnlyBottomUp = false;
2780 }
2781}
2782
Sam Clegg705f7982017-06-21 22:19:17 +00002783void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002784 // Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002786 dbgs() << "GenericScheduler RegionPolicy: "
2787 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2788 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2789 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2790 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002791#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002792}
2793
Andrew Trickfc127d12013-12-07 05:59:44 +00002794/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2795/// critical path by more cycles than it takes to drain the instruction buffer.
2796/// We estimate an upper bounds on in-flight instructions as:
2797///
2798/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2799/// InFlightIterations = AcyclicPath / CyclesPerIteration
2800/// InFlightResources = InFlightIterations * LoopResources
2801///
2802/// TODO: Check execution resources in addition to IssueCount.
2803void GenericScheduler::checkAcyclicLatency() {
2804 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2805 return;
2806
2807 // Scaled number of cycles per loop iteration.
2808 unsigned IterCount =
2809 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2810 Rem.RemIssueCount);
2811 // Scaled acyclic critical path.
2812 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2813 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2814 unsigned InFlightCount =
2815 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2816 unsigned BufferLimit =
2817 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2818
2819 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2820
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002821 LLVM_DEBUG(
2822 dbgs() << "IssueCycles="
2823 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2824 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2825 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2826 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2827 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2828 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
Andrew Trickfc127d12013-12-07 05:59:44 +00002829}
2830
2831void GenericScheduler::registerRoots() {
2832 Rem.CriticalPath = DAG->ExitSU.getDepth();
2833
2834 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002835 for (const SUnit *SU : Bot.Available) {
2836 if (SU->getDepth() > Rem.CriticalPath)
2837 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002838 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002839 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002840 if (DumpCriticalPathLength) {
2841 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2842 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002843
Matthias Braun99551052017-04-12 18:09:05 +00002844 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002845 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2846 checkAcyclicLatency();
2847 }
2848}
2849
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002850namespace llvm {
2851bool tryPressure(const PressureChange &TryP,
2852 const PressureChange &CandP,
2853 GenericSchedulerBase::SchedCandidate &TryCand,
2854 GenericSchedulerBase::SchedCandidate &Cand,
2855 GenericSchedulerBase::CandReason Reason,
2856 const TargetRegisterInfo *TRI,
2857 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002858 // If one candidate decreases and the other increases, go with it.
2859 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002860 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2861 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002862 return true;
2863 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002864 // Do not compare the magnitude of pressure changes between top and bottom
2865 // boundary.
2866 if (Cand.AtTop != TryCand.AtTop)
2867 return false;
2868
2869 // If both candidates affect the same set in the same boundary, go with the
2870 // smallest increase.
2871 unsigned TryPSet = TryP.getPSetOrMax();
2872 unsigned CandPSet = CandP.getPSetOrMax();
2873 if (TryPSet == CandPSet) {
2874 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2875 Reason);
2876 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002877
2878 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2879 std::numeric_limits<int>::max();
2880
2881 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2882 std::numeric_limits<int>::max();
2883
Andrew Trick401b6952013-07-25 07:26:35 +00002884 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002885 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002886 std::swap(TryRank, CandRank);
2887 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2888}
2889
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002890unsigned getWeakLeft(const SUnit *SU, bool isTop) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002891 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2892}
2893
Andrew Tricke833e1c2013-04-13 06:07:40 +00002894/// Minimize physical register live ranges. Regalloc wants them adjacent to
2895/// their physreg def/use.
2896///
2897/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2898/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2899/// with the operation that produces or consumes the physreg. We'll do this when
2900/// regalloc has support for parallel copies.
Nirav Dave1241dcb2018-11-14 21:11:53 +00002901int biasPhysReg(const SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002902 const MachineInstr *MI = SU->getInstr();
Andrew Tricke833e1c2013-04-13 06:07:40 +00002903
Nirav Dave1241dcb2018-11-14 21:11:53 +00002904 if (MI->isCopy()) {
2905 unsigned ScheduledOper = isTop ? 1 : 0;
2906 unsigned UnscheduledOper = isTop ? 0 : 1;
2907 // If we have already scheduled the physreg produce/consumer, immediately
2908 // schedule the copy.
2909 if (TargetRegisterInfo::isPhysicalRegister(
2910 MI->getOperand(ScheduledOper).getReg()))
2911 return 1;
2912 // If the physreg is at the boundary, defer it. Otherwise schedule it
2913 // immediately to free the dependent. We can hoist the copy later.
2914 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2915 if (TargetRegisterInfo::isPhysicalRegister(
2916 MI->getOperand(UnscheduledOper).getReg()))
2917 return AtBoundary ? -1 : 1;
2918 }
2919
2920 if (MI->isMoveImmediate()) {
2921 // If we have a move immediate and all successors have been assigned, bias
2922 // towards scheduling this later. Make sure all register defs are to
2923 // physical registers.
2924 bool DoBias = true;
2925 for (const MachineOperand &Op : MI->defs()) {
2926 if (Op.isReg() && !TargetRegisterInfo::isPhysicalRegister(Op.getReg())) {
2927 DoBias = false;
2928 break;
2929 }
2930 }
2931
2932 if (DoBias)
2933 return isTop ? -1 : 1;
2934 }
2935
Andrew Tricke833e1c2013-04-13 06:07:40 +00002936 return 0;
2937}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002938} // end namespace llvm
Andrew Tricke833e1c2013-04-13 06:07:40 +00002939
Matthias Braun4f573772016-04-22 19:10:15 +00002940void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2941 bool AtTop,
2942 const RegPressureTracker &RPTracker,
2943 RegPressureTracker &TempTracker) {
2944 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002945 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002946 if (DAG->isTrackingPressure()) {
2947 if (AtTop) {
2948 TempTracker.getMaxDownwardPressureDelta(
2949 Cand.SU->getInstr(),
2950 Cand.RPDelta,
2951 DAG->getRegionCriticalPSets(),
2952 DAG->getRegPressure().MaxSetPressure);
2953 } else {
2954 if (VerifyScheduling) {
2955 TempTracker.getMaxUpwardPressureDelta(
2956 Cand.SU->getInstr(),
2957 &DAG->getPressureDiff(Cand.SU),
2958 Cand.RPDelta,
2959 DAG->getRegionCriticalPSets(),
2960 DAG->getRegPressure().MaxSetPressure);
2961 } else {
2962 RPTracker.getUpwardPressureDelta(
2963 Cand.SU->getInstr(),
2964 DAG->getPressureDiff(Cand.SU),
2965 Cand.RPDelta,
2966 DAG->getRegionCriticalPSets(),
2967 DAG->getRegPressure().MaxSetPressure);
2968 }
2969 }
2970 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002971 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
2972 << " Try SU(" << Cand.SU->NodeNum << ") "
2973 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
2974 << Cand.RPDelta.Excess.getUnitInc() << "\n");
Matthias Braun4f573772016-04-22 19:10:15 +00002975}
2976
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002977/// Apply a set of heuristics to a new candidate. Heuristics are currently
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002978/// hierarchical. This may be more efficient than a graduated cost model because
2979/// we don't need to evaluate all aspects of the model for each node in the
2980/// queue. But it's really done to make the heuristics easier to debug and
2981/// statistically analyze.
2982///
2983/// \param Cand provides the policy and current best candidate.
2984/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002985/// \param Zone describes the scheduled zone that we are extending, or nullptr
2986// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002987void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002988 SchedCandidate &TryCand,
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002989 SchedBoundary *Zone) const {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002990 // Initialize the candidate if needed.
2991 if (!Cand.isValid()) {
2992 TryCand.Reason = NodeOrder;
2993 return;
2994 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002995
Nirav Dave1241dcb2018-11-14 21:11:53 +00002996 // Bias PhysReg Defs and copies to their uses and defined respectively.
2997 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
2998 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
Andrew Tricke833e1c2013-04-13 06:07:40 +00002999 return;
3000
Andrew Tricke02d5da2015-05-17 23:40:27 +00003001 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00003002 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
3003 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00003004 TryCand, Cand, RegExcess, TRI,
3005 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003006 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003007
3008 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00003009 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
3010 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00003011 TryCand, Cand, RegCritical, TRI,
3012 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003013 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003014
Matthias Braun6ad3d052016-06-25 00:23:00 +00003015 // We only compare a subset of features when comparing nodes between
3016 // Top and Bottom boundary. Some properties are simply incomparable, in many
3017 // other instances we should only override the other boundary if something
3018 // is a clear good pick on one boundary. Skip heuristics that are more
3019 // "tie-breaking" in nature.
3020 bool SameBoundary = Zone != nullptr;
3021 if (SameBoundary) {
3022 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00003023 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
3024 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003025 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
3026 tryLatency(TryCand, Cand, *Zone))
3027 return;
Andrew Trickddffae92013-09-06 17:32:36 +00003028
Matthias Braun6ad3d052016-06-25 00:23:00 +00003029 // Prioritize instructions that read unbuffered resources by stall cycles.
3030 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
3031 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3032 return;
3033 }
Andrew Trick880e5732013-12-05 17:55:58 +00003034
Andrew Tricka7714a02012-11-12 19:40:10 +00003035 // Keep clustered nodes together to encourage downstream peephole
3036 // optimizations which may reduce resource requirements.
3037 //
3038 // This is a best effort to set things up for a post-RA pass. Optimizations
3039 // like generating loads of multiple registers should ideally be done within
3040 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003041 const SUnit *CandNextClusterSU =
3042 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
3043 const SUnit *TryCandNextClusterSU =
3044 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
3045 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
3046 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00003047 TryCand, Cand, Cluster))
3048 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003049
Matthias Braun6ad3d052016-06-25 00:23:00 +00003050 if (SameBoundary) {
3051 // Weak edges are for clustering and other constraints.
3052 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
3053 getWeakLeft(Cand.SU, Cand.AtTop),
3054 TryCand, Cand, Weak))
3055 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00003056 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00003057
Andrew Trick71f08a32013-06-17 21:45:13 +00003058 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00003059 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
3060 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00003061 TryCand, Cand, RegMax, TRI,
3062 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00003063 return;
3064
Matthias Braun6ad3d052016-06-25 00:23:00 +00003065 if (SameBoundary) {
3066 // Avoid critical resource consumption and balance the schedule.
3067 TryCand.initResourceDelta(DAG, SchedModel);
3068 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3069 TryCand, Cand, ResourceReduce))
3070 return;
3071 if (tryGreater(TryCand.ResDelta.DemandedResources,
3072 Cand.ResDelta.DemandedResources,
3073 TryCand, Cand, ResourceDemand))
3074 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003075
Matthias Braun6ad3d052016-06-25 00:23:00 +00003076 // Avoid serializing long latency dependence chains.
3077 // For acyclic path limited loops, latency was already checked above.
3078 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
3079 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
3080 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003081
Matthias Braun6ad3d052016-06-25 00:23:00 +00003082 // Fall through to original instruction order.
3083 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
3084 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
3085 TryCand.Reason = NodeOrder;
3086 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003087 }
3088}
Andrew Trick419eae22012-05-10 21:06:19 +00003089
Andrew Trickc573cd92013-09-06 17:32:44 +00003090/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00003091///
3092/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
3093/// DAG building. To adjust for the current scheduling location we need to
3094/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003095void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00003096 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00003097 const RegPressureTracker &RPTracker,
3098 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003099 // getMaxPressureDelta temporarily modifies the tracker.
3100 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3101
Matthias Braund29d31e2016-06-23 21:27:38 +00003102 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003103 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003104
Matthias Braun6ad3d052016-06-25 00:23:00 +00003105 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003106 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003107 // Pass SchedBoundary only when comparing nodes from the same boundary.
3108 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3109 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003110 if (TryCand.Reason != NoCand) {
3111 // Initialize resource delta if needed in case future heuristics query it.
3112 if (TryCand.ResDelta == SchedResourceDelta())
3113 TryCand.initResourceDelta(DAG, SchedModel);
3114 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003115 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00003116 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003117 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003118}
3119
Andrew Trick22025772012-05-17 18:35:10 +00003120/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003121SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00003122 // Schedule as far as possible in the direction of no choice. This is most
3123 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00003124 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003125 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003126 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003127 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003128 }
Andrew Trick61f1a272012-05-24 22:11:09 +00003129 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003130 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003131 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003132 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003133 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003134 // Set the bottom-up policy based on the state of the current bottom zone and
3135 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003136 CandPolicy BotPolicy;
3137 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003138 // Set the top-down policy based on the state of the current top zone and
3139 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003140 CandPolicy TopPolicy;
3141 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003142
Matthias Brauncc676c42016-06-25 02:03:36 +00003143 // See if BotCand is still valid (because we previously scheduled from Top).
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003144 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003145 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3146 BotCand.Policy != BotPolicy) {
3147 BotCand.reset(CandPolicy());
3148 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3149 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3150 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003151 LLVM_DEBUG(traceCandidate(BotCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003152#ifndef NDEBUG
3153 if (VerifyScheduling) {
3154 SchedCandidate TCand;
3155 TCand.reset(CandPolicy());
3156 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3157 assert(TCand.SU == BotCand.SU &&
3158 "Last pick result should correspond to re-picking right now");
3159 }
3160#endif
3161 }
Andrew Trick22025772012-05-17 18:35:10 +00003162
Andrew Trick22025772012-05-17 18:35:10 +00003163 // Check if the top Q has a better candidate.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003164 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003165 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3166 TopCand.Policy != TopPolicy) {
3167 TopCand.reset(CandPolicy());
3168 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3169 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3170 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003171 LLVM_DEBUG(traceCandidate(TopCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003172#ifndef NDEBUG
3173 if (VerifyScheduling) {
3174 SchedCandidate TCand;
3175 TCand.reset(CandPolicy());
3176 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3177 assert(TCand.SU == TopCand.SU &&
3178 "Last pick result should correspond to re-picking right now");
3179 }
3180#endif
3181 }
3182
3183 // Pick best from BotCand and TopCand.
3184 assert(BotCand.isValid());
3185 assert(TopCand.isValid());
3186 SchedCandidate Cand = BotCand;
3187 TopCand.Reason = NoCand;
3188 tryCandidate(Cand, TopCand, nullptr);
3189 if (TopCand.Reason != NoCand) {
3190 Cand.setBest(TopCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003191 LLVM_DEBUG(traceCandidate(Cand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003192 }
Andrew Trick22025772012-05-17 18:35:10 +00003193
Matthias Braun6ad3d052016-06-25 00:23:00 +00003194 IsTopNode = Cand.AtTop;
3195 tracePick(Cand);
3196 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003197}
3198
3199/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003200SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003201 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003202 assert(Top.Available.empty() && Top.Pending.empty() &&
3203 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003204 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003205 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003206 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003207 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003208 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003209 SU = Top.pickOnlyChoice();
3210 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003211 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003212 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003213 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003214 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003215 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003216 SU = TopCand.SU;
3217 }
3218 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003219 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003220 SU = Bot.pickOnlyChoice();
3221 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003222 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003223 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003224 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003225 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003226 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003227 SU = BotCand.SU;
3228 }
3229 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003230 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003231 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003232 }
3233 } while (SU->isScheduled);
3234
Andrew Trick61f1a272012-05-24 22:11:09 +00003235 if (SU->isTopReady())
3236 Top.removeReady(SU);
3237 if (SU->isBottomReady())
3238 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003239
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003240 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3241 << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003242 return SU;
3243}
3244
Nirav Dave1241dcb2018-11-14 21:11:53 +00003245void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003246 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3247 if (!isTop)
3248 ++InsertPos;
3249 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3250
3251 // Find already scheduled copies with a single physreg dependence and move
3252 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003253 for (SDep &Dep : Deps) {
3254 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003255 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003256 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003257 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3258 continue;
3259 MachineInstr *Copy = DepSU->getInstr();
Nirav Dave1241dcb2018-11-14 21:11:53 +00003260 if (!Copy->isCopy() && !Copy->isMoveImmediate())
Andrew Tricke833e1c2013-04-13 06:07:40 +00003261 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003262 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
Matthias Braun726e12c2018-09-19 00:23:35 +00003263 DAG->dumpNode(*Dep.getSUnit()));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003264 DAG->moveInstruction(Copy, InsertPos);
3265 }
3266}
3267
Andrew Trick61f1a272012-05-24 22:11:09 +00003268/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003269/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3270/// update it's state based on the current cycle before MachineSchedStrategy
3271/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003272///
3273/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
Nirav Dave1241dcb2018-11-14 21:11:53 +00003274/// them here. See comments in biasPhysReg.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003275void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003276 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003277 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003278 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003279 if (SU->hasPhysRegUses)
Nirav Dave1241dcb2018-11-14 21:11:53 +00003280 reschedulePhysReg(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003281 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003282 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003283 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003284 if (SU->hasPhysRegDefs)
Nirav Dave1241dcb2018-11-14 21:11:53 +00003285 reschedulePhysReg(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003286 }
3287}
3288
Andrew Trick8823dec2012-03-14 04:00:41 +00003289/// Create the standard converging machine scheduler. This will be used as the
3290/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003291ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003292 ScheduleDAGMILive *DAG =
3293 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003294 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003295 //
3296 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3297 // data and pass it to later mutations. Have a single mutation that gathers
3298 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003299 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003300 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003301}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003302
Matthias Braun115efcd2016-11-28 20:11:54 +00003303static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3304 return createGenericSchedLive(C);
3305}
3306
Andrew Tricke1c034f2012-01-17 06:55:03 +00003307static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003308GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003309 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003310
3311//===----------------------------------------------------------------------===//
3312// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3313//===----------------------------------------------------------------------===//
3314
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003315void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3316 DAG = Dag;
3317 SchedModel = DAG->getSchedModel();
3318 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003319
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003320 Rem.init(DAG, SchedModel);
3321 Top.init(DAG, SchedModel, &Rem);
3322 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003323
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003324 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3325 // or are disabled, then these HazardRecs will be disabled.
3326 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003327 if (!Top.HazardRec) {
3328 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003329 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003330 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003331 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003332}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003333
Andrew Trickd14d7c22013-12-28 21:56:57 +00003334void PostGenericScheduler::registerRoots() {
3335 Rem.CriticalPath = DAG->ExitSU.getDepth();
3336
3337 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003338 for (const SUnit *SU : BotRoots) {
3339 if (SU->getDepth() > Rem.CriticalPath)
3340 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003341 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003342 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003343 if (DumpCriticalPathLength) {
3344 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3345 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003346}
3347
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003348/// Apply a set of heuristics to a new candidate for PostRA scheduling.
Andrew Trickd14d7c22013-12-28 21:56:57 +00003349///
3350/// \param Cand provides the policy and current best candidate.
3351/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3352void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3353 SchedCandidate &TryCand) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003354 // Initialize the candidate if needed.
3355 if (!Cand.isValid()) {
3356 TryCand.Reason = NodeOrder;
3357 return;
3358 }
3359
3360 // Prioritize instructions that read unbuffered resources by stall cycles.
3361 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3362 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3363 return;
3364
Florian Hahnabb42182017-05-23 09:33:34 +00003365 // Keep clustered nodes together.
3366 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3367 Cand.SU == DAG->getNextClusterSucc(),
3368 TryCand, Cand, Cluster))
3369 return;
3370
Andrew Trickd14d7c22013-12-28 21:56:57 +00003371 // Avoid critical resource consumption and balance the schedule.
3372 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3373 TryCand, Cand, ResourceReduce))
3374 return;
3375 if (tryGreater(TryCand.ResDelta.DemandedResources,
3376 Cand.ResDelta.DemandedResources,
3377 TryCand, Cand, ResourceDemand))
3378 return;
3379
3380 // Avoid serializing long latency dependence chains.
3381 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3382 return;
3383 }
3384
3385 // Fall through to original instruction order.
3386 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3387 TryCand.Reason = NodeOrder;
3388}
3389
3390void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3391 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003392 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003393 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003394 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003395 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003396 TryCand.initResourceDelta(DAG, SchedModel);
3397 tryCandidate(Cand, TryCand);
3398 if (TryCand.Reason != NoCand) {
3399 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003400 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trickd14d7c22013-12-28 21:56:57 +00003401 }
3402 }
3403}
3404
3405/// Pick the next node to schedule.
3406SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3407 if (DAG->top() == DAG->bottom()) {
3408 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003409 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003410 }
3411 SUnit *SU;
3412 do {
3413 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003414 if (SU) {
3415 tracePick(Only1, true);
3416 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003417 CandPolicy NoPolicy;
3418 SchedCandidate TopCand(NoPolicy);
3419 // Set the top-down policy based on the state of the current top zone and
3420 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003421 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003422 pickNodeFromQueue(TopCand);
3423 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003424 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003425 SU = TopCand.SU;
3426 }
3427 } while (SU->isScheduled);
3428
3429 IsTopNode = true;
3430 Top.removeReady(SU);
3431
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003432 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3433 << *SU->getInstr());
Andrew Trickd14d7c22013-12-28 21:56:57 +00003434 return SU;
3435}
3436
3437/// Called after ScheduleDAGMI has scheduled an instruction and updated
3438/// scheduled/remaining flags in the DAG nodes.
3439void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3440 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3441 Top.bumpNode(SU);
3442}
3443
Matthias Braun115efcd2016-11-28 20:11:54 +00003444ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003445 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003446 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003447}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003448
3449//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003450// ILP Scheduler. Currently for experimental analysis of heuristics.
3451//===----------------------------------------------------------------------===//
3452
3453namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003454
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003455/// Order nodes by the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003456struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003457 const SchedDFSResult *DFSResult = nullptr;
3458 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003459 bool MaximizeILP;
3460
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003461 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003462
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003463 /// Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003464 ///
3465 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003466 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003467 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3468 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3469 if (SchedTreeA != SchedTreeB) {
3470 // Unscheduled trees have lower priority.
3471 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3472 return ScheduledTrees->test(SchedTreeB);
3473
3474 // Trees with shallower connections have have lower priority.
3475 if (DFSResult->getSubtreeLevel(SchedTreeA)
3476 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3477 return DFSResult->getSubtreeLevel(SchedTreeA)
3478 < DFSResult->getSubtreeLevel(SchedTreeB);
3479 }
3480 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003481 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003482 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003483 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003484 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003485 }
3486};
3487
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003488/// Schedule based on the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003489class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003490 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003491 ILPOrder Cmp;
3492
3493 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003494
Andrew Trick90f711d2012-10-15 18:02:27 +00003495public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003496 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003497
Craig Topper4584cd52014-03-07 09:26:03 +00003498 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003499 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3500 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003501 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003502 Cmp.DFSResult = DAG->getDFSResult();
3503 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003504 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003505 }
3506
Craig Topper4584cd52014-03-07 09:26:03 +00003507 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003508 // Restore the heap in ReadyQ with the updated DFS results.
3509 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003510 }
3511
3512 /// Implement MachineSchedStrategy interface.
3513 /// -----------------------------------------
3514
Andrew Trick48d392e2012-11-28 05:13:28 +00003515 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003516 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003517 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003518 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003519 SUnit *SU = ReadyQ.back();
3520 ReadyQ.pop_back();
3521 IsTopNode = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003522 LLVM_DEBUG(dbgs() << "Pick node "
3523 << "SU(" << SU->NodeNum << ") "
3524 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3525 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
3526 << " @"
3527 << DAG->getDFSResult()->getSubtreeLevel(
3528 DAG->getDFSResult()->getSubtreeID(SU))
3529 << '\n'
3530 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003531 return SU;
3532 }
3533
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003534 /// Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003535 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003536 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3537 }
3538
Andrew Trick48d392e2012-11-28 05:13:28 +00003539 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3540 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003541 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003542 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003543 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003544
Craig Topper4584cd52014-03-07 09:26:03 +00003545 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003546
Craig Topper4584cd52014-03-07 09:26:03 +00003547 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003548 ReadyQ.push_back(SU);
3549 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3550 }
3551};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003552
3553} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003554
3555static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003556 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003557}
3558static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003559 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003560}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003561
Andrew Trick90f711d2012-10-15 18:02:27 +00003562static MachineSchedRegistry ILPMaxRegistry(
3563 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3564static MachineSchedRegistry ILPMinRegistry(
3565 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3566
3567//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003568// Machine Instruction Shuffler for Correctness Testing
3569//===----------------------------------------------------------------------===//
3570
Andrew Tricke77e84e2012-01-13 06:30:30 +00003571#ifndef NDEBUG
3572namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003573
Andrew Trick8823dec2012-03-14 04:00:41 +00003574/// Apply a less-than relation on the node order, which corresponds to the
3575/// instruction order prior to scheduling. IsReverse implements greater-than.
3576template<bool IsReverse>
3577struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003578 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003579 if (IsReverse)
3580 return A->NodeNum > B->NodeNum;
3581 else
3582 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003583 }
3584};
3585
Andrew Tricke77e84e2012-01-13 06:30:30 +00003586/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003587class InstructionShuffler : public MachineSchedStrategy {
3588 bool IsAlternating;
3589 bool IsTopDown;
3590
3591 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3592 // gives nodes with a higher number higher priority causing the latest
3593 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003594 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003595 TopQ;
Eugene Zelenko32a40562017-09-11 23:00:48 +00003596
Andrew Trick8823dec2012-03-14 04:00:41 +00003597 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003598 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003599 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003600
Andrew Tricke77e84e2012-01-13 06:30:30 +00003601public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003602 InstructionShuffler(bool alternate, bool topdown)
3603 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003604
Craig Topper9d74a5a2014-04-29 07:58:41 +00003605 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003606 TopQ.clear();
3607 BottomQ.clear();
3608 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003609
Andrew Trick8823dec2012-03-14 04:00:41 +00003610 /// Implement MachineSchedStrategy interface.
3611 /// -----------------------------------------
3612
Craig Topper9d74a5a2014-04-29 07:58:41 +00003613 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003614 SUnit *SU;
3615 if (IsTopDown) {
3616 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003617 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003618 SU = TopQ.top();
3619 TopQ.pop();
3620 } while (SU->isScheduled);
3621 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003622 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003623 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003624 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003625 SU = BottomQ.top();
3626 BottomQ.pop();
3627 } while (SU->isScheduled);
3628 IsTopNode = false;
3629 }
3630 if (IsAlternating)
3631 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003632 return SU;
3633 }
3634
Craig Topper9d74a5a2014-04-29 07:58:41 +00003635 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003636
Craig Topper9d74a5a2014-04-29 07:58:41 +00003637 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003638 TopQ.push(SU);
3639 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003640 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003641 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003642 }
3643};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003644
3645} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003646
Andrew Trick02a80da2012-03-08 01:41:12 +00003647static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003648 bool Alternate = !ForceTopDown && !ForceBottomUp;
3649 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003650 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003651 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003652 return new ScheduleDAGMILive(
3653 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003654}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003655
Andrew Trick8823dec2012-03-14 04:00:41 +00003656static MachineSchedRegistry ShufflerRegistry(
3657 "shuffle", "Shuffle machine instructions alternating directions",
3658 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003659#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003660
3661//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003662// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003663//===----------------------------------------------------------------------===//
3664
3665#ifndef NDEBUG
3666namespace llvm {
3667
3668template<> struct GraphTraits<
3669 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3670
3671template<>
3672struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003673 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003674
3675 static std::string getGraphName(const ScheduleDAG *G) {
3676 return G->MF.getName();
3677 }
3678
3679 static bool renderGraphFromBottomUp() {
3680 return true;
3681 }
3682
3683 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003684 if (ViewMISchedCutoff == 0)
3685 return false;
3686 return (Node->Preds.size() > ViewMISchedCutoff
3687 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003688 }
3689
Andrew Trickea9fd952013-01-25 07:45:29 +00003690 /// If you want to override the dot attributes printed for a particular
3691 /// edge, override this method.
3692 static std::string getEdgeAttributes(const SUnit *Node,
3693 SUnitIterator EI,
3694 const ScheduleDAG *Graph) {
3695 if (EI.isArtificialDep())
3696 return "color=cyan,style=dashed";
3697 if (EI.isCtrlDep())
3698 return "color=blue,style=dashed";
3699 return "";
3700 }
3701
3702 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003703 std::string Str;
3704 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003705 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3706 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003707 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003708 SS << "SU:" << SU->NodeNum;
3709 if (DFS)
3710 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003711 return SS.str();
3712 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00003713
Andrew Trickea9fd952013-01-25 07:45:29 +00003714 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3715 return G->getGraphNodeLabel(SU);
3716 }
3717
Andrew Trickd7f890e2013-12-28 21:56:47 +00003718 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003719 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003720 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3721 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003722 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003723 if (DFS) {
3724 Str += ",style=filled,fillcolor=\"#";
3725 Str += DOT::getColorString(DFS->getSubtreeID(N));
3726 Str += '"';
3727 }
3728 return Str;
3729 }
3730};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003731
3732} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003733#endif // NDEBUG
3734
3735/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3736/// rendered using 'dot'.
Andrew Trickea9fd952013-01-25 07:45:29 +00003737void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3738#ifndef NDEBUG
3739 ViewGraph(this, Name, false, Title);
3740#else
3741 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3742 << "systems with Graphviz or gv!\n";
3743#endif // NDEBUG
3744}
3745
3746/// Out-of-line implementation with no arguments is handy for gdb.
3747void ScheduleDAGMI::viewGraph() {
3748 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3749}